session-pool.js
9.33 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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/**
* SessionPool — 可复用会话池管理
*
* 职责:
* - 会话的创建 / 获取 / 重置 / 关闭
* - 生命周期事件通知
* - 会话统计
*
* 不负责:
* - Protocol 选择(由 protocol-factory 决定)
* - Prompt 执行(由 stream-executor 决定)
* - Agent 配置查询(由 AgentManager 决定)
*/
const { EventEmitter } = require('events');
const { randomUUID } = require('crypto');
const { createProtocol } = require('./protocol-factory');
const { IdleTimer } = require('../engine/idle-timer');
/**
* 会话空闲上限。与 routes/agent-chat.js 的 `sessions` 池共用同一个旋钮和同一个含义
* —— 两边存的都是**常驻**的 claude CLI 子进程,回收判据也一样。
*
* 在此之前这个池子只有三条回收路径:换新会话 / reset() / killActive()。
* 「正常跑完」和「不可重试的报错」都不在其中,而 getKey 里带了 taskId
* —— 每个图节点一个新 key,于是一节点一进程、永不释放,且不报错。
* 实测 23 小时漏出 7 个图执行进程(另有 38 个来自 agent-chat 侧的另一个洞)。
*
* 每次读 env 而不是模块加载时读一次:单测要能改这个值,不然只能等 30 分钟。
*/
function idleMs() {
return Number(process.env.AGENT_SESSION_IDLE_MS) || 30 * 60 * 1000;
}
class SessionPool extends EventEmitter {
constructor() {
super();
this.sessions = new Map();
this.activeKey = null;
}
/**
* 生成会话唯一 Key
*
* key 里必须带 (companyId, taskId)(28 §6 批次 3-12):Agent 本体合并成一份之后
* `agentName` 不再唯一标识一次运行 —— 两家公司调同一个本体,key 相同就会**复用同一个
* CLI 会话**,A 公司的上下文直接漏进 B 公司的对话,而且两边都成功返回、不报错。
* 不能靠 workDir 顺带带上:body 模式的 cwd 确实含这两段,legacy / scoped skill 模式的
* 不含(cwd 分别是公司私有目录和本体目录),指望「路径里恰好有」就是又一份手抄的约定。
* 缺省值与 agent-locator 的保留值同名,含义一致:没有公司 / 没有任务。
*/
getKey(agentName, agentConfig, workDir, scope) {
const runtime = `${agentConfig.companyId || '_global'}/${agentConfig.taskId || '_no-task'}`;
const base = `acp:${agentName}:${agentConfig.client}:${agentConfig.deploy}:${runtime}:${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
* @param {string} [scope] - 会话细分维度(如 conversationId);必须与 getOrCreate 查询时用的一致
* @returns {Promise<object>} session object
*/
async create(agentName, agentConfig, launcherConfig, protocolName, workDir, scope) {
// scope 必须透传:不透传的话 getOrCreate 用「带 scope 的 key」查、create 用
// 「不带 scope 的 key」存,两个 key 永远对不上 —— 查不到就再建一个,会话池里
// 堆的全是查不到的死会话,且每次调用都新起一个 CLI 进程,同样不报错。
const sessionKey = this.getKey(agentName, agentConfig, workDir, scope);
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(),
idleTimer: null, // 由 armIdle 上弦;新建会话在首次调用期间故意不计时
};
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) {
existing.idleTimer?.cancel(); // 请求在途期间不计空闲
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, scope);
}
/**
* 调用结束后给会话上弦;调用开始时由 getOrCreate 停表。
*
* 计时器只在「没有在途请求」的间隙走,所以再长的单次生成也不会被 TTL 打断
* —— 与 agent-chat 侧同一套写法,比在流式回调里 touch() 少一处要维护的调用点。
*
* ponytail: 这是**兜底**不是精算 —— 一次性 taskId(图节点跑完就不会再用)也要
* 白占一个 TTL 周期的内存,天花板是「并发会话数 × 单进程 RSS(实测约 300MB)× TTL」。
* 要更紧的话,调用方在明知 taskId 一次性时直接 reset(key) 立刻释放;这里不替它判断,
* 因为 devloop 的 retry-with-reflection 复用同一个 taskId,一刀切关掉会砍掉复用能力。
*/
armIdle(sessionKey) {
const session = this.sessions.get(sessionKey);
if (!session) return;
session.idleTimer?.cancel();
const ms = idleMs();
session.idleTimer = new IdleTimer(
ms,
() => {
console.log(`[SessionPool] 🧹 会话空闲超过 ${Math.round(ms / 60000)} 分钟,回收 ${sessionKey}`);
this.reset(sessionKey).catch(() => {});
},
{ label: `pool-session:${sessionKey}` }
).start();
}
/**
* 重置(断开 + 清理)单个会话
*/
async reset(sessionKey) {
const session = this.sessions.get(sessionKey);
session?.idleTimer?.cancel();
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;
session.idleTimer?.cancel();
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 };