agent-gear 2.12.0 → 2.14.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 (164) hide show
  1. package/AGENTS.md +20 -2
  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 +140 -69
  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 +25 -2
  114. package/dist/worktree-handler.d.ts.map +1 -1
  115. package/dist/worktree-handler.js +95 -5
  116. package/dist/worktree-handler.js.map +1 -1
  117. package/dist/worktree-handler.test.js +88 -5
  118. package/dist/worktree-handler.test.js.map +1 -1
  119. package/package.json +8 -1
  120. package/src/acp/bridge.test.ts +63 -34
  121. package/src/acp/bridge.ts +95 -51
  122. package/src/acp/process-registry.test.ts +1 -0
  123. package/src/acp/process-registry.ts +4 -1
  124. package/src/acp/spawner.ts +68 -4
  125. package/src/acp/sync-bridge.ts +4 -1
  126. package/src/cloud-host/supervisor.test.ts +25 -14
  127. package/src/cloud-host/supervisor.ts +29 -14
  128. package/src/commands/harness.ts +4 -2
  129. package/src/commands/mcp-proxy.ts +41 -18
  130. package/src/commands/mcp.ts +1 -1
  131. package/src/gateway.test.ts +10 -5
  132. package/src/gateway.ts +15 -8
  133. package/src/github/commit-identity-manager.test.ts +30 -24
  134. package/src/github/commit-identity-manager.ts +19 -9
  135. package/src/github/credential-manager.test.ts +42 -33
  136. package/src/github/credential-manager.ts +28 -15
  137. package/src/index.ts +85 -74
  138. package/src/mcp/local-server.ts +31 -9
  139. package/src/mcp/relay.ts +32 -13
  140. package/src/observability/http-context.ts +122 -0
  141. package/src/observability/log-context.ts +39 -0
  142. package/src/observability/logger.ts +160 -0
  143. package/src/observability/no-console.test.ts +99 -0
  144. package/src/observability/register.ts +34 -0
  145. package/src/observability/telemetry.ts +180 -0
  146. package/src/observability/testing.ts +51 -0
  147. package/src/observability/trace.ts +163 -0
  148. package/src/socketio-client.auth-gate.test.ts +0 -3
  149. package/src/socketio-client.test.ts +0 -6
  150. package/src/socketio-client.ts +220 -71
  151. package/src/startup-span.test.ts +83 -0
  152. package/src/startup-span.ts +27 -0
  153. package/src/worktree-handler.test.ts +106 -5
  154. package/src/worktree-handler.ts +116 -6
  155. package/tests/acp-bridge.test.ts +11 -3
  156. package/tests/acp-spawner.test.ts +119 -14
  157. package/tests/acp-wire-elicitation.test.ts +0 -3
  158. package/tests/acp-wire-mcp.test.ts +9 -6
  159. package/tests/commands/harness.test.ts +6 -0
  160. package/tests/commands/mcp-proxy-dispatcher.test.ts +0 -2
  161. package/tests/commands/mcp-proxy.test.ts +43 -0
  162. package/tests/commands/mcp.test.ts +4 -0
  163. package/tests/socketio-client.test.ts +114 -36
  164. package/vitest.config.ts +3 -0
@@ -2,12 +2,58 @@ import { spawn, execFileSync, execFile, type ChildProcess, type SpawnOptions } f
2
2
  import { Writable, Readable } from 'node:stream';
3
3
  import { existsSync, mkdirSync } from 'fs';
4
4
  import { platform } from 'os';
5
+ import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
6
+ import { collectSecretValues, redactSecrets, REDACTED } from '../workload-executor.js';
7
+
8
+ /** B4:ACP 子进程 stderr 单条入日志前的截断上限(脱敏后截断,原文长段不进日志)。 */
9
+ export const STDERR_LOG_MAX_CHARS = 500;
10
+
11
+ /**
12
+ * B4 敏感键值对(契约 §6.1 脱敏名单:token/key/password/secret 等 + authorization/cookie)。
13
+ * 覆盖 `键 = 值` / `键: 值` / JSON `"键":"值"` 形态,仅替换值、保留键名便于排障。
14
+ */
15
+ const SENSITIVE_KV_RE =
16
+ /\b(password[_-]?hash|passwords?|passwd|passphrase|pwd|model[_-]?api[_-]?key|api[_-]?key|private[_-]?key|client[_-]?secret|secrets?|access[_-]?token|refresh[_-]?token|id[_-]?token|tokens?|authorization|cookie|key)\b(["']?\s*[=:]\s*)(?:Bearer\s+|Basic\s+)?(?:"[^"]*"|'[^']*'|[^\s"'`,;)\]}]+)/gi;
17
+
18
+ /** B4 命令行 flag 形态(`--token <值>` / `--api-key=<值>`)。 */
19
+ const SENSITIVE_FLAG_RE =
20
+ /(--?(?:[A-Za-z0-9]+[-_])*(?:tokens?|keys?|secrets?|passwords?|passwd|credentials?))\b(["']?\s*[= ]\s*)(?:"[^"]*"|'[^']*'|[^\s"'`,;)\]}]+)/gi;
21
+
22
+ /** B4 形似凭据的串(GitHub/OpenAI/Slack/AWS/JWT/Bearer/zag key 等已知形态)。 */
23
+ const CREDENTIAL_LIKE_RES: RegExp[] = [
24
+ /\bgh[pousr]_[A-Za-z0-9]{16,}/g,
25
+ /\bgithub_pat_[A-Za-z0-9_]{16,}/g,
26
+ /\bsk-[A-Za-z0-9_-]{16,}/g,
27
+ /\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
28
+ /\bAKIA[0-9A-Z]{16}\b/g,
29
+ /\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
30
+ /\bBearer\s+[A-Za-z0-9._~+/=-]{16,}/gi,
31
+ /\bzag_(?:sk|k)_[A-Za-z0-9_-]{6,}/g,
32
+ ];
33
+
34
+ /**
35
+ * B4:ACP 子进程 stderr 入日志前的脱敏(不得原文入 info/error)。
36
+ *
37
+ * 三层防护(先脱敏、后截断见调用方):
38
+ * 1. `redactSecrets` 复用 workload-executor 工具:`ZAG_*` secret 精确值替换为 `***`;
39
+ * 2. 契约 §6.1 名单键值对(token/key/password/secret 等)只留键名;
40
+ * 3. 形似凭据的串(token 前缀 / JWT / Bearer / zag key)整体替换。
41
+ */
42
+ export function redactStderrText(text: string, env: NodeJS.ProcessEnv = process.env): string {
43
+ let out = redactSecrets(text, collectSecretValues(env));
44
+ out = out.replace(SENSITIVE_KV_RE, (_m, key: string, sep: string) => `${key}${sep}${REDACTED}`);
45
+ out = out.replace(SENSITIVE_FLAG_RE, (_m, flag: string, sep: string) => `${flag}${sep}${REDACTED}`);
46
+ for (const re of CREDENTIAL_LIKE_RES) out = out.replace(re, REDACTED);
47
+ return out;
48
+ }
5
49
 
6
50
  export interface AcpProcessOptions {
7
51
  sessionId: string;
8
52
  cwd: string;
9
53
  command?: string;
10
54
  args?: string[];
55
+ /** 注入 logger(测试用);缺省进程级单例,`component: 'acp-spawner'` + `sessionId` 字段化。 */
56
+ logger?: ObservationLogger;
11
57
  }
12
58
 
13
59
  export class AcpSpawner {
@@ -16,6 +62,7 @@ export class AcpSpawner {
16
62
  private cwd: string;
17
63
  private command: string;
18
64
  private args: string[];
65
+ private log: ObservationLogger;
19
66
  private resolveClosed: (() => void) | null = null;
20
67
  private _closed: Promise<void>;
21
68
 
@@ -24,12 +71,16 @@ export class AcpSpawner {
24
71
  this.cwd = options.cwd;
25
72
  this.command = options.command ?? 'opencode';
26
73
  this.args = options.args ?? ['acp'];
74
+ this.log = options.logger ?? rootLogger.child({ component: 'acp-spawner', sessionId: options.sessionId });
27
75
  this._closed = new Promise((resolve) => { this.resolveClosed = resolve; });
28
76
  }
29
77
 
30
78
  start(): void {
31
79
  const cmd = this.resolveCommand();
32
- console.log(`Starting ACP server: session=${this.sessionId} cmd=${cmd} args=${JSON.stringify(this.args)} cwd=${this.cwd}`);
80
+ this.log.info(
81
+ { event: 'acp_spawn', command: cmd, args: this.args, cwd: this.cwd },
82
+ 'starting ACP server',
83
+ );
33
84
  mkdirSync(this.cwd, { recursive: true });
34
85
 
35
86
  const spawnOptions: SpawnOptions = {
@@ -50,17 +101,30 @@ export class AcpSpawner {
50
101
  this.process = spawn(cmd, this.args, spawnOptions);
51
102
 
52
103
  this.process.stderr?.on('data', (data: Buffer) => {
53
- console.error(`ACP stderr (session=${this.sessionId}): ${data.toString()}`);
104
+ // B4:子进程 stderr 不得原文入 info/error —— 先脱敏(secret 值 + 键值对 + 形似凭据串)再截断。
105
+ const safe = redactStderrText(data.toString());
106
+ const truncated = safe.length > STDERR_LOG_MAX_CHARS;
107
+ this.log.error(
108
+ {
109
+ event: 'acp_stderr',
110
+ stderr: truncated ? safe.slice(0, STDERR_LOG_MAX_CHARS) : safe,
111
+ ...(truncated ? { stderrTruncated: true } : {}),
112
+ },
113
+ 'acp server stderr',
114
+ );
54
115
  });
55
116
 
56
117
  this.process.on('exit', (code, signal) => {
57
- console.log(`ACP process exited: session=${this.sessionId} code=${code} signal=${signal} cmd=${cmd} args=${JSON.stringify(this.args)}`);
118
+ this.log.info(
119
+ { event: 'acp_exit', exitCode: code, signal, command: cmd, args: this.args },
120
+ 'acp process exited',
121
+ );
58
122
  this.process = null;
59
123
  this.resolveClosed?.();
60
124
  });
61
125
 
62
126
  this.process.on('error', (error) => {
63
- console.error(`ACP process error (session=${this.sessionId}, cmd=${cmd}):`, error);
127
+ this.log.error({ event: 'acp_process_error', command: cmd, err: error }, 'acp process error');
64
128
  // spawn 失败同样视为进程终止:必须 resolve closed,让 bridge 收敛 pending,避免 65s 迟到 timeout
65
129
  this.process = null;
66
130
  this.resolveClosed?.();
@@ -1,6 +1,9 @@
1
1
  import * as acp from '@agentclientprotocol/sdk';
2
2
  import { AcpSpawner } from './spawner.js';
3
3
  import { CLIENT_CAPABILITIES } from './capabilities.js';
4
+ import { logger } from '../observability/logger.js';
5
+
6
+ const log = logger.child({ component: 'acp-sync-bridge' });
4
7
 
5
8
  const ACP_PROTOCOL_VERSION = 1;
6
9
  const CONNECT_TIMEOUT_MS = 30_000;
@@ -129,7 +132,7 @@ export class AcpSyncBridge implements acp.Client {
129
132
  async unstable_createElicitation(): Promise<acp.CreateElicitationResponse> {
130
133
  // 同步链路无用户交互通道:声明了 elicitation 能力后 Agent 可能发起问询,
131
134
  // 这里显式取消并留日志(声明 + 立即取消是合法降级,不引入交互链路)。
132
- console.warn('[ACP sync-bridge] elicitation request auto-cancelled: no user channel');
135
+ log.warn({ event: 'elicitation_auto_cancelled' }, 'elicitation request auto-cancelled: no user channel');
133
136
  return { action: 'cancel' };
134
137
  }
135
138
 
@@ -18,6 +18,7 @@ import {
18
18
  import type { ConnectToServerOptions } from '../socketio-client.js';
19
19
  import type { GithubCredentialRefreshResult } from '../github/credential-manager.js';
20
20
  import type { CommitIdentityRefreshResult } from '../github/commit-identity-manager.js';
21
+ import { createTestLogger, type TestLogger } from '../observability/testing.js';
21
22
 
22
23
  const TMP_BASE = '/tmp/opencode';
23
24
 
@@ -56,19 +57,19 @@ function setup(overrides: {
56
57
  return (connect.mock.calls.length === 1 ? worker : controller) as unknown as Socket;
57
58
  });
58
59
  const exit = vi.fn();
59
- const logs: string[] = [];
60
+ const testLog: TestLogger = createTestLogger();
60
61
  return {
61
62
  worker,
62
63
  controller,
63
64
  connect,
64
65
  exit,
65
- logs,
66
+ testLog,
66
67
  deps: {
67
68
  env: overrides.env ?? { ...BASE_ENV },
68
69
  connect: connect as never,
69
70
  makeDir: overrides.makeDir ?? (async () => {}),
70
71
  exit,
71
- log: (message: string) => logs.push(message),
72
+ log: testLog.logger,
72
73
  installSignalHandlers: false,
73
74
  credentialManager: overrides.credentialManager,
74
75
  commitIdentityManager: overrides.useDefaultCommitIdentityManager
@@ -301,7 +302,9 @@ describe('startCloudHostSupervisor', () => {
301
302
  // 超时后迟到的 initializing registered 不得再次进入等待(不产生幽灵定时器/重复连接)
302
303
  workerOptions.onRegistered?.({ controllerId: 'container-1', initializing: true });
303
304
  expect(context.connect).toHaveBeenCalledTimes(2);
304
- expect(context.logs.join('\n')).toContain('timed out');
305
+ expect(context.testLog.records).toContainEqual(
306
+ expect.objectContaining({ level: 'warn', msg: expect.stringContaining('timed out') }),
307
+ );
305
308
  });
306
309
 
307
310
  it('T-AG4d: connects immediately when the init batch finished before registered', async () => {
@@ -480,11 +483,15 @@ describe('cloud host github credential manager (T-SUP-G)', () => {
480
483
  expect(handle.workerSocket).toBe(context.worker);
481
484
  expect(context.connect).toHaveBeenCalledTimes(1);
482
485
  expect(context.exit).not.toHaveBeenCalled();
483
- const output = context.logs.join('\n');
484
- expect(output).toContain('disabled');
485
- expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
486
- expect(output).toContain('ZAG_CONTROLLER_ID');
487
- expect(output).not.toContain(BASE_ENV.ZAG_HOST_KEY);
486
+ // 缺省凭据管理器只 warn 变量名(不泄漏任何值)
487
+ expect(context.testLog.records).toContainEqual(
488
+ expect.objectContaining({
489
+ component: 'github-credential',
490
+ msg: expect.stringContaining('disabled'),
491
+ missing: expect.arrayContaining(['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID']),
492
+ }),
493
+ );
494
+ expect(JSON.stringify(context.testLog.records)).not.toContain(BASE_ENV.ZAG_HOST_KEY);
488
495
  });
489
496
  });
490
497
 
@@ -520,10 +527,14 @@ describe('cloud host commit identity manager (T-SUP-CI)', () => {
520
527
  expect(handle.workerSocket).toBe(context.worker);
521
528
  expect(context.connect).toHaveBeenCalledTimes(1);
522
529
  expect(context.exit).not.toHaveBeenCalled();
523
- const output = context.logs.join('\n');
524
- expect(output).toContain('[CommitIdentity] disabled');
525
- expect(output).toContain('ZAG_AGENT_API_ENDPOINT');
526
- expect(output).toContain('ZAG_CONTROLLER_ID');
527
- expect(output).not.toContain(BASE_ENV.ZAG_HOST_KEY);
530
+ // 缺省提交身份管理器只 warn 变量名(不泄漏任何值)
531
+ expect(context.testLog.records).toContainEqual(
532
+ expect.objectContaining({
533
+ component: 'commit-identity',
534
+ msg: expect.stringContaining('disabled'),
535
+ missing: expect.arrayContaining(['ZAG_AGENT_API_ENDPOINT', 'ZAG_CONTROLLER_ID']),
536
+ }),
537
+ );
538
+ expect(JSON.stringify(context.testLog.records)).not.toContain(BASE_ENV.ZAG_HOST_KEY);
528
539
  });
529
540
  });
@@ -1,6 +1,7 @@
1
1
  import { mkdir } from 'node:fs/promises';
2
2
  import { hostname } from 'node:os';
3
3
  import type { Socket } from 'socket.io-client';
4
+ import type { Logger as PinoLogger } from 'pino';
4
5
  import {
5
6
  connectToServer,
6
7
  parseEndpoint,
@@ -21,6 +22,7 @@ import {
21
22
  isServerTerminationReason,
22
23
  resolveShutdownExitCode,
23
24
  } from '../exit-codes.js';
25
+ import { logger as rootLogger } from '../observability/logger.js';
24
26
 
25
27
  // 既有导入路径(`cloud-host/supervisor.js`)继续可用;实现统一在 `exit-codes.ts`。
26
28
  export {
@@ -139,7 +141,8 @@ export interface CloudHostSupervisorDeps {
139
141
  connect?: (endpoint: string, key: string, options?: ConnectToServerOptions) => Socket;
140
142
  makeDir?: (path: string) => Promise<void>;
141
143
  exit?: (code: number) => void;
142
- log?: (message: string) => void;
144
+ /** 注入 logger(测试用);缺省进程级单例,`component: 'cloud-host-supervisor'`。 */
145
+ log?: PinoLogger;
143
146
  /** 是否接管 SIGINT/SIGTERM(默认 true;测试关闭以免污染进程)。 */
144
147
  installSignalHandlers?: boolean;
145
148
  /** 注入 Github 凭据管理器(测试用);缺省按容器 env 创建。 */
@@ -188,22 +191,24 @@ export async function startCloudHostSupervisor(
188
191
  const connect = deps.connect ?? connectToServer;
189
192
  const makeDir = deps.makeDir ?? ((path: string) => mkdir(path, { recursive: true }).then(() => undefined));
190
193
  const exit = deps.exit ?? ((code: number) => process.exit(code));
191
- const log = deps.log ?? ((message: string) => console.log(message));
194
+ // 管理器等子组件从 base 派生自己的 component child(避免同键嵌套绑定产生重复键)
195
+ const baseLog = deps.log ?? rootLogger;
196
+ const log = baseLog.child({ component: 'cloud-host-supervisor' });
192
197
 
193
198
  // 初始化脚本/工作负载需要在工作区落地前执行,先幂等创建工作区。
194
199
  await makeDir(env.workspace);
195
- log(`[CloudHost] workspace ready: ${env.workspace}`);
200
+ log.info({ event: 'workspace_ready', workspace: env.workspace }, 'workspace ready');
196
201
 
197
202
  // Github 凭据管理器:env 缺失时自身只 warn 并禁用,绝不阻塞云主机上线。
198
203
  const credentialManager =
199
204
  deps.credentialManager ??
200
- new GithubCredentialManager({ env: deps.env ?? process.env, log });
205
+ new GithubCredentialManager({ env: deps.env ?? process.env, log: baseLog });
201
206
  credentialManager.start();
202
207
 
203
208
  // 提交身份管理器:与凭据管理器完全独立(不依赖 gh 凭据 / Git 项目绑定存在)。
204
209
  const commitIdentityManager =
205
210
  deps.commitIdentityManager ??
206
- new CommitIdentityManager({ env: deps.env ?? process.env, log });
211
+ new CommitIdentityManager({ env: deps.env ?? process.env, log: baseLog });
207
212
  commitIdentityManager.start();
208
213
 
209
214
  const beforeWorkloadBatch = async (payload: WorkloadRunPayload): Promise<void> => {
@@ -233,7 +238,7 @@ export async function startCloudHostSupervisor(
233
238
  shutdownStarted = true;
234
239
  clearInitTimer();
235
240
  const exitCode = code ?? resolveShutdownExitCode(reason);
236
- log(`[CloudHost] shutting down: ${reason} (exit ${exitCode})`);
241
+ log.info({ event: 'shutdown', reason, exitCode }, 'cloud host shutting down');
237
242
  credentialManager.stop();
238
243
  commitIdentityManager.stop();
239
244
  try {
@@ -255,7 +260,10 @@ export async function startCloudHostSupervisor(
255
260
  if (controllerSocket) return;
256
261
  clearInitTimer();
257
262
  waitingForInit = false;
258
- log(`[CloudHost] connecting controller-api: ${describeEndpoint(env.hostEndpoint)}`);
263
+ log.info(
264
+ { event: 'connecting_controller', endpoint: describeEndpoint(env.hostEndpoint) },
265
+ 'connecting controller-api',
266
+ );
259
267
  controllerSocket = connect(env.hostEndpoint, env.hostKey, {
260
268
  serverName: env.hostName,
261
269
  handshakeToken: env.hostKey,
@@ -273,12 +281,12 @@ export async function startCloudHostSupervisor(
273
281
  }
274
282
  if (waitingForInit) return;
275
283
  waitingForInit = true;
276
- log(`[CloudHost] waiting for harness initialization (timeout ${env.initWaitMs}ms)`);
284
+ log.info({ event: 'init_wait', timeoutMs: env.initWaitMs }, 'waiting for harness initialization');
277
285
  initWaitTimer = setTimeout(() => {
278
286
  initWaitTimer = null;
279
287
  // 超时后视为已完成:迟到的 registered(initializing=true) 不得再次进入等待(幽灵定时器)。
280
288
  initBatchCompleted = true;
281
- log('[CloudHost] harness initialization wait timed out; connecting controller-api anyway');
289
+ log.warn({ event: 'init_wait_timeout', timeoutMs: env.initWaitMs }, 'harness initialization wait timed out; connecting controller-api anyway');
282
290
  connectController();
283
291
  }, env.initWaitMs);
284
292
  };
@@ -291,7 +299,10 @@ export async function startCloudHostSupervisor(
291
299
  persistConfig: false,
292
300
  onBeforeWorkloadBatch: beforeWorkloadBatch,
293
301
  onRegistered: (payload) => {
294
- log(`[CloudHost] worker registered: ${payload.controllerId}${payload.initializing ? ' (initializing)' : ''}`);
302
+ log.info(
303
+ { event: 'worker_registered', controllerId: payload.controllerId, initializing: payload.initializing ?? false },
304
+ 'worker registered',
305
+ );
295
306
  if (payload.initializing) {
296
307
  waitForInitBatch();
297
308
  } else {
@@ -302,14 +313,18 @@ export async function startCloudHostSupervisor(
302
313
  if (summary.phase !== 'init') return;
303
314
  if (summary.cancelled || summary.status === 'cancelled') {
304
315
  // 被新批次/销毁打断:不得视为初始化完成(重连重放 init 时 OpenCode 可能仍在安装)。
305
- log('[CloudHost] harness initialization interrupted; waiting for replay');
316
+ log.info({ event: 'init_interrupted' }, 'harness initialization interrupted; waiting for replay');
306
317
  return;
307
318
  }
308
319
  initBatchCompleted = true;
309
320
  if (waitingForInit) {
310
- log(
311
- `[CloudHost] harness initialization finished (${summary.status}` +
312
- `${summary.failedCount ? `, failed=${summary.failedCount}` : ''}); connecting controller-api`,
321
+ log.info(
322
+ {
323
+ event: 'init_finished',
324
+ status: summary.status,
325
+ ...(summary.failedCount ? { failedCount: summary.failedCount } : {}),
326
+ },
327
+ 'harness initialization finished; connecting controller-api',
313
328
  );
314
329
  connectController();
315
330
  }
@@ -36,11 +36,13 @@ export function registerHarnessCommands(
36
36
  .action(async () => {
37
37
  try {
38
38
  const result = await (deps.prepare ?? prepareHarness)();
39
- console.log(formatPrepareSummary(result));
39
+ // 摘要为 CLI 结果输出(init 脚本/上游脚本按纯文本解析,R3),不走结构化日志。
40
+ console.log(formatPrepareSummary(result)); // no-console-allow: CLI 用户可见输出(结果摘要)
40
41
  } catch (error) {
41
42
  const secrets = collectSecretValues(process.env);
42
43
  const message = redactSecrets((error as Error).message, secrets);
43
- console.error(`harness prepare failed: ${message}`);
44
+ // 失败原因为 CLI 结果输出(给使用者的失败结果),不走结构化日志。
45
+ console.error(`harness prepare failed: ${message}`); // no-console-allow: CLI 用户可见输出(失败结果)
44
46
  // 非零退出:不直接 process.exit,便于测试断言 exitCode 与已刷新的日志。
45
47
  process.exitCode = 1;
46
48
  }
@@ -1,5 +1,6 @@
1
1
  import { spawn, ChildProcess } from 'child_process';
2
2
  import { io as ioClient, Socket } from 'socket.io-client';
3
+ import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
3
4
 
4
5
  interface McpProxyOptions {
5
6
  server: string;
@@ -27,7 +28,8 @@ function isNotification(request: JsonRpcRequest): boolean {
27
28
  // Responses are matched to requests by id, so chunked responses (a single
28
29
  // 'data' event is NOT guaranteed to contain exactly one complete JSON
29
30
  // message) and concurrent in-flight requests are handled correctly.
30
- export function createStdioDispatcher(child: ChildProcess) {
31
+ export function createStdioDispatcher(child: ChildProcess, logger?: ObservationLogger) {
32
+ const log = logger ?? rootLogger.child({ component: 'mcp-proxy' });
31
33
  let buffer = '';
32
34
  const pending = new Map<unknown, { resolve: (value: unknown) => void; reject: (reason: Error) => void; timeout: NodeJS.Timeout; method: string }>();
33
35
 
@@ -42,17 +44,26 @@ export function createStdioDispatcher(child: ChildProcess) {
42
44
  try {
43
45
  msg = JSON.parse(line);
44
46
  } catch {
45
- console.error(`[MCP proxy] ignoring non-JSON line from child: ${line.slice(0, 200)}`);
47
+ log.error(
48
+ { event: 'non_json_line', preview: line.slice(0, 200) },
49
+ 'ignoring non-JSON line from child',
50
+ );
46
51
  continue;
47
52
  }
48
53
  const entry = pending.get(msg.id);
49
54
  if (!entry) {
50
- console.error(`[MCP proxy] ignoring response with unknown id: ${JSON.stringify(msg.id)}`);
55
+ log.error(
56
+ { event: 'unknown_response_id', id: typeof msg.id === 'string' || typeof msg.id === 'number' ? msg.id : undefined },
57
+ 'ignoring response with unknown id',
58
+ );
51
59
  continue;
52
60
  }
53
61
  clearTimeout(entry.timeout);
54
62
  pending.delete(msg.id);
55
- console.log(`[MCP proxy] response: method=${entry.method} id=${JSON.stringify(msg.id)}${msg.error ? ` error=${msg.error.message}` : ''}`);
63
+ log.debug(
64
+ { event: 'mcp_response', method: entry.method, id: msg.id, ...(msg.error ? { error: msg.error.message } : {}) },
65
+ 'mcp response',
66
+ );
56
67
  entry.resolve(msg);
57
68
  }
58
69
  });
@@ -66,7 +77,10 @@ export function createStdioDispatcher(child: ChildProcess) {
66
77
  };
67
78
 
68
79
  child.on('exit', (code) => {
69
- console.log(`[MCP proxy] MCP command exited with code ${code}, rejecting ${pending.size} pending request(s)`);
80
+ log.info(
81
+ { event: 'mcp_command_exited', exitCode: code, pendingCount: pending.size },
82
+ 'MCP command exited',
83
+ );
70
84
  rejectAll(new Error(`MCP command exited with code ${code}`));
71
85
  });
72
86
 
@@ -76,11 +90,11 @@ export function createStdioDispatcher(child: ChildProcess) {
76
90
  if (isNotification(request)) {
77
91
  // Fire-and-forget: deliver the notification (e.g. notifications/initialized
78
92
  // completes the MCP handshake) but do not wait for a response.
79
- console.log(`[MCP proxy] forwarding notification: method=${method}`);
93
+ log.debug({ event: 'forward_notification', method }, 'forwarding notification');
80
94
  child.stdin?.write(JSON.stringify(request) + '\n');
81
95
  return Promise.resolve(null);
82
96
  }
83
- console.log(`[MCP proxy] forwarding request: method=${method} id=${JSON.stringify(request.id)}`);
97
+ log.debug({ event: 'forward_request', method, id: request.id }, 'forwarding request');
84
98
  return new Promise((resolve, reject) => {
85
99
  const timeout = setTimeout(() => {
86
100
  pending.delete(request.id);
@@ -95,8 +109,9 @@ export function createStdioDispatcher(child: ChildProcess) {
95
109
 
96
110
  export async function startMcpRegistration(options: McpProxyOptions): Promise<void> {
97
111
  const { server, key, command } = options;
112
+ const log = rootLogger.child({ component: 'mcp-proxy' });
98
113
 
99
- console.log(`Registering MCP proxy with server ${server}...`);
114
+ console.log(`Registering MCP proxy with server ${server}...`); // no-console-allow: CLI 用户可见输出(进度)
100
115
 
101
116
  // 1. Register with server
102
117
  const response = await fetch(`${server}/api/mcp-proxy/register`, {
@@ -112,15 +127,15 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
112
127
 
113
128
  const result = await response.json() as any;
114
129
  if (!result.success) {
115
- console.error('Registration failed:', result.error);
130
+ console.error('Registration failed:', result.error); // no-console-allow: CLI 用户可见输出(失败结果)
116
131
  process.exit(1);
117
132
  }
118
133
 
119
- console.log(`Registered as proxy ${result.proxyId}, server ${result.serverId}`);
134
+ console.log(`Registered as proxy ${result.proxyId}, server ${result.serverId}`); // no-console-allow: CLI 用户可见输出(结果:代理标识)
120
135
 
121
136
  // 2. Spawn local command
122
137
  const [cmd, ...args] = command.split(' ');
123
- console.log(`Starting local MCP command: ${cmd} ${args.join(' ')}`);
138
+ console.log(`Starting local MCP command: ${cmd} ${args.join(' ')}`); // no-console-allow: CLI 用户可见输出(进度)
124
139
 
125
140
  const child = spawn(cmd, args, {
126
141
  stdio: ['pipe', 'pipe', 'pipe'],
@@ -128,7 +143,7 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
128
143
  });
129
144
 
130
145
  child.on('error', (err) => {
131
- console.error('Failed to start MCP command:', err.message);
146
+ console.error('Failed to start MCP command:', err.message); // no-console-allow: CLI 用户可见输出(失败结果)
132
147
  });
133
148
 
134
149
  // 3. Establish WebSocket connection
@@ -138,26 +153,34 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
138
153
  });
139
154
 
140
155
  socket.on('connect', () => {
141
- console.log('WebSocket connected to proxy namespace');
156
+ console.log('WebSocket connected to proxy namespace'); // no-console-allow: CLI 用户可见输出(进度)
142
157
  socket.emit('proxy:register', { proxyId: result.proxyId, key });
143
158
  });
144
159
 
145
160
  socket.on('proxy:registered', (data: { proxyId: string; serverId: string }) => {
146
- console.log(`Registered with proxy namespace, serverId: ${data.serverId}`);
161
+ console.log(`Registered with proxy namespace, serverId: ${data.serverId}`); // no-console-allow: CLI 用户可见输出(结果)
147
162
  });
148
163
 
149
164
  socket.on('proxy:error', (data: { code: string; message: string }) => {
150
- console.error(`Proxy error: ${data.code} - ${data.message}`);
165
+ log.error({ event: 'proxy_error', code: data.code, serverMessage: data.message }, 'proxy error');
151
166
  });
152
167
 
153
168
  // 4. Bridge requests
154
- const dispatcher = createStdioDispatcher(child);
169
+ const dispatcher = createStdioDispatcher(child, log);
155
170
  socket.on('proxy:request', async (data: { requestId: string; request: JsonRpcRequest }) => {
156
171
  try {
157
172
  const response = await dispatcher.forward(data.request);
158
173
  socket.emit('proxy:response', { requestId: data.requestId, response });
159
174
  } catch (err: any) {
160
- console.error(`[MCP proxy] forward failed: method=${data.request?.method} id=${JSON.stringify(data.request?.id)} error=${err.message}`);
175
+ log.error(
176
+ {
177
+ event: 'forward_failed',
178
+ method: data.request?.method,
179
+ id: data.request?.id,
180
+ err: { message: err?.message ?? String(err) },
181
+ },
182
+ 'mcp forward failed',
183
+ );
161
184
  socket.emit('proxy:response', {
162
185
  requestId: data.requestId,
163
186
  response: {
@@ -178,7 +201,7 @@ export async function startMcpRegistration(options: McpProxyOptions): Promise<vo
178
201
 
179
202
  // 6. Cleanup
180
203
  const shutdown = () => {
181
- console.log('Shutting down MCP proxy...');
204
+ console.log('Shutting down MCP proxy...'); // no-console-allow: CLI 用户可见输出(进度/生命周期)
182
205
  clearInterval(heartbeatInterval);
183
206
  socket.emit('proxy:unregister', { proxyId: result.proxyId });
184
207
  child.kill();
@@ -8,7 +8,7 @@ interface McpProxyOptions {
8
8
  export async function startMcpProxy(options: McpProxyOptions): Promise<void> {
9
9
  const { endpoint, token } = options;
10
10
 
11
- console.log(`Starting MCP proxy for endpoint: ${endpoint}`);
11
+ console.log(`Starting MCP proxy for endpoint: ${endpoint}`); // no-console-allow: CLI 用户可见输出(进度:代理端点)
12
12
 
13
13
  const rl = readline.createInterface({ input: process.stdin });
14
14
 
@@ -8,6 +8,7 @@ vi.mock('node:net', () => ({
8
8
 
9
9
  import net from 'node:net';
10
10
  import { GatewayManager } from './gateway.js';
11
+ import { createTestLogger, type TestLogger } from './observability/testing.js';
11
12
 
12
13
  function createMockLocalSocket() {
13
14
  const handlers = new Map<string, Function>();
@@ -39,10 +40,12 @@ function createMockServerSocket() {
39
40
 
40
41
  describe('GatewayManager', () => {
41
42
  let gatewayManager: GatewayManager;
43
+ let testLog: TestLogger;
42
44
 
43
45
  beforeEach(() => {
44
46
  vi.clearAllMocks();
45
- gatewayManager = new GatewayManager();
47
+ testLog = createTestLogger('gateway');
48
+ gatewayManager = new GatewayManager(testLog.logger);
46
49
  });
47
50
 
48
51
  describe('createTunnel', () => {
@@ -237,12 +240,14 @@ describe('GatewayManager', () => {
237
240
  });
238
241
 
239
242
  it('should log warning and ignore for unknown tunnelId', () => {
240
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
241
243
  gatewayManager.handleTunnelData('unknown-tunnel', 'data');
242
- expect(warnSpy).toHaveBeenCalledWith(
243
- expect.stringContaining('unknown tunnel'),
244
+ expect(testLog.records).toContainEqual(
245
+ expect.objectContaining({
246
+ level: 'warn',
247
+ msg: expect.stringContaining('unknown tunnel'),
248
+ tunnelId: 'unknown-tunnel',
249
+ }),
244
250
  );
245
- warnSpy.mockRestore();
246
251
  });
247
252
  });
248
253