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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-gear",
3
- "version": "2.11.0",
3
+ "version": "2.12.0",
4
4
  "description": "ZeroAsh Agent Gear - Agent controller daemon",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,7 +23,7 @@
23
23
  "license": "ISC",
24
24
  "type": "module",
25
25
  "dependencies": {
26
- "@agentclientprotocol/sdk": "^1.3.0",
26
+ "@agentclientprotocol/sdk": "1.9.0",
27
27
  "commander": "^13.1.0",
28
28
  "jsonc-parser": "^3.3.1",
29
29
  "smol-toml": "^1.6.1",
package/src/acp/bridge.ts CHANGED
@@ -196,7 +196,10 @@ function toAuthMethods(authMethods: acp.AuthMethod[] | undefined): AcpAuthMethod
196
196
  if (!authMethods || authMethods.length === 0) return [];
197
197
  return authMethods.map((m) => {
198
198
  if ('type' in m) {
199
- const kind = m.type === 'env_var' ? 'env_var' : m.type === 'terminal' ? 'terminal' : 'agent';
199
+ // SDK 1.9.0 起 AuthMethod 仅声明 terminal/agent 变体(env_var 变体已移除),
200
+ // 但线上 Agent 仍可能下发 env_var:按原始 wire 值判定,行为与旧版一致。
201
+ const wireType = (m as { type?: string }).type;
202
+ const kind = wireType === 'env_var' ? 'env_var' : wireType === 'terminal' ? 'terminal' : 'agent';
200
203
  return {
201
204
  id: m.id,
202
205
  kind,
@@ -1025,6 +1028,13 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1025
1028
  });
1026
1029
  }
1027
1030
 
1031
+ // SDK ≥1.4.0 把客户端 elicitation 处理器改名为 createElicitation/completeElicitation
1032
+ // (1.9.0 起不再注册 unstable_*),而 lockfile 1.3.0 只认旧名;两个名字同时暴露,
1033
+ // 保证仓库与发布包(实际安装 1.9.0)都能命中处理器,避免 elicitation/create 无处理器被秒取消。
1034
+ async createElicitation(params: acp.CreateElicitationRequest): Promise<acp.CreateElicitationResponse> {
1035
+ return this.unstable_createElicitation(params);
1036
+ }
1037
+
1028
1038
  handleElicitationResponse(
1029
1039
  requestId: string,
1030
1040
  action: 'accept' | 'decline' | 'cancel',
@@ -1072,6 +1082,10 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1072
1082
  });
1073
1083
  }
1074
1084
 
1085
+ async completeElicitation(params: acp.CompleteElicitationNotification): Promise<void> {
1086
+ return this.unstable_completeElicitation(params);
1087
+ }
1088
+
1075
1089
  // ── text buffering ──
1076
1090
 
1077
1091
  private scheduleTextFlush(): void {
@@ -136,4 +136,13 @@ export class AcpSyncBridge implements acp.Client {
136
136
  async unstable_completeElicitation(): Promise<void> {
137
137
  // no-op
138
138
  }
139
+
140
+ // SDK ≥1.4.0 注册的新方法名(1.9.0 起仅注册新名),委托到与 unstable_* 相同的实现。
141
+ async createElicitation(): Promise<acp.CreateElicitationResponse> {
142
+ return this.unstable_createElicitation();
143
+ }
144
+
145
+ async completeElicitation(): Promise<void> {
146
+ return this.unstable_completeElicitation();
147
+ }
139
148
  }
@@ -2,6 +2,7 @@ import { describe, it, expect, vi } from 'vitest';
2
2
  import {
3
3
  GithubCredentialManager,
4
4
  REFRESH_INTERVAL_MS,
5
+ EXPIRY_SKEW_MS,
5
6
  BACKOFF_MS,
6
7
  } from './credential-manager.js';
7
8
 
@@ -174,6 +175,139 @@ describe('GithubCredentialManager', () => {
174
175
  earlyManager.stop();
175
176
  });
176
177
 
178
+ it('T-CM9 (REPRO): 续期拿到仅剩 10 分钟的 token 时必须在到期前再次续期,而不是再等 50 分钟', async () => {
179
+ const t0 = Date.parse('2026-10-22T10:00:00.000Z');
180
+ let now = t0;
181
+ // 复现服务端进程内缓存:首次签发 60 分钟有效的 token,50 分钟后续期仍返回同一枚
182
+ // (命中缓存,剩余有效期只剩 10 分钟)。
183
+ const minted = new Date(t0 + 60 * 60 * 1000).toISOString();
184
+ const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: minted }));
185
+ const scheduler = fakeScheduler();
186
+
187
+ const manager = new GithubCredentialManager({
188
+ env: BASE_ENV,
189
+ fetch: fetchFn,
190
+ writeGhAuth: async () => {},
191
+ now: () => now,
192
+ log: () => {},
193
+ setTimeout: scheduler.setTimeoutFn,
194
+ });
195
+
196
+ manager.start();
197
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(1));
198
+ expect(scheduler.timers[0].delay).toBe(REFRESH_INTERVAL_MS);
199
+
200
+ // 50 分钟后续期:服务端返回缓存 token(仅剩 10 分钟)
201
+ now = t0 + REFRESH_INTERVAL_MS;
202
+ scheduler.timers[0].fn();
203
+ await vi.waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2));
204
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(2));
205
+
206
+ // 期望:下一次续期必须早于 token 过期(留出 EXPIRY_SKEW_MS 余量)。
207
+ // 实际:beforeExpiry 计算为 0 → 回落到 50 分钟,token 过期 40 分钟后才续期。
208
+ expect(now + scheduler.timers[1].delay).toBeLessThanOrEqual(
209
+ t0 + 60 * 60 * 1000 - EXPIRY_SKEW_MS,
210
+ );
211
+
212
+ manager.stop();
213
+ });
214
+
215
+ it('T-CM10 (REPRO): 收到即将过期的 token 时短间隔重试,而不是 50 分钟后再来', async () => {
216
+ const t0 = Date.parse('2026-10-22T10:00:00.000Z');
217
+ let now = t0;
218
+ const writeGhAuth = vi.fn(async () => {});
219
+ // 服务端返回的 token 在 1 分钟后过期(已是「续期也救不回来」的临界值)
220
+ const fetchFn = fakeFetch(async () =>
221
+ jsonResponse({ token: TOKEN, expiresAt: new Date(t0 + 60 * 1000).toISOString() }),
222
+ );
223
+ const scheduler = fakeScheduler();
224
+
225
+ const manager = new GithubCredentialManager({
226
+ env: BASE_ENV,
227
+ fetch: fetchFn,
228
+ writeGhAuth,
229
+ now: () => now,
230
+ log: () => {},
231
+ setTimeout: scheduler.setTimeoutFn,
232
+ });
233
+
234
+ manager.start();
235
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(1));
236
+
237
+ // 期望:近过期 token 不应按 50 分钟排期,而是短间隔重试拿新凭据。
238
+ expect(scheduler.timers[0].delay).toBeLessThan(REFRESH_INTERVAL_MS);
239
+
240
+ manager.stop();
241
+ });
242
+
243
+ it('T-CM11: 非 401/403/404 的续期失败必须留下脱敏日志(5xx / 非法 JSON / 网络错误不再静默)', async () => {
244
+ const scenarios: Array<() => Promise<Response>> = [
245
+ async () => new Response('boom', { status: 500 }),
246
+ async () =>
247
+ new Response('not json', { status: 200, headers: { 'content-type': 'application/json' } }),
248
+ async () => {
249
+ throw new Error('ECONNREFUSED');
250
+ },
251
+ ];
252
+
253
+ for (const scenario of scenarios) {
254
+ const logs: string[] = [];
255
+ const manager = new GithubCredentialManager({
256
+ env: BASE_ENV,
257
+ fetch: fakeFetch(scenario),
258
+ writeGhAuth: async () => {},
259
+ log: (message) => logs.push(message),
260
+ });
261
+
262
+ const result = await manager.refreshNow();
263
+
264
+ expect(result.ok).toBe(false);
265
+ const joined = logs.join('\n');
266
+ expect(joined).toContain('[GithubCredential] 凭据续期失败');
267
+ expect(joined).not.toContain(TOKEN);
268
+ }
269
+ });
270
+
271
+ it('T-CM12: 进入近过期区首次立即重试、其后按短间隔退避,并留下不含 token 的告警日志', async () => {
272
+ const t0 = Date.parse('2026-10-22T10:00:00.000Z');
273
+ let now = t0;
274
+ const logs: string[] = [];
275
+ // 服务端持续返回近过期 token(复现 R1 未修复时的缓存命中)
276
+ const minted = new Date(t0 + 60 * 60 * 1000).toISOString();
277
+ const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: minted }));
278
+ const scheduler = fakeScheduler();
279
+
280
+ const manager = new GithubCredentialManager({
281
+ env: BASE_ENV,
282
+ fetch: fetchFn,
283
+ writeGhAuth: async () => {},
284
+ now: () => now,
285
+ log: (message) => logs.push(message),
286
+ setTimeout: scheduler.setTimeoutFn,
287
+ });
288
+
289
+ manager.start();
290
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(1));
291
+
292
+ // 50 分钟后续期仍拿到同一枚只剩 10 分钟的 token → 进入近过期区
293
+ now = t0 + REFRESH_INTERVAL_MS;
294
+ scheduler.timers[0].fn();
295
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(2));
296
+ // 首次发现已到/已过续期余量:立即重试,绝不排到 token 过期之后
297
+ expect(scheduler.timers[1].delay).toBe(0);
298
+
299
+ scheduler.timers[1].fn();
300
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(3));
301
+ // 服务端仍返回近过期 token → 退到短间隔重试(60s),避免热循环打爆 agent-api
302
+ expect(scheduler.timers[2].delay).toBe(60_000);
303
+
304
+ const joined = logs.join('\n');
305
+ expect(joined).toContain('[GithubCredential] 凭据剩余有效期不足');
306
+ expect(joined).not.toContain(TOKEN);
307
+
308
+ manager.stop();
309
+ });
310
+
177
311
  it('T-CM5: concurrent refreshNow calls are serialized into a single request', async () => {
178
312
  let release!: (response: Response) => void;
179
313
  const gate = new Promise<Response>((resolve) => {
@@ -13,6 +13,13 @@ export const REQUEST_TIMEOUT_MS = 10_000;
13
13
  /** 401/403 退避序列(1/2/4 分钟,最多 3 次重试)。 */
14
14
  export const BACKOFF_MS = [60_000, 120_000, 240_000] as const;
15
15
 
16
+ /**
17
+ * 凭据已进入「到期前余量区」(`beforeExpiry <= 0`)时的短间隔重试(60 秒)。
18
+ * 首次发现时立即重试一次(`delay=0`),其后按本间隔退避,避免服务端持续返回
19
+ * 近过期 token 时热循环打爆 agent-api。
20
+ */
21
+ export const NEAR_EXPIRY_RETRY_MS = 60_000;
22
+
16
23
  /** 凭据管理器依赖注入(测试锚定网络/时钟/副作用;生产使用缺省实现)。 */
17
24
  export interface GithubCredentialManagerDeps {
18
25
  env?: NodeJS.ProcessEnv;
@@ -40,10 +47,12 @@ type Timer = ReturnType<typeof setTimeout>;
40
47
  * 云主机内 Github 凭据管理器(容器侧唯一凭据写入口)。
41
48
  *
42
49
  * - `start()`:校验 env 后立即申请一次,并按「50 分钟」或「token 到期前 10 分钟」(取较早)
43
- * 自续期;定时器 `unref()`,不阻止进程退出;
50
+ * 自续期;已进入/越过余量区(`beforeExpiry <= 0`)时首次立即重试、其后按 60 秒短间隔
51
+ * 重试并告警(绝不回落到 50 分钟);定时器 `unref()`,不阻止进程退出;
44
52
  * - `refreshNow()`:向 agent-api 申请仓库级 token 并写入 gh 配置;并发调用合并为一次请求;
45
53
  * 401/403 在本次调用内按 1/2/4 分钟退避(最多 3 次);
46
- * - 404(未绑定 Git 项目)返回 `no-binding`,不告警;
54
+ * - 404(未绑定 Git 项目)返回 `no-binding`,不告警;除 `disabled`/`no-binding` 外的失败
55
+ * 一律输出脱敏错误日志(便于线上取证);
47
56
  * - token 只交给 `writeGhAuth`(stdin),从不进入日志/错误。
48
57
  */
49
58
  export class GithubCredentialManager {
@@ -60,6 +69,8 @@ export class GithubCredentialManager {
60
69
  private stopped = false;
61
70
  private expiresAt: Date | null = null;
62
71
  private activeRefresh: Promise<GithubCredentialRefreshResult> | null = null;
72
+ /** 近过期区「立即重试」是否已被消费(防止服务端持续返回近过期 token 时热循环)。 */
73
+ private nearExpiryImmediateTaken = false;
63
74
 
64
75
  constructor(deps: GithubCredentialManagerDeps = {}) {
65
76
  this.env = deps.env ?? process.env;
@@ -143,9 +154,16 @@ export class GithubCredentialManager {
143
154
  continue;
144
155
  }
145
156
  if (result.kind === 'retryable') {
157
+ // 退避耗尽:每次尝试已在上方记录告警,不重复输出。
146
158
  return { ok: false, error: `Github 凭据无效(HTTP ${result.status})` };
147
159
  }
148
- return result.value;
160
+ const value = result.value;
161
+ // 非 401/403/404 的失败(5xx / 超时 / 非法 JSON / 写 gh 失败)必须留痕,
162
+ // 否则线上只能看到「凭据没更新」而无任何线索;`disabled`/`no-binding` 属正常态不告警。
163
+ if (!value.ok && value.error && value.error !== 'no-binding' && value.error !== 'disabled') {
164
+ this.log(`[GithubCredential] 凭据续期失败:${value.error}`);
165
+ }
166
+ return value;
149
167
  }
150
168
  }
151
169
 
@@ -224,13 +242,25 @@ export class GithubCredentialManager {
224
242
  }
225
243
  }
226
244
 
227
- /** 下一次续期:50 分钟与「到期前 10 分钟」取较早;定时器 unref,不阻止进程退出。 */
245
+ /** 下一次续期:50 分钟与「到期前 10 分钟」取较早;已进入/越过余量区时首次立即重试、
246
+ * 其后按 `NEAR_EXPIRY_RETRY_MS` 短间隔退避并告警(绝不回落 50 分钟,否则 token 过期后
247
+ * 还要再等 40 分钟才续期)。定时器 unref,不阻止进程退出。 */
228
248
  private scheduleNext(): void {
229
249
  if (this.stopped || !this.started || !this.isEnabled()) return;
230
250
  let delay = REFRESH_INTERVAL_MS;
231
251
  if (this.expiresAt) {
232
252
  const beforeExpiry = this.expiresAt.getTime() - EXPIRY_SKEW_MS - this.now();
233
- if (beforeExpiry > 0 && beforeExpiry < delay) delay = beforeExpiry;
253
+ if (beforeExpiry <= 0) {
254
+ delay = this.nearExpiryImmediateTaken ? NEAR_EXPIRY_RETRY_MS : 0;
255
+ this.nearExpiryImmediateTaken = true;
256
+ this.log(
257
+ `[GithubCredential] 凭据剩余有效期不足(至 ${this.expiresAt.toISOString()}),` +
258
+ (delay === 0 ? '立即重试' : `${Math.round(delay / 1000)} 秒后重试`),
259
+ );
260
+ } else {
261
+ this.nearExpiryImmediateTaken = false;
262
+ if (beforeExpiry < delay) delay = beforeExpiry;
263
+ }
234
264
  }
235
265
  this.timer = this.setTimeoutFn(() => {
236
266
  this.timer = null;
@@ -48,4 +48,21 @@ describe('T-DSH7 dsh config atomic write failure cleanup', () => {
48
48
  { force: true },
49
49
  );
50
50
  });
51
+
52
+ it('T-MASQ9: insert 条目与扁平条目在同一次原子写中落盘', async () => {
53
+ fs.rename.mockResolvedValue(undefined);
54
+
55
+ await writeDshConfig({ env: ENV, dshHome: '/tmp/opencode-dsh-atomic' });
56
+
57
+ const patchWrite = fs.writeFile.mock.calls.find(
58
+ ([path]) => typeof path === 'string' && /\.cordis\.patch\..*\.tmp$/.test(path),
59
+ );
60
+ expect(patchWrite).toBeDefined();
61
+ const content = String(patchWrite![1]);
62
+ expect(content).toContain('- insert:');
63
+ expect(content).toContain('id: header-masq');
64
+ expect(content).toContain('name: dsh-header-masq');
65
+ expect(content).toContain('x-opencode-session');
66
+ expect(content).not.toContain('hosts:');
67
+ });
51
68
  });
@@ -14,6 +14,18 @@ const ENV = {
14
14
  modelContextLengths: { 'model-a': 128000 },
15
15
  };
16
16
 
17
+ /** 需求给定四键(`hosts` 缺省不写)。 */
18
+ const HEADER_MASQ_ENTRY = {
19
+ id: 'header-masq',
20
+ name: 'dsh-header-masq',
21
+ config: {
22
+ source: 'x-deepseek-harness-session-id',
23
+ targets: ['x-opencode-session'],
24
+ fallbackToSessionId: true,
25
+ debug: false,
26
+ },
27
+ };
28
+
17
29
  async function makeHome(): Promise<string> {
18
30
  await mkdir(TMP_BASE, { recursive: true });
19
31
  return mkdtemp(join(TMP_BASE, 'dsh-'));
@@ -35,7 +47,7 @@ describe('writeDshConfig (T-DSH*)', () => {
35
47
  expect(defaultDshHome({})).toMatch(/\/\.dsh$/);
36
48
  });
37
49
 
38
- it('T-DSH1: 新建 patch 写入 4 个条目与 ZAG provider,并新建 credentials', async () => {
50
+ it('T-DSH1: 新建 patch 写入 4 个扁平条目 + insert header-masq 与 ZAG provider,并新建 credentials', async () => {
39
51
  const home = await makeHome();
40
52
  dirs.push(home);
41
53
 
@@ -45,7 +57,7 @@ describe('writeDshConfig (T-DSH*)', () => {
45
57
  patchCreated: true,
46
58
  credentialsCreated: true,
47
59
  modelCount: 2,
48
- entryCount: 4,
60
+ entryCount: 5,
49
61
  });
50
62
  expect(result.patchPath).toBe(join(home, 'profiles', 'acp', 'cordis.patch.yml'));
51
63
  expect(result.credentialsPath).toBe(join(home, '.credentials.yaml'));
@@ -56,6 +68,7 @@ describe('writeDshConfig (T-DSH*)', () => {
56
68
  'llm-pi-ai',
57
69
  'agent-default-model',
58
70
  'acp',
71
+ undefined,
59
72
  ]);
60
73
  expect(patch[0]).toEqual({ id: 'llm-deepseek', disabled: true });
61
74
  expect(patch[1].config.providers.zag).toMatchObject({
@@ -77,6 +90,7 @@ describe('writeDshConfig (T-DSH*)', () => {
77
90
  name: '@deepseek-ai/dsh-acp',
78
91
  config: { provider: 'zag', model: 'model-a' },
79
92
  });
93
+ expect(patch[4]).toEqual({ insert: [HEADER_MASQ_ENTRY] });
80
94
 
81
95
  const credentials = (await readYaml(result.credentialsPath)) as Record<string, any>;
82
96
  expect(credentials).toEqual({ version: 1, refs: { ZAG_MODEL_API_KEY: API_KEY } });
@@ -248,7 +262,9 @@ describe('writeDshConfig (T-DSH*)', () => {
248
262
  expect(await readFile(second.patchPath, 'utf-8')).toBe(firstPatch);
249
263
  expect(await readFile(second.credentialsPath, 'utf-8')).toBe(firstCredentials);
250
264
  const patch = parse(firstPatch) as Array<Record<string, any>>;
251
- expect(patch).toHaveLength(4);
265
+ expect(patch).toHaveLength(5);
266
+ expect(patch.filter((entry) => entry.id === 'header-masq')).toHaveLength(0);
267
+ expect(patch.filter((entry) => entry.insert !== undefined)).toHaveLength(1);
252
268
  expect((await stat(second.patchPath)).mode & 0o777).toBe(0o600);
253
269
  expect((await stat(join(home, 'profiles', 'acp'))).mode & 0o777).toBe(0o700);
254
270
  });
@@ -273,3 +289,158 @@ describe('writeDshConfig (T-DSH*)', () => {
273
289
  }
274
290
  });
275
291
  });
292
+
293
+ describe('writeDshConfig insert 受管条目(T-MASQ*)', () => {
294
+ const dirs: string[] = [];
295
+
296
+ afterEach(async () => {
297
+ await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })));
298
+ });
299
+
300
+ async function writePatch(home: string, text: string): Promise<string> {
301
+ const profilesDir = join(home, 'profiles', 'acp');
302
+ await mkdir(profilesDir, { recursive: true });
303
+ const patchPath = join(profilesDir, 'cordis.patch.yml');
304
+ await writeFile(patchPath, text, 'utf-8');
305
+ return patchPath;
306
+ }
307
+
308
+ it('T-MASQ1: 无 patch / 无 insert 块时在末尾追加单条目 insert 块(四键、hosts 不写)', async () => {
309
+ const home = await makeHome();
310
+ dirs.push(home);
311
+
312
+ const result = await writeDshConfig({ env: ENV, dshHome: home });
313
+
314
+ const text = await readFile(result.patchPath, 'utf-8');
315
+ const patch = parse(text) as Array<Record<string, any>>;
316
+ expect(patch).toHaveLength(5);
317
+ expect(patch[4]).toEqual({ insert: [HEADER_MASQ_ENTRY] });
318
+ expect(patch[4].insert[0].config).not.toHaveProperty('hosts');
319
+ expect(text).toContain('- insert:\n - id: header-masq\n name: dsh-header-masq\n');
320
+ });
321
+
322
+ it('T-MASQ2: 既有 insert 块含 header-masq 时整体替换为我方单条目块(config 全量覆盖)', async () => {
323
+ const home = await makeHome();
324
+ dirs.push(home);
325
+ const patchPath = await writePatch(
326
+ home,
327
+ [
328
+ '# top comment',
329
+ '- id: other',
330
+ ' value: 1',
331
+ '- insert:',
332
+ ' - id: header-masq',
333
+ ' name: dsh-header-masq',
334
+ ' config:',
335
+ ' source: stale-source',
336
+ ' targets:',
337
+ ' - x-stale',
338
+ ' debug: true',
339
+ '- insert:',
340
+ ' - id: unrelated-plugin',
341
+ ' name: unrelated',
342
+ '',
343
+ ].join('\n'),
344
+ );
345
+
346
+ await writeDshConfig({ env: ENV, dshHome: home });
347
+
348
+ const text = await readFile(patchPath, 'utf-8');
349
+ const patch = parse(text) as Array<Record<string, any>>;
350
+ const headerBlocks = patch.filter(
351
+ (entry) =>
352
+ Array.isArray(entry.insert) &&
353
+ entry.insert.some((inner: { id?: string }) => inner?.id === 'header-masq'),
354
+ );
355
+ expect(headerBlocks).toHaveLength(1);
356
+ expect(headerBlocks[0]).toEqual({ insert: [HEADER_MASQ_ENTRY] });
357
+ expect(text).not.toContain('stale-source');
358
+ expect(text).not.toContain('x-stale');
359
+ // 他插件 insert 块原样保留
360
+ expect(patch).toContainEqual({ insert: [{ id: 'unrelated-plugin', name: 'unrelated' }] });
361
+ });
362
+
363
+ it('T-MASQ3: 连续两次写入逐字一致,不产生重复 insert 块', async () => {
364
+ const home = await makeHome();
365
+ dirs.push(home);
366
+
367
+ const first = await writeDshConfig({ env: ENV, dshHome: home });
368
+ const firstText = await readFile(first.patchPath, 'utf-8');
369
+ await writeDshConfig({ env: ENV, dshHome: home });
370
+ const secondText = await readFile(first.patchPath, 'utf-8');
371
+
372
+ expect(secondText).toBe(firstText);
373
+ const patch = parse(secondText) as Array<Record<string, any>>;
374
+ expect(patch).toHaveLength(5);
375
+ expect(secondText.match(/id: header-masq/g)).toHaveLength(1);
376
+ });
377
+
378
+ it('T-MASQ4: insert 合并保留他条目、他插件条目与注释', async () => {
379
+ const home = await makeHome();
380
+ dirs.push(home);
381
+ const patchPath = await writePatch(
382
+ home,
383
+ [
384
+ '# top comment',
385
+ '- id: other',
386
+ ' value: 1 # keep inline',
387
+ '- id: acp',
388
+ ' name: "@deepseek-ai/dsh-acp"',
389
+ ' config: { provider: old }',
390
+ '- insert:',
391
+ ' - id: unrelated-plugin',
392
+ ' name: unrelated',
393
+ '',
394
+ ].join('\n'),
395
+ );
396
+
397
+ await writeDshConfig({ env: ENV, dshHome: home });
398
+
399
+ const text = await readFile(patchPath, 'utf-8');
400
+ expect(text).toContain('# top comment');
401
+ expect(text).toContain('value: 1 # keep inline');
402
+ const patch = parse(text) as Array<Record<string, any>>;
403
+ expect(patch[0]).toEqual({ id: 'other', value: 1 });
404
+ expect(patch.filter((entry) => entry.id === 'acp')).toHaveLength(1);
405
+ expect(patch).toContainEqual({ insert: [{ id: 'unrelated-plugin', name: 'unrelated' }] });
406
+ expect(patch).toContainEqual({ insert: [HEADER_MASQ_ENTRY] });
407
+ });
408
+
409
+ it('T-MASQ6: insert 块含多个内层条目时整体替换(共块他条目被丢弃,已登记风险)', async () => {
410
+ const home = await makeHome();
411
+ dirs.push(home);
412
+ const patchPath = await writePatch(
413
+ home,
414
+ [
415
+ '- insert:',
416
+ ' - id: shared-plugin',
417
+ ' name: shared',
418
+ ' - id: header-masq',
419
+ ' name: dsh-header-masq',
420
+ ' config: { source: stale }',
421
+ '',
422
+ ].join('\n'),
423
+ );
424
+
425
+ await writeDshConfig({ env: ENV, dshHome: home });
426
+
427
+ const patch = (await readYaml(patchPath)) as Array<Record<string, any>>;
428
+ const headerBlock = patch.find(
429
+ (entry) =>
430
+ Array.isArray(entry.insert) &&
431
+ entry.insert.some((inner: { id?: string }) => inner?.id === 'header-masq'),
432
+ )!;
433
+ expect(headerBlock.insert).toEqual([HEADER_MASQ_ENTRY]);
434
+ expect(JSON.stringify(patch)).not.toContain('shared-plugin');
435
+ });
436
+
437
+ it('T-MASQ8: insert 路径下非法 YAML 抛错且不覆盖既有文件', async () => {
438
+ const home = await makeHome();
439
+ dirs.push(home);
440
+ const broken = '- insert: [\n';
441
+ const patchPath = await writePatch(home, broken);
442
+
443
+ await expect(writeDshConfig({ env: ENV, dshHome: home })).rejects.toBeInstanceOf(DshConfigError);
444
+ expect(await readFile(patchPath, 'utf-8')).toBe(broken);
445
+ });
446
+ });
@@ -14,7 +14,7 @@ export const DSH_ACP_PROFILE = 'acp';
14
14
  /** dsh ACP profile 组合包名(写入 patch 的 `acp` 条目)。 */
15
15
  export const DSH_ACP_APP_NAME = '@deepseek-ai/dsh-acp';
16
16
 
17
- /** 我方在 `cordis.patch.yml` 中维护的 4 个条目(按此顺序写入,按 id 替换)。 */
17
+ /** 我方在 `cordis.patch.yml` 中维护的 4 个扁平条目(按此顺序写入,按 id 替换)。 */
18
18
  export const DSH_PATCH_ENTRY_IDS = [
19
19
  'llm-deepseek',
20
20
  'llm-pi-ai',
@@ -22,6 +22,15 @@ export const DSH_PATCH_ENTRY_IDS = [
22
22
  'acp',
23
23
  ] as const;
24
24
 
25
+ /**
26
+ * 我方在 `cordis.patch.yml` 中维护的 insert 形态条目 id(位于顶层 `- insert: [...]` 块内)。
27
+ * 与扁平条目合计 5 个受管条目(`entryCount`)。
28
+ */
29
+ export const DSH_PATCH_INSERT_ENTRY_IDS = ['header-masq'] as const;
30
+
31
+ /** `header-masq` insert 条目对应的插件包名。 */
32
+ export const DSH_HEADER_MASQ_PLUGIN_NAME = 'dsh-header-masq';
33
+
25
34
  /** 写入 dsh 配置失败(消息只含路径/条目名,不含 API Key 等 secret)。 */
26
35
  export class DshConfigError extends Error {
27
36
  constructor(message: string) {
@@ -53,7 +62,7 @@ export interface WriteDshConfigResult {
53
62
  credentialsCreated: boolean;
54
63
  /** 写入的模型数量。 */
55
64
  modelCount: number;
56
- /** patch 中我方维护的条目数(固定 4)。 */
65
+ /** patch 中我方维护的条目数(4 扁平 + 1 insert,固定 5)。 */
57
66
  entryCount: number;
58
67
  }
59
68
 
@@ -113,6 +122,40 @@ function buildEntry(id: (typeof DSH_PATCH_ENTRY_IDS)[number], env: DshConfigEnv)
113
122
  }
114
123
  }
115
124
 
125
+ /**
126
+ * 我方 insert 条目(`- insert: [{id, name, config}]` 的内层条目)。
127
+ *
128
+ * 需求给定四键:`source` / `targets` / `fallbackToSessionId` / `debug`;
129
+ * `hosts` 缺省不写(插件缺省 `[]` = 所有主机,D6)。
130
+ */
131
+ function buildInsertEntry(
132
+ id: (typeof DSH_PATCH_INSERT_ENTRY_IDS)[number],
133
+ ): Record<string, unknown> {
134
+ switch (id) {
135
+ case 'header-masq':
136
+ return {
137
+ id,
138
+ name: DSH_HEADER_MASQ_PLUGIN_NAME,
139
+ config: {
140
+ source: 'x-deepseek-harness-session-id',
141
+ targets: ['x-opencode-session'],
142
+ fallbackToSessionId: true,
143
+ debug: false,
144
+ },
145
+ };
146
+ default:
147
+ throw new DshConfigError(`unsupported dsh patch insert entry: ${String(id)}`);
148
+ }
149
+ }
150
+
151
+ /** 顶层块是否为「内层条目 id 命中」的 insert 块。 */
152
+ function isInsertBlockFor(item: unknown, id: string): boolean {
153
+ if (!isMap(item)) return false;
154
+ const insert = item.get('insert');
155
+ if (!isSeq(insert)) return false;
156
+ return insert.items.some((inner) => isMap(inner) && inner.get('id') === id);
157
+ }
158
+
116
159
  function parsePatchDocument(text: string, path: string): Document {
117
160
  if (text.trim().length === 0) return new Document([]);
118
161
  const doc = parseDocument(text);
@@ -130,7 +173,9 @@ function parsePatchDocument(text: string, path: string): Document {
130
173
  /**
131
174
  * 合并 `cordis.patch.yml`:
132
175
  *
133
- * - 顶层条目数组,按 `id` 定位我方 4 个条目并**整体替换其 config**;
176
+ * - 顶层条目数组,按 `id` 定位我方 4 个扁平条目并**整体替换其 config**;
177
+ * - insert 形态条目:遍历顶层 `insert` 为 seq 的块,内层 `id` 命中即**整体替换该 insert 块**
178
+ * (我方块恰一个内层条目);未命中则在顶层数组**末尾追加**;
134
179
  * - 其余条目与注释逐字保留(新条目追加在末尾);
135
180
  * - 解析失败抛错、不写文件(不静默丢数据)。
136
181
  */
@@ -155,9 +200,22 @@ function mergePatchDocument(doc: Document, env: DshConfigEnv): { content: string
155
200
  if (id === 'acp') doc.setIn([index, 'name'], DSH_ACP_APP_NAME);
156
201
  }
157
202
 
203
+ for (const id of DSH_PATCH_INSERT_ENTRY_IDS) {
204
+ const block = doc.createNode({ insert: [buildInsertEntry(id)] });
205
+ const index = seq.items.findIndex((item) => isInsertBlockFor(item, id));
206
+ if (index === -1) {
207
+ seq.add(block);
208
+ continue;
209
+ }
210
+ doc.setIn([index], block);
211
+ }
212
+
158
213
  let content = doc.toString();
159
214
  if (!content.endsWith('\n')) content += '\n';
160
- return { content, entryCount: DSH_PATCH_ENTRY_IDS.length };
215
+ return {
216
+ content,
217
+ entryCount: DSH_PATCH_ENTRY_IDS.length + DSH_PATCH_INSERT_ENTRY_IDS.length,
218
+ };
161
219
  }
162
220
 
163
221
  /**
@@ -297,6 +297,8 @@ interface GitWorktreeAddPayload {
297
297
  repoPath: string;
298
298
  worktreePath: string;
299
299
  branch: string;
300
+ /** 可选:Worktree 级提交人;缺省 = 不写身份(沿用容器级 bot),旧 worker 忽略该字段。 */
301
+ committer?: { name: string; email: string };
300
302
  }
301
303
 
302
304
  interface GitWorktreeRemovePayload {
@@ -1349,7 +1351,7 @@ export function connectToServer(
1349
1351
  });
1350
1352
 
1351
1353
  socket.on('git:worktree:add', async (data: GitWorktreeAddPayload) => {
1352
- const result = await worktreeHandler.add(data.repoPath, data.worktreePath, data.branch);
1354
+ const result = await worktreeHandler.add(data.repoPath, data.worktreePath, data.branch, data.committer);
1353
1355
  if (result.success) {
1354
1356
  fsHandler.registerAllowedPath(data.worktreePath);
1355
1357
  }