agent-gear 2.13.0 → 2.15.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 (165) hide show
  1. package/AGENTS.md +24 -11
  2. package/dist/acp/bridge.d.ts +4 -0
  3. package/dist/acp/bridge.d.ts.map +1 -1
  4. package/dist/acp/bridge.js +72 -45
  5. package/dist/acp/bridge.js.map +1 -1
  6. package/dist/acp/bridge.test.js +40 -33
  7. package/dist/acp/bridge.test.js.map +1 -1
  8. package/dist/acp/process-registry.d.ts.map +1 -1
  9. package/dist/acp/process-registry.js +3 -1
  10. package/dist/acp/process-registry.js.map +1 -1
  11. package/dist/acp/process-registry.test.js +1 -0
  12. package/dist/acp/process-registry.test.js.map +1 -1
  13. package/dist/acp/spawner.d.ts +15 -0
  14. package/dist/acp/spawner.d.ts.map +1 -1
  15. package/dist/acp/spawner.js +51 -4
  16. package/dist/acp/spawner.js.map +1 -1
  17. package/dist/acp/sync-bridge.d.ts.map +1 -1
  18. package/dist/acp/sync-bridge.js +3 -1
  19. package/dist/acp/sync-bridge.js.map +1 -1
  20. package/dist/cloud-host/supervisor.d.ts +3 -1
  21. package/dist/cloud-host/supervisor.d.ts.map +1 -1
  22. package/dist/cloud-host/supervisor.js +18 -12
  23. package/dist/cloud-host/supervisor.js.map +1 -1
  24. package/dist/cloud-host/supervisor.test.js +19 -14
  25. package/dist/cloud-host/supervisor.test.js.map +1 -1
  26. package/dist/commands/harness.d.ts.map +1 -1
  27. package/dist/commands/harness.js +4 -2
  28. package/dist/commands/harness.js.map +1 -1
  29. package/dist/commands/mcp-proxy.d.ts +2 -1
  30. package/dist/commands/mcp-proxy.d.ts.map +1 -1
  31. package/dist/commands/mcp-proxy.js +26 -18
  32. package/dist/commands/mcp-proxy.js.map +1 -1
  33. package/dist/commands/mcp.js +1 -1
  34. package/dist/commands/mcp.js.map +1 -1
  35. package/dist/gateway.d.ts +3 -0
  36. package/dist/gateway.d.ts.map +1 -1
  37. package/dist/gateway.js +14 -8
  38. package/dist/gateway.js.map +1 -1
  39. package/dist/gateway.test.js +9 -4
  40. package/dist/gateway.test.js.map +1 -1
  41. package/dist/github/commit-identity-manager.d.ts +3 -1
  42. package/dist/github/commit-identity-manager.d.ts.map +1 -1
  43. package/dist/github/commit-identity-manager.js +13 -6
  44. package/dist/github/commit-identity-manager.js.map +1 -1
  45. package/dist/github/commit-identity-manager.test.js +26 -24
  46. package/dist/github/commit-identity-manager.test.js.map +1 -1
  47. package/dist/github/credential-manager.d.ts +3 -1
  48. package/dist/github/credential-manager.d.ts.map +1 -1
  49. package/dist/github/credential-manager.js +18 -10
  50. package/dist/github/credential-manager.js.map +1 -1
  51. package/dist/github/credential-manager.test.js +36 -33
  52. package/dist/github/credential-manager.test.js.map +1 -1
  53. package/dist/index.d.ts +1 -0
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +77 -70
  56. package/dist/index.js.map +1 -1
  57. package/dist/mcp/local-server.d.ts +3 -1
  58. package/dist/mcp/local-server.d.ts.map +1 -1
  59. package/dist/mcp/local-server.js +19 -9
  60. package/dist/mcp/local-server.js.map +1 -1
  61. package/dist/mcp/relay.d.ts +3 -1
  62. package/dist/mcp/relay.d.ts.map +1 -1
  63. package/dist/mcp/relay.js +20 -12
  64. package/dist/mcp/relay.js.map +1 -1
  65. package/dist/observability/http-context.d.ts +32 -0
  66. package/dist/observability/http-context.d.ts.map +1 -0
  67. package/dist/observability/http-context.js +97 -0
  68. package/dist/observability/http-context.js.map +1 -0
  69. package/dist/observability/log-context.d.ts +19 -0
  70. package/dist/observability/log-context.d.ts.map +1 -0
  71. package/dist/observability/log-context.js +21 -0
  72. package/dist/observability/log-context.js.map +1 -0
  73. package/dist/observability/logger.d.ts +31 -0
  74. package/dist/observability/logger.d.ts.map +1 -0
  75. package/dist/observability/logger.js +129 -0
  76. package/dist/observability/logger.js.map +1 -0
  77. package/dist/observability/no-console.test.d.ts +2 -0
  78. package/dist/observability/no-console.test.d.ts.map +1 -0
  79. package/dist/observability/no-console.test.js +78 -0
  80. package/dist/observability/no-console.test.js.map +1 -0
  81. package/dist/observability/register.d.ts +2 -0
  82. package/dist/observability/register.d.ts.map +1 -0
  83. package/dist/observability/register.js +29 -0
  84. package/dist/observability/register.js.map +1 -0
  85. package/dist/observability/telemetry.d.ts +12 -0
  86. package/dist/observability/telemetry.d.ts.map +1 -0
  87. package/dist/observability/telemetry.js +164 -0
  88. package/dist/observability/telemetry.js.map +1 -0
  89. package/dist/observability/testing.d.ts +24 -0
  90. package/dist/observability/testing.d.ts.map +1 -0
  91. package/dist/observability/testing.js +31 -0
  92. package/dist/observability/testing.js.map +1 -0
  93. package/dist/observability/trace.d.ts +42 -0
  94. package/dist/observability/trace.d.ts.map +1 -0
  95. package/dist/observability/trace.js +123 -0
  96. package/dist/observability/trace.js.map +1 -0
  97. package/dist/socketio-client.auth-gate.test.js +0 -3
  98. package/dist/socketio-client.auth-gate.test.js.map +1 -1
  99. package/dist/socketio-client.d.ts +3 -0
  100. package/dist/socketio-client.d.ts.map +1 -1
  101. package/dist/socketio-client.js +141 -70
  102. package/dist/socketio-client.js.map +1 -1
  103. package/dist/socketio-client.test.js +0 -6
  104. package/dist/socketio-client.test.js.map +1 -1
  105. package/dist/startup-span.d.ts +15 -0
  106. package/dist/startup-span.d.ts.map +1 -0
  107. package/dist/startup-span.js +21 -0
  108. package/dist/startup-span.js.map +1 -0
  109. package/dist/startup-span.test.d.ts +2 -0
  110. package/dist/startup-span.test.d.ts.map +1 -0
  111. package/dist/startup-span.test.js +71 -0
  112. package/dist/startup-span.test.js.map +1 -0
  113. package/dist/worktree-handler.d.ts +4 -1
  114. package/dist/worktree-handler.d.ts.map +1 -1
  115. package/dist/worktree-handler.js +10 -4
  116. package/dist/worktree-handler.js.map +1 -1
  117. package/dist/worktree-handler.test.js +6 -7
  118. package/dist/worktree-handler.test.js.map +1 -1
  119. package/package.json +21 -10
  120. package/pnpm-workspace.yaml +3 -0
  121. package/src/acp/bridge.test.ts +63 -34
  122. package/src/acp/bridge.ts +95 -51
  123. package/src/acp/process-registry.test.ts +1 -0
  124. package/src/acp/process-registry.ts +4 -1
  125. package/src/acp/spawner.ts +68 -4
  126. package/src/acp/sync-bridge.ts +4 -1
  127. package/src/cloud-host/supervisor.test.ts +25 -14
  128. package/src/cloud-host/supervisor.ts +29 -14
  129. package/src/commands/harness.ts +4 -2
  130. package/src/commands/mcp-proxy.ts +41 -18
  131. package/src/commands/mcp.ts +1 -1
  132. package/src/gateway.test.ts +10 -5
  133. package/src/gateway.ts +15 -8
  134. package/src/github/commit-identity-manager.test.ts +30 -24
  135. package/src/github/commit-identity-manager.ts +19 -9
  136. package/src/github/credential-manager.test.ts +42 -33
  137. package/src/github/credential-manager.ts +28 -15
  138. package/src/index.ts +85 -74
  139. package/src/mcp/local-server.ts +31 -9
  140. package/src/mcp/relay.ts +32 -13
  141. package/src/observability/http-context.ts +122 -0
  142. package/src/observability/log-context.ts +39 -0
  143. package/src/observability/logger.ts +160 -0
  144. package/src/observability/no-console.test.ts +99 -0
  145. package/src/observability/register.ts +34 -0
  146. package/src/observability/telemetry.ts +180 -0
  147. package/src/observability/testing.ts +51 -0
  148. package/src/observability/trace.ts +163 -0
  149. package/src/socketio-client.auth-gate.test.ts +0 -3
  150. package/src/socketio-client.test.ts +0 -6
  151. package/src/socketio-client.ts +211 -70
  152. package/src/startup-span.test.ts +83 -0
  153. package/src/startup-span.ts +27 -0
  154. package/src/worktree-handler.test.ts +10 -7
  155. package/src/worktree-handler.ts +12 -8
  156. package/tests/acp-bridge.test.ts +11 -3
  157. package/tests/acp-spawner.test.ts +119 -14
  158. package/tests/acp-wire-elicitation.test.ts +0 -3
  159. package/tests/acp-wire-mcp.test.ts +9 -6
  160. package/tests/commands/harness.test.ts +6 -0
  161. package/tests/commands/mcp-proxy-dispatcher.test.ts +0 -2
  162. package/tests/commands/mcp-proxy.test.ts +43 -0
  163. package/tests/commands/mcp.test.ts +4 -0
  164. package/tests/socketio-client.test.ts +114 -36
  165. package/vitest.config.ts +3 -0
@@ -5,6 +5,7 @@ import {
5
5
  EXPIRY_SKEW_MS,
6
6
  BACKOFF_MS,
7
7
  } from './credential-manager.js';
8
+ import { createTestLogger, type TestLogger } from '../observability/testing.js';
8
9
 
9
10
  const TOKEN = 'ghs_credential_manager_secret';
10
11
  const BASE_ENV: NodeJS.ProcessEnv = {
@@ -60,7 +61,7 @@ describe('GithubCredentialManager', () => {
60
61
  env: BASE_ENV,
61
62
  fetch: fetchFn,
62
63
  writeGhAuth,
63
- log: () => {},
64
+ log: createTestLogger().logger,
64
65
  });
65
66
 
66
67
  const result = await manager.refreshNow();
@@ -86,13 +87,13 @@ describe('GithubCredentialManager', () => {
86
87
  it('T-CM2: 404 means no binding: no write, no error log, returns no-binding', async () => {
87
88
  const fetchFn = fakeFetch(async () => new Response('', { status: 404 }));
88
89
  const writeGhAuth = vi.fn(async () => {});
89
- const logs: string[] = [];
90
+ const testLog: TestLogger = createTestLogger();
90
91
 
91
92
  const manager = new GithubCredentialManager({
92
93
  env: BASE_ENV,
93
94
  fetch: fetchFn,
94
95
  writeGhAuth,
95
- log: (message) => logs.push(message),
96
+ log: testLog.logger,
96
97
  });
97
98
 
98
99
  const result = await manager.refreshNow();
@@ -100,20 +101,22 @@ describe('GithubCredentialManager', () => {
100
101
  expect(result).toEqual({ ok: false, error: 'no-binding' });
101
102
  expect(writeGhAuth).not.toHaveBeenCalled();
102
103
  expect(fetchFn).toHaveBeenCalledTimes(1);
103
- expect(logs.join('\n')).not.toMatch(/error|失败|warn/i);
104
+ // no-binding 属正常态:无任何告警/错误日志
105
+ expect(testLog.records.filter((r) => r.level === 'warn' || r.level === 'error')).toEqual([]);
106
+ expect(JSON.stringify(testLog.records)).not.toMatch(/失败/);
104
107
  });
105
108
 
106
109
  it('T-CM3: 401 retries with 1/2/4 minute backoff and eventually returns a readable error', async () => {
107
110
  const fetchFn = fakeFetch(async () => new Response('', { status: 401 }));
108
111
  const delays: number[] = [];
109
- const logs: string[] = [];
112
+ const testLog: TestLogger = createTestLogger();
110
113
  const writeGhAuth = vi.fn(async () => {});
111
114
 
112
115
  const manager = new GithubCredentialManager({
113
116
  env: BASE_ENV,
114
117
  fetch: fetchFn,
115
118
  writeGhAuth,
116
- log: (message) => logs.push(message),
119
+ log: testLog.logger,
117
120
  sleep: async (ms) => {
118
121
  delays.push(ms);
119
122
  },
@@ -126,7 +129,7 @@ describe('GithubCredentialManager', () => {
126
129
  expect(delays).toEqual([...BACKOFF_MS]);
127
130
  expect(fetchFn).toHaveBeenCalledTimes(BACKOFF_MS.length + 1);
128
131
  expect(writeGhAuth).not.toHaveBeenCalled();
129
- expect(logs.join('\n')).not.toContain(TOKEN);
132
+ expect(JSON.stringify(testLog.records)).not.toContain(TOKEN);
130
133
  });
131
134
 
132
135
  it('T-CM4: schedules every 50 minutes, or earlier when the token expires within the skew', async () => {
@@ -141,7 +144,7 @@ describe('GithubCredentialManager', () => {
141
144
  fetch: fetchFn,
142
145
  writeGhAuth: async () => {},
143
146
  now: () => now,
144
- log: () => {},
147
+ log: createTestLogger().logger,
145
148
  setTimeout: scheduler.setTimeoutFn,
146
149
  });
147
150
 
@@ -164,7 +167,7 @@ describe('GithubCredentialManager', () => {
164
167
  fetch: earlyFetch,
165
168
  writeGhAuth: async () => {},
166
169
  now: () => now,
167
- log: () => {},
170
+ log: createTestLogger().logger,
168
171
  setTimeout: earlyScheduler.setTimeoutFn,
169
172
  });
170
173
  earlyManager.start();
@@ -189,7 +192,7 @@ describe('GithubCredentialManager', () => {
189
192
  fetch: fetchFn,
190
193
  writeGhAuth: async () => {},
191
194
  now: () => now,
192
- log: () => {},
195
+ log: createTestLogger().logger,
193
196
  setTimeout: scheduler.setTimeoutFn,
194
197
  });
195
198
 
@@ -227,7 +230,7 @@ describe('GithubCredentialManager', () => {
227
230
  fetch: fetchFn,
228
231
  writeGhAuth,
229
232
  now: () => now,
230
- log: () => {},
233
+ log: createTestLogger().logger,
231
234
  setTimeout: scheduler.setTimeoutFn,
232
235
  });
233
236
 
@@ -251,27 +254,28 @@ describe('GithubCredentialManager', () => {
251
254
  ];
252
255
 
253
256
  for (const scenario of scenarios) {
254
- const logs: string[] = [];
257
+ const testLog: TestLogger = createTestLogger();
255
258
  const manager = new GithubCredentialManager({
256
259
  env: BASE_ENV,
257
260
  fetch: fakeFetch(scenario),
258
261
  writeGhAuth: async () => {},
259
- log: (message) => logs.push(message),
262
+ log: testLog.logger,
260
263
  });
261
264
 
262
265
  const result = await manager.refreshNow();
263
266
 
264
267
  expect(result.ok).toBe(false);
265
- const joined = logs.join('\n');
266
- expect(joined).toContain('[GithubCredential] 凭据续期失败');
267
- expect(joined).not.toContain(TOKEN);
268
+ expect(testLog.records).toContainEqual(
269
+ expect.objectContaining({ component: 'github-credential', msg: '凭据续期失败' }),
270
+ );
271
+ expect(JSON.stringify(testLog.records)).not.toContain(TOKEN);
268
272
  }
269
273
  });
270
274
 
271
275
  it('T-CM12: 进入近过期区首次立即重试、其后按短间隔退避,并留下不含 token 的告警日志', async () => {
272
276
  const t0 = Date.parse('2026-10-22T10:00:00.000Z');
273
277
  let now = t0;
274
- const logs: string[] = [];
278
+ const testLog: TestLogger = createTestLogger();
275
279
  // 服务端持续返回近过期 token(复现 R1 未修复时的缓存命中)
276
280
  const minted = new Date(t0 + 60 * 60 * 1000).toISOString();
277
281
  const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: minted }));
@@ -282,7 +286,7 @@ describe('GithubCredentialManager', () => {
282
286
  fetch: fetchFn,
283
287
  writeGhAuth: async () => {},
284
288
  now: () => now,
285
- log: (message) => logs.push(message),
289
+ log: testLog.logger,
286
290
  setTimeout: scheduler.setTimeoutFn,
287
291
  });
288
292
 
@@ -301,9 +305,10 @@ describe('GithubCredentialManager', () => {
301
305
  // 服务端仍返回近过期 token → 退到短间隔重试(60s),避免热循环打爆 agent-api
302
306
  expect(scheduler.timers[2].delay).toBe(60_000);
303
307
 
304
- const joined = logs.join('\n');
305
- expect(joined).toContain('[GithubCredential] 凭据剩余有效期不足');
306
- expect(joined).not.toContain(TOKEN);
308
+ expect(testLog.records).toContainEqual(
309
+ expect.objectContaining({ component: 'github-credential', msg: '凭据剩余有效期不足' }),
310
+ );
311
+ expect(JSON.stringify(testLog.records)).not.toContain(TOKEN);
307
312
 
308
313
  manager.stop();
309
314
  });
@@ -320,7 +325,7 @@ describe('GithubCredentialManager', () => {
320
325
  env: BASE_ENV,
321
326
  fetch: fetchFn,
322
327
  writeGhAuth,
323
- log: () => {},
328
+ log: createTestLogger().logger,
324
329
  });
325
330
 
326
331
  const first = manager.refreshNow();
@@ -335,20 +340,24 @@ describe('GithubCredentialManager', () => {
335
340
 
336
341
  it('T-CM6: missing env disables startup with a warn that only lists variable names', async () => {
337
342
  const fetchFn = fakeFetch(async () => jsonResponse({}));
338
- const logs: string[] = [];
343
+ const testLog: TestLogger = createTestLogger();
339
344
  const manager = new GithubCredentialManager({
340
345
  env: { ZAG_HOST_KEY: 'should-not-appear' },
341
346
  fetch: fetchFn,
342
- log: (message) => logs.push(message),
347
+ log: testLog.logger,
343
348
  });
344
349
 
345
350
  manager.start();
346
351
 
347
352
  expect(fetchFn).not.toHaveBeenCalled();
348
- const output = logs.join('\n');
349
- expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
350
- expect(output).toContain('ZAG_CONTROLLER_ID');
351
- expect(output).not.toContain('should-not-appear');
353
+ expect(testLog.records).toContainEqual(
354
+ expect.objectContaining({
355
+ component: 'github-credential',
356
+ msg: expect.stringContaining('disabled'),
357
+ missing: expect.arrayContaining(['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID']),
358
+ }),
359
+ );
360
+ expect(JSON.stringify(testLog.records)).not.toContain('should-not-appear');
352
361
  await expect(manager.refreshNow()).resolves.toEqual({ ok: false, error: 'disabled' });
353
362
  });
354
363
 
@@ -360,7 +369,7 @@ describe('GithubCredentialManager', () => {
360
369
  env: BASE_ENV,
361
370
  fetch: invalidJson,
362
371
  writeGhAuth: async () => {},
363
- log: () => {},
372
+ log: createTestLogger().logger,
364
373
  });
365
374
  const invalid = await manager.refreshNow();
366
375
  expect(invalid.ok).toBe(false);
@@ -373,7 +382,7 @@ describe('GithubCredentialManager', () => {
373
382
  env: BASE_ENV,
374
383
  fetch: network,
375
384
  writeGhAuth: async () => {},
376
- log: () => {},
385
+ log: createTestLogger().logger,
377
386
  });
378
387
  const failed = await networkManager.refreshNow();
379
388
  expect(failed.ok).toBe(false);
@@ -381,7 +390,7 @@ describe('GithubCredentialManager', () => {
381
390
  });
382
391
 
383
392
  it('T-CM8: logs and returned errors never contain the token', async () => {
384
- const logs: string[] = [];
393
+ const testLog: TestLogger = createTestLogger();
385
394
  const fetchFn = fakeFetch(async () => jsonResponse({ token: TOKEN, expiresAt: EXPIRES_AT }));
386
395
  const manager = new GithubCredentialManager({
387
396
  env: BASE_ENV,
@@ -389,13 +398,13 @@ describe('GithubCredentialManager', () => {
389
398
  writeGhAuth: async () => {
390
399
  throw new Error(`unable to write ${TOKEN}`);
391
400
  },
392
- log: (message) => logs.push(message),
401
+ log: testLog.logger,
393
402
  });
394
403
 
395
404
  const result = await manager.refreshNow();
396
405
 
397
406
  expect(result.ok).toBe(false);
398
- expect(logs.join('\n')).not.toContain(TOKEN);
407
+ expect(JSON.stringify(testLog.records)).not.toContain(TOKEN);
399
408
  // writeGhAuth 的实现负责脱敏;管理器不额外拼接 token
400
409
  expect(JSON.stringify(result)).not.toContain(TOKEN);
401
410
  });
@@ -1,5 +1,7 @@
1
1
  import { writeGhAuth } from './gh-config.js';
2
2
  import { redactSecrets } from '../workload-executor.js';
3
+ import type { Logger as PinoLogger } from 'pino';
4
+ import { logger as rootLogger } from '../observability/logger.js';
3
5
 
4
6
  /** 定时续期间隔(50 分钟,覆盖 Github App installation token 约 1 小时有效期)。 */
5
7
  export const REFRESH_INTERVAL_MS = 50 * 60 * 1000;
@@ -26,7 +28,8 @@ export interface GithubCredentialManagerDeps {
26
28
  fetch?: typeof fetch;
27
29
  writeGhAuth?: (token: string) => Promise<void>;
28
30
  now?: () => number;
29
- log?: (message: string) => void;
31
+ /** 注入 logger(测试用);缺省进程级单例,`component: 'github-credential'`。 */
32
+ log?: PinoLogger;
30
33
  /** 定时器注入(测试用);缺省使用全局 `setTimeout`。 */
31
34
  setTimeout?: typeof setTimeout;
32
35
  /** 退避等待注入(测试用);缺省使用 `setTimeout`。 */
@@ -60,7 +63,7 @@ export class GithubCredentialManager {
60
63
  private readonly fetchFn: typeof fetch;
61
64
  private readonly writeAuth: (token: string) => Promise<void>;
62
65
  private readonly now: () => number;
63
- private readonly log: (message: string) => void;
66
+ private readonly log: PinoLogger;
64
67
  private readonly setTimeoutFn: typeof setTimeout;
65
68
  private readonly sleepFn: (ms: number) => Promise<void>;
66
69
 
@@ -77,7 +80,8 @@ export class GithubCredentialManager {
77
80
  this.fetchFn = deps.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args));
78
81
  this.writeAuth = deps.writeGhAuth ?? ((token: string) => writeGhAuth(token));
79
82
  this.now = deps.now ?? (() => Date.now());
80
- this.log = deps.log ?? ((message: string) => console.log(message));
83
+ // component 固定绑定:无论注入哪路 logger,`[GithubCredential]` 前缀语义由 component 字段承接
84
+ this.log = (deps.log ?? rootLogger).child({ component: 'github-credential' });
81
85
  this.setTimeoutFn = deps.setTimeout ?? setTimeout;
82
86
  this.sleepFn =
83
87
  deps.sleep ??
@@ -99,7 +103,7 @@ export class GithubCredentialManager {
99
103
  this.stopped = false;
100
104
  const missing = this.missingEnv();
101
105
  if (missing.length > 0) {
102
- this.log(`[GithubCredential] disabled: missing environment variable(s): ${missing.join(', ')}`);
106
+ this.log.warn({ event: 'disabled', missing }, 'github credential manager disabled: missing environment variables');
103
107
  return;
104
108
  }
105
109
  this.started = true;
@@ -146,9 +150,15 @@ export class GithubCredentialManager {
146
150
  const result = await this.request(url, hostKey);
147
151
  if (result.kind === 'retryable' && attempt < BACKOFF_MS.length) {
148
152
  const delay = BACKOFF_MS[attempt]!;
149
- this.log(
150
- `[GithubCredential] 凭据无效(HTTP ${result.status}),${Math.round(delay / 60_000)} 分钟后重试` +
151
- `(${attempt + 1}/${BACKOFF_MS.length})`,
153
+ this.log.warn(
154
+ {
155
+ event: 'credential_invalid_retry',
156
+ status: result.status,
157
+ delayMs: delay,
158
+ attempt: attempt + 1,
159
+ maxAttempts: BACKOFF_MS.length,
160
+ },
161
+ '凭据无效,稍后重试',
152
162
  );
153
163
  await this.sleepFn(delay);
154
164
  continue;
@@ -161,7 +171,7 @@ export class GithubCredentialManager {
161
171
  // 非 401/403/404 的失败(5xx / 超时 / 非法 JSON / 写 gh 失败)必须留痕,
162
172
  // 否则线上只能看到「凭据没更新」而无任何线索;`disabled`/`no-binding` 属正常态不告警。
163
173
  if (!value.ok && value.error && value.error !== 'no-binding' && value.error !== 'disabled') {
164
- this.log(`[GithubCredential] 凭据续期失败:${value.error}`);
174
+ this.log.error({ event: 'renew_failed', error: value.error }, '凭据续期失败');
165
175
  }
166
176
  return value;
167
177
  }
@@ -225,10 +235,9 @@ export class GithubCredentialManager {
225
235
  }
226
236
 
227
237
  this.expiresAt = expiresAt ?? null;
228
- this.log(
229
- expiresAt
230
- ? `[GithubCredential] gh 凭据已更新,有效期至 ${expiresAt.toISOString()}`
231
- : '[GithubCredential] gh 凭据已更新',
238
+ this.log.info(
239
+ { event: 'credential_updated', ...(expiresAt ? { expiresAt: expiresAt.toISOString() } : {}) },
240
+ 'gh 凭据已更新',
232
241
  );
233
242
  return { kind: 'result', value: { ok: true, expiresAt } };
234
243
  } catch (error) {
@@ -253,9 +262,13 @@ export class GithubCredentialManager {
253
262
  if (beforeExpiry <= 0) {
254
263
  delay = this.nearExpiryImmediateTaken ? NEAR_EXPIRY_RETRY_MS : 0;
255
264
  this.nearExpiryImmediateTaken = true;
256
- this.log(
257
- `[GithubCredential] 凭据剩余有效期不足(至 ${this.expiresAt.toISOString()}),` +
258
- (delay === 0 ? '立即重试' : `${Math.round(delay / 1000)} 秒后重试`),
265
+ this.log.warn(
266
+ {
267
+ event: 'near_expiry',
268
+ expiresAt: this.expiresAt.toISOString(),
269
+ delayMs: delay,
270
+ },
271
+ '凭据剩余有效期不足',
259
272
  );
260
273
  } else {
261
274
  this.nearExpiryImmediateTaken = false;
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import './observability/register.js';
2
3
  import { Command } from 'commander';
3
4
  import { createRequire } from 'node:module';
4
5
  import { hostname, platform } from 'os';
@@ -10,6 +11,8 @@ import { startMcpProxy } from './commands/mcp.js';
10
11
  import { registerHarnessCommands } from './commands/harness.js';
11
12
  import { isCloudHostMode, startCloudHostSupervisor } from './cloud-host/supervisor.js';
12
13
  import { processRegistry, isProcessAlive } from './acp/process-registry.js';
14
+ import { logger as rootLogger } from './observability/logger.js';
15
+ import { withStartupSpan } from './startup-span.js';
13
16
  export {
14
17
  EXIT_SERVER_SHUTDOWN,
15
18
  isFailureShutdownReason,
@@ -23,6 +26,8 @@ const { version: CLI_VERSION } = createRequire(import.meta.url)('../package.json
23
26
  version: string;
24
27
  };
25
28
 
29
+ const log = rootLogger.child({ component: 'index' });
30
+
26
31
  const program = new Command();
27
32
 
28
33
  program
@@ -33,86 +38,92 @@ program
33
38
  .option('-s, --server <endpoint>', 'Server endpoint URL')
34
39
  .option('-n, --name <name>', 'Controller name')
35
40
  .action(async (options) => {
36
- if (isRunning()) {
37
- console.error('Controller is already running. Stop it first or remove the PID file.');
38
- process.exit(1);
39
- }
40
-
41
- // 云电脑模式(`ZAG_HOST_ENDPOINT` + `ZAG_HOST_KEY` + `ZAG_CONTROLLER_KEY` 同时存在):
42
- // 双连接编排(/worker 初始化 → controller-api 标准连接),不读取/写入本地 key 配置。
43
- if (isCloudHostMode()) {
44
- writePid();
45
- process.on('exit', () => {
46
- removePid();
47
- });
48
- try {
49
- await startCloudHostSupervisor();
50
- } catch (error) {
51
- console.error(`Cloud host supervisor failed: ${(error as Error).message}`);
52
- removePid();
53
- process.exit(1);
54
- }
55
- return;
56
- }
57
-
58
- const key = resolveKey(options.key);
59
- if (!key) {
60
- console.error('No key provided. Use --key, ZAG_CONTROLLER_KEY env, or configure in ~/.zag/config.toml');
61
- process.exit(1);
62
- }
63
-
64
- const endpoint = resolveEndpoint(options.server);
65
- if (!endpoint) {
66
- console.error('No server endpoint provided. Use --server, ZAG_SERVER_ENDPOINT env, or configure in ~/.zag/config.toml');
67
- process.exit(1);
68
- }
69
-
70
- if (options.key) saveKeyToConfig(options.key);
71
- if (options.server) saveEndpointToConfig(options.server);
72
-
73
- writePid();
74
-
75
- const socket = connectToServer(endpoint, key, {
76
- serverName: options.name || hostname(),
77
- });
41
+ // 启动链路一个 startup span;ZAG_INIT_TRACEPARENT(云电脑 Job env)以 link 关联创建链路(T-OBS18)。
42
+ await withStartupSpan(
43
+ { 'agent.mode': isCloudHostMode() ? 'cloud-host' : 'local', 'agent.version': CLI_VERSION },
44
+ async () => {
45
+ if (isRunning()) {
46
+ log.error('Controller is already running. Stop it first or remove the PID file.');
47
+ process.exit(1);
48
+ }
78
49
 
79
- const shutdown = async () => {
80
- console.log('Shutting down...');
81
- // Kill all registered ACP processes before exiting, using the same
82
- // TERM → short wait → KILL semantics as the acp:stop handler
83
- const registered = processRegistry.listEntries();
84
- if (registered.length > 0) {
85
- console.log(`Killing ${registered.length} registered ACP process(es)...`);
86
- for (const entry of registered) {
50
+ // 云电脑模式(`ZAG_HOST_ENDPOINT` + `ZAG_HOST_KEY` + `ZAG_CONTROLLER_KEY` 同时存在):
51
+ // 双连接编排(/worker 初始化 → controller-api 标准连接),不读取/写入本地 key 配置。
52
+ if (isCloudHostMode()) {
53
+ writePid();
54
+ process.on('exit', () => {
55
+ removePid();
56
+ });
87
57
  try {
88
- if (platform() === 'win32') {
89
- const { execFileSync } = await import('child_process');
90
- execFileSync('taskkill', ['/PID', String(entry.pid), '/T', '/F'], { timeout: 5000 });
91
- } else {
92
- process.kill(-entry.pid, 'SIGTERM');
93
- }
94
- } catch { /* process may already be dead */ }
95
- }
96
- // Give processes a moment to exit
97
- await new Promise((r) => setTimeout(r, 1000));
98
- for (const entry of registered) {
99
- if (platform() !== 'win32' && isProcessAlive(entry.pid)) {
100
- try { process.kill(-entry.pid, 'SIGKILL'); } catch { /* already dead */ }
58
+ await startCloudHostSupervisor();
59
+ } catch (error) {
60
+ log.error({ err: error }, 'cloud host supervisor failed');
61
+ removePid();
62
+ process.exit(1);
101
63
  }
102
- processRegistry.deregister(entry.sessionId);
64
+ return;
65
+ }
66
+
67
+ const key = resolveKey(options.key);
68
+ if (!key) {
69
+ log.error('No key provided. Use --key, ZAG_CONTROLLER_KEY env, or configure in ~/.zag/config.toml');
70
+ process.exit(1);
103
71
  }
104
- }
105
- socket.disconnect();
106
- removePid();
107
- process.exit(0);
108
- };
109
72
 
110
- process.on('SIGINT', shutdown);
111
- process.on('SIGTERM', shutdown);
73
+ const endpoint = resolveEndpoint(options.server);
74
+ if (!endpoint) {
75
+ log.error('No server endpoint provided. Use --server, ZAG_SERVER_ENDPOINT env, or configure in ~/.zag/config.toml');
76
+ process.exit(1);
77
+ }
112
78
 
113
- process.on('exit', () => {
114
- removePid();
115
- });
79
+ if (options.key) saveKeyToConfig(options.key);
80
+ if (options.server) saveEndpointToConfig(options.server);
81
+
82
+ writePid();
83
+
84
+ const socket = connectToServer(endpoint, key, {
85
+ serverName: options.name || hostname(),
86
+ });
87
+
88
+ const shutdown = async () => {
89
+ log.info('shutting down');
90
+ // Kill all registered ACP processes before exiting, using the same
91
+ // TERM → short wait → KILL semantics as the acp:stop handler
92
+ const registered = processRegistry.listEntries();
93
+ if (registered.length > 0) {
94
+ log.info({ count: registered.length }, 'killing registered ACP processes');
95
+ for (const entry of registered) {
96
+ try {
97
+ if (platform() === 'win32') {
98
+ const { execFileSync } = await import('child_process');
99
+ execFileSync('taskkill', ['/PID', String(entry.pid), '/T', '/F'], { timeout: 5000 });
100
+ } else {
101
+ process.kill(-entry.pid, 'SIGTERM');
102
+ }
103
+ } catch { /* process may already be dead */ }
104
+ }
105
+ // Give processes a moment to exit
106
+ await new Promise((r) => setTimeout(r, 1000));
107
+ for (const entry of registered) {
108
+ if (platform() !== 'win32' && isProcessAlive(entry.pid)) {
109
+ try { process.kill(-entry.pid, 'SIGKILL'); } catch { /* already dead */ }
110
+ }
111
+ processRegistry.deregister(entry.sessionId);
112
+ }
113
+ }
114
+ socket.disconnect();
115
+ removePid();
116
+ process.exit(0);
117
+ };
118
+
119
+ process.on('SIGINT', shutdown);
120
+ process.on('SIGTERM', shutdown);
121
+
122
+ process.on('exit', () => {
123
+ removePid();
124
+ });
125
+ },
126
+ );
116
127
  });
117
128
 
118
129
  program
@@ -1,14 +1,17 @@
1
1
  import http from 'node:http';
2
2
  import { McpRelay } from './relay.js';
3
+ import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
3
4
 
4
5
  const MAX_BODY_BYTES = 16 * 1024 * 1024;
5
6
 
6
7
  export class LocalMcpServer {
7
8
  private relay: McpRelay;
8
9
  private server: http.Server;
10
+ private log: ObservationLogger;
9
11
 
10
- constructor(relay: McpRelay) {
12
+ constructor(relay: McpRelay, logger?: ObservationLogger) {
11
13
  this.relay = relay;
14
+ this.log = logger ?? rootLogger.child({ component: 'mcp-local' });
12
15
  this.server = http.createServer((req, res) => void this.handle(req, res));
13
16
  }
14
17
 
@@ -28,16 +31,16 @@ export class LocalMcpServer {
28
31
 
29
32
  private handle(req: http.IncomingMessage, res: http.ServerResponse): void {
30
33
  const startedAt = Date.now();
31
- console.log(`[MCP local] ${req.method} ${req.url} accept=${req.headers.accept ?? '-'}`);
34
+ this.log.debug({ event: 'mcp_request', method: req.method, url: req.url, accept: req.headers.accept ?? null }, 'mcp request');
32
35
  if (req.method !== 'POST') {
33
- console.log(`[MCP local] -> 405 (method not allowed)`);
36
+ this.log.debug({ event: 'mcp_request_rejected', status: 405, reason: 'method_not_allowed' }, 'mcp request rejected');
34
37
  res.writeHead(405);
35
38
  res.end();
36
39
  return;
37
40
  }
38
41
  const match = /^\/mcp\/([^/]+)\/([^/]+)\/?$/.exec(req.url ?? '');
39
42
  if (!match) {
40
- console.log(`[MCP local] -> 404 (bad path)`);
43
+ this.log.debug({ event: 'mcp_request_rejected', status: 404, reason: 'bad_path' }, 'mcp request rejected');
41
44
  res.writeHead(404);
42
45
  res.end();
43
46
  return;
@@ -46,19 +49,28 @@ export class LocalMcpServer {
46
49
  const serverName = decodeURIComponent(match[2]);
47
50
 
48
51
  if (!this.relay.hasSession(sessionId)) {
49
- console.log(`[MCP local] ${sessionId}/${serverName} -> 404 (session not registered in relay)`);
52
+ this.log.debug(
53
+ { event: 'mcp_request_rejected', status: 404, reason: 'session_not_registered', sessionId, serverName },
54
+ 'mcp request rejected',
55
+ );
50
56
  res.writeHead(404);
51
57
  res.end();
52
58
  return;
53
59
  }
54
60
  if (!this.relay.hasServer(sessionId, serverName)) {
55
- console.log(`[MCP local] ${sessionId}/${serverName} -> 404 (server not assembled in session)`);
61
+ this.log.debug(
62
+ { event: 'mcp_request_rejected', status: 404, reason: 'server_not_assembled', sessionId, serverName },
63
+ 'mcp request rejected',
64
+ );
56
65
  res.writeHead(404);
57
66
  res.end();
58
67
  return;
59
68
  }
60
69
  if (!req.headers.authorization) {
61
- console.log(`[MCP local] ${sessionId}/${serverName} -> 401 (missing Authorization)`);
70
+ this.log.debug(
71
+ { event: 'mcp_request_rejected', status: 401, reason: 'missing_authorization', sessionId, serverName },
72
+ 'mcp request rejected',
73
+ );
62
74
  res.writeHead(401);
63
75
  res.end();
64
76
  return;
@@ -93,11 +105,21 @@ export class LocalMcpServer {
93
105
  try {
94
106
  const rpcMethod = (body as { method?: string })?.method ?? '?';
95
107
  const result = await this.relay.forward(sessionId, serverName, body);
96
- console.log(`[MCP local] ${sessionId}/${serverName} ${rpcMethod} -> ${result.status} (${Date.now() - startedAt}ms)`);
108
+ this.log.debug(
109
+ {
110
+ event: 'mcp_request_completed',
111
+ sessionId,
112
+ serverName,
113
+ method: rpcMethod,
114
+ status: result.status,
115
+ durationMs: Date.now() - startedAt,
116
+ },
117
+ 'mcp request completed',
118
+ );
97
119
  res.writeHead(result.status, { 'Content-Type': 'application/json' });
98
120
  res.end(JSON.stringify(result.body));
99
121
  } catch (err) {
100
- console.error(`[MCP local] forward failed: session=${sessionId} server=${serverName}: ${(err as Error).message}`);
122
+ this.log.error({ event: 'mcp_forward_failed', sessionId, serverName, err }, 'mcp forward failed');
101
123
  res.writeHead(502, { 'Content-Type': 'application/json' });
102
124
  res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: 'FORWARD_ERROR', message: 'MCP forward failed' } }));
103
125
  }