agent-gear 2.4.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 (159) hide show
  1. package/AGENTS.md +108 -5
  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 +105 -0
  32. package/dist/cloud-host/supervisor.d.ts.map +1 -0
  33. package/dist/cloud-host/supervisor.js +237 -0
  34. package/dist/cloud-host/supervisor.js.map +1 -0
  35. package/dist/cloud-host/supervisor.test.d.ts +2 -0
  36. package/dist/cloud-host/supervisor.test.d.ts.map +1 -0
  37. package/dist/cloud-host/supervisor.test.js +367 -0
  38. package/dist/cloud-host/supervisor.test.js.map +1 -0
  39. package/dist/commands/harness.d.ts +17 -0
  40. package/dist/commands/harness.d.ts.map +1 -0
  41. package/dist/commands/harness.js +35 -0
  42. package/dist/commands/harness.js.map +1 -0
  43. package/dist/config.d.ts.map +1 -1
  44. package/dist/config.js +10 -3
  45. package/dist/config.js.map +1 -1
  46. package/dist/github/credential-manager.d.ts +70 -0
  47. package/dist/github/credential-manager.d.ts.map +1 -0
  48. package/dist/github/credential-manager.js +205 -0
  49. package/dist/github/credential-manager.js.map +1 -0
  50. package/dist/github/credential-manager.test.d.ts +2 -0
  51. package/dist/github/credential-manager.test.d.ts.map +1 -0
  52. package/dist/github/credential-manager.test.js +215 -0
  53. package/dist/github/credential-manager.test.js.map +1 -0
  54. package/dist/github/gh-config.d.ts +17 -0
  55. package/dist/github/gh-config.d.ts.map +1 -0
  56. package/dist/github/gh-config.js +68 -0
  57. package/dist/github/gh-config.js.map +1 -0
  58. package/dist/github/gh-config.test.d.ts +2 -0
  59. package/dist/github/gh-config.test.d.ts.map +1 -0
  60. package/dist/github/gh-config.test.js +90 -0
  61. package/dist/github/gh-config.test.js.map +1 -0
  62. package/dist/harness/env.d.ts +36 -0
  63. package/dist/harness/env.d.ts.map +1 -0
  64. package/dist/harness/env.js +78 -0
  65. package/dist/harness/env.js.map +1 -0
  66. package/dist/harness/env.test.d.ts +2 -0
  67. package/dist/harness/env.test.d.ts.map +1 -0
  68. package/dist/harness/env.test.js +70 -0
  69. package/dist/harness/env.test.js.map +1 -0
  70. package/dist/harness/opencode-cli.d.ts +24 -0
  71. package/dist/harness/opencode-cli.d.ts.map +1 -0
  72. package/dist/harness/opencode-cli.js +74 -0
  73. package/dist/harness/opencode-cli.js.map +1 -0
  74. package/dist/harness/opencode-cli.test.d.ts +2 -0
  75. package/dist/harness/opencode-cli.test.d.ts.map +1 -0
  76. package/dist/harness/opencode-cli.test.js +62 -0
  77. package/dist/harness/opencode-cli.test.js.map +1 -0
  78. package/dist/harness/opencode-config.atomic-failure.test.d.ts +2 -0
  79. package/dist/harness/opencode-config.atomic-failure.test.d.ts.map +1 -0
  80. package/dist/harness/opencode-config.atomic-failure.test.js +35 -0
  81. package/dist/harness/opencode-config.atomic-failure.test.js.map +1 -0
  82. package/dist/harness/opencode-config.d.ts +54 -0
  83. package/dist/harness/opencode-config.d.ts.map +1 -0
  84. package/dist/harness/opencode-config.js +130 -0
  85. package/dist/harness/opencode-config.js.map +1 -0
  86. package/dist/harness/opencode-config.test.d.ts +2 -0
  87. package/dist/harness/opencode-config.test.d.ts.map +1 -0
  88. package/dist/harness/opencode-config.test.js +183 -0
  89. package/dist/harness/opencode-config.test.js.map +1 -0
  90. package/dist/harness/prepare.d.ts +34 -0
  91. package/dist/harness/prepare.d.ts.map +1 -0
  92. package/dist/harness/prepare.js +46 -0
  93. package/dist/harness/prepare.js.map +1 -0
  94. package/dist/harness/prepare.test.d.ts +2 -0
  95. package/dist/harness/prepare.test.d.ts.map +1 -0
  96. package/dist/harness/prepare.test.js +96 -0
  97. package/dist/harness/prepare.test.js.map +1 -0
  98. package/dist/heartbeat.d.ts.map +1 -1
  99. package/dist/heartbeat.js +2 -0
  100. package/dist/heartbeat.js.map +1 -1
  101. package/dist/index.js +21 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/socketio-client.d.ts +74 -3
  104. package/dist/socketio-client.d.ts.map +1 -1
  105. package/dist/socketio-client.github.test.d.ts +2 -0
  106. package/dist/socketio-client.github.test.d.ts.map +1 -0
  107. package/dist/socketio-client.github.test.js +66 -0
  108. package/dist/socketio-client.github.test.js.map +1 -0
  109. package/dist/socketio-client.js +267 -78
  110. package/dist/socketio-client.js.map +1 -1
  111. package/dist/socketio-client.test.d.ts +2 -0
  112. package/dist/socketio-client.test.d.ts.map +1 -0
  113. package/dist/socketio-client.test.js +382 -0
  114. package/dist/socketio-client.test.js.map +1 -0
  115. package/dist/workload-executor.d.ts +37 -1
  116. package/dist/workload-executor.d.ts.map +1 -1
  117. package/dist/workload-executor.js +111 -19
  118. package/dist/workload-executor.js.map +1 -1
  119. package/dist/workload-executor.test.js +205 -3
  120. package/dist/workload-executor.test.js.map +1 -1
  121. package/package.json +2 -1
  122. package/src/acp/__fixtures__/fake-elicitation-agent.mjs +113 -0
  123. package/src/acp/__fixtures__/opencode-2.0.31-capabilities.json +25 -0
  124. package/src/acp/bridge.test.ts +480 -1
  125. package/src/acp/bridge.ts +163 -18
  126. package/src/acp/capabilities.test.ts +200 -0
  127. package/src/acp/capabilities.ts +274 -0
  128. package/src/acp/elicitation.integration.test.ts +126 -0
  129. package/src/acp/prober.ts +4 -0
  130. package/src/acp/spawner.ts +3 -0
  131. package/src/acp/sync-bridge.ts +5 -1
  132. package/src/cloud-host/supervisor.test.ts +462 -0
  133. package/src/cloud-host/supervisor.ts +326 -0
  134. package/src/commands/harness.ts +44 -0
  135. package/src/config.ts +9 -3
  136. package/src/github/credential-manager.test.ts +268 -0
  137. package/src/github/credential-manager.ts +251 -0
  138. package/src/github/gh-config.test.ts +103 -0
  139. package/src/github/gh-config.ts +76 -0
  140. package/src/harness/env.test.ts +79 -0
  141. package/src/harness/env.ts +89 -0
  142. package/src/harness/opencode-cli.test.ts +82 -0
  143. package/src/harness/opencode-cli.ts +99 -0
  144. package/src/harness/opencode-config.atomic-failure.test.ts +51 -0
  145. package/src/harness/opencode-config.test.ts +238 -0
  146. package/src/harness/opencode-config.ts +176 -0
  147. package/src/harness/prepare.test.ts +117 -0
  148. package/src/harness/prepare.ts +69 -0
  149. package/src/heartbeat.ts +2 -0
  150. package/src/index.ts +22 -0
  151. package/src/socketio-client.github.test.ts +76 -0
  152. package/src/socketio-client.test.ts +460 -0
  153. package/src/socketio-client.ts +314 -68
  154. package/src/workload-executor.test.ts +264 -2
  155. package/src/workload-executor.ts +147 -18
  156. package/tests/acp-sync-bridge.test.ts +5 -1
  157. package/tests/commands/harness.test.ts +90 -0
  158. package/tests/socketio-client.test.ts +140 -2
  159. package/vitest.config.ts +5 -1
@@ -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
+ }
@@ -0,0 +1,79 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { HarnessEnvError, parseModelIds, readHarnessEnv } from './env.js';
3
+
4
+ const VALID_ENV: NodeJS.ProcessEnv = {
5
+ ZAG_MODEL_BASE_URL: 'http://admin-api:8002/v1',
6
+ ZAG_MODEL_API_KEY: 'zag_sk_super_secret',
7
+ ZAG_MODEL_IDS: '["model-a","model-b"]',
8
+ ZAG_DEFAULT_WORKSPACE: '/root/workspace',
9
+ };
10
+
11
+ describe('readHarnessEnv (T-AG7/T-AG11)', () => {
12
+ it('reads a valid harness env', () => {
13
+ expect(readHarnessEnv(VALID_ENV)).toEqual({
14
+ modelBaseUrl: 'http://admin-api:8002/v1',
15
+ modelApiKey: 'zag_sk_super_secret',
16
+ modelIds: ['model-a', 'model-b'],
17
+ defaultWorkspace: '/root/workspace',
18
+ });
19
+ });
20
+
21
+ it('lists all missing variables by name and never leaks secret values', () => {
22
+ let error: unknown;
23
+ try {
24
+ readHarnessEnv({ ZAG_MODEL_API_KEY: 'zag_sk_super_secret' });
25
+ } catch (caught) {
26
+ error = caught;
27
+ }
28
+
29
+ expect(error).toBeInstanceOf(HarnessEnvError);
30
+ const message = (error as Error).message;
31
+ expect(message).toContain('ZAG_MODEL_BASE_URL');
32
+ expect(message).toContain('ZAG_MODEL_IDS');
33
+ expect(message).toContain('ZAG_DEFAULT_WORKSPACE');
34
+ expect(message).not.toContain('ZAG_MODEL_API_KEY');
35
+ expect(message).not.toContain('zag_sk_super_secret');
36
+ });
37
+
38
+ it('trims values', () => {
39
+ const env = readHarnessEnv({
40
+ ...VALID_ENV,
41
+ ZAG_MODEL_BASE_URL: ' http://admin-api:8002/v1 ',
42
+ } as NodeJS.ProcessEnv);
43
+ expect(env.modelBaseUrl).toBe('http://admin-api:8002/v1');
44
+ });
45
+
46
+ it('rejects a missing default workspace', () => {
47
+ expect(() => readHarnessEnv({ ...VALID_ENV, ZAG_DEFAULT_WORKSPACE: '' })).toThrowError(
48
+ /ZAG_DEFAULT_WORKSPACE/,
49
+ );
50
+ });
51
+ });
52
+
53
+ describe('parseModelIds (T-AG11)', () => {
54
+ it('dedupes and drops empty/whitespace entries while preserving order', () => {
55
+ expect(parseModelIds('["b"," a ","b",""," ","c","a"]')).toEqual(['b', 'a', 'c']);
56
+ });
57
+
58
+ it('accepts an empty array', () => {
59
+ expect(parseModelIds('[]')).toEqual([]);
60
+ });
61
+
62
+ it('rejects invalid JSON without echoing the raw value', () => {
63
+ let error: unknown;
64
+ try {
65
+ parseModelIds('not-json');
66
+ } catch (caught) {
67
+ error = caught;
68
+ }
69
+ expect(error).toBeInstanceOf(HarnessEnvError);
70
+ expect((error as Error).message).toContain('ZAG_MODEL_IDS');
71
+ expect((error as Error).message).not.toContain('not-json');
72
+ });
73
+
74
+ it('rejects non-array and non-string elements', () => {
75
+ expect(() => parseModelIds('{"a":1}')).toThrowError(/JSON array of strings/);
76
+ expect(() => parseModelIds('["a",1]')).toThrowError(/non-string element/);
77
+ expect(() => parseModelIds('null')).toThrowError(/JSON array of strings/);
78
+ });
79
+ });
@@ -0,0 +1,89 @@
1
+ /**
2
+ * harness(OpenCode 云电脑)初始化环境校验。
3
+ *
4
+ * 只读取 `harness prepare` 需要的变量;缺失/非法时一次性列出**变量名**,
5
+ * 绝不回显其它 env 的值(尤其 `ZAG_MODEL_API_KEY` 等 secret)。
6
+ */
7
+
8
+ /** harness prepare 需要的环境(已归一)。 */
9
+ export interface HarnessEnv {
10
+ /** 模型网关地址(`ZAG_MODEL_BASE_URL`)。 */
11
+ modelBaseUrl: string;
12
+ /** 运行专用模型 Key(`ZAG_MODEL_API_KEY`,禁止打印)。 */
13
+ modelApiKey: string;
14
+ /** 可用模型 ID 列表(`ZAG_MODEL_IDS`,JSON 数组字符串,去空去重)。 */
15
+ modelIds: string[];
16
+ /** 默认工作区(`ZAG_DEFAULT_WORKSPACE`)。 */
17
+ defaultWorkspace: string;
18
+ }
19
+
20
+ /** env 校验失败(消息不含任何变量值)。 */
21
+ export class HarnessEnvError extends Error {
22
+ constructor(message: string) {
23
+ super(message);
24
+ this.name = 'HarnessEnvError';
25
+ }
26
+ }
27
+
28
+ function nonEmpty(value: string | undefined): string {
29
+ return typeof value === 'string' ? value.trim() : '';
30
+ }
31
+
32
+ /**
33
+ * 解析 `ZAG_MODEL_IDS`:必须是字符串 JSON 数组;元素 trim 后去空、去重(保持原顺序)。
34
+ *
35
+ * - `[]` 合法(T-AG11:空数组仍写 `models:{}`);
36
+ * - 非数组/非法 JSON/含非字符串元素 → 明确报错(不输出原始值)。
37
+ */
38
+ export function parseModelIds(raw: string): string[] {
39
+ let parsed: unknown;
40
+ try {
41
+ parsed = JSON.parse(raw);
42
+ } catch {
43
+ throw new HarnessEnvError('ZAG_MODEL_IDS must be a JSON array of strings (invalid JSON)');
44
+ }
45
+ if (!Array.isArray(parsed)) {
46
+ throw new HarnessEnvError('ZAG_MODEL_IDS must be a JSON array of strings');
47
+ }
48
+ if (!parsed.every((item) => typeof item === 'string')) {
49
+ throw new HarnessEnvError('ZAG_MODEL_IDS must be a JSON array of strings (non-string element)');
50
+ }
51
+ const unique: string[] = [];
52
+ const seen = new Set<string>();
53
+ for (const item of parsed as string[]) {
54
+ const value = item.trim();
55
+ if (!value || seen.has(value)) continue;
56
+ seen.add(value);
57
+ unique.push(value);
58
+ }
59
+ return unique;
60
+ }
61
+
62
+ /**
63
+ * 读取并校验 harness env。
64
+ *
65
+ * 必需:`ZAG_MODEL_BASE_URL` / `ZAG_MODEL_API_KEY` / `ZAG_MODEL_IDS` / `ZAG_DEFAULT_WORKSPACE`
66
+ * (云电脑 Job env 与 `workload:run.env` 均由 agent-api 注入,缺失说明编排不正确)。
67
+ */
68
+ export function readHarnessEnv(env: NodeJS.ProcessEnv = process.env): HarnessEnv {
69
+ const missing: string[] = [];
70
+ const modelBaseUrl = nonEmpty(env.ZAG_MODEL_BASE_URL);
71
+ if (!modelBaseUrl) missing.push('ZAG_MODEL_BASE_URL');
72
+ const modelApiKey = nonEmpty(env.ZAG_MODEL_API_KEY);
73
+ if (!modelApiKey) missing.push('ZAG_MODEL_API_KEY');
74
+ const rawModelIds = nonEmpty(env.ZAG_MODEL_IDS);
75
+ if (!rawModelIds) missing.push('ZAG_MODEL_IDS');
76
+ const defaultWorkspace = nonEmpty(env.ZAG_DEFAULT_WORKSPACE);
77
+ if (!defaultWorkspace) missing.push('ZAG_DEFAULT_WORKSPACE');
78
+
79
+ if (missing.length > 0) {
80
+ throw new HarnessEnvError(`missing required environment variable(s): ${missing.join(', ')}`);
81
+ }
82
+
83
+ return {
84
+ modelBaseUrl,
85
+ modelApiKey,
86
+ modelIds: parseModelIds(rawModelIds),
87
+ defaultWorkspace,
88
+ };
89
+ }
@@ -0,0 +1,82 @@
1
+ import { describe, it, expect, vi } from 'vitest';
2
+ import {
3
+ OpencodeCliError,
4
+ extractVersion,
5
+ verifyOpencodeCli,
6
+ type CommandRunner,
7
+ } from './opencode-cli.js';
8
+
9
+ describe('verifyOpencodeCli (T-AG8)', () => {
10
+ it('runs `opencode --version` and returns the version', async () => {
11
+ const runner = vi.fn<CommandRunner>(async () => ({ stdout: '1.2.3\n', stderr: '' }));
12
+
13
+ await expect(verifyOpencodeCli(runner)).resolves.toBe('1.2.3');
14
+ expect(runner).toHaveBeenCalledWith('opencode', ['--version']);
15
+ expect(runner).toHaveBeenCalledTimes(1);
16
+ });
17
+
18
+ it('falls back to `opencode -v` for legacy CLIs', async () => {
19
+ const runner = vi.fn<CommandRunner>(async (_command, args) => {
20
+ if (args[0] === '--version') throw new Error('unknown option');
21
+ return { stdout: 'v0.9.1\n', stderr: '' };
22
+ });
23
+
24
+ await expect(verifyOpencodeCli(runner)).resolves.toBe('0.9.1');
25
+ expect(runner).toHaveBeenNthCalledWith(1, 'opencode', ['--version']);
26
+ expect(runner).toHaveBeenNthCalledWith(2, 'opencode', ['-v']);
27
+ });
28
+
29
+ it('falls back to `-v` when `--version` prints no version', async () => {
30
+ const runner = vi.fn<CommandRunner>(async (_command, args) =>
31
+ args[0] === '--version'
32
+ ? { stdout: ' \n', stderr: '' }
33
+ : { stdout: '2.0.0\n', stderr: '' },
34
+ );
35
+
36
+ await expect(verifyOpencodeCli(runner)).resolves.toBe('2.0.0');
37
+ });
38
+
39
+ it('throws a version-check error when both commands fail', async () => {
40
+ const runner = vi.fn<CommandRunner>(async () => {
41
+ throw new Error('spawn opencode ENOENT');
42
+ });
43
+
44
+ let error: unknown;
45
+ try {
46
+ await verifyOpencodeCli(runner);
47
+ } catch (caught) {
48
+ error = caught;
49
+ }
50
+
51
+ expect(error).toBeInstanceOf(OpencodeCliError);
52
+ const message = (error as Error).message;
53
+ expect(message).toContain('version check failed');
54
+ expect(message).toContain('opencode --version');
55
+ expect(message).toContain('opencode -v');
56
+ expect(message).toContain('ENOENT');
57
+ });
58
+
59
+ it('C-5: validates the expected pinned version (tolerates v prefix and command output prefix)', async () => {
60
+ const runner = vi.fn<CommandRunner>(async () => ({ stdout: 'v2.1.1\n', stderr: '' }));
61
+ await expect(verifyOpencodeCli(runner, '2.1.1')).resolves.toBe('2.1.1');
62
+
63
+ const prefixed = vi.fn<CommandRunner>(async () => ({ stdout: 'opencode 2.1.1\n', stderr: '' }));
64
+ await expect(verifyOpencodeCli(prefixed, '2.1.1')).resolves.toBe('opencode 2.1.1');
65
+ });
66
+
67
+ it('C-5: throws immediately on a pinned version mismatch', async () => {
68
+ const runner = vi.fn<CommandRunner>(async () => ({ stdout: '2.0.0\n', stderr: '' }));
69
+
70
+ await expect(verifyOpencodeCli(runner, '2.1.1')).rejects.toThrow(
71
+ /version mismatch: expected 2\.1\.1, got 2\.0\.0/,
72
+ );
73
+ // 不匹配即失败,不再退回 `-v`
74
+ expect(runner).toHaveBeenCalledTimes(1);
75
+ });
76
+
77
+ it('reads the version from stderr when stdout is empty', () => {
78
+ expect(extractVersion('', 'opencode 1.0.0\n')).toBe('opencode 1.0.0');
79
+ expect(extractVersion('\n\n3.2.1\n')).toBe('3.2.1');
80
+ expect(extractVersion(' ')).toBeUndefined();
81
+ });
82
+ });