agent-gear 2.13.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 +14 -1
  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 +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 +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 +210 -69
  151. package/src/startup-span.test.ts +83 -0
  152. package/src/startup-span.ts +27 -0
  153. package/src/worktree-handler.test.ts +10 -7
  154. package/src/worktree-handler.ts +12 -8
  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
package/src/acp/bridge.ts CHANGED
@@ -7,6 +7,8 @@ import {
7
7
  normalizeCapabilities,
8
8
  type AgentCapabilitySnapshot,
9
9
  } from './capabilities.js';
10
+ import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
11
+ import { withSpan } from '../observability/trace.js';
10
12
 
11
13
  const ACP_PROTOCOL_VERSION = 1;
12
14
 
@@ -29,6 +31,8 @@ export interface AcpBridgeOptions {
29
31
  /** 会话初始化时应用的工作模式/模型(工作流节点配置;不提供则使用 harness 默认) */
30
32
  initialModeId?: string;
31
33
  initialModelId?: string;
34
+ /** 注入 logger(测试用);缺省进程级单例,`component: 'acp-bridge'` + `sessionId` 字段化。 */
35
+ logger?: ObservationLogger;
32
36
  }
33
37
 
34
38
  interface QueuedInput {
@@ -217,6 +221,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
217
221
  private socket: Socket;
218
222
  private sessionId: string;
219
223
  private cwd: string;
224
+ private log: ObservationLogger;
220
225
  private additionalDirectories: string[];
221
226
  private mcpServers: AcpBridgeOptions['mcpServers'];
222
227
  private mcpEndpoint: AcpBridgeOptions['mcpEndpoint'];
@@ -277,6 +282,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
277
282
  this.socket = socket;
278
283
  this.sessionId = options.sessionId;
279
284
  this.cwd = options.cwd;
285
+ this.log = options.logger ?? rootLogger.child({ component: 'acp-bridge', sessionId: options.sessionId });
280
286
  this.additionalDirectories = options.additionalDirectories ?? [];
281
287
  this.mcpServers = options.mcpServers;
282
288
  this.mcpEndpoint = options.mcpEndpoint;
@@ -297,12 +303,20 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
297
303
  // session/new (or session/resume), and warn when the agent did not
298
304
  // advertise the required MCP transport capability in initialize.
299
305
  private logMcpServersForSession(method: 'session/new' | 'session/resume', servers: acp.McpServer[]): void {
300
- console.log(`[ACP bridge] session ${this.sessionId}: passing MCP servers via ${method}: ${describeMcpServersForLog(servers)}`);
306
+ this.log.info(
307
+ { event: 'mcp_servers_passed', method, servers: describeMcpServersForLog(servers) },
308
+ 'passing MCP servers to agent',
309
+ );
301
310
  const httpServers = servers.filter((s) => 'url' in s && (s as { type?: string }).type === 'http');
302
311
  if (httpServers.length > 0 && this.agentMcpCapabilities && this.agentMcpCapabilities.http === false) {
303
- console.warn(
304
- `[ACP bridge] session ${this.sessionId}: agent did not advertise mcpCapabilities.http ` +
305
- `but ${httpServers.length} http MCP server(s) are being passed: ${httpServers.map((s) => s.name).join(', ')}`,
312
+ this.log.warn(
313
+ {
314
+ event: 'mcp_http_capability_missing',
315
+ method,
316
+ httpServerCount: httpServers.length,
317
+ httpServerNames: httpServers.map((s) => s.name).join(', '),
318
+ },
319
+ 'agent did not advertise mcpCapabilities.http but http MCP servers are being passed',
306
320
  );
307
321
  }
308
322
  }
@@ -311,7 +325,10 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
311
325
  if (this.initializing) return;
312
326
  this.initializing = true;
313
327
 
314
- this.spawner.start();
328
+ // acp child spawn:一次 spawn 一个 span(进程事件不逐条开 span)
329
+ withSpan('acp.child.spawn', { sessionId: this.sessionId, cwd: this.cwd }, () => {
330
+ this.spawner.start();
331
+ });
315
332
  this.subscribeToProcessExit();
316
333
  try {
317
334
  await this.initConnection();
@@ -341,7 +358,10 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
341
358
  if (this.initializing) return;
342
359
  this.initializing = true;
343
360
 
344
- this.spawner.start();
361
+ // acp child spawn:一次 spawn 一个 span(进程事件不逐条开 span)
362
+ withSpan('acp.child.spawn', { sessionId: this.sessionId, cwd: this.cwd }, () => {
363
+ this.spawner.start();
364
+ });
345
365
  this.subscribeToProcessExit();
346
366
  try {
347
367
  await this.initConnection();
@@ -442,8 +462,11 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
442
462
  this.processExitSubscribed = true;
443
463
  this.spawner.closed.then(() => {
444
464
  if (this.stopped) return;
445
- console.warn(`[ACP bridge] session ${this.sessionId}: process exited, settling pending requests`);
446
- this.settlePendingRequests('process exited');
465
+ // acp child exit:进程退出收敛一个 span(不逐进程事件开 span)
466
+ withSpan('acp.child.exit', { sessionId: this.sessionId }, () => {
467
+ this.log.warn({ event: 'acp_process_exited' }, 'acp process exited, settling pending requests');
468
+ this.settlePendingRequests('process exited');
469
+ });
447
470
  }).catch(() => { /* ignore */ });
448
471
  }
449
472
 
@@ -536,7 +559,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
536
559
  else await this.setModel(requested);
537
560
  const config = findConfigByCategory(this.configOptions, kind);
538
561
  if (!config || config.currentValue === requested) {
539
- console.log(`[ACP bridge] session ${this.sessionId}: applied initial ${kind}=${requested}`);
562
+ this.log.info({ event: 'initial_config_applied', kind, requested }, 'applied initial config');
540
563
  return null;
541
564
  }
542
565
  lastError = `agent confirmed "${config.currentValue ?? 'null'}" instead of "${requested}"`;
@@ -544,9 +567,9 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
544
567
  lastError = (err as Error).message;
545
568
  }
546
569
  }
547
- console.warn(
548
- `[ACP bridge] session ${this.sessionId}: failed to apply initial ${kind}: ` +
549
- `requested=${requested}, ${lastError}`,
570
+ this.log.warn(
571
+ { event: 'initial_config_failed', kind, requested, error: lastError },
572
+ 'failed to apply initial config',
550
573
  );
551
574
  return `requested "${requested}": ${lastError}`;
552
575
  }
@@ -575,9 +598,9 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
575
598
  for (const kind of this.pendingInitialConfigKinds.splice(0)) {
576
599
  const requested = kind === 'mode' ? this.initialModeId : this.initialModelId;
577
600
  const error = `agent did not expose a ${kind} config option within ${timeoutMs}ms`;
578
- console.warn(
579
- `[ACP bridge] session ${this.sessionId}: failed to apply initial ${kind}: ` +
580
- `requested=${requested}, ${error}`,
601
+ this.log.warn(
602
+ { event: 'initial_config_timeout', kind, requested, error },
603
+ 'failed to apply initial config: config option not exposed',
581
604
  );
582
605
  this.recordInitialConfigStatus(kind, 'failed', `requested "${requested}": ${error}`);
583
606
  }
@@ -705,31 +728,35 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
705
728
  }
706
729
  prompt.push({ type: 'text' as const, text: message.content });
707
730
 
708
- this.activePrompt = this.connection.prompt({
709
- sessionId: this.acpSessionId,
710
- prompt,
711
- });
731
+ // session.prompt:一条 prompt 一个 span(流式 chunk 不逐条开 span)
732
+ await withSpan('session.prompt', { sessionId: this.sessionId }, async (span) => {
733
+ this.activePrompt = this.connection!.prompt({
734
+ sessionId: this.acpSessionId!,
735
+ prompt,
736
+ });
712
737
 
713
- this.socket.emit('acp:prompt:start', { sessionId: this.sessionId });
738
+ this.socket.emit('acp:prompt:start', { sessionId: this.sessionId });
714
739
 
715
- let stopReason = 'end_turn';
716
- try {
717
- const result = await this.activePrompt;
718
- stopReason = result?.stopReason ?? 'end_turn';
719
- } catch {
720
- stopReason = 'error';
721
- } finally {
722
- this.activePrompt = null;
723
- if (!this.stopped) {
724
- this.socket.emit('acp:prompt:complete', {
725
- sessionId: this.sessionId,
726
- stopReason,
727
- });
728
- }
729
- if (this.inputQueue.length > 0) {
730
- this.processPrompt(this.inputQueue.shift()!);
740
+ let stopReason = 'end_turn';
741
+ try {
742
+ const result = await this.activePrompt;
743
+ stopReason = result?.stopReason ?? 'end_turn';
744
+ } catch {
745
+ stopReason = 'error';
746
+ } finally {
747
+ span.setAttribute('acp.stop_reason', stopReason);
748
+ this.activePrompt = null;
749
+ if (!this.stopped) {
750
+ this.socket.emit('acp:prompt:complete', {
751
+ sessionId: this.sessionId,
752
+ stopReason,
753
+ });
754
+ }
755
+ if (this.inputQueue.length > 0) {
756
+ this.processPrompt(this.inputQueue.shift()!);
757
+ }
731
758
  }
732
- }
759
+ });
733
760
  }
734
761
 
735
762
  private async initConnection(): Promise<void> {
@@ -772,10 +799,15 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
772
799
  this.authMethodsRaw = result.authMethods ?? null;
773
800
  this.authMethods = toAuthMethods(result.authMethods);
774
801
  this.agentMcpCapabilities = result.agentCapabilities?.mcpCapabilities ?? null;
775
- console.log(
776
- `[ACP bridge] session ${this.sessionId}: agent capabilities: ` +
777
- `protocolVersion=${result.protocolVersion ?? 'n/a'} mcp=${JSON.stringify(this.agentMcpCapabilities)} ` +
778
- `agent=${this.agentInfo ? `${this.agentInfo.name}@${this.agentInfo.version ?? 'n/a'}` : 'n/a'}`,
802
+ this.log.info(
803
+ {
804
+ event: 'agent_capabilities',
805
+ protocolVersion: result.protocolVersion ?? null,
806
+ mcp: this.agentMcpCapabilities,
807
+ agentName: this.agentInfo?.name ?? null,
808
+ agentVersion: this.agentInfo?.version ?? null,
809
+ },
810
+ 'agent capabilities',
779
811
  );
780
812
  this.supportsAdditionalDirectories =
781
813
  result.agentCapabilities?.sessionCapabilities?.additionalDirectories !== undefined &&
@@ -943,7 +975,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
943
975
  handlePermissionResponse(requestId: string, outcome: acp.RequestPermissionOutcome): void {
944
976
  const pending = this.pendingPermissions.get(requestId);
945
977
  if (!pending) {
946
- console.warn(`Permission request ${requestId} not found`);
978
+ this.log.warn({ event: 'permission_response_unknown', requestId }, 'permission request not found');
947
979
  return;
948
980
  }
949
981
 
@@ -964,7 +996,10 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
964
996
  // 否则「Agent 发起问询但用户从未看到弹窗」无法从日志/待办侧定位。
965
997
  if (!acp.CreateElicitationRequest.isForm(params) && !acp.CreateElicitationRequest.isUrl(params)) {
966
998
  const mode = (params as { mode?: unknown }).mode ?? 'unknown';
967
- console.warn('[ACP bridge] session %s: unsupported elicitation mode=%j', this.sessionId, mode);
999
+ this.log.warn(
1000
+ { event: 'elicitation_unsupported_mode', mode: String(mode).slice(0, 100) },
1001
+ 'unsupported elicitation mode',
1002
+ );
968
1003
  this.socket.emit('acp:elicitation:resolved', {
969
1004
  requestId,
970
1005
  sessionId: this.sessionId,
@@ -979,12 +1014,16 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
979
1014
 
980
1015
  return new Promise((resolve) => {
981
1016
  const timeout = setTimeout(() => {
1017
+ const pending = this.pendingElicitations.get(requestId);
982
1018
  this.pendingElicitations.delete(requestId);
983
1019
  this.emit('elicitation:settled', requestId);
984
- console.warn(
985
- '[ACP bridge] session %s: elicitation %s timed out after 65s, auto-cancelling',
986
- this.sessionId,
987
- requestId,
1020
+ this.log.warn(
1021
+ {
1022
+ event: 'elicitation_timeout',
1023
+ requestId,
1024
+ ...(pending?.elicitationId ? { elicitationId: pending.elicitationId } : {}),
1025
+ },
1026
+ 'elicitation timed out after 65s, auto-cancelling',
988
1027
  );
989
1028
  this.socket.emit('acp:elicitation:resolved', {
990
1029
  requestId,
@@ -1042,7 +1081,7 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1042
1081
  ): void {
1043
1082
  const pending = this.pendingElicitations.get(requestId);
1044
1083
  if (!pending) {
1045
- console.warn(`Elicitation request ${requestId} not found`);
1084
+ this.log.warn({ event: 'elicitation_response_unknown', elicitationId: requestId }, 'elicitation request not found');
1046
1085
  return;
1047
1086
  }
1048
1087
 
@@ -1119,7 +1158,10 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1119
1158
  }
1120
1159
 
1121
1160
  private emitStopped(reason: string, exitCode?: number, silent = false): void {
1122
- console.log(`[ACP bridge] session ${this.sessionId} stopped: reason=${reason} exitCode=${exitCode ?? 'n/a'}${silent ? ' (silent)' : ''}`);
1161
+ this.log.info(
1162
+ { event: 'acp_stopped', reason, exitCode: exitCode ?? null, silent },
1163
+ 'acp session stopped',
1164
+ );
1123
1165
  this.stopped = true;
1124
1166
  if (this.textChunkTimer) {
1125
1167
  clearTimeout(this.textChunkTimer);
@@ -1135,8 +1177,10 @@ export class AcpSessionBridge extends EventEmitter implements acp.Client {
1135
1177
 
1136
1178
  private handleError(error: unknown): void {
1137
1179
  const msg = error instanceof Error ? error.message : String(error);
1138
- const stack = error instanceof Error ? error.stack : undefined;
1139
- console.error(`[ACP bridge] session ${this.sessionId} failed: ${msg}${stack ? `\n${stack}` : ''}`);
1180
+ this.log.error(
1181
+ { err: error instanceof Error ? error : new Error(msg) },
1182
+ 'acp session failed',
1183
+ );
1140
1184
  const wasStopped = this.stopped || this.silentStop;
1141
1185
  this.stopped = true;
1142
1186
  // 进程崩溃同样必须收敛 pending:否则 65s timer 泄漏且迟发 timeout 事件
@@ -17,6 +17,7 @@ vi.mock('fs', () => ({
17
17
  vi.mock('os', () => ({
18
18
  homedir: vi.fn(() => '/home/test'),
19
19
  tmpdir: vi.fn(() => '/tmp'),
20
+ hostname: vi.fn(() => 'test-host'),
20
21
  }));
21
22
 
22
23
  import { ProcessRegistry } from './process-registry.js';
@@ -1,6 +1,9 @@
1
1
  import { readFileSync, writeFileSync, existsSync, mkdirSync, renameSync } from 'fs';
2
2
  import { join } from 'path';
3
3
  import { homedir } from 'os';
4
+ import { logger } from '../observability/logger.js';
5
+
6
+ const log = logger.child({ component: 'process-registry' });
4
7
 
5
8
  const REGISTRY_DIR = join(homedir(), '.zag');
6
9
  const REGISTRY_FILE = join(REGISTRY_DIR, 'processes.json');
@@ -131,7 +134,7 @@ export class ProcessRegistry {
131
134
  } catch (err) {
132
135
  // Persistence is best-effort: a flush failure must never crash the
133
136
  // controller (this can be called from timer callbacks).
134
- console.warn(`[ProcessRegistry] flush failed: ${(err as Error).message}`);
137
+ log.warn({ err }, 'process registry flush failed');
135
138
  }
136
139
  }
137
140
  }
@@ -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
  }