session-pool.js
5.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/**
* SessionPool — 可复用会话池管理
*
* 职责:
* - 会话的创建 / 获取 / 重置 / 关闭
* - 生命周期事件通知
* - 会话统计
*
* 不负责:
* - Protocol 选择(由 protocol-factory 决定)
* - Prompt 执行(由 stream-executor 决定)
* - Agent 配置查询(由 AgentManager 决定)
*/
const { EventEmitter } = require('events');
const { randomUUID } = require('crypto');
const { createProtocol } = require('./protocol-factory');
class SessionPool extends EventEmitter {
constructor() {
super();
this.sessions = new Map();
this.activeKey = null;
}
/**
* 生成会话唯一 Key
*/
getKey(agentName, agentConfig, workDir, scope) {
const base = `acp:${agentName}:${agentConfig.client}:${agentConfig.deploy}:${workDir}`;
return scope ? `${base}:${scope}` : base;
}
/**
* 创建新会话(Launcher + Transport + Protocol 全链路)
*
* @param {string} agentName
* @param {object} agentConfig - { type, client, deploy, ... }
* @param {object} launcherConfig - 来自 runtime-resolver
* @param {string} protocolName - acp / claude-stream / codex-jsonl
* @param {string} workDir
* @returns {Promise<object>} session object
*/
async create(agentName, agentConfig, launcherConfig, protocolName, workDir) {
const sessionKey = this.getKey(agentName, agentConfig, workDir);
this._emit(agentName, protocolName, 'initializing', null, sessionKey);
// 通过工厂创建 Protocol(无 if/else)
const protocol = createProtocol(
protocolName,
{ id: agentName, name: agentName },
{ yolo: true }
);
let launcher = null;
if (protocolName === 'claude-cli') {
// ClaudeCliProtocol 自行管理子进程(每次 sendPrompt 启动 claude -p)
// 不需要 launcher/transport
await protocol.connect(null, workDir);
await protocol.initialize();
await protocol.newSession({ cwd: workDir });
} else {
// 其他协议:组合 Launcher + Transport + JSON-RPC
const { createConnection } = require('@mas/acp-core');
const { transport, launcher: lnch } = await createConnection(
agentConfig, launcherConfig, workDir
);
launcher = lnch;
await protocol.connect(transport, workDir);
await protocol.initialize();
await protocol.newSession({ cwd: workDir });
}
const sessionId = protocol.sessionId || `${protocolName}-${agentName}-${randomUUID()}`;
if (!protocol.sessionId) {
protocol.sessionId = sessionId;
}
this._emit(agentName, protocolName, 'ready', sessionId, sessionKey);
const session = {
key: sessionKey,
agentName,
protocolName,
protocol,
launcher,
sessionId,
callQueue: Promise.resolve(),
};
this.sessions.set(sessionKey, session);
return session;
}
/**
* 获取已有会话或创建新会话
*/
async getOrCreate(agentName, agentConfig, launcherConfig, protocolName, workDir, scope) {
const key = this.getKey(agentName, agentConfig, workDir, scope);
const existing = this.sessions.get(key);
if (existing?.protocol?.isConnected) {
this._emit(agentName, protocolName, 'reused', existing.sessionId, key);
return existing;
}
// 清理失效会话
if (existing?.protocol) {
try { existing.protocol.disconnect(); } catch { }
if (existing.launcher) {
try { await existing.launcher.stop(); } catch { }
}
this.sessions.delete(key);
}
return this.create(agentName, agentConfig, launcherConfig, protocolName, workDir);
}
/**
* 重置(断开 + 清理)单个会话
*/
async reset(sessionKey) {
const session = this.sessions.get(sessionKey);
if (session?.protocol) {
this._emit(
session.agentName, session.protocolName, 'closed',
session.sessionId, sessionKey, 'reset'
);
try { session.protocol.disconnect(); } catch { }
if (session.launcher) {
try { await session.launcher.stop(); } catch { }
}
}
this.sessions.delete(sessionKey);
if (this.activeKey === sessionKey) {
this.activeKey = null;
}
}
/**
* 关闭所有会话(并行)
*/
async closeAll() {
const keys = [...this.sessions.keys()];
if (keys.length === 0) return;
console.log(`[AgentManager] 关闭 ${keys.length} 个会话...`);
await Promise.allSettled(keys.map(key => this.reset(key)));
this.sessions.clear();
this.activeKey = null;
console.log(`[AgentManager] 所有会话已关闭`);
}
/**
* 会话池统计
*/
getStats() {
const list = [];
for (const [key, session] of this.sessions) {
list.push({
key,
agentName: session.agentName,
protocol: session.protocolName,
sessionId: session.sessionId,
connected: !!session.protocol?.isConnected,
active: this.activeKey === key,
});
}
return {
total: list.length,
connected: list.filter(s => s.connected).length,
active: this.activeKey,
sessions: list,
};
}
/**
* 终止当前活跃会话
* @returns {object|null} 被终止的会话信息,或 null
*/
killActive() {
if (!this.activeKey) return null;
const session = this.sessions.get(this.activeKey);
if (!session?.protocol) return null;
this._emit(
session.agentName, session.protocolName, 'closed',
session.sessionId, session.key, 'killed'
);
session.protocol.disconnect();
this.sessions.delete(this.activeKey);
this.activeKey = null;
return session;
}
/** @private */
_emit(agentName, protocol, status, sessionId, sessionKey, reason) {
const payload = { agentName, protocol, status, sessionId, sessionKey };
if (reason) payload.reason = reason;
this.emit('session_event', payload);
}
}
module.exports = { SessionPool };