agent-gear 2.5.0 → 2.6.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 (93) hide show
  1. package/AGENTS.md +48 -4
  2. package/dist/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  3. package/dist/acp/bridge.d.ts +23 -1
  4. package/dist/acp/bridge.d.ts.map +1 -1
  5. package/dist/acp/bridge.js +152 -17
  6. package/dist/acp/bridge.js.map +1 -1
  7. package/dist/acp/bridge.test.js +366 -1
  8. package/dist/acp/bridge.test.js.map +1 -1
  9. package/dist/acp/capabilities.d.ts +81 -0
  10. package/dist/acp/capabilities.d.ts.map +1 -0
  11. package/dist/acp/capabilities.js +211 -0
  12. package/dist/acp/capabilities.js.map +1 -0
  13. package/dist/acp/capabilities.test.d.ts +2 -0
  14. package/dist/acp/capabilities.test.d.ts.map +1 -0
  15. package/dist/acp/capabilities.test.js +156 -0
  16. package/dist/acp/capabilities.test.js.map +1 -0
  17. package/dist/acp/elicitation.integration.test.d.ts +2 -0
  18. package/dist/acp/elicitation.integration.test.d.ts.map +1 -0
  19. package/dist/acp/elicitation.integration.test.js +98 -0
  20. package/dist/acp/elicitation.integration.test.js.map +1 -0
  21. package/dist/acp/prober.d.ts +4 -0
  22. package/dist/acp/prober.d.ts.map +1 -1
  23. package/dist/acp/prober.js +1 -0
  24. package/dist/acp/prober.js.map +1 -1
  25. package/dist/acp/spawner.d.ts.map +1 -1
  26. package/dist/acp/spawner.js +3 -0
  27. package/dist/acp/spawner.js.map +1 -1
  28. package/dist/acp/sync-bridge.d.ts.map +1 -1
  29. package/dist/acp/sync-bridge.js +5 -1
  30. package/dist/acp/sync-bridge.js.map +1 -1
  31. package/dist/cloud-host/supervisor.d.ts +13 -0
  32. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  33. package/dist/cloud-host/supervisor.js +21 -0
  34. package/dist/cloud-host/supervisor.js.map +1 -1
  35. package/dist/cloud-host/supervisor.test.js +71 -0
  36. package/dist/cloud-host/supervisor.test.js.map +1 -1
  37. package/dist/github/credential-manager.d.ts +70 -0
  38. package/dist/github/credential-manager.d.ts.map +1 -0
  39. package/dist/github/credential-manager.js +205 -0
  40. package/dist/github/credential-manager.js.map +1 -0
  41. package/dist/github/credential-manager.test.d.ts +2 -0
  42. package/dist/github/credential-manager.test.d.ts.map +1 -0
  43. package/dist/github/credential-manager.test.js +215 -0
  44. package/dist/github/credential-manager.test.js.map +1 -0
  45. package/dist/github/gh-config.d.ts +17 -0
  46. package/dist/github/gh-config.d.ts.map +1 -0
  47. package/dist/github/gh-config.js +68 -0
  48. package/dist/github/gh-config.js.map +1 -0
  49. package/dist/github/gh-config.test.d.ts +2 -0
  50. package/dist/github/gh-config.test.d.ts.map +1 -0
  51. package/dist/github/gh-config.test.js +90 -0
  52. package/dist/github/gh-config.test.js.map +1 -0
  53. package/dist/socketio-client.d.ts +12 -0
  54. package/dist/socketio-client.d.ts.map +1 -1
  55. package/dist/socketio-client.github.test.d.ts +2 -0
  56. package/dist/socketio-client.github.test.d.ts.map +1 -0
  57. package/dist/socketio-client.github.test.js +66 -0
  58. package/dist/socketio-client.github.test.js.map +1 -0
  59. package/dist/socketio-client.js +115 -65
  60. package/dist/socketio-client.js.map +1 -1
  61. package/dist/socketio-client.test.js +251 -1
  62. package/dist/socketio-client.test.js.map +1 -1
  63. package/dist/workload-executor.d.ts +14 -1
  64. package/dist/workload-executor.d.ts.map +1 -1
  65. package/dist/workload-executor.js +33 -3
  66. package/dist/workload-executor.js.map +1 -1
  67. package/dist/workload-executor.test.js +106 -2
  68. package/dist/workload-executor.test.js.map +1 -1
  69. package/package.json +1 -1
  70. package/src/acp/__fixtures__/fake-elicitation-agent.mjs +113 -0
  71. package/src/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  72. package/src/acp/bridge.test.ts +480 -1
  73. package/src/acp/bridge.ts +163 -18
  74. package/src/acp/capabilities.test.ts +200 -0
  75. package/src/acp/capabilities.ts +274 -0
  76. package/src/acp/elicitation.integration.test.ts +126 -0
  77. package/src/acp/prober.ts +4 -0
  78. package/src/acp/spawner.ts +3 -0
  79. package/src/acp/sync-bridge.ts +5 -1
  80. package/src/cloud-host/supervisor.test.ts +96 -1
  81. package/src/cloud-host/supervisor.ts +37 -0
  82. package/src/github/credential-manager.test.ts +268 -0
  83. package/src/github/credential-manager.ts +251 -0
  84. package/src/github/gh-config.test.ts +103 -0
  85. package/src/github/gh-config.ts +76 -0
  86. package/src/socketio-client.github.test.ts +76 -0
  87. package/src/socketio-client.test.ts +306 -1
  88. package/src/socketio-client.ts +113 -53
  89. package/src/workload-executor.test.ts +144 -2
  90. package/src/workload-executor.ts +48 -2
  91. package/tests/acp-sync-bridge.test.ts +5 -1
  92. package/tests/socketio-client.test.ts +2 -2
  93. package/vitest.config.ts +5 -1
@@ -0,0 +1,268 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import {
3
+ GithubCredentialManager,
4
+ REFRESH_INTERVAL_MS,
5
+ BACKOFF_MS,
6
+ } from './credential-manager.js';
7
+
8
+ const TOKEN = 'ghs_credential_manager_secret';
9
+ const BASE_ENV: NodeJS.ProcessEnv = {
10
+ ZAG_AGENT_API_ENDPOINT: 'http://agent-api:8002/',
11
+ ZAG_CONTROLLER_ID: 'controller-123',
12
+ ZAG_HOST_KEY: 'zag_k_1_host_secret',
13
+ };
14
+
15
+ function jsonResponse(body: unknown, status = 200): Response {
16
+ return new Response(JSON.stringify(body), {
17
+ status,
18
+ headers: { 'content-type': 'application/json' },
19
+ });
20
+ }
21
+
22
+ function fakeFetch(handler: (...args: Parameters<typeof fetch>) => Promise<Response>) {
23
+ return vi.fn(handler) as unknown as typeof fetch & ReturnType<typeof vi.fn>;
24
+ }
25
+
26
+ interface ScheduledTimer {
27
+ fn: () => void;
28
+ delay: number;
29
+ handle: ReturnType<typeof setTimeout>;
30
+ }
31
+
32
+ function fakeScheduler() {
33
+ const timers: ScheduledTimer[] = [];
34
+ const setTimeoutFn = ((fn: () => void, delay: number) => {
35
+ const handle = setTimeout(() => {}, 0);
36
+ handle.unref();
37
+ timers.push({ fn, delay, handle });
38
+ return handle;
39
+ }) as unknown as typeof setTimeout;
40
+ return { timers, setTimeoutFn };
41
+ }
42
+
43
+ const EXPIRES_AT = '2026-10-22T12:00:00.000Z';
44
+
45
+ describe('GithubCredentialManager', () => {
46
+ it('T-CM1: first refresh posts with the host key and writes gh credentials before returning', async () => {
47
+ const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: EXPIRES_AT }));
48
+ const writeGhAuth = vi.fn(async () => {});
49
+ const callOrder: string[] = [];
50
+ fetchFn.mockImplementation(async () => {
51
+ callOrder.push('fetch');
52
+ return jsonResponse({ token: TOKEN, expiresAt: EXPIRES_AT });
53
+ });
54
+ writeGhAuth.mockImplementation(async () => {
55
+ callOrder.push('write');
56
+ });
57
+
58
+ const manager = new GithubCredentialManager({
59
+ env: BASE_ENV,
60
+ fetch: fetchFn,
61
+ writeGhAuth,
62
+ log: () => {},
63
+ });
64
+
65
+ const result = await manager.refreshNow();
66
+
67
+ expect(result.ok).toBe(true);
68
+ expect(result.expiresAt).toEqual(new Date(EXPIRES_AT));
69
+ expect(writeGhAuth).toHaveBeenCalledWith(TOKEN);
70
+ expect(callOrder).toEqual(['fetch', 'write']);
71
+
72
+ expect(fetchFn).toHaveBeenCalledTimes(1);
73
+ const [url, init] = fetchFn.mock.calls[0] as unknown as [string, RequestInit];
74
+ expect(url).toBe(
75
+ 'http://agent-api:8002/internal/cloud-hosts/controller-123/github-credential',
76
+ );
77
+ expect(init).toMatchObject({
78
+ method: 'POST',
79
+ headers: { Authorization: 'Bearer zag_k_1_host_secret' },
80
+ });
81
+ expect(init).not.toHaveProperty('body');
82
+ expect(init.signal).toBeInstanceOf(AbortSignal);
83
+ });
84
+
85
+ it('T-CM2: 404 means no binding: no write, no error log, returns no-binding', async () => {
86
+ const fetchFn = fakeFetch(async () => new Response('', { status: 404 }));
87
+ const writeGhAuth = vi.fn(async () => {});
88
+ const logs: string[] = [];
89
+
90
+ const manager = new GithubCredentialManager({
91
+ env: BASE_ENV,
92
+ fetch: fetchFn,
93
+ writeGhAuth,
94
+ log: (message) => logs.push(message),
95
+ });
96
+
97
+ const result = await manager.refreshNow();
98
+
99
+ expect(result).toEqual({ ok: false, error: 'no-binding' });
100
+ expect(writeGhAuth).not.toHaveBeenCalled();
101
+ expect(fetchFn).toHaveBeenCalledTimes(1);
102
+ expect(logs.join('\n')).not.toMatch(/error|失败|warn/i);
103
+ });
104
+
105
+ it('T-CM3: 401 retries with 1/2/4 minute backoff and eventually returns a readable error', async () => {
106
+ const fetchFn = fakeFetch(async () => new Response('', { status: 401 }));
107
+ const delays: number[] = [];
108
+ const logs: string[] = [];
109
+ const writeGhAuth = vi.fn(async () => {});
110
+
111
+ const manager = new GithubCredentialManager({
112
+ env: BASE_ENV,
113
+ fetch: fetchFn,
114
+ writeGhAuth,
115
+ log: (message) => logs.push(message),
116
+ sleep: async (ms) => {
117
+ delays.push(ms);
118
+ },
119
+ });
120
+
121
+ const result = await manager.refreshNow();
122
+
123
+ expect(result.ok).toBe(false);
124
+ expect(result.error).toContain('凭据无效');
125
+ expect(delays).toEqual([...BACKOFF_MS]);
126
+ expect(fetchFn).toHaveBeenCalledTimes(BACKOFF_MS.length + 1);
127
+ expect(writeGhAuth).not.toHaveBeenCalled();
128
+ expect(logs.join('\n')).not.toContain(TOKEN);
129
+ });
130
+
131
+ it('T-CM4: schedules every 50 minutes, or earlier when the token expires within the skew', async () => {
132
+ const now = Date.parse('2026-10-22T10:00:00.000Z');
133
+ const fetchFn = fakeFetch(async () =>
134
+ jsonResponse({ token: TOKEN, expiresAt: new Date(now + 2 * 60 * 60 * 1000).toISOString() }),
135
+ );
136
+ const scheduler = fakeScheduler();
137
+
138
+ const manager = new GithubCredentialManager({
139
+ env: BASE_ENV,
140
+ fetch: fetchFn,
141
+ writeGhAuth: async () => {},
142
+ now: () => now,
143
+ log: () => {},
144
+ setTimeout: scheduler.setTimeoutFn,
145
+ });
146
+
147
+ manager.start();
148
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(1));
149
+ expect(scheduler.timers[0].delay).toBe(REFRESH_INTERVAL_MS);
150
+
151
+ // 触发一次定时续期:再申请一次并重新排期
152
+ scheduler.timers[0].fn();
153
+ await vi.waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(2));
154
+ await vi.waitFor(() => expect(scheduler.timers).toHaveLength(2));
155
+
156
+ // token 剩余 40 分钟 → 到期前 10 分钟(30 分钟后)优先于 50 分钟
157
+ const earlyScheduler = fakeScheduler();
158
+ const earlyFetch = fakeFetch(async () =>
159
+ jsonResponse({ token: TOKEN, expiresAt: new Date(now + 40 * 60 * 1000).toISOString() }),
160
+ );
161
+ const earlyManager = new GithubCredentialManager({
162
+ env: BASE_ENV,
163
+ fetch: earlyFetch,
164
+ writeGhAuth: async () => {},
165
+ now: () => now,
166
+ log: () => {},
167
+ setTimeout: earlyScheduler.setTimeoutFn,
168
+ });
169
+ earlyManager.start();
170
+ await vi.waitFor(() => expect(earlyScheduler.timers).toHaveLength(1));
171
+ expect(earlyScheduler.timers[0].delay).toBe(30 * 60 * 1000);
172
+
173
+ manager.stop();
174
+ earlyManager.stop();
175
+ });
176
+
177
+ it('T-CM5: concurrent refreshNow calls are serialized into a single request', async () => {
178
+ let release!: (response: Response) => void;
179
+ const gate = new Promise<Response>((resolve) => {
180
+ release = resolve;
181
+ });
182
+ const fetchFn = fakeFetch(() => gate);
183
+ const writeGhAuth = vi.fn(async () => {});
184
+
185
+ const manager = new GithubCredentialManager({
186
+ env: BASE_ENV,
187
+ fetch: fetchFn,
188
+ writeGhAuth,
189
+ log: () => {},
190
+ });
191
+
192
+ const first = manager.refreshNow();
193
+ const second = manager.refreshNow();
194
+ release(jsonResponse({ token: TOKEN, expiresAt: EXPIRES_AT }));
195
+
196
+ const [a, b] = await Promise.all([first, second]);
197
+ expect(a).toEqual(b);
198
+ expect(fetchFn).toHaveBeenCalledTimes(1);
199
+ expect(writeGhAuth).toHaveBeenCalledTimes(1);
200
+ });
201
+
202
+ it('T-CM6: missing env disables startup with a warn that only lists variable names', async () => {
203
+ const fetchFn = fakeFetch(async () => jsonResponse({}));
204
+ const logs: string[] = [];
205
+ const manager = new GithubCredentialManager({
206
+ env: { ZAG_HOST_KEY: 'should-not-appear' },
207
+ fetch: fetchFn,
208
+ log: (message) => logs.push(message),
209
+ });
210
+
211
+ manager.start();
212
+
213
+ expect(fetchFn).not.toHaveBeenCalled();
214
+ const output = logs.join('\n');
215
+ expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
216
+ expect(output).toContain('ZAG_CONTROLLER_ID');
217
+ expect(output).not.toContain('should-not-appear');
218
+ await expect(manager.refreshNow()).resolves.toEqual({ ok: false, error: 'disabled' });
219
+ });
220
+
221
+ it('T-CM7: invalid JSON and network failures produce readable errors without throwing', async () => {
222
+ const invalidJson = fakeFetch(
223
+ async () => new Response('not json', { status: 200, headers: { 'content-type': 'application/json' } }),
224
+ );
225
+ const manager = new GithubCredentialManager({
226
+ env: BASE_ENV,
227
+ fetch: invalidJson,
228
+ writeGhAuth: async () => {},
229
+ log: () => {},
230
+ });
231
+ const invalid = await manager.refreshNow();
232
+ expect(invalid.ok).toBe(false);
233
+ expect(invalid.error).toContain('合法 JSON');
234
+
235
+ const network = fakeFetch(async () => {
236
+ throw new Error('ECONNREFUSED');
237
+ });
238
+ const networkManager = new GithubCredentialManager({
239
+ env: BASE_ENV,
240
+ fetch: network,
241
+ writeGhAuth: async () => {},
242
+ log: () => {},
243
+ });
244
+ const failed = await networkManager.refreshNow();
245
+ expect(failed.ok).toBe(false);
246
+ expect(failed.error).toContain('ECONNREFUSED');
247
+ });
248
+
249
+ it('T-CM8: logs and returned errors never contain the token', async () => {
250
+ const logs: string[] = [];
251
+ const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: EXPIRES_AT }));
252
+ const manager = new GithubCredentialManager({
253
+ env: BASE_ENV,
254
+ fetch: fetchFn,
255
+ writeGhAuth: async () => {
256
+ throw new Error(`unable to write ${TOKEN}`);
257
+ },
258
+ log: (message) => logs.push(message),
259
+ });
260
+
261
+ const result = await manager.refreshNow();
262
+
263
+ expect(result.ok).toBe(false);
264
+ expect(logs.join('\n')).not.toContain(TOKEN);
265
+ // writeGhAuth 的实现负责脱敏;管理器不额外拼接 token
266
+ expect(JSON.stringify(result)).not.toContain(TOKEN);
267
+ });
268
+ });
@@ -0,0 +1,251 @@
1
+ import { writeGhAuth } from './gh-config.js';
2
+ import { redactSecrets } from '../workload-executor.js';
3
+
4
+ /** 定时续期间隔(50 分钟,覆盖 Github App installation token 约 1 小时有效期)。 */
5
+ export const REFRESH_INTERVAL_MS = 50 * 60 * 1000;
6
+
7
+ /** token 到期前提前续期的余量(10 分钟)。 */
8
+ export const EXPIRY_SKEW_MS = 10 * 60 * 1000;
9
+
10
+ /** 申请接口超时(10 秒)。 */
11
+ export const REQUEST_TIMEOUT_MS = 10_000;
12
+
13
+ /** 401/403 退避序列(1/2/4 分钟,最多 3 次重试)。 */
14
+ export const BACKOFF_MS = [60_000, 120_000, 240_000] as const;
15
+
16
+ /** 凭据管理器依赖注入(测试锚定网络/时钟/副作用;生产使用缺省实现)。 */
17
+ export interface GithubCredentialManagerDeps {
18
+ env?: NodeJS.ProcessEnv;
19
+ fetch?: typeof fetch;
20
+ writeGhAuth?: (token: string) => Promise<void>;
21
+ now?: () => number;
22
+ log?: (message: string) => void;
23
+ /** 定时器注入(测试用);缺省使用全局 `setTimeout`。 */
24
+ setTimeout?: typeof setTimeout;
25
+ /** 退避等待注入(测试用);缺省使用 `setTimeout`。 */
26
+ sleep?: (ms: number) => Promise<void>;
27
+ }
28
+
29
+ /** `refreshNow()` 的统一返回(不包含 token)。 */
30
+ export interface GithubCredentialRefreshResult {
31
+ ok: boolean;
32
+ expiresAt?: Date;
33
+ /** 可读错误码/文案;`no-binding` 表示尚未设置 Git 项目(正常跳过)。 */
34
+ error?: string;
35
+ }
36
+
37
+ type Timer = ReturnType<typeof setTimeout>;
38
+
39
+ /**
40
+ * 云主机内 Github 凭据管理器(容器侧唯一凭据写入口)。
41
+ *
42
+ * - `start()`:校验 env 后立即申请一次,并按「50 分钟」或「token 到期前 10 分钟」(取较早)
43
+ * 自续期;定时器 `unref()`,不阻止进程退出;
44
+ * - `refreshNow()`:向 agent-api 申请仓库级 token 并写入 gh 配置;并发调用合并为一次请求;
45
+ * 401/403 在本次调用内按 1/2/4 分钟退避(最多 3 次);
46
+ * - 404(未绑定 Git 项目)返回 `no-binding`,不告警;
47
+ * - token 只交给 `writeGhAuth`(stdin),从不进入日志/错误。
48
+ */
49
+ export class GithubCredentialManager {
50
+ private readonly env: NodeJS.ProcessEnv;
51
+ private readonly fetchFn: typeof fetch;
52
+ private readonly writeAuth: (token: string) => Promise<void>;
53
+ private readonly now: () => number;
54
+ private readonly log: (message: string) => void;
55
+ private readonly setTimeoutFn: typeof setTimeout;
56
+ private readonly sleepFn: (ms: number) => Promise<void>;
57
+
58
+ private timer: Timer | null = null;
59
+ private started = false;
60
+ private stopped = false;
61
+ private expiresAt: Date | null = null;
62
+ private activeRefresh: Promise<GithubCredentialRefreshResult> | null = null;
63
+
64
+ constructor(deps: GithubCredentialManagerDeps = {}) {
65
+ this.env = deps.env ?? process.env;
66
+ this.fetchFn = deps.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
67
+ this.writeAuth = deps.writeGhAuth ?? ((token: string) => writeGhAuth(token));
68
+ this.now = deps.now ?? (() => Date.now());
69
+ this.log = deps.log ?? ((message: string) => console.log(message));
70
+ this.setTimeoutFn = deps.setTimeout ?? setTimeout;
71
+ this.sleepFn =
72
+ deps.sleep ??
73
+ ((ms: number) =>
74
+ new Promise<void>((resolve) => {
75
+ const timer = setTimeout(resolve, ms);
76
+ timer.unref?.();
77
+ }));
78
+ }
79
+
80
+ /** 当前是否具备申请条件(三个 env 均非空)。 */
81
+ isEnabled(): boolean {
82
+ return this.missingEnv().length === 0;
83
+ }
84
+
85
+ /** 启动:立即申请一次,并安排下一次续期(env 缺失时只 warn,不抛错)。 */
86
+ start(): void {
87
+ if (this.started) return;
88
+ this.stopped = false;
89
+ const missing = this.missingEnv();
90
+ if (missing.length > 0) {
91
+ this.log(`[GithubCredential] disabled: missing environment variable(s): ${missing.join(', ')}`);
92
+ return;
93
+ }
94
+ this.started = true;
95
+ void this.refreshNow()
96
+ .catch(() => undefined)
97
+ .finally(() => this.scheduleNext());
98
+ }
99
+
100
+ /** 停止定时续期(进程退出/云主机 shutdown)。 */
101
+ stop(): void {
102
+ this.stopped = true;
103
+ this.started = false;
104
+ if (this.timer) {
105
+ clearTimeout(this.timer);
106
+ this.timer = null;
107
+ }
108
+ }
109
+
110
+ /**
111
+ * 立即申请并写入 gh 配置。
112
+ *
113
+ * 并发调用共享同一个 in-flight Promise(只发一次请求),从而串行化「申请 → 写入」。
114
+ */
115
+ refreshNow(): Promise<GithubCredentialRefreshResult> {
116
+ if (this.activeRefresh) return this.activeRefresh;
117
+ const refresh = this.doRefresh().finally(() => {
118
+ if (this.activeRefresh === refresh) this.activeRefresh = null;
119
+ });
120
+ this.activeRefresh = refresh;
121
+ return refresh;
122
+ }
123
+
124
+ private async doRefresh(): Promise<GithubCredentialRefreshResult> {
125
+ if (!this.isEnabled()) {
126
+ return { ok: false, error: 'disabled' };
127
+ }
128
+
129
+ const endpoint = this.env.ZAG_AGENT_API_ENDPOINT!.trim().replace(/\/+$/, '');
130
+ const controllerId = this.env.ZAG_CONTROLLER_ID!.trim();
131
+ const hostKey = this.env.ZAG_HOST_KEY!.trim();
132
+ const url = `${endpoint}/internal/cloud-hosts/${encodeURIComponent(controllerId)}/github-credential`;
133
+
134
+ for (let attempt = 0; ; attempt += 1) {
135
+ const result = await this.request(url, hostKey);
136
+ if (result.kind === 'retryable' && attempt < BACKOFF_MS.length) {
137
+ const delay = BACKOFF_MS[attempt]!;
138
+ this.log(
139
+ `[GithubCredential] 凭据无效(HTTP ${result.status}),${Math.round(delay / 60_000)} 分钟后重试` +
140
+ `(${attempt + 1}/${BACKOFF_MS.length})`,
141
+ );
142
+ await this.sleepFn(delay);
143
+ continue;
144
+ }
145
+ if (result.kind === 'retryable') {
146
+ return { ok: false, error: `Github 凭据无效(HTTP ${result.status})` };
147
+ }
148
+ return result.value;
149
+ }
150
+ }
151
+
152
+ private async request(
153
+ url: string,
154
+ hostKey: string,
155
+ ): Promise<
156
+ | { kind: 'retryable'; status: number }
157
+ | { kind: 'result'; value: GithubCredentialRefreshResult }
158
+ > {
159
+ const controller = new AbortController();
160
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
161
+ timer.unref?.();
162
+ try {
163
+ const response = await this.fetchFn(url, {
164
+ method: 'POST',
165
+ headers: { Authorization: `Bearer ${hostKey}` },
166
+ signal: controller.signal,
167
+ });
168
+
169
+ if (response.status === 404) {
170
+ // 未设置 Git 项目:正常跳过,不告警、不重试。
171
+ return { kind: 'result', value: { ok: false, error: 'no-binding' } };
172
+ }
173
+ if (response.status === 401 || response.status === 403) {
174
+ return { kind: 'retryable', status: response.status };
175
+ }
176
+ if (!response.ok) {
177
+ return {
178
+ kind: 'result',
179
+ value: { ok: false, error: `Github 凭据申请失败(HTTP ${response.status})` },
180
+ };
181
+ }
182
+
183
+ let payload: unknown;
184
+ try {
185
+ payload = await response.json();
186
+ } catch {
187
+ return { kind: 'result', value: { ok: false, error: 'Github 凭据响应不是合法 JSON' } };
188
+ }
189
+ const token = (payload as { token?: unknown } | null)?.token;
190
+ if (typeof token !== 'string' || token.length === 0) {
191
+ return { kind: 'result', value: { ok: false, error: 'Github 凭据响应缺少 token' } };
192
+ }
193
+ const rawExpiresAt = (payload as { expiresAt?: unknown } | null)?.expiresAt;
194
+ const expiresAt =
195
+ typeof rawExpiresAt === 'string' && !Number.isNaN(Date.parse(rawExpiresAt))
196
+ ? new Date(rawExpiresAt)
197
+ : undefined;
198
+
199
+ try {
200
+ await this.writeAuth(token);
201
+ } catch (error) {
202
+ const reason = error instanceof Error ? error.message : String(error);
203
+ return {
204
+ kind: 'result',
205
+ value: { ok: false, error: `写入 gh 配置失败:${redactSecrets(reason, [token])}` },
206
+ };
207
+ }
208
+
209
+ this.expiresAt = expiresAt ?? null;
210
+ this.log(
211
+ expiresAt
212
+ ? `[GithubCredential] gh 凭据已更新,有效期至 ${expiresAt.toISOString()}`
213
+ : '[GithubCredential] gh 凭据已更新',
214
+ );
215
+ return { kind: 'result', value: { ok: true, expiresAt } };
216
+ } catch (error) {
217
+ const reason = error instanceof Error ? error.message : String(error);
218
+ const message = /abort/i.test(reason)
219
+ ? 'Github 凭据申请超时(10s)'
220
+ : `Github 凭据申请失败:${reason}`;
221
+ return { kind: 'result', value: { ok: false, error: message } };
222
+ } finally {
223
+ clearTimeout(timer);
224
+ }
225
+ }
226
+
227
+ /** 下一次续期:50 分钟与「到期前 10 分钟」取较早;定时器 unref,不阻止进程退出。 */
228
+ private scheduleNext(): void {
229
+ if (this.stopped || !this.started || !this.isEnabled()) return;
230
+ let delay = REFRESH_INTERVAL_MS;
231
+ if (this.expiresAt) {
232
+ const beforeExpiry = this.expiresAt.getTime() - EXPIRY_SKEW_MS - this.now();
233
+ if (beforeExpiry > 0 && beforeExpiry < delay) delay = beforeExpiry;
234
+ }
235
+ this.timer = this.setTimeoutFn(() => {
236
+ this.timer = null;
237
+ void this.refreshNow()
238
+ .catch(() => undefined)
239
+ .finally(() => this.scheduleNext());
240
+ }, delay);
241
+ this.timer.unref?.();
242
+ }
243
+
244
+ private missingEnv(): string[] {
245
+ const keys = ['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID', 'ZAG_HOST_KEY'] as const;
246
+ return keys.filter((key) => {
247
+ const value = this.env[key];
248
+ return typeof value !== 'string' || value.trim().length === 0;
249
+ });
250
+ }
251
+ }
@@ -0,0 +1,103 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import { EventEmitter } from 'node:events';
3
+ import type { ChildProcess } from 'node:child_process';
4
+ import { writeGhAuth, type GhSpawn } from './gh-config.js';
5
+
6
+ const TOKEN = 'ghs_super_secret_token_value';
7
+
8
+ interface FakeChildOptions {
9
+ exitCode?: number | null;
10
+ stdout?: string;
11
+ stderr?: string;
12
+ emitError?: string;
13
+ }
14
+
15
+ /** 最小 ChildProcess 替身:stdin.end 后异步触发 close。 */
16
+ class FakeChild extends EventEmitter {
17
+ readonly stdout = new EventEmitter();
18
+ readonly stderr = new EventEmitter();
19
+ readonly stdin: { chunks: string[]; end: (chunk?: string) => void };
20
+
21
+ constructor(private readonly options: FakeChildOptions = {}) {
22
+ super();
23
+ this.stdin = {
24
+ chunks: [],
25
+ end: (chunk?: string) => {
26
+ if (chunk !== undefined) this.stdin.chunks.push(chunk);
27
+ if (options.emitError) {
28
+ queueMicrotask(() => this.emit('error', new Error(options.emitError)));
29
+ return;
30
+ }
31
+ if (options.stdout) queueMicrotask(() => this.stdout.emit('data', options.stdout));
32
+ if (options.stderr) queueMicrotask(() => this.stderr.emit('data', options.stderr));
33
+ queueMicrotask(() => this.emit('close', options.exitCode ?? 0, null));
34
+ },
35
+ };
36
+ }
37
+ }
38
+
39
+ function scriptedSpawn(children: FakeChild[]) {
40
+ const calls: Array<{ command: string; args: string[]; options: unknown }> = [];
41
+ const spawnFn = vi.fn((command: string, args: string[], options: unknown) => {
42
+ calls.push({ command, args, options });
43
+ const child = children.shift();
44
+ if (!child) throw new Error('unexpected spawn');
45
+ return child as unknown as ChildProcess;
46
+ }) as unknown as GhSpawn;
47
+ return { spawnFn, calls };
48
+ }
49
+
50
+ describe('writeGhAuth', () => {
51
+ it('T-GC1: passes the token via stdin only and then runs gh auth setup-git', async () => {
52
+ const login = new FakeChild();
53
+ const setup = new FakeChild();
54
+ const { spawnFn, calls } = scriptedSpawn([login, setup]);
55
+
56
+ await writeGhAuth(TOKEN, { spawn: spawnFn });
57
+
58
+ expect(calls.map((call) => call.command)).toEqual(['gh', 'gh']);
59
+ expect(calls[0].args).toEqual(['auth', 'login', '--with-token']);
60
+ expect(calls[1].args).toEqual(['auth', 'setup-git']);
61
+ expect(login.stdin.chunks).toEqual([TOKEN]);
62
+ // token 绝不进入 argv
63
+ for (const call of calls) {
64
+ expect(call.args.join(' ')).not.toContain(TOKEN);
65
+ }
66
+ expect(calls[0].options).toMatchObject({ stdio: ['pipe', 'pipe', 'pipe'] });
67
+ });
68
+
69
+ it('T-GC2: reports the login exit code without leaking the token', async () => {
70
+ const login = new FakeChild({ exitCode: 1, stderr: `bad credentials: ${TOKEN}` });
71
+ const { spawnFn } = scriptedSpawn([login]);
72
+
73
+ let error: Error | undefined;
74
+ try {
75
+ await writeGhAuth(TOKEN, { spawn: spawnFn });
76
+ } catch (caught) {
77
+ error = caught as Error;
78
+ }
79
+
80
+ expect(error).toBeInstanceOf(Error);
81
+ expect(error!.message).toContain('退出码 1');
82
+ expect(error!.message).toContain('auth login');
83
+ expect(error!.message).not.toContain(TOKEN);
84
+ expect(error!.message).toContain('***');
85
+ });
86
+
87
+ it('T-GC3: setup-git failure is returned once without an infinite retry loop', async () => {
88
+ const login = new FakeChild();
89
+ const setup = new FakeChild({ exitCode: 2, stderr: 'helper failed' });
90
+ const { spawnFn, calls } = scriptedSpawn([login, setup]);
91
+
92
+ await expect(writeGhAuth(TOKEN, { spawn: spawnFn })).rejects.toThrow(/setup-git.*退出码 2/s);
93
+ expect(calls).toHaveLength(2);
94
+ expect(login.stdin.chunks).toEqual([TOKEN]);
95
+ expect(setup.stdin.chunks).toEqual([]);
96
+ });
97
+
98
+ it('rejects an empty token before spawning anything', async () => {
99
+ const { spawnFn, calls } = scriptedSpawn([]);
100
+ await expect(writeGhAuth('', { spawn: spawnFn })).rejects.toThrow('Github token 为空');
101
+ expect(calls).toHaveLength(0);
102
+ });
103
+ });
@@ -0,0 +1,76 @@
1
+ import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process';
2
+ import { redactSecrets } from '../workload-executor.js';
3
+
4
+ /** `gh` 进程启动函数(测试注入;生产使用 `node:child_process.spawn`)。 */
5
+ export type GhSpawn = (command: string, args: string[], options: SpawnOptions) => ChildProcess;
6
+
7
+ export interface WriteGhAuthOptions {
8
+ /** 注入 spawn(测试用);生产缺省使用 `node:child_process.spawn`。 */
9
+ spawn?: GhSpawn;
10
+ }
11
+
12
+ /**
13
+ * 执行一次 `gh` 子命令并收集输出。
14
+ *
15
+ * - `stdin` 只经管道写入(token 绝不进入 argv/env);
16
+ * - 失败时按 `redactSecrets` 脱敏后再拼接错误,错误信息不含任何 secret;
17
+ * - 每次调用只执行一次,不做重试(避免无限循环)。
18
+ */
19
+ function runGh(spawnFn: GhSpawn, args: string[], stdin?: string): Promise<void> {
20
+ return new Promise<void>((resolve, reject) => {
21
+ const child = spawnFn('gh', args, { stdio: ['pipe', 'pipe', 'pipe'] });
22
+ let output = '';
23
+ let settled = false;
24
+
25
+ const finish = (error?: Error): void => {
26
+ if (settled) return;
27
+ settled = true;
28
+ if (error) reject(error);
29
+ else resolve();
30
+ };
31
+
32
+ child.stdout?.on('data', (chunk: Buffer | string) => {
33
+ output += chunk.toString();
34
+ });
35
+ child.stderr?.on('data', (chunk: Buffer | string) => {
36
+ output += chunk.toString();
37
+ });
38
+ child.on('error', (error: Error) => {
39
+ // spawn 级别错误(如 ENOENT)通常不含输出,但仍统一脱敏。
40
+ finish(new Error(`执行 gh ${args.join(' ')} 失败:${redactSecrets(error.message, [stdin ?? ''])}`));
41
+ });
42
+ child.on('close', (code: number | null, signal: NodeJS.Signals | null) => {
43
+ if (code === 0) {
44
+ finish();
45
+ return;
46
+ }
47
+ const detail = redactSecrets(output.trim(), [stdin ?? '']);
48
+ const suffix = signal ? `signal=${signal}` : `退出码 ${code ?? 'null'}`;
49
+ finish(new Error(`gh ${args.join(' ')} 失败(${suffix})${detail ? `:${detail}` : ''}`));
50
+ });
51
+
52
+ // token 只经 stdin 传递,不进入 argv/env。
53
+ if (stdin !== undefined) {
54
+ child.stdin?.end(stdin);
55
+ } else {
56
+ child.stdin?.end();
57
+ }
58
+ });
59
+ }
60
+
61
+ /**
62
+ * 将 Github token 写入容器内 `gh` 配置(云主机唯一凭据写入口)。
63
+ *
64
+ * 1. `gh auth login --with-token`:token 经 stdin 传入;
65
+ * 2. `gh auth setup-git`:配置 git credential helper。
66
+ *
67
+ * 任一步失败立即抛错(不重试);错误信息不含 token。
68
+ */
69
+ export async function writeGhAuth(token: string, options: WriteGhAuthOptions = {}): Promise<void> {
70
+ if (typeof token !== 'string' || token.length === 0) {
71
+ throw new Error('Github token 为空');
72
+ }
73
+ const spawnFn = options.spawn ?? (spawn as unknown as GhSpawn);
74
+ await runGh(spawnFn, ['auth', 'login', '--with-token'], token);
75
+ await runGh(spawnFn, ['auth', 'setup-git']);
76
+ }