agent-gear 2.10.1 → 2.11.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 (60) hide show
  1. package/AGENTS.md +38 -3
  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/cloud-host/supervisor.d.ts +9 -0
  11. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  12. package/dist/cloud-host/supervisor.js +6 -0
  13. package/dist/cloud-host/supervisor.js.map +1 -1
  14. package/dist/cloud-host/supervisor.test.js +42 -0
  15. package/dist/cloud-host/supervisor.test.js.map +1 -1
  16. package/dist/github/commit-identity-manager.d.ts +75 -0
  17. package/dist/github/commit-identity-manager.d.ts.map +1 -0
  18. package/dist/github/commit-identity-manager.js +223 -0
  19. package/dist/github/commit-identity-manager.js.map +1 -0
  20. package/dist/github/commit-identity-manager.test.d.ts +2 -0
  21. package/dist/github/commit-identity-manager.test.d.ts.map +1 -0
  22. package/dist/github/commit-identity-manager.test.js +224 -0
  23. package/dist/github/commit-identity-manager.test.js.map +1 -0
  24. package/dist/github/commit-identity.d.ts +68 -0
  25. package/dist/github/commit-identity.d.ts.map +1 -0
  26. package/dist/github/commit-identity.js +242 -0
  27. package/dist/github/commit-identity.js.map +1 -0
  28. package/dist/github/commit-identity.test.d.ts +2 -0
  29. package/dist/github/commit-identity.test.d.ts.map +1 -0
  30. package/dist/github/commit-identity.test.js +210 -0
  31. package/dist/github/commit-identity.test.js.map +1 -0
  32. package/dist/github/credential-manager.d.ts +15 -3
  33. package/dist/github/credential-manager.d.ts.map +1 -1
  34. package/dist/github/credential-manager.js +34 -6
  35. package/dist/github/credential-manager.js.map +1 -1
  36. package/dist/github/credential-manager.test.js +107 -1
  37. package/dist/github/credential-manager.test.js.map +1 -1
  38. package/dist/harness/dsh-config.atomic-failure.test.js +12 -0
  39. package/dist/harness/dsh-config.atomic-failure.test.js.map +1 -1
  40. package/dist/harness/dsh-config.d.ts +9 -2
  41. package/dist/harness/dsh-config.d.ts.map +1 -1
  42. package/dist/harness/dsh-config.js +56 -3
  43. package/dist/harness/dsh-config.js.map +1 -1
  44. package/dist/harness/dsh-config.test.js +138 -3
  45. package/dist/harness/dsh-config.test.js.map +1 -1
  46. package/package.json +2 -2
  47. package/src/acp/bridge.ts +15 -1
  48. package/src/acp/sync-bridge.ts +9 -0
  49. package/src/cloud-host/supervisor.test.ts +58 -0
  50. package/src/cloud-host/supervisor.ts +20 -0
  51. package/src/github/commit-identity-manager.test.ts +272 -0
  52. package/src/github/commit-identity-manager.ts +284 -0
  53. package/src/github/commit-identity.test.ts +258 -0
  54. package/src/github/commit-identity.ts +284 -0
  55. package/src/github/credential-manager.test.ts +134 -0
  56. package/src/github/credential-manager.ts +35 -5
  57. package/src/harness/dsh-config.atomic-failure.test.ts +17 -0
  58. package/src/harness/dsh-config.test.ts +174 -3
  59. package/src/harness/dsh-config.ts +62 -4
  60. package/tests/manual/repro-question-tool.ts +118 -0
@@ -0,0 +1,272 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import {
3
+ CommitIdentityManager,
4
+ REFRESH_INTERVAL_MS,
5
+ BACKOFF_MS,
6
+ type CommitIdentityApplier,
7
+ type CommitIdentityRefreshResult,
8
+ } from './commit-identity-manager.js';
9
+
10
+ const HOST_KEY = 'zag_k_1_host_secret';
11
+ const BASE_ENV: NodeJS.ProcessEnv = {
12
+ ZAG_AGENT_API_ENDPOINT: 'http://agent-api:8002/',
13
+ ZAG_CONTROLLER_ID: 'controller-123',
14
+ ZAG_HOST_KEY: HOST_KEY,
15
+ };
16
+
17
+ const HUMAN = { name: 'Alice', email: '1001+alice@users.noreply.github.com' };
18
+ const CO_AUTHOR = {
19
+ name: 'Alice',
20
+ email: '1001+alice@users.noreply.github.com',
21
+ coAuthorName: 'zag-bot[bot]',
22
+ coAuthorEmail: '123456+zag-bot[bot]@users.noreply.github.com',
23
+ };
24
+
25
+ function jsonResponse(body: unknown, status = 200): Response {
26
+ return new Response(JSON.stringify(body), {
27
+ status,
28
+ headers: { 'content-type': 'application/json' },
29
+ });
30
+ }
31
+
32
+ function fakeFetch(handler: (...args: Parameters<typeof fetch>) => Promise<Response>) {
33
+ return vi.fn(handler) as unknown as typeof fetch & ReturnType<typeof vi.fn>;
34
+ }
35
+
36
+ function fakeApplier() {
37
+ const apply = vi.fn(async () => {});
38
+ const remove = vi.fn(async () => {});
39
+ return { apply, remove } satisfies CommitIdentityApplier;
40
+ }
41
+
42
+ interface ScheduledTimer {
43
+ fn: () => void;
44
+ delay: number;
45
+ handle: ReturnType<typeof setTimeout>;
46
+ }
47
+
48
+ function fakeScheduler() {
49
+ const timers: ScheduledTimer[] = [];
50
+ const setTimeoutFn = ((fn: () => void, delay: number) => {
51
+ const handle = setTimeout(() => {}, 0);
52
+ handle.unref();
53
+ timers.push({ fn, delay, handle });
54
+ return handle;
55
+ }) as unknown as typeof setTimeout;
56
+ return { timers, setTimeoutFn };
57
+ }
58
+
59
+ describe('CommitIdentityManager', () => {
60
+ it('T-CIM1: first refresh posts with the host key and applies the returned identity', async () => {
61
+ const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'co_author', ...CO_AUTHOR }));
62
+ const applier = fakeApplier();
63
+ const logs: string[] = [];
64
+ const manager = new CommitIdentityManager({
65
+ env: BASE_ENV,
66
+ fetch: fetchFn,
67
+ applier,
68
+ log: (message) => logs.push(message),
69
+ });
70
+
71
+ const result = await manager.refreshNow();
72
+
73
+ expect(result).toEqual({ ok: true, mode: 'co_author' });
74
+ expect(applier.apply).toHaveBeenCalledWith('co_author', CO_AUTHOR);
75
+ expect(applier.remove).not.toHaveBeenCalled();
76
+
77
+ expect(fetchFn).toHaveBeenCalledTimes(1);
78
+ const [url, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];
79
+ expect(url).toBe('http://agent-api:8002/internal/cloud-hosts/controller-123/commit-identity');
80
+ expect(init).toMatchObject({
81
+ method: 'POST',
82
+ headers: { Authorization: `Bearer ${HOST_KEY}` },
83
+ });
84
+ expect(init).not.toHaveProperty('body');
85
+ expect(init.signal).toBeInstanceOf(AbortSignal);
86
+
87
+ // 日志不含身份值(邮箱 / 姓名)与 host key
88
+ const output = logs.join('\n');
89
+ expect(output).toContain('co_author');
90
+ expect(output).not.toContain('Alice');
91
+ expect(output).not.toContain('alice@users.noreply.github.com');
92
+ expect(output).not.toContain(HOST_KEY);
93
+ });
94
+
95
+ it('T-CIM2: mode=unset removes the managed configuration instead of applying it', async () => {
96
+ const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'unset' }));
97
+ const applier = fakeApplier();
98
+ const manager = new CommitIdentityManager({
99
+ env: BASE_ENV,
100
+ fetch: fetchFn,
101
+ applier,
102
+ log: () => {},
103
+ });
104
+
105
+ const result = await manager.refreshNow();
106
+
107
+ expect(result).toEqual({ ok: true, mode: 'unset' });
108
+ expect(applier.remove).toHaveBeenCalledTimes(1);
109
+ expect(applier.apply).not.toHaveBeenCalled();
110
+ });
111
+
112
+ it('T-CIM3: refreshes immediately on start and then every 50 minutes with an unref timer', async () => {
113
+ const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'human_only', ...HUMAN }));
114
+ const applier = fakeApplier();
115
+ const scheduler = fakeScheduler();
116
+ const manager = new CommitIdentityManager({
117
+ env: BASE_ENV,
118
+ fetch: fetchFn,
119
+ applier,
120
+ log: () => {},
121
+ setTimeout: scheduler.setTimeoutFn,
122
+ });
123
+
124
+ manager.start();
125
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(1));
126
+ expect(fetchFn).toHaveBeenCalledTimes(1);
127
+ expect(applier.apply).toHaveBeenCalledTimes(1);
128
+ expect(scheduler.timers[0]!.delay).toBe(REFRESH_INTERVAL_MS);
129
+ expect(REFRESH_INTERVAL_MS).toBe(50 * 60 * 1000);
130
+
131
+ scheduler.timers[0]!.fn();
132
+ await vi.waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2));
133
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(2));
134
+
135
+ manager.stop();
136
+ expect(scheduler.timers[1]!.handle.hasRef()).toBe(false);
137
+ });
138
+
139
+ it('T-CIM4: 401/403 retries with 1/2/4 minute backoff and keeps the current configuration', async () => {
140
+ const fetchFn = fakeFetch(async () => new Response('', { status: 401 }));
141
+ const applier = fakeApplier();
142
+ const delays: number[] = [];
143
+ const manager = new CommitIdentityManager({
144
+ env: BASE_ENV,
145
+ fetch: fetchFn,
146
+ applier,
147
+ log: () => {},
148
+ sleep: async (ms) => {
149
+ delays.push(ms);
150
+ },
151
+ });
152
+
153
+ const result = await manager.refreshNow();
154
+
155
+ expect(result.ok).toBe(false);
156
+ expect(result.error).toContain('提交身份');
157
+ expect(delays).toEqual([...BACKOFF_MS]);
158
+ expect(fetchFn).toHaveBeenCalledTimes(BACKOFF_MS.length + 1);
159
+ expect(applier.apply).not.toHaveBeenCalled();
160
+ expect(applier.remove).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it('T-CIM5: concurrent refreshNow calls are merged into a single request', async () => {
164
+ let release!: (response: Response) => void;
165
+ const gate = new Promise<Response>((resolve) => {
166
+ release = resolve;
167
+ });
168
+ const fetchFn = fakeFetch(() => gate);
169
+ const applier = fakeApplier();
170
+ const manager = new CommitIdentityManager({
171
+ env: BASE_ENV,
172
+ fetch: fetchFn,
173
+ applier,
174
+ log: () => {},
175
+ });
176
+
177
+ const first = manager.refreshNow();
178
+ const second = manager.refreshNow();
179
+ release(jsonResponse({ mode: 'human_only', ...HUMAN }));
180
+
181
+ const [a, b] = await Promise.all([first, second]);
182
+ expect(a).toEqual(b);
183
+ expect(fetchFn).toHaveBeenCalledTimes(1);
184
+ expect(applier.apply).toHaveBeenCalledTimes(1);
185
+ });
186
+
187
+ it('T-CIM6: missing env disables startup with a warn that only lists variable names', async () => {
188
+ const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'unset' }));
189
+ const logs: string[] = [];
190
+ const manager = new CommitIdentityManager({
191
+ env: { ZAG_HOST_KEY: 'should-not-appear' },
192
+ fetch: fetchFn,
193
+ log: (message) => logs.push(message),
194
+ });
195
+
196
+ manager.start();
197
+
198
+ expect(fetchFn).not.toHaveBeenCalled();
199
+ const output = logs.join('\n');
200
+ expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
201
+ expect(output).toContain('ZAG_CONTROLLER_ID');
202
+ expect(output).not.toContain('should-not-appear');
203
+ await expect(manager.refreshNow()).resolves.toEqual({ ok: false, error: 'disabled' });
204
+ });
205
+
206
+ it('T-CIM7: invalid JSON, invalid mode and network failures produce readable errors without crashing', async () => {
207
+ const invalidJson = fakeFetch(
208
+ async () =>
209
+ new Response('not json', { status: 200, headers: { 'content-type': 'application/json' } }),
210
+ );
211
+ const applier = fakeApplier();
212
+ const manager = new CommitIdentityManager({
213
+ env: BASE_ENV,
214
+ fetch: invalidJson,
215
+ applier,
216
+ log: () => {},
217
+ });
218
+ const invalid = await manager.refreshNow();
219
+ expect(invalid.ok).toBe(false);
220
+ expect(invalid.error).toContain('合法 JSON');
221
+
222
+ const invalidMode = fakeFetch(async () => jsonResponse({ mode: 'everyone' }));
223
+ const modeManager = new CommitIdentityManager({
224
+ env: BASE_ENV,
225
+ fetch: invalidMode,
226
+ applier,
227
+ log: () => {},
228
+ });
229
+ const modeResult = await modeManager.refreshNow();
230
+ expect(modeResult.ok).toBe(false);
231
+ expect(modeResult.error).toContain('mode');
232
+
233
+ const network = fakeFetch(async () => {
234
+ throw new Error('ECONNREFUSED');
235
+ });
236
+ const networkManager = new CommitIdentityManager({
237
+ env: BASE_ENV,
238
+ fetch: network,
239
+ applier,
240
+ log: () => {},
241
+ });
242
+ const failed = await networkManager.refreshNow();
243
+ expect(failed.ok).toBe(false);
244
+ expect(failed.error).toContain('ECONNREFUSED');
245
+
246
+ // 失败一律保留现状:不 apply、不 remove
247
+ expect(applier.apply).not.toHaveBeenCalled();
248
+ expect(applier.remove).not.toHaveBeenCalled();
249
+ });
250
+
251
+ it('T-CIM8: logs and returned errors never contain the host key', async () => {
252
+ const logs: string[] = [];
253
+ const fetchFn = fakeFetch(async () => jsonResponse({ mode: 'co_author', ...CO_AUTHOR }));
254
+ const applier = fakeApplier();
255
+ applier.apply.mockImplementation(async () => {
256
+ throw new Error(`write failed with ${HOST_KEY}`);
257
+ });
258
+ const manager = new CommitIdentityManager({
259
+ env: BASE_ENV,
260
+ fetch: fetchFn,
261
+ applier,
262
+ log: (message) => logs.push(message),
263
+ });
264
+
265
+ const result: CommitIdentityRefreshResult = await manager.refreshNow();
266
+
267
+ expect(result.ok).toBe(false);
268
+ expect(JSON.stringify(result)).not.toContain(HOST_KEY);
269
+ expect(logs.join('\n')).not.toContain(HOST_KEY);
270
+ expect(logs.join('\n')).not.toContain(CO_AUTHOR.coAuthorEmail);
271
+ });
272
+ });
@@ -0,0 +1,284 @@
1
+ import { CommitIdentity, type CommitIdentityMode } from './commit-identity.js';
2
+ import { redactSecrets } from '../workload-executor.js';
3
+
4
+ /** 提交身份同步间隔(50 分钟)。 */
5
+ export const REFRESH_INTERVAL_MS = 50 * 60 * 1000;
6
+
7
+ /** 下发接口超时(10 秒)。 */
8
+ export const REQUEST_TIMEOUT_MS = 10_000;
9
+
10
+ /** 401/403 退避序列(1/2/4 分钟,最多 3 次重试)。 */
11
+ export const BACKOFF_MS = [60_000, 120_000, 240_000] as const;
12
+
13
+ /** 托管配置应用器(测试注入;生产为 `CommitIdentity`)。 */
14
+ export interface CommitIdentityApplier {
15
+ apply(
16
+ mode: Exclude<CommitIdentityMode, 'unset'>,
17
+ identity: {
18
+ name: string;
19
+ email: string;
20
+ coAuthorName?: string;
21
+ coAuthorEmail?: string;
22
+ },
23
+ ): Promise<void>;
24
+ remove(): Promise<void>;
25
+ }
26
+
27
+ /** 提交身份管理器依赖注入(测试锚定网络 / 时钟 / 副作用;生产使用缺省实现)。 */
28
+ export interface CommitIdentityManagerDeps {
29
+ env?: NodeJS.ProcessEnv;
30
+ fetch?: typeof fetch;
31
+ applier?: CommitIdentityApplier;
32
+ log?: (message: string) => void;
33
+ /** 定时器注入(测试用);缺省使用全局 `setTimeout`。 */
34
+ setTimeout?: typeof setTimeout;
35
+ /** 退避等待注入(测试用);缺省使用 `setTimeout`。 */
36
+ sleep?: (ms: number) => Promise<void>;
37
+ }
38
+
39
+ /** `refreshNow()` 的统一返回(不含任何身份值)。 */
40
+ export interface CommitIdentityRefreshResult {
41
+ ok: boolean;
42
+ /** 成功应用 / 移除的模式;失败或缺省时不返回。 */
43
+ mode?: CommitIdentityMode;
44
+ /** 可读错误文案;`disabled` 表示 env 缺失。 */
45
+ error?: string;
46
+ }
47
+
48
+ const VALID_MODES: readonly CommitIdentityMode[] = [
49
+ 'agent_only',
50
+ 'co_author',
51
+ 'human_only',
52
+ 'unset',
53
+ ];
54
+
55
+ type Timer = ReturnType<typeof setTimeout>;
56
+
57
+ function nonEmptyString(value: unknown): string | null {
58
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;
59
+ }
60
+
61
+ /**
62
+ * 容器内提交身份同步管理器(实现点 3,与 `GithubCredentialManager` 同构)。
63
+ *
64
+ * - `start()`:校验 env 后立即拉取一次,之后每 50 分钟拉取;定时器 `unref()`;
65
+ * - `refreshNow()`:POST 内部端点,并发调用合并为一次请求;401/403 按 1/2/4 分钟退避(≤3 次);
66
+ * - 成功响应按字段存在性消费:`mode=unset` → `remove()`,其余 → `apply()`;
67
+ * - 网络 / 解析 / 应用失败保留现状,返回可读错误,不崩溃、不回滚已应用配置;
68
+ * - 与凭据管理器相互独立(不依赖 gh 凭据 / Git 项目绑定);日志不含 host key 与身份值。
69
+ */
70
+ export class CommitIdentityManager {
71
+ private readonly env: NodeJS.ProcessEnv;
72
+ private readonly fetchFn: typeof fetch;
73
+ private readonly applier: CommitIdentityApplier;
74
+ private readonly log: (message: string) => void;
75
+ private readonly setTimeoutFn: typeof setTimeout;
76
+ private readonly sleepFn: (ms: number) => Promise<void>;
77
+
78
+ private timer: Timer | null = null;
79
+ private started = false;
80
+ private stopped = false;
81
+ private activeRefresh: Promise<CommitIdentityRefreshResult> | null = null;
82
+
83
+ constructor(deps: CommitIdentityManagerDeps = {}) {
84
+ this.env = deps.env ?? process.env;
85
+ this.fetchFn = deps.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
86
+ this.applier = deps.applier ?? new CommitIdentity();
87
+ this.log = deps.log ?? ((message: string) => console.log(message));
88
+ this.setTimeoutFn = deps.setTimeout ?? setTimeout;
89
+ this.sleepFn =
90
+ deps.sleep ??
91
+ ((ms: number) =>
92
+ new Promise<void>((resolve) => {
93
+ const timer = setTimeout(resolve, ms);
94
+ timer.unref?.();
95
+ }));
96
+ }
97
+
98
+ /** 当前是否具备拉取条件(三个 env 均非空)。 */
99
+ isEnabled(): boolean {
100
+ return this.missingEnv().length === 0;
101
+ }
102
+
103
+ /** 启动:立即拉取一次并安排下一次同步(env 缺失时只 warn,不抛错)。 */
104
+ start(): void {
105
+ if (this.started) return;
106
+ this.stopped = false;
107
+ const missing = this.missingEnv();
108
+ if (missing.length > 0) {
109
+ this.log(`[CommitIdentity] disabled: missing environment variable(s): ${missing.join(', ')}`);
110
+ return;
111
+ }
112
+ this.started = true;
113
+ void this.refreshNow()
114
+ .catch(() => undefined)
115
+ .finally(() => this.scheduleNext());
116
+ }
117
+
118
+ /** 停止周期同步(进程退出 / 云主机 shutdown)。 */
119
+ stop(): void {
120
+ this.stopped = true;
121
+ this.started = false;
122
+ if (this.timer) {
123
+ clearTimeout(this.timer);
124
+ this.timer = null;
125
+ }
126
+ }
127
+
128
+ /** 立即拉取并应用 / 移除托管配置;并发调用共享同一个 in-flight Promise。 */
129
+ refreshNow(): Promise<CommitIdentityRefreshResult> {
130
+ if (this.activeRefresh) return this.activeRefresh;
131
+ const refresh = this.doRefresh().finally(() => {
132
+ if (this.activeRefresh === refresh) this.activeRefresh = null;
133
+ });
134
+ this.activeRefresh = refresh;
135
+ return refresh;
136
+ }
137
+
138
+ private async doRefresh(): Promise<CommitIdentityRefreshResult> {
139
+ if (!this.isEnabled()) {
140
+ return { ok: false, error: 'disabled' };
141
+ }
142
+
143
+ const endpoint = this.env.ZAG_AGENT_API_ENDPOINT!.trim().replace(/\/+$/, '');
144
+ const controllerId = this.env.ZAG_CONTROLLER_ID!.trim();
145
+ const hostKey = this.env.ZAG_HOST_KEY!.trim();
146
+ const url = `${endpoint}/internal/cloud-hosts/${encodeURIComponent(controllerId)}/commit-identity`;
147
+
148
+ for (let attempt = 0; ; attempt += 1) {
149
+ const result = await this.request(url, hostKey);
150
+ if (result.kind === 'retryable' && attempt < BACKOFF_MS.length) {
151
+ const delay = BACKOFF_MS[attempt]!;
152
+ this.log(
153
+ `[CommitIdentity] 提交身份下发未授权(HTTP ${result.status}),` +
154
+ `${Math.round(delay / 60_000)} 分钟后重试(${attempt + 1}/${BACKOFF_MS.length})`,
155
+ );
156
+ await this.sleepFn(delay);
157
+ continue;
158
+ }
159
+ if (result.kind === 'retryable') {
160
+ return { ok: false, error: `提交身份下发未授权(HTTP ${result.status})` };
161
+ }
162
+ return result.value;
163
+ }
164
+ }
165
+
166
+ private async request(
167
+ url: string,
168
+ hostKey: string,
169
+ ): Promise<
170
+ | { kind: 'retryable'; status: number }
171
+ | { kind: 'result'; value: CommitIdentityRefreshResult }
172
+ > {
173
+ const controller = new AbortController();
174
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
175
+ timer.unref?.();
176
+ try {
177
+ const response = await this.fetchFn(url, {
178
+ method: 'POST',
179
+ headers: { Authorization: `Bearer ${hostKey}` },
180
+ signal: controller.signal,
181
+ });
182
+
183
+ if (response.status === 401 || response.status === 403) {
184
+ return { kind: 'retryable', status: response.status };
185
+ }
186
+ if (!response.ok) {
187
+ return {
188
+ kind: 'result',
189
+ value: { ok: false, error: `提交身份下发失败(HTTP ${response.status})` },
190
+ };
191
+ }
192
+
193
+ let payload: unknown;
194
+ try {
195
+ payload = await response.json();
196
+ } catch {
197
+ return { kind: 'result', value: { ok: false, error: '提交身份响应不是合法 JSON' } };
198
+ }
199
+
200
+ return { kind: 'result', value: await this.consume(payload, hostKey) };
201
+ } catch (error) {
202
+ const reason = error instanceof Error ? error.message : String(error);
203
+ const message = /abort/i.test(reason)
204
+ ? '提交身份下发超时(10s)'
205
+ : `提交身份下发失败:${redactSecrets(reason, [hostKey])}`;
206
+ return { kind: 'result', value: { ok: false, error: message } };
207
+ } finally {
208
+ clearTimeout(timer);
209
+ }
210
+ }
211
+
212
+ /** 按字段存在性消费响应:unset → remove;其余 → apply。 */
213
+ private async consume(payload: unknown, hostKey: string): Promise<CommitIdentityRefreshResult> {
214
+ const body = (payload ?? {}) as Record<string, unknown>;
215
+ const mode = body.mode;
216
+ if (typeof mode !== 'string' || !VALID_MODES.includes(mode as CommitIdentityMode)) {
217
+ return { ok: false, error: `提交身份响应 mode 非法:${String(mode)}` };
218
+ }
219
+
220
+ if (mode === 'unset') {
221
+ try {
222
+ await this.applier.remove();
223
+ } catch (error) {
224
+ return { ok: false, error: this.applyError('移除', error, hostKey) };
225
+ }
226
+ this.log('[CommitIdentity] 托管配置已移除(mode=unset)');
227
+ return { ok: true, mode: 'unset' };
228
+ }
229
+
230
+ const name = nonEmptyString(body.name);
231
+ const email = nonEmptyString(body.email);
232
+ if (!name || !email) {
233
+ return { ok: false, error: '提交身份响应缺少 name/email' };
234
+ }
235
+
236
+ if (mode === 'co_author') {
237
+ const coAuthorName = nonEmptyString(body.coAuthorName);
238
+ const coAuthorEmail = nonEmptyString(body.coAuthorEmail);
239
+ if (!coAuthorName || !coAuthorEmail) {
240
+ return { ok: false, error: '提交身份响应缺少 coAuthorName/coAuthorEmail' };
241
+ }
242
+ try {
243
+ await this.applier.apply(mode, { name, email, coAuthorName, coAuthorEmail });
244
+ } catch (error) {
245
+ return { ok: false, error: this.applyError('应用', error, hostKey) };
246
+ }
247
+ } else {
248
+ const narrowed = mode as 'agent_only' | 'human_only';
249
+ try {
250
+ await this.applier.apply(narrowed, { name, email });
251
+ } catch (error) {
252
+ return { ok: false, error: this.applyError('应用', error, hostKey) };
253
+ }
254
+ }
255
+
256
+ this.log(`[CommitIdentity] 提交身份已更新(mode=${mode})`);
257
+ return { ok: true, mode: mode as CommitIdentityMode };
258
+ }
259
+
260
+ private applyError(action: string, error: unknown, hostKey: string): string {
261
+ const reason = error instanceof Error ? error.message : String(error);
262
+ return `提交身份${action}失败:${redactSecrets(reason, [hostKey])}`;
263
+ }
264
+
265
+ /** 下一次同步:固定 50 分钟;定时器 unref,不阻止进程退出。 */
266
+ private scheduleNext(): void {
267
+ if (this.stopped || !this.started || !this.isEnabled()) return;
268
+ this.timer = this.setTimeoutFn(() => {
269
+ this.timer = null;
270
+ void this.refreshNow()
271
+ .catch(() => undefined)
272
+ .finally(() => this.scheduleNext());
273
+ }, REFRESH_INTERVAL_MS);
274
+ this.timer.unref?.();
275
+ }
276
+
277
+ private missingEnv(): string[] {
278
+ const keys = ['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID', 'ZAG_HOST_KEY'] as const;
279
+ return keys.filter((key) => {
280
+ const value = this.env[key];
281
+ return typeof value !== 'string' || value.trim().length === 0;
282
+ });
283
+ }
284
+ }