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.
- package/AGENTS.md +20 -2
- package/dist/acp/bridge.d.ts +4 -0
- package/dist/acp/bridge.d.ts.map +1 -1
- package/dist/acp/bridge.js +72 -45
- package/dist/acp/bridge.js.map +1 -1
- package/dist/acp/bridge.test.js +40 -33
- package/dist/acp/bridge.test.js.map +1 -1
- package/dist/acp/process-registry.d.ts.map +1 -1
- package/dist/acp/process-registry.js +3 -1
- package/dist/acp/process-registry.js.map +1 -1
- package/dist/acp/process-registry.test.js +1 -0
- package/dist/acp/process-registry.test.js.map +1 -1
- package/dist/acp/spawner.d.ts +15 -0
- package/dist/acp/spawner.d.ts.map +1 -1
- package/dist/acp/spawner.js +51 -4
- package/dist/acp/spawner.js.map +1 -1
- package/dist/acp/sync-bridge.d.ts.map +1 -1
- package/dist/acp/sync-bridge.js +3 -1
- package/dist/acp/sync-bridge.js.map +1 -1
- package/dist/cloud-host/supervisor.d.ts +3 -1
- package/dist/cloud-host/supervisor.d.ts.map +1 -1
- package/dist/cloud-host/supervisor.js +18 -12
- package/dist/cloud-host/supervisor.js.map +1 -1
- package/dist/cloud-host/supervisor.test.js +19 -14
- package/dist/cloud-host/supervisor.test.js.map +1 -1
- package/dist/commands/harness.d.ts.map +1 -1
- package/dist/commands/harness.js +4 -2
- package/dist/commands/harness.js.map +1 -1
- package/dist/commands/mcp-proxy.d.ts +2 -1
- package/dist/commands/mcp-proxy.d.ts.map +1 -1
- package/dist/commands/mcp-proxy.js +26 -18
- package/dist/commands/mcp-proxy.js.map +1 -1
- package/dist/commands/mcp.js +1 -1
- package/dist/commands/mcp.js.map +1 -1
- package/dist/gateway.d.ts +3 -0
- package/dist/gateway.d.ts.map +1 -1
- package/dist/gateway.js +14 -8
- package/dist/gateway.js.map +1 -1
- package/dist/gateway.test.js +9 -4
- package/dist/gateway.test.js.map +1 -1
- package/dist/github/commit-identity-manager.d.ts +3 -1
- package/dist/github/commit-identity-manager.d.ts.map +1 -1
- package/dist/github/commit-identity-manager.js +13 -6
- package/dist/github/commit-identity-manager.js.map +1 -1
- package/dist/github/commit-identity-manager.test.js +26 -24
- package/dist/github/commit-identity-manager.test.js.map +1 -1
- package/dist/github/credential-manager.d.ts +3 -1
- package/dist/github/credential-manager.d.ts.map +1 -1
- package/dist/github/credential-manager.js +18 -10
- package/dist/github/credential-manager.js.map +1 -1
- package/dist/github/credential-manager.test.js +36 -33
- package/dist/github/credential-manager.test.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +77 -70
- package/dist/index.js.map +1 -1
- package/dist/mcp/local-server.d.ts +3 -1
- package/dist/mcp/local-server.d.ts.map +1 -1
- package/dist/mcp/local-server.js +19 -9
- package/dist/mcp/local-server.js.map +1 -1
- package/dist/mcp/relay.d.ts +3 -1
- package/dist/mcp/relay.d.ts.map +1 -1
- package/dist/mcp/relay.js +20 -12
- package/dist/mcp/relay.js.map +1 -1
- package/dist/observability/http-context.d.ts +32 -0
- package/dist/observability/http-context.d.ts.map +1 -0
- package/dist/observability/http-context.js +97 -0
- package/dist/observability/http-context.js.map +1 -0
- package/dist/observability/log-context.d.ts +19 -0
- package/dist/observability/log-context.d.ts.map +1 -0
- package/dist/observability/log-context.js +21 -0
- package/dist/observability/log-context.js.map +1 -0
- package/dist/observability/logger.d.ts +31 -0
- package/dist/observability/logger.d.ts.map +1 -0
- package/dist/observability/logger.js +129 -0
- package/dist/observability/logger.js.map +1 -0
- package/dist/observability/no-console.test.d.ts +2 -0
- package/dist/observability/no-console.test.d.ts.map +1 -0
- package/dist/observability/no-console.test.js +78 -0
- package/dist/observability/no-console.test.js.map +1 -0
- package/dist/observability/register.d.ts +2 -0
- package/dist/observability/register.d.ts.map +1 -0
- package/dist/observability/register.js +29 -0
- package/dist/observability/register.js.map +1 -0
- package/dist/observability/telemetry.d.ts +12 -0
- package/dist/observability/telemetry.d.ts.map +1 -0
- package/dist/observability/telemetry.js +164 -0
- package/dist/observability/telemetry.js.map +1 -0
- package/dist/observability/testing.d.ts +24 -0
- package/dist/observability/testing.d.ts.map +1 -0
- package/dist/observability/testing.js +31 -0
- package/dist/observability/testing.js.map +1 -0
- package/dist/observability/trace.d.ts +42 -0
- package/dist/observability/trace.d.ts.map +1 -0
- package/dist/observability/trace.js +123 -0
- package/dist/observability/trace.js.map +1 -0
- package/dist/socketio-client.auth-gate.test.js +0 -3
- package/dist/socketio-client.auth-gate.test.js.map +1 -1
- package/dist/socketio-client.d.ts +3 -0
- package/dist/socketio-client.d.ts.map +1 -1
- package/dist/socketio-client.js +140 -69
- package/dist/socketio-client.js.map +1 -1
- package/dist/socketio-client.test.js +0 -6
- package/dist/socketio-client.test.js.map +1 -1
- package/dist/startup-span.d.ts +15 -0
- package/dist/startup-span.d.ts.map +1 -0
- package/dist/startup-span.js +21 -0
- package/dist/startup-span.js.map +1 -0
- package/dist/startup-span.test.d.ts +2 -0
- package/dist/startup-span.test.d.ts.map +1 -0
- package/dist/startup-span.test.js +71 -0
- package/dist/startup-span.test.js.map +1 -0
- package/dist/worktree-handler.d.ts +25 -2
- package/dist/worktree-handler.d.ts.map +1 -1
- package/dist/worktree-handler.js +95 -5
- package/dist/worktree-handler.js.map +1 -1
- package/dist/worktree-handler.test.js +88 -5
- package/dist/worktree-handler.test.js.map +1 -1
- package/package.json +8 -1
- package/src/acp/bridge.test.ts +63 -34
- package/src/acp/bridge.ts +95 -51
- package/src/acp/process-registry.test.ts +1 -0
- package/src/acp/process-registry.ts +4 -1
- package/src/acp/spawner.ts +68 -4
- package/src/acp/sync-bridge.ts +4 -1
- package/src/cloud-host/supervisor.test.ts +25 -14
- package/src/cloud-host/supervisor.ts +29 -14
- package/src/commands/harness.ts +4 -2
- package/src/commands/mcp-proxy.ts +41 -18
- package/src/commands/mcp.ts +1 -1
- package/src/gateway.test.ts +10 -5
- package/src/gateway.ts +15 -8
- package/src/github/commit-identity-manager.test.ts +30 -24
- package/src/github/commit-identity-manager.ts +19 -9
- package/src/github/credential-manager.test.ts +42 -33
- package/src/github/credential-manager.ts +28 -15
- package/src/index.ts +85 -74
- package/src/mcp/local-server.ts +31 -9
- package/src/mcp/relay.ts +32 -13
- package/src/observability/http-context.ts +122 -0
- package/src/observability/log-context.ts +39 -0
- package/src/observability/logger.ts +160 -0
- package/src/observability/no-console.test.ts +99 -0
- package/src/observability/register.ts +34 -0
- package/src/observability/telemetry.ts +180 -0
- package/src/observability/testing.ts +51 -0
- package/src/observability/trace.ts +163 -0
- package/src/socketio-client.auth-gate.test.ts +0 -3
- package/src/socketio-client.test.ts +0 -6
- package/src/socketio-client.ts +220 -71
- package/src/startup-span.test.ts +83 -0
- package/src/startup-span.ts +27 -0
- package/src/worktree-handler.test.ts +106 -5
- package/src/worktree-handler.ts +116 -6
- package/tests/acp-bridge.test.ts +11 -3
- package/tests/acp-spawner.test.ts +119 -14
- package/tests/acp-wire-elicitation.test.ts +0 -3
- package/tests/acp-wire-mcp.test.ts +9 -6
- package/tests/commands/harness.test.ts +6 -0
- package/tests/commands/mcp-proxy-dispatcher.test.ts +0 -2
- package/tests/commands/mcp-proxy.test.ts +43 -0
- package/tests/commands/mcp.test.ts +4 -0
- package/tests/socketio-client.test.ts +114 -36
- package/vitest.config.ts +3 -0
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
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
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
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
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
|
-
|
|
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
|
-
|
|
111
|
-
|
|
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
|
-
|
|
114
|
-
|
|
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
|
package/src/mcp/local-server.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/mcp/relay.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { logger as rootLogger, type ObservationLogger } from '../observability/logger.js';
|
|
2
|
+
import { withSpan } from '../observability/trace.js';
|
|
3
|
+
|
|
1
4
|
export interface SessionEndpoint {
|
|
2
5
|
token: string;
|
|
3
6
|
serverNames: string[];
|
|
@@ -28,9 +31,11 @@ export class McpRelay {
|
|
|
28
31
|
private pendingRequests = new Map<string, PendingRequest>();
|
|
29
32
|
private sessionEndpoints = new Map<string, SessionEndpoint>();
|
|
30
33
|
private emitMcpRequest: (payload: McpRequestPayload) => void;
|
|
34
|
+
private log: ObservationLogger;
|
|
31
35
|
|
|
32
|
-
constructor(emitMcpRequest: (payload: McpRequestPayload) => void) {
|
|
36
|
+
constructor(emitMcpRequest: (payload: McpRequestPayload) => void, logger?: ObservationLogger) {
|
|
33
37
|
this.emitMcpRequest = emitMcpRequest;
|
|
38
|
+
this.log = logger ?? rootLogger.child({ component: 'mcp-relay' });
|
|
34
39
|
}
|
|
35
40
|
|
|
36
41
|
registerSession(sessionId: string, endpoint: SessionEndpoint): void {
|
|
@@ -60,25 +65,39 @@ export class McpRelay {
|
|
|
60
65
|
const endpoint = this.sessionEndpoints.get(sessionId);
|
|
61
66
|
if (!endpoint) return { status: 404, body: { error: 'SESSION_NOT_FOUND' } };
|
|
62
67
|
const requestId = `mcpreq_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
68
|
+
const method = (body as { method?: string })?.method ?? '?';
|
|
69
|
+
// mcp tool call:一次 MCP 调用一个 span(请求体 chunk 不逐条开 span)
|
|
70
|
+
return withSpan(
|
|
71
|
+
'mcp.tool.call',
|
|
72
|
+
{ sessionId, serverName, method },
|
|
73
|
+
() => {
|
|
74
|
+
this.log.debug({ event: 'mcp_forward', requestId, sessionId, serverName, method }, 'mcp forward');
|
|
75
|
+
return new Promise<McpRelayResult>((resolve) => {
|
|
76
|
+
const timer = setTimeout(() => {
|
|
77
|
+
this.pendingRequests.delete(requestId);
|
|
78
|
+
this.log.info(
|
|
79
|
+
{ event: 'mcp_forward_timeout', requestId, timeoutMs: REQUEST_TIMEOUT_MS },
|
|
80
|
+
'mcp request timed out',
|
|
81
|
+
);
|
|
82
|
+
resolve({ status: 504, body: { error: 'TIMEOUT', message: 'MCP request timed out' } });
|
|
83
|
+
}, REQUEST_TIMEOUT_MS);
|
|
84
|
+
this.pendingRequests.set(requestId, { sessionId, resolve, timer });
|
|
85
|
+
this.emitMcpRequest({ requestId, sessionId, serverName, token: endpoint.token, body });
|
|
86
|
+
});
|
|
87
|
+
},
|
|
88
|
+
);
|
|
73
89
|
}
|
|
74
90
|
|
|
75
91
|
handleMcpResponse(requestId: string, status: number, body: unknown): void {
|
|
76
92
|
const pending = this.pendingRequests.get(requestId);
|
|
77
93
|
if (!pending) {
|
|
78
|
-
|
|
94
|
+
this.log.info(
|
|
95
|
+
{ event: 'mcp_response_ignored', requestId, status },
|
|
96
|
+
'mcp response ignored (no pending request)',
|
|
97
|
+
);
|
|
79
98
|
return;
|
|
80
99
|
}
|
|
81
|
-
|
|
100
|
+
this.log.debug({ event: 'mcp_response', requestId, status }, 'mcp response');
|
|
82
101
|
clearTimeout(pending.timer);
|
|
83
102
|
this.pendingRequests.delete(requestId);
|
|
84
103
|
pending.resolve({ status, body });
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// GENERATED FROM packages/observability/src/http-context.ts — DO NOT EDIT
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* HTTP 请求上下文中间件:requestId 归一化 + traceparent 提取 + SERVER span + 访问日志。
|
|
5
|
+
*
|
|
6
|
+
* - 不读 body(agent-api webhook 需先验签,F10);
|
|
7
|
+
* - `/health` 与 K8s 探针路径降噪(debug 级别);SSE 只记连接建立/断开(D8);
|
|
8
|
+
* - 响应头回写 `x-request-id`;入站非法标注 `requestIdReplaced: true`(D5)。
|
|
9
|
+
*/
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import { context, SpanStatusCode, type Attributes } from '@opentelemetry/api';
|
|
12
|
+
import { readContext, runWithLogContext, type LogContext } from './log-context.js';
|
|
13
|
+
import { logger as rootLogger, type ObservationLogger } from './logger.js';
|
|
14
|
+
import { withSpan } from './trace.js';
|
|
15
|
+
|
|
16
|
+
/** 结构化最小请求面(不依赖 express 类型,agent-gear 无 express 也可 vendor)。 */
|
|
17
|
+
export interface HttpContextRequest {
|
|
18
|
+
method?: string;
|
|
19
|
+
path?: string;
|
|
20
|
+
url?: string;
|
|
21
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
22
|
+
route?: { path?: string | string[] };
|
|
23
|
+
ip?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface HttpContextResponse {
|
|
27
|
+
statusCode: number;
|
|
28
|
+
setHeader(name: string, value: string): void;
|
|
29
|
+
on(event: string, listener: () => void): unknown;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const REQUEST_ID_RE = /^[A-Za-z0-9._:-]{8,128}$/;
|
|
33
|
+
|
|
34
|
+
/** 入站合法沿用;缺失生成 UUID v4;非法生成 UUID v4 并置 `replaced`(D5)。 */
|
|
35
|
+
export function normalizeRequestId(raw: string | undefined): { requestId: string; replaced: boolean } {
|
|
36
|
+
if (raw !== undefined && REQUEST_ID_RE.test(raw)) return { requestId: raw, replaced: false };
|
|
37
|
+
return { requestId: randomUUID(), replaced: raw !== undefined };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const HEALTH_PATHS = new Set(['/health', '/healthz', '/readyz', '/livez', '/api/health']);
|
|
41
|
+
// SSE 端点(agent-api session-stream.ts):`/api/session/:id/stream` 与 `/api/user/stream`。
|
|
42
|
+
// routePath 可能是路由模式(`/session/:id/stream`)或完整路径(`/api/session/<id>/stream`),
|
|
43
|
+
// 统一按可选 `/api` 前缀 + `session/<id>|user` + `/stream` 匹配(D8:连接建立/断开各一条日志)。
|
|
44
|
+
const SSE_PATH_RE = /^(?:\/api)?\/(?:session\/[^/]+|user)\/stream\/?$/;
|
|
45
|
+
|
|
46
|
+
function headerValue(req: HttpContextRequest, name: string): string | undefined {
|
|
47
|
+
const raw = req.headers?.[name];
|
|
48
|
+
return Array.isArray(raw) ? raw[0] : raw;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* `app.use(httpContext())`:挂载在 `cors()` 之后、业务路由之前。
|
|
53
|
+
* `opts.logger` 仅供测试注入;缺省用进程级单例。
|
|
54
|
+
*/
|
|
55
|
+
export function httpContext(
|
|
56
|
+
opts: { logger?: ObservationLogger } = {},
|
|
57
|
+
): (req: HttpContextRequest, res: HttpContextResponse, next: () => void) => void {
|
|
58
|
+
const log = opts.logger ?? rootLogger;
|
|
59
|
+
return (req, res, next) => {
|
|
60
|
+
const { requestId, replaced } = normalizeRequestId(headerValue(req, 'x-request-id'));
|
|
61
|
+
res.setHeader('x-request-id', requestId);
|
|
62
|
+
|
|
63
|
+
const logCtx: LogContext = { requestId, ...(replaced ? { requestIdReplaced: true } : {}) };
|
|
64
|
+
runWithLogContext(logCtx, () => {
|
|
65
|
+
const method = req.method ?? 'GET';
|
|
66
|
+
const routePath = (Array.isArray(req.route?.path) ? req.route?.path[0] : req.route?.path) ?? req.path ?? req.url ?? '/';
|
|
67
|
+
const name = `${method} ${routePath}`;
|
|
68
|
+
const isHealth = HEALTH_PATHS.has(routePath);
|
|
69
|
+
const isSse = SSE_PATH_RE.test(routePath);
|
|
70
|
+
const attrs: Attributes = {
|
|
71
|
+
'http.request.method': method,
|
|
72
|
+
'url.path': routePath,
|
|
73
|
+
'url.scheme': 'http',
|
|
74
|
+
};
|
|
75
|
+
const parent = headerValue(req, 'traceparent');
|
|
76
|
+
void withSpan(
|
|
77
|
+
name,
|
|
78
|
+
attrs,
|
|
79
|
+
(span) => {
|
|
80
|
+
return new Promise<void>((resolve) => {
|
|
81
|
+
const startedAt = Date.now();
|
|
82
|
+
const logCtxInner = context.active();
|
|
83
|
+
let done = false;
|
|
84
|
+
const finish = (): void => {
|
|
85
|
+
if (done) return;
|
|
86
|
+
done = true;
|
|
87
|
+
const status = res.statusCode;
|
|
88
|
+
const durationMs = Date.now() - startedAt;
|
|
89
|
+
span.setAttribute('http.response.status_code', status);
|
|
90
|
+
if (status >= 500) span.setStatus({ code: SpanStatusCode.ERROR });
|
|
91
|
+
context.with(logCtxInner, () => {
|
|
92
|
+
runWithLogContext(logCtx, () => {
|
|
93
|
+
const fields = { component: 'http', method, path: routePath, status, durationMs };
|
|
94
|
+
if (isSse) {
|
|
95
|
+
log.info(fields, 'sse disconnected');
|
|
96
|
+
} else if (isHealth) {
|
|
97
|
+
log.debug(fields, 'request completed');
|
|
98
|
+
} else {
|
|
99
|
+
log.info(fields, 'request completed');
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
resolve();
|
|
104
|
+
};
|
|
105
|
+
res.on('finish', finish);
|
|
106
|
+
res.on('close', finish);
|
|
107
|
+
if (isSse) {
|
|
108
|
+
log.info({ component: 'http', method, path: routePath }, 'sse connected');
|
|
109
|
+
}
|
|
110
|
+
next();
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
{ parent },
|
|
114
|
+
);
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 供测试/调用方读取当前请求上下文标识。 */
|
|
120
|
+
export function currentRequestId(): string | undefined {
|
|
121
|
+
return readContext().requestId;
|
|
122
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// GENERATED FROM packages/observability/src/log-context.ts — DO NOT EDIT
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 进程内日志上下文(AsyncLocalStorage)。
|
|
5
|
+
*
|
|
6
|
+
* `runWithLogContext(ctx, fn)` 把 ctx **合并**入当前上下文(不整体覆盖);
|
|
7
|
+
* 已存在的键不被嵌套调用覆盖(先写入者优先,见 contracts/observability.md §5.3)。
|
|
8
|
+
* `logger` 的 `mixin()` 在打日志时自动注入,业务代码不手工传 `requestId` 等字段。
|
|
9
|
+
*/
|
|
10
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
11
|
+
|
|
12
|
+
export interface LogContext {
|
|
13
|
+
requestId?: string;
|
|
14
|
+
userId?: string;
|
|
15
|
+
tenantId?: string;
|
|
16
|
+
workspaceId?: string;
|
|
17
|
+
sessionId?: string;
|
|
18
|
+
controllerId?: string;
|
|
19
|
+
cloudHostId?: string;
|
|
20
|
+
containerId?: string;
|
|
21
|
+
workflowInstanceId?: string;
|
|
22
|
+
nodeId?: string;
|
|
23
|
+
/** 入站 `x-request-id` 非法被替换时置 true(D5,不静默替换) */
|
|
24
|
+
requestIdReplaced?: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const storage = new AsyncLocalStorage<LogContext>();
|
|
28
|
+
|
|
29
|
+
/** 读取当前日志上下文;无上下文时返回空对象(不抛错)。 */
|
|
30
|
+
export function readContext(): LogContext {
|
|
31
|
+
return storage.getStore() ?? {};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 在合并后的上下文中执行 `fn`:ctx 的键合并入当前上下文,**已存在的键不被覆盖**。 */
|
|
35
|
+
export function runWithLogContext<T>(ctx: LogContext, fn: () => T): T {
|
|
36
|
+
const existing = storage.getStore();
|
|
37
|
+
const merged: LogContext = existing ? { ...ctx, ...existing } : { ...ctx };
|
|
38
|
+
return storage.run(merged, fn);
|
|
39
|
+
}
|