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,326 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { hostname } from 'node:os';
3
+ import type { Socket } from 'socket.io-client';
4
+ import {
5
+ connectToServer,
6
+ parseEndpoint,
7
+ type ConnectToServerOptions,
8
+ } from '../socketio-client.js';
9
+ import {
10
+ GithubCredentialManager,
11
+ type GithubCredentialRefreshResult,
12
+ } from '../github/credential-manager.js';
13
+ import type { WorkloadRunPayload } from '../workload-executor.js';
14
+
15
+ /** 未设置 `HARNESS_INIT_WAIT_MS` 时的初始化等待上限(10 分钟)。 */
16
+ export const DEFAULT_HARNESS_INIT_WAIT_MS = 600_000;
17
+
18
+ /** 未设置 `ZAG_DEFAULT_WORKSPACE` 时的默认工作区(容器内以 root 运行)。 */
19
+ export const DEFAULT_WORKSPACE = '/root/workspace';
20
+
21
+ /** 云电脑模式必需的环境变量(三者同时非空才进入 supervisor)。 */
22
+ export const CLOUD_HOST_MODE_KEYS = ['ZAG_HOST_ENDPOINT', 'ZAG_HOST_KEY', 'ZAG_CONTROLLER_KEY'] as const;
23
+
24
+ /** 云电脑 supervisor 的运行参数(从容器 env 读取)。 */
25
+ export interface CloudHostEnv {
26
+ /** controller-api 标准连接地址(env `ZAG_HOST_ENDPOINT`)。 */
27
+ hostEndpoint: string;
28
+ /** 标准连接凭据(env `ZAG_HOST_KEY`,仅经握手 auth.token 携带)。 */
29
+ hostKey: string;
30
+ /** cloud-controller `/worker` 一次性 token(env `ZAG_CONTROLLER_KEY`)。 */
31
+ controllerKey: string;
32
+ /** cloud-controller `/worker` 地址(env `ZAG_SERVER_ENDPOINT`)。 */
33
+ serverEndpoint: string;
34
+ /** 注册上报的主机名(env `ZAG_HOST_NAME`,缺省 `os.hostname()`)。 */
35
+ hostName: string;
36
+ /** 默认工作区(env `ZAG_DEFAULT_WORKSPACE`,缺省 `/root/workspace`)。 */
37
+ workspace: string;
38
+ /** 初始化等待超时(env `HARNESS_INIT_WAIT_MS`,缺省 10 分钟)。 */
39
+ initWaitMs: number;
40
+ /** agent-api 内部地址(env `ZAG_AGENT_API_ENDPOINT`;缺失时凭据管理器禁用)。 */
41
+ agentApiEndpoint?: string;
42
+ /** 云主机 controllerId(env `ZAG_CONTROLLER_ID`;缺失时凭据管理器禁用)。 */
43
+ controllerId?: string;
44
+ }
45
+
46
+ /** 云电脑 env 校验失败(消息只含变量名,不含任何值)。 */
47
+ export class CloudHostEnvError extends Error {
48
+ constructor(message: string) {
49
+ super(message);
50
+ this.name = 'CloudHostEnvError';
51
+ }
52
+ }
53
+
54
+ function nonEmpty(value: string | undefined): string {
55
+ return typeof value === 'string' ? value.trim() : '';
56
+ }
57
+
58
+ /**
59
+ * 模式检测:同时设置 `ZAG_HOST_ENDPOINT` + `ZAG_HOST_KEY` + `ZAG_CONTROLLER_KEY` 且非空
60
+ * → 云电脑模式;否则沿用本地控制器单连接旧路径。
61
+ */
62
+ export function isCloudHostMode(env: NodeJS.ProcessEnv = process.env): boolean {
63
+ return CLOUD_HOST_MODE_KEYS.every((key) => nonEmpty(env[key]).length > 0);
64
+ }
65
+
66
+ /** 解析初始化等待超时:显式非正整数时回退默认值(不因错误配置阻塞上线)。 */
67
+ export function parseInitWaitMs(value: string | undefined): number {
68
+ const parsed = Number.parseInt(value ?? '', 10);
69
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_HARNESS_INIT_WAIT_MS;
70
+ }
71
+
72
+ /**
73
+ * 读取并校验云电脑模式 env。
74
+ *
75
+ * 缺失项一次性列出变量名(便于 init 日志定位),**绝不输出变量值**(含 secret)。
76
+ */
77
+ export function readCloudHostEnv(env: NodeJS.ProcessEnv = process.env): CloudHostEnv {
78
+ const required = [
79
+ 'ZAG_HOST_ENDPOINT',
80
+ 'ZAG_HOST_KEY',
81
+ 'ZAG_CONTROLLER_KEY',
82
+ 'ZAG_SERVER_ENDPOINT',
83
+ ] as const;
84
+ const missing = required.filter((key) => nonEmpty(env[key]).length === 0);
85
+ if (missing.length > 0) {
86
+ throw new CloudHostEnvError(
87
+ `missing required environment variable(s) for cloud-host mode: ${missing.join(', ')}`,
88
+ );
89
+ }
90
+
91
+ return {
92
+ hostEndpoint: nonEmpty(env.ZAG_HOST_ENDPOINT),
93
+ hostKey: nonEmpty(env.ZAG_HOST_KEY),
94
+ controllerKey: nonEmpty(env.ZAG_CONTROLLER_KEY),
95
+ serverEndpoint: nonEmpty(env.ZAG_SERVER_ENDPOINT),
96
+ hostName: nonEmpty(env.ZAG_HOST_NAME) || hostname(),
97
+ workspace: nonEmpty(env.ZAG_DEFAULT_WORKSPACE) || DEFAULT_WORKSPACE,
98
+ initWaitMs: parseInitWaitMs(env.HARNESS_INIT_WAIT_MS),
99
+ agentApiEndpoint: nonEmpty(env.ZAG_AGENT_API_ENDPOINT) || undefined,
100
+ controllerId: nonEmpty(env.ZAG_CONTROLLER_ID) || undefined,
101
+ };
102
+ }
103
+
104
+ /** 凭据管理器最小接口(supervisor 只依赖生命周期与 refreshNow,便于测试注入)。 */
105
+ export interface CredentialManagerLike {
106
+ start(): void;
107
+ stop(): void;
108
+ refreshNow(): Promise<GithubCredentialRefreshResult>;
109
+ }
110
+
111
+ /** 依赖注入(测试锚定时序与副作用;生产使用默认实现)。 */
112
+ export interface CloudHostSupervisorDeps {
113
+ env?: NodeJS.ProcessEnv;
114
+ connect?: (endpoint: string, key: string, options?: ConnectToServerOptions) => Socket;
115
+ makeDir?: (path: string) => Promise<void>;
116
+ exit?: (code: number) => void;
117
+ log?: (message: string) => void;
118
+ /** 是否接管 SIGINT/SIGTERM(默认 true;测试关闭以免污染进程)。 */
119
+ installSignalHandlers?: boolean;
120
+ /** 注入 Github 凭据管理器(测试用);缺省按容器 env 创建。 */
121
+ credentialManager?: CredentialManagerLike;
122
+ }
123
+
124
+ export interface CloudHostSupervisorHandle {
125
+ /** `/worker` 连接(cloud-controller)。 */
126
+ workerSocket: Socket;
127
+ /** controller-api 标准连接(初始化完成后才建立)。 */
128
+ readonly controllerSocket: Socket | null;
129
+ /** 已创建(幂等)的默认工作区。 */
130
+ workspace: string;
131
+ /**
132
+ * 关闭两端并退出(不发送 `unregister`)。
133
+ *
134
+ * `code` 缺省按 `reason` 自动判定:服务端主动 shutdown / 信号 / unregistered → 0;
135
+ * `version_mismatch:*` / `error:*` / 初始化失败类 → 1(避免错误路径 `exit(0)` 掩盖失败,
136
+ * 并让 entrypoint 的 VERSION_MISMATCH 自愈生效,C-2)。
137
+ */
138
+ shutdown: (reason: string, code?: number) => void;
139
+ }
140
+
141
+ /**
142
+ * 错误/失败类 shutdown reason 判定(C-2):
143
+ *
144
+ * - `socketio-client` 把 `VERSION_MISMATCH` / 其它 `error` 事件转成
145
+ * `version_mismatch:*` / `error:<code>` 前缀;
146
+ * - cloud-controller 的必须工作负载失败 reason 形如「必须工作负载「x」初始化失败」
147
+ * (经 `worker shutdown: ...` 包装后仍需识别);
148
+ * - 其余(服务端主动 shutdown、`unregistered`、SIGINT/SIGTERM)视为正常退出。
149
+ */
150
+ export function isFailureShutdownReason(reason: string): boolean {
151
+ const normalized = reason.trim().toLowerCase();
152
+ // reason 可能被 `worker shutdown:` / `controller-api shutdown:` 包装,用 includes 判定前缀。
153
+ if (normalized.includes('version_mismatch:') || /(^|[\s:])error:/.test(normalized)) {
154
+ return true;
155
+ }
156
+ return (
157
+ reason.includes('初始化失败') ||
158
+ normalized.includes('init failed') ||
159
+ normalized.includes('initialization failed')
160
+ );
161
+ }
162
+
163
+ /** 由 shutdown reason 推导退出码:失败路径 1、正常退出 0。 */
164
+ export function resolveShutdownExitCode(reason: string): number {
165
+ return isFailureShutdownReason(reason) ? 1 : 0;
166
+ }
167
+
168
+ /** 日志中的连接目标:仅 origin + namespace,绝不包含 query/token。 */
169
+ function describeEndpoint(endpoint: string): string {
170
+ const { origin, namespace } = parseEndpoint(endpoint);
171
+ return namespace === '/' ? origin : `${origin}${namespace}`;
172
+ }
173
+
174
+ /**
175
+ * 云电脑双连接 supervisor(契约 `agent-controller-websocket.md` §4.3):
176
+ *
177
+ * 1. `mkdir -p ZAG_DEFAULT_WORKSPACE`(幂等);
178
+ * 2. 先连 cloud-controller `/worker`(`ZAG_SERVER_ENDPOINT` + `ZAG_CONTROLLER_KEY`);
179
+ * 3. `registered.initializing=true` → 等待首个 `workload:run` 批次结束(成功/失败/超时)后
180
+ * 再连 controller-api(`ZAG_HOST_ENDPOINT` + `ZAG_HOST_KEY`);`false`/缺省立即连接;
181
+ * 4. 任一端 `shutdown` → 关闭两端并退出(正常 0;`version_mismatch`/`error`/初始化失败 1);**始终不发送 `unregister`**;
182
+ * 5. 仅 controller-api 标准连接启动本地 MCP 回环服务(worker 连接跳过,避免端口冲突)。
183
+ */
184
+ export async function startCloudHostSupervisor(
185
+ deps: CloudHostSupervisorDeps = {},
186
+ ): Promise<CloudHostSupervisorHandle> {
187
+ const env = readCloudHostEnv(deps.env ?? process.env);
188
+ const connect = deps.connect ?? connectToServer;
189
+ const makeDir = deps.makeDir ?? ((path: string) => mkdir(path, { recursive: true }).then(() => undefined));
190
+ const exit = deps.exit ?? ((code: number) => process.exit(code));
191
+ const log = deps.log ?? ((message: string) => console.log(message));
192
+
193
+ // 初始化脚本/工作负载需要在工作区落地前执行,先幂等创建工作区。
194
+ await makeDir(env.workspace);
195
+ log(`[CloudHost] workspace ready: ${env.workspace}`);
196
+
197
+ // Github 凭据管理器:env 缺失时自身只 warn 并禁用,绝不阻塞云主机上线。
198
+ const credentialManager =
199
+ deps.credentialManager ??
200
+ new GithubCredentialManager({ env: deps.env ?? process.env, log });
201
+ credentialManager.start();
202
+
203
+ const beforeWorkloadBatch = async (payload: WorkloadRunPayload): Promise<void> => {
204
+ if (payload.githubAuth !== true) return;
205
+ const result = await credentialManager.refreshNow();
206
+ if (result.ok) return;
207
+ if (result.error === 'no-binding') throw new Error('未设置 Github 项目');
208
+ if (result.error === 'disabled') throw new Error('云主机未配置 Github 凭据申请环境');
209
+ throw new Error(result.error || 'Github 凭据申请失败');
210
+ };
211
+
212
+ let controllerSocket: Socket | null = null;
213
+ let initWaitTimer: ReturnType<typeof setTimeout> | null = null;
214
+ let waitingForInit = false;
215
+ let initBatchCompleted = false;
216
+ let shutdownStarted = false;
217
+
218
+ const clearInitTimer = (): void => {
219
+ if (initWaitTimer) {
220
+ clearTimeout(initWaitTimer);
221
+ initWaitTimer = null;
222
+ }
223
+ };
224
+
225
+ const shutdown = (reason: string, code?: number): void => {
226
+ if (shutdownStarted) return;
227
+ shutdownStarted = true;
228
+ clearInitTimer();
229
+ const exitCode = code ?? resolveShutdownExitCode(reason);
230
+ log(`[CloudHost] shutting down: ${reason} (exit ${exitCode})`);
231
+ credentialManager.stop();
232
+ try {
233
+ workerSocket.disconnect();
234
+ } catch {
235
+ /* socket may already be closed */
236
+ }
237
+ try {
238
+ controllerSocket?.disconnect();
239
+ } catch {
240
+ /* socket may already be closed */
241
+ }
242
+ // 不发送 unregister:容器销毁由 agent-api 编排(stopCloudHost / TTL / 失败回调)。
243
+ // 失败/版本不兼容路径必须非零退出:Job 终态映射为 failed,且 entrypoint 的自愈升级生效(C-2)。
244
+ exit(exitCode);
245
+ };
246
+
247
+ const connectController = (): void => {
248
+ if (controllerSocket) return;
249
+ clearInitTimer();
250
+ waitingForInit = false;
251
+ log(`[CloudHost] connecting controller-api: ${describeEndpoint(env.hostEndpoint)}`);
252
+ controllerSocket = connect(env.hostEndpoint, env.hostKey, {
253
+ serverName: env.hostName,
254
+ handshakeToken: env.hostKey,
255
+ handleWorkload: false,
256
+ skipLocalMcpStart: false,
257
+ persistConfig: false,
258
+ onShutdown: (payload) => shutdown(`controller-api shutdown: ${payload.reason}`),
259
+ });
260
+ };
261
+
262
+ const waitForInitBatch = (): void => {
263
+ if (initBatchCompleted) {
264
+ connectController();
265
+ return;
266
+ }
267
+ if (waitingForInit) return;
268
+ waitingForInit = true;
269
+ log(`[CloudHost] waiting for harness initialization (timeout ${env.initWaitMs}ms)`);
270
+ initWaitTimer = setTimeout(() => {
271
+ initWaitTimer = null;
272
+ // 超时后视为已完成:迟到的 registered(initializing=true) 不得再次进入等待(幽灵定时器)。
273
+ initBatchCompleted = true;
274
+ log('[CloudHost] harness initialization wait timed out; connecting controller-api anyway');
275
+ connectController();
276
+ }, env.initWaitMs);
277
+ };
278
+
279
+ const workerSocket = connect(env.serverEndpoint, env.controllerKey, {
280
+ serverName: env.hostName,
281
+ handshakeToken: env.controllerKey,
282
+ handleWorkload: true,
283
+ skipLocalMcpStart: true,
284
+ persistConfig: false,
285
+ onBeforeWorkloadBatch: beforeWorkloadBatch,
286
+ onRegistered: (payload) => {
287
+ log(`[CloudHost] worker registered: ${payload.controllerId}${payload.initializing ? ' (initializing)' : ''}`);
288
+ if (payload.initializing) {
289
+ waitForInitBatch();
290
+ } else {
291
+ connectController();
292
+ }
293
+ },
294
+ onWorkloadBatchComplete: (summary) => {
295
+ if (summary.phase !== 'init') return;
296
+ if (summary.cancelled || summary.status === 'cancelled') {
297
+ // 被新批次/销毁打断:不得视为初始化完成(重连重放 init 时 OpenCode 可能仍在安装)。
298
+ log('[CloudHost] harness initialization interrupted; waiting for replay');
299
+ return;
300
+ }
301
+ initBatchCompleted = true;
302
+ if (waitingForInit) {
303
+ log(
304
+ `[CloudHost] harness initialization finished (${summary.status}` +
305
+ `${summary.failedCount ? `, failed=${summary.failedCount}` : ''}); connecting controller-api`,
306
+ );
307
+ connectController();
308
+ }
309
+ },
310
+ onShutdown: (payload) => shutdown(`worker shutdown: ${payload.reason}`),
311
+ });
312
+
313
+ if (deps.installSignalHandlers !== false) {
314
+ process.once('SIGINT', () => shutdown('SIGINT'));
315
+ process.once('SIGTERM', () => shutdown('SIGTERM'));
316
+ }
317
+
318
+ return {
319
+ workerSocket,
320
+ get controllerSocket() {
321
+ return controllerSocket;
322
+ },
323
+ workspace: env.workspace,
324
+ shutdown,
325
+ };
326
+ }
@@ -0,0 +1,44 @@
1
+ import type { Command } from 'commander';
2
+ import { collectSecretValues, redactSecrets } from '../workload-executor.js';
3
+ import { formatPrepareSummary, prepareHarness, type PrepareHarnessOptions } from '../harness/prepare.js';
4
+
5
+ export interface RegisterHarnessCommandsDeps {
6
+ prepare?: (options?: PrepareHarnessOptions) => Promise<Awaited<ReturnType<typeof prepareHarness>>>;
7
+ }
8
+
9
+ /**
10
+ * 注册 `agent-gear harness` 命令组。
11
+ *
12
+ * ```
13
+ * agent-gear harness prepare # 校验 env → opencode --version → 写 opencode.jsonc
14
+ * ```
15
+ *
16
+ * 失败以退出码 1 结束(供 harness 工作负载 `required=true` 触发容器强制注销);
17
+ * 输出/错误均对 `ZAG_MODEL_API_KEY` 等 secret 脱敏。
18
+ */
19
+ export function registerHarnessCommands(
20
+ program: Command,
21
+ deps: RegisterHarnessCommandsDeps = {},
22
+ ): Command {
23
+ const harness = program
24
+ .command('harness')
25
+ .description('Prepare harness runtime (OpenCode) for cloud-host containers');
26
+
27
+ harness
28
+ .command('prepare')
29
+ .description('Validate harness env, verify OpenCode CLI and write provider.zag into opencode.jsonc')
30
+ .action(async () => {
31
+ try {
32
+ const result = await (deps.prepare ?? prepareHarness)();
33
+ console.log(formatPrepareSummary(result));
34
+ } catch (error) {
35
+ const secrets = collectSecretValues(process.env);
36
+ const message = redactSecrets((error as Error).message, secrets);
37
+ console.error(`harness prepare failed: ${message}`);
38
+ // 非零退出:不直接 process.exit,便于测试断言 exitCode 与已刷新的日志。
39
+ process.exitCode = 1;
40
+ }
41
+ });
42
+
43
+ return harness;
44
+ }
package/src/config.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
1
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  import { homedir } from 'os';
4
4
  import { parse, stringify } from 'smol-toml';
@@ -23,9 +23,15 @@ export function readConfig(): ConfigData {
23
23
 
24
24
  export function writeConfig(data: ConfigData): void {
25
25
  if (!existsSync(CONFIG_DIR)) {
26
- mkdirSync(CONFIG_DIR, { recursive: true });
26
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
27
+ }
28
+ // 配置含 Key/resumeToken:仅属主可读写(避免 world-readable 凭据落盘)。
29
+ writeFileSync(CONFIG_FILE, stringify(data), { encoding: 'utf-8', mode: 0o600 });
30
+ try {
31
+ chmodSync(CONFIG_FILE, 0o600);
32
+ } catch {
33
+ // 某些平台/文件系统不支持 chmod:不阻断配置写入(已在 Windows 等平台降级)
27
34
  }
28
- writeFileSync(CONFIG_FILE, stringify(data), 'utf-8');
29
35
  }
30
36
 
31
37
  export function clearConfigKey(): void {
@@ -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
+ });