wherever-dev 0.2.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/LICENSE +21 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1264 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.d.ts +157 -0
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +2 -0
- package/dist/protocol.js.map +1 -0
- package/dist/session-pool.d.ts +119 -0
- package/dist/session-pool.d.ts.map +1 -0
- package/dist/session-pool.js +909 -0
- package/dist/session-pool.js.map +1 -0
- package/dist/session-types.d.ts +44 -0
- package/dist/session-types.d.ts.map +1 -0
- package/dist/session-types.js +2 -0
- package/dist/session-types.js.map +1 -0
- package/package.json +42 -0
- package/public/_app/env.js +1 -0
- package/public/_app/immutable/assets/0.DvZxoQjW.css +2754 -0
- package/public/_app/immutable/chunks/B5WJGjcR.js +23 -0
- package/public/_app/immutable/chunks/B5WJGjcR.js.map +1 -0
- package/public/_app/immutable/chunks/BEWoN05F.js +110 -0
- package/public/_app/immutable/chunks/BEWoN05F.js.map +1 -0
- package/public/_app/immutable/chunks/BqMutrfe.js +2129 -0
- package/public/_app/immutable/chunks/BqMutrfe.js.map +1 -0
- package/public/_app/immutable/chunks/DFxBx2vA.js +897 -0
- package/public/_app/immutable/chunks/DFxBx2vA.js.map +1 -0
- package/public/_app/immutable/chunks/DiYtJzYU.js +396 -0
- package/public/_app/immutable/chunks/DiYtJzYU.js.map +1 -0
- package/public/_app/immutable/chunks/_lppinj8.js +879 -0
- package/public/_app/immutable/chunks/_lppinj8.js.map +1 -0
- package/public/_app/immutable/chunks/rMw82gDs.js +3048 -0
- package/public/_app/immutable/chunks/rMw82gDs.js.map +1 -0
- package/public/_app/immutable/entry/app.BFki2czn.js +309 -0
- package/public/_app/immutable/entry/app.BFki2czn.js.map +1 -0
- package/public/_app/immutable/entry/start.BceUuq27.js +6 -0
- package/public/_app/immutable/entry/start.BceUuq27.js.map +1 -0
- package/public/_app/immutable/nodes/0.BzvDOlXz.js +546 -0
- package/public/_app/immutable/nodes/0.BzvDOlXz.js.map +1 -0
- package/public/_app/immutable/nodes/1.DMtW3tA5.js +24 -0
- package/public/_app/immutable/nodes/1.DMtW3tA5.js.map +1 -0
- package/public/_app/immutable/nodes/2.CnZp8abw.js +5152 -0
- package/public/_app/immutable/nodes/2.CnZp8abw.js.map +1 -0
- package/public/_app/version.json +1 -0
- package/public/icon.png +0 -0
- package/public/index.html +84 -0
- package/public/logo.svg +52 -0
- package/public/pwa/apple-touch-icon.png +0 -0
- package/public/pwa/favicon-192.png +0 -0
- package/public/pwa/favicon-512.png +0 -0
- package/public/pwa/favicon.ico +0 -0
- package/public/pwa/favicon.png +0 -0
- package/public/pwa/manifest.webmanifest +27 -0
- package/public/service-worker.js +305 -0
|
@@ -0,0 +1,909 @@
|
|
|
1
|
+
import path from 'path';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { execSync } from 'node:child_process';
|
|
5
|
+
/**
|
|
6
|
+
* Normalize a path to prevent duplicate session folders.
|
|
7
|
+
* - Removes trailing slashes (except for root "/")
|
|
8
|
+
* - Resolves . and .. segments
|
|
9
|
+
* - Ensures consistent encoding for same physical path
|
|
10
|
+
*/
|
|
11
|
+
export function normalizePath(p) {
|
|
12
|
+
// Resolve to absolute path first (handles . and ..)
|
|
13
|
+
let normalized = path.resolve(p);
|
|
14
|
+
// Remove trailing slash (except for root "/")
|
|
15
|
+
if (normalized !== '/' && normalized.endsWith('/')) {
|
|
16
|
+
normalized = normalized.slice(0, -1);
|
|
17
|
+
}
|
|
18
|
+
return normalized;
|
|
19
|
+
}
|
|
20
|
+
export function getWhereverConfig() {
|
|
21
|
+
const configDir = path.join(os.homedir(), '.wherever');
|
|
22
|
+
const configPath = path.join(configDir, 'config.json');
|
|
23
|
+
if (!fs.existsSync(configPath)) {
|
|
24
|
+
try {
|
|
25
|
+
fs.mkdirSync(configDir, { recursive: true });
|
|
26
|
+
const defaultConfig = {
|
|
27
|
+
gitInitDefault: false,
|
|
28
|
+
remoteRepoRules: [],
|
|
29
|
+
commonFolders: []
|
|
30
|
+
};
|
|
31
|
+
fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2), 'utf8');
|
|
32
|
+
return defaultConfig;
|
|
33
|
+
}
|
|
34
|
+
catch (err) {
|
|
35
|
+
console.error('Failed to create default wherever config:', err);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
try {
|
|
40
|
+
const content = fs.readFileSync(configPath, 'utf8');
|
|
41
|
+
return JSON.parse(content);
|
|
42
|
+
}
|
|
43
|
+
catch (err) {
|
|
44
|
+
console.error('Failed to parse wherever config file:', err);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return {};
|
|
48
|
+
}
|
|
49
|
+
export function setupUpstreamTracking(resolvedCwd) {
|
|
50
|
+
try {
|
|
51
|
+
let defaultBranch = '';
|
|
52
|
+
try {
|
|
53
|
+
defaultBranch = execSync('git symbolic-ref --short HEAD', { cwd: resolvedCwd }).toString().trim();
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
try {
|
|
57
|
+
defaultBranch = execSync('git config --get init.defaultBranch', { cwd: resolvedCwd }).toString().trim();
|
|
58
|
+
}
|
|
59
|
+
catch (e2) { }
|
|
60
|
+
}
|
|
61
|
+
if (!defaultBranch) {
|
|
62
|
+
defaultBranch = 'main'; // fallback
|
|
63
|
+
}
|
|
64
|
+
execSync(`git config branch.${defaultBranch}.remote origin`, { cwd: resolvedCwd, stdio: 'ignore' });
|
|
65
|
+
execSync(`git config branch.${defaultBranch}.merge refs/heads/${defaultBranch}`, { cwd: resolvedCwd, stdio: 'ignore' });
|
|
66
|
+
console.log(`Successfully pre-configured branch '${defaultBranch}' upstream tracking to origin`);
|
|
67
|
+
}
|
|
68
|
+
catch (err) {
|
|
69
|
+
console.error('Failed to pre-configure upstream tracking branch:', err);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
import { createAgentSession, AuthStorage, ModelRegistry, DefaultResourceLoader, SettingsManager, getAgentDir, SessionManager } from '@earendil-works/pi-coding-agent';
|
|
73
|
+
export class SessionPool {
|
|
74
|
+
sessions = new Map();
|
|
75
|
+
pendingSessions = new Map();
|
|
76
|
+
pendingCreateSessions = new Map();
|
|
77
|
+
authStorage;
|
|
78
|
+
modelRegistry;
|
|
79
|
+
agentDir;
|
|
80
|
+
idleTimeoutMs;
|
|
81
|
+
onEvent;
|
|
82
|
+
constructor(idleTimeoutMs = 300_000) {
|
|
83
|
+
this.agentDir = getAgentDir();
|
|
84
|
+
this.authStorage = AuthStorage.create();
|
|
85
|
+
this.modelRegistry = ModelRegistry.create(this.authStorage);
|
|
86
|
+
this.idleTimeoutMs = idleTimeoutMs;
|
|
87
|
+
}
|
|
88
|
+
async initialize() {
|
|
89
|
+
this.modelRegistry.refresh();
|
|
90
|
+
}
|
|
91
|
+
getAvailableModels() {
|
|
92
|
+
const available = this.modelRegistry.getAvailable();
|
|
93
|
+
const settings = SettingsManager.create(process.cwd(), this.agentDir);
|
|
94
|
+
const defaultProvider = settings.getDefaultProvider();
|
|
95
|
+
const defaultModel = settings.getDefaultModel();
|
|
96
|
+
return available.map((m) => {
|
|
97
|
+
const isDefault = m.provider === defaultProvider && m.id === defaultModel;
|
|
98
|
+
return {
|
|
99
|
+
provider: m.provider,
|
|
100
|
+
modelId: m.id,
|
|
101
|
+
label: `${this.modelRegistry.getProviderDisplayName(m.provider)}: ${m.name}`,
|
|
102
|
+
isDefault,
|
|
103
|
+
};
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
findModel(provider, modelId) {
|
|
107
|
+
return this.modelRegistry.find(provider, modelId);
|
|
108
|
+
}
|
|
109
|
+
async loadSession(sessionFile, cwd, modelStr) {
|
|
110
|
+
let resolvedFile = sessionFile;
|
|
111
|
+
// Resolve short session ID/name (no path delimiters and doesn't end in .json or .jsonl) to full absolute path
|
|
112
|
+
if (!sessionFile.includes('/') && !sessionFile.includes('\\') && !sessionFile.endsWith('.json') && !sessionFile.endsWith('.jsonl')) {
|
|
113
|
+
// 1. Check if the session is already active in memory
|
|
114
|
+
const active = Array.from(this.sessions.values()).find(s => s.sessionId === sessionFile);
|
|
115
|
+
if (active) {
|
|
116
|
+
resolvedFile = active.sessionFile;
|
|
117
|
+
}
|
|
118
|
+
else {
|
|
119
|
+
// 2. Scan the disk to find the session with the matching ID/name
|
|
120
|
+
const diskSessions = await SessionManager.listAll();
|
|
121
|
+
const found = diskSessions.find(s => s.id === sessionFile || s.name === sessionFile);
|
|
122
|
+
if (found) {
|
|
123
|
+
resolvedFile = found.path;
|
|
124
|
+
}
|
|
125
|
+
else {
|
|
126
|
+
return { tracked: null, error: `Session with ID "${sessionFile}" not found` };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
// Continue with the resolved absolute path
|
|
131
|
+
if (this.sessions.has(resolvedFile)) {
|
|
132
|
+
return { tracked: this.sessions.get(resolvedFile) };
|
|
133
|
+
}
|
|
134
|
+
if (this.pendingSessions.has(resolvedFile)) {
|
|
135
|
+
return this.pendingSessions.get(resolvedFile);
|
|
136
|
+
}
|
|
137
|
+
const loadPromise = (async () => {
|
|
138
|
+
try {
|
|
139
|
+
const sessionManager = SessionManager.open(resolvedFile);
|
|
140
|
+
const header = sessionManager.getHeader();
|
|
141
|
+
if (!header) {
|
|
142
|
+
return { tracked: null, error: 'Session file has no header' };
|
|
143
|
+
}
|
|
144
|
+
const sessionCwd = cwd || header.cwd || process.cwd();
|
|
145
|
+
const normalizedCwd = normalizePath(sessionCwd);
|
|
146
|
+
let model;
|
|
147
|
+
if (modelStr) {
|
|
148
|
+
const parsed = this.parseModelStr(modelStr);
|
|
149
|
+
if (parsed) {
|
|
150
|
+
model = this.modelRegistry.find(parsed.provider, parsed.id);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (!model && header) {
|
|
154
|
+
const entries = sessionManager.getEntries();
|
|
155
|
+
const modelChange = [...entries].reverse().find((e) => e.type === 'model_change');
|
|
156
|
+
if (modelChange && 'provider' in modelChange && 'modelId' in modelChange) {
|
|
157
|
+
model = this.modelRegistry.find(modelChange.provider, modelChange.modelId);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const settingsManager = SettingsManager.create(normalizedCwd, this.agentDir);
|
|
161
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
162
|
+
cwd: normalizedCwd,
|
|
163
|
+
agentDir: this.agentDir,
|
|
164
|
+
settingsManager,
|
|
165
|
+
});
|
|
166
|
+
await resourceLoader.reload();
|
|
167
|
+
const { session: agentSession } = await createAgentSession({
|
|
168
|
+
cwd: normalizedCwd,
|
|
169
|
+
authStorage: this.authStorage,
|
|
170
|
+
modelRegistry: this.modelRegistry,
|
|
171
|
+
model,
|
|
172
|
+
sessionManager,
|
|
173
|
+
settingsManager,
|
|
174
|
+
resourceLoader,
|
|
175
|
+
});
|
|
176
|
+
const modelLabel = agentSession.model ? `${agentSession.model.provider}:${agentSession.model.id}` : '';
|
|
177
|
+
const tracked = {
|
|
178
|
+
type: 'server',
|
|
179
|
+
sessionId: agentSession.sessionId,
|
|
180
|
+
sessionFile: resolvedFile,
|
|
181
|
+
cwd: normalizedCwd,
|
|
182
|
+
model: modelLabel,
|
|
183
|
+
agentSession,
|
|
184
|
+
clients: new Set(),
|
|
185
|
+
isIdle: true,
|
|
186
|
+
idleTimer: null,
|
|
187
|
+
eventUnsubscribe: this.setupEventListeners(resolvedFile, agentSession),
|
|
188
|
+
createdAt: Date.now(),
|
|
189
|
+
lastActivity: Date.now(),
|
|
190
|
+
};
|
|
191
|
+
this.sessions.set(resolvedFile, tracked);
|
|
192
|
+
return { tracked };
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
return { tracked: null, error: err.message };
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
this.pendingSessions.delete(resolvedFile);
|
|
199
|
+
}
|
|
200
|
+
})();
|
|
201
|
+
this.pendingSessions.set(resolvedFile, loadPromise);
|
|
202
|
+
return loadPromise;
|
|
203
|
+
}
|
|
204
|
+
async createNewSession(cwd, modelStr, gitInit, createRemote, repoVisibility) {
|
|
205
|
+
let resolvedCwd = cwd;
|
|
206
|
+
if (cwd.startsWith('~')) {
|
|
207
|
+
resolvedCwd = path.join(os.homedir(), cwd.slice(1));
|
|
208
|
+
}
|
|
209
|
+
else if (!path.isAbsolute(cwd)) {
|
|
210
|
+
resolvedCwd = path.join(os.homedir(), cwd);
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
resolvedCwd = path.resolve(cwd);
|
|
214
|
+
}
|
|
215
|
+
resolvedCwd = normalizePath(resolvedCwd);
|
|
216
|
+
const existing = this.findActiveSessionByCwd(resolvedCwd);
|
|
217
|
+
if (existing && existing.clients.size > 0) {
|
|
218
|
+
return { tracked: existing };
|
|
219
|
+
}
|
|
220
|
+
if (this.pendingCreateSessions.has(resolvedCwd)) {
|
|
221
|
+
return this.pendingCreateSessions.get(resolvedCwd);
|
|
222
|
+
}
|
|
223
|
+
const createPromise = (async () => {
|
|
224
|
+
try {
|
|
225
|
+
if (!fs.existsSync(resolvedCwd)) {
|
|
226
|
+
fs.mkdirSync(resolvedCwd, { recursive: true });
|
|
227
|
+
}
|
|
228
|
+
// Git initialization if requested
|
|
229
|
+
if (gitInit) {
|
|
230
|
+
try {
|
|
231
|
+
if (!fs.existsSync(path.join(resolvedCwd, '.git'))) {
|
|
232
|
+
execSync('git init', { cwd: resolvedCwd, stdio: 'ignore' });
|
|
233
|
+
console.log(`Initialized empty Git repository in ${resolvedCwd}`);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
catch (err) {
|
|
237
|
+
console.error(`Failed to initialize git repository in ${resolvedCwd}:`, err);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// Check if we should create a remote repo (GitHub/Codeberg etc) based on config patterns
|
|
241
|
+
const config = getWhereverConfig();
|
|
242
|
+
if (createRemote !== false && config.remoteRepoRules && Array.isArray(config.remoteRepoRules)) {
|
|
243
|
+
const rule = config.remoteRepoRules.find(r => new RegExp(r.pattern).test(resolvedCwd));
|
|
244
|
+
if (rule) {
|
|
245
|
+
const provider = rule.provider;
|
|
246
|
+
const visibility = repoVisibility || rule.visibility || 'private';
|
|
247
|
+
const repoName = path.basename(resolvedCwd);
|
|
248
|
+
// Initialize Git if matching rules and not yet a Git repo
|
|
249
|
+
if (!fs.existsSync(path.join(resolvedCwd, '.git'))) {
|
|
250
|
+
try {
|
|
251
|
+
execSync('git init', { cwd: resolvedCwd, stdio: 'ignore' });
|
|
252
|
+
console.log(`Initialized empty Git repository in ${resolvedCwd} (due to matching remote rule)`);
|
|
253
|
+
}
|
|
254
|
+
catch (e) {
|
|
255
|
+
console.error(`Failed to initialize git repository in ${resolvedCwd} for remote rule:`, e);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
// Check if remote already exists
|
|
259
|
+
let hasOrigin = false;
|
|
260
|
+
try {
|
|
261
|
+
const remotes = execSync('git remote', { cwd: resolvedCwd }).toString();
|
|
262
|
+
hasOrigin = remotes.split('\n').map(r => r.trim()).includes('origin');
|
|
263
|
+
}
|
|
264
|
+
catch (e) { }
|
|
265
|
+
if (!hasOrigin) {
|
|
266
|
+
if (provider === 'github') {
|
|
267
|
+
try {
|
|
268
|
+
console.log(`Creating GitHub repository: ${repoName} (${visibility})...`);
|
|
269
|
+
execSync(`gh repo create "${repoName}" --${visibility} --source=. --remote=origin`, { cwd: resolvedCwd, stdio: 'ignore' });
|
|
270
|
+
console.log(`Successfully created GitHub repo ${repoName} and added remote 'origin'`);
|
|
271
|
+
setupUpstreamTracking(resolvedCwd);
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
console.error('Failed to create GitHub repository:', err);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
else if (provider === 'codeberg' || provider === 'gitea' || provider === 'forgejo') {
|
|
278
|
+
try {
|
|
279
|
+
let created = false;
|
|
280
|
+
let repoUrl = '';
|
|
281
|
+
console.log(`Creating Codeberg/Gitea repository: ${repoName}...`);
|
|
282
|
+
try {
|
|
283
|
+
// Try tea CLI
|
|
284
|
+
const output = execSync(`tea repo create --name "${repoName}" ${visibility === 'private' ? '--private' : ''}`, { cwd: resolvedCwd }).toString();
|
|
285
|
+
created = true;
|
|
286
|
+
const urlMatch = output.match(/https?:\/\/\S+/i) || output.match(/git@\S+/i);
|
|
287
|
+
if (urlMatch)
|
|
288
|
+
repoUrl = urlMatch[0];
|
|
289
|
+
}
|
|
290
|
+
catch (err) {
|
|
291
|
+
try {
|
|
292
|
+
// Try cb CLI
|
|
293
|
+
const output = execSync(`cb repo create --name "${repoName}" ${visibility === 'private' ? '--private' : ''}`, { cwd: resolvedCwd }).toString();
|
|
294
|
+
created = true;
|
|
295
|
+
const urlMatch = output.match(/https?:\/\/\S+/i) || output.match(/git@\S+/i);
|
|
296
|
+
if (urlMatch)
|
|
297
|
+
repoUrl = urlMatch[0];
|
|
298
|
+
}
|
|
299
|
+
catch (err2) {
|
|
300
|
+
console.error('Failed to create repository with tea or cb CLI:', err, err2);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (created) {
|
|
304
|
+
if (!repoUrl) {
|
|
305
|
+
// fallback to constructing the URL
|
|
306
|
+
const domain = provider === 'codeberg' ? 'codeberg.org' : 'gitea.com';
|
|
307
|
+
let user = '';
|
|
308
|
+
try {
|
|
309
|
+
user = execSync('tea whoami').toString().trim().split(/\s+/).pop() || '';
|
|
310
|
+
}
|
|
311
|
+
catch (e) {
|
|
312
|
+
try {
|
|
313
|
+
const cbWho = execSync('cb auth whoami').toString().trim();
|
|
314
|
+
user = cbWho.split(/\s+/).pop() || '';
|
|
315
|
+
}
|
|
316
|
+
catch (e2) { }
|
|
317
|
+
}
|
|
318
|
+
if (!user) {
|
|
319
|
+
user = 'username_placeholder';
|
|
320
|
+
}
|
|
321
|
+
repoUrl = `git@${domain}:${user}/${repoName}.git`;
|
|
322
|
+
}
|
|
323
|
+
execSync(`git remote add origin "${repoUrl}"`, { cwd: resolvedCwd, stdio: 'ignore' });
|
|
324
|
+
console.log(`Successfully created Codeberg/Gitea repo and added remote origin: ${repoUrl}`);
|
|
325
|
+
setupUpstreamTracking(resolvedCwd);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
catch (err) {
|
|
329
|
+
console.error('Failed to configure remote repository:', err);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
const sessionManager = SessionManager.create(resolvedCwd);
|
|
336
|
+
let model;
|
|
337
|
+
if (modelStr) {
|
|
338
|
+
const parsed = this.parseModelStr(modelStr);
|
|
339
|
+
if (parsed) {
|
|
340
|
+
model = this.modelRegistry.find(parsed.provider, parsed.id);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
const settingsManager = SettingsManager.create(resolvedCwd, this.agentDir);
|
|
344
|
+
const resourceLoader = new DefaultResourceLoader({
|
|
345
|
+
cwd: resolvedCwd,
|
|
346
|
+
agentDir: this.agentDir,
|
|
347
|
+
settingsManager,
|
|
348
|
+
});
|
|
349
|
+
await resourceLoader.reload();
|
|
350
|
+
const { session: agentSession } = await createAgentSession({
|
|
351
|
+
cwd: resolvedCwd,
|
|
352
|
+
authStorage: this.authStorage,
|
|
353
|
+
modelRegistry: this.modelRegistry,
|
|
354
|
+
model,
|
|
355
|
+
sessionManager,
|
|
356
|
+
settingsManager,
|
|
357
|
+
resourceLoader,
|
|
358
|
+
});
|
|
359
|
+
const sessionFile = agentSession.sessionFile || '';
|
|
360
|
+
const modelLabel = agentSession.model ? `${agentSession.model.provider}:${agentSession.model.id}` : '';
|
|
361
|
+
const tracked = {
|
|
362
|
+
type: 'server',
|
|
363
|
+
sessionId: agentSession.sessionId,
|
|
364
|
+
sessionFile,
|
|
365
|
+
cwd: resolvedCwd,
|
|
366
|
+
model: modelLabel,
|
|
367
|
+
agentSession,
|
|
368
|
+
clients: new Set(),
|
|
369
|
+
isIdle: true,
|
|
370
|
+
idleTimer: null,
|
|
371
|
+
eventUnsubscribe: this.setupEventListeners(sessionFile, agentSession),
|
|
372
|
+
createdAt: Date.now(),
|
|
373
|
+
lastActivity: Date.now(),
|
|
374
|
+
};
|
|
375
|
+
this.sessions.set(sessionFile, tracked);
|
|
376
|
+
return { tracked, sessionFile };
|
|
377
|
+
}
|
|
378
|
+
catch (err) {
|
|
379
|
+
return { tracked: null, error: err.message };
|
|
380
|
+
}
|
|
381
|
+
finally {
|
|
382
|
+
this.pendingCreateSessions.delete(resolvedCwd);
|
|
383
|
+
}
|
|
384
|
+
})();
|
|
385
|
+
this.pendingCreateSessions.set(resolvedCwd, createPromise);
|
|
386
|
+
return createPromise;
|
|
387
|
+
}
|
|
388
|
+
addClient(sessionFileOrId, clientId) {
|
|
389
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
390
|
+
if (!tracked)
|
|
391
|
+
return null;
|
|
392
|
+
tracked.clients.add(clientId);
|
|
393
|
+
tracked.lastActivity = Date.now();
|
|
394
|
+
this.cancelIdleCheck(tracked.sessionFile);
|
|
395
|
+
return tracked;
|
|
396
|
+
}
|
|
397
|
+
removeClient(sessionFileOrId, clientId) {
|
|
398
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
399
|
+
if (!tracked)
|
|
400
|
+
return;
|
|
401
|
+
tracked.clients.delete(clientId);
|
|
402
|
+
this.scheduleIdleCheck(tracked.sessionFile);
|
|
403
|
+
}
|
|
404
|
+
getSession(sessionFileOrId) {
|
|
405
|
+
if (this.sessions.has(sessionFileOrId)) {
|
|
406
|
+
return this.sessions.get(sessionFileOrId);
|
|
407
|
+
}
|
|
408
|
+
for (const s of this.sessions.values()) {
|
|
409
|
+
if (s.sessionId === sessionFileOrId)
|
|
410
|
+
return s;
|
|
411
|
+
}
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
findActiveSessionByCwd(cwd) {
|
|
415
|
+
const normalizedCwd = normalizePath(cwd);
|
|
416
|
+
for (const s of this.sessions.values()) {
|
|
417
|
+
if (s.cwd === normalizedCwd)
|
|
418
|
+
return s;
|
|
419
|
+
}
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
detectConflict(sessionFileOrId, targetCwd) {
|
|
423
|
+
if (this.getSession(sessionFileOrId)) {
|
|
424
|
+
return { conflict: false };
|
|
425
|
+
}
|
|
426
|
+
const normalizedTargetCwd = normalizePath(targetCwd);
|
|
427
|
+
for (const s of this.sessions.values()) {
|
|
428
|
+
if (s.cwd === normalizedTargetCwd && s.clients.size > 0) {
|
|
429
|
+
return { conflict: true, otherSessionId: s.sessionId, otherCwd: s.cwd };
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return { conflict: false };
|
|
433
|
+
}
|
|
434
|
+
getSessionHistory(sessionFileOrId) {
|
|
435
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
436
|
+
if (!tracked)
|
|
437
|
+
return [];
|
|
438
|
+
const sessionManager = SessionManager.open(tracked.sessionFile);
|
|
439
|
+
const entries = sessionManager.getEntries();
|
|
440
|
+
const messages = [];
|
|
441
|
+
for (const entry of entries) {
|
|
442
|
+
if (entry.type === 'message') {
|
|
443
|
+
const msgEntry = entry;
|
|
444
|
+
const msg = msgEntry.message;
|
|
445
|
+
const ts = Date.parse(msgEntry.timestamp);
|
|
446
|
+
if (msg.role === 'user') {
|
|
447
|
+
const content = this.extractMessageText(msg);
|
|
448
|
+
if (content) {
|
|
449
|
+
messages.push({ role: 'user', content, timestamp: ts });
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
else if (msg.role === 'assistant') {
|
|
453
|
+
const content = msg.content;
|
|
454
|
+
if (Array.isArray(content)) {
|
|
455
|
+
for (const block of content) {
|
|
456
|
+
if (block.type === 'thinking') {
|
|
457
|
+
const thinking = block.thinking || '';
|
|
458
|
+
if (thinking) {
|
|
459
|
+
messages.push({ role: 'thinking', content: thinking, timestamp: ts });
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
else if (block.type === 'text') {
|
|
463
|
+
const text = block.text || '';
|
|
464
|
+
if (text) {
|
|
465
|
+
messages.push({ role: 'assistant', content: text, timestamp: ts });
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
else if (block.type === 'toolCall') {
|
|
469
|
+
const tc = block;
|
|
470
|
+
const toolName = tc.name || tc.toolName || 'unknown';
|
|
471
|
+
const rawArgs = tc.arguments || tc.args;
|
|
472
|
+
const args = rawArgs ? JSON.stringify(rawArgs) : '';
|
|
473
|
+
messages.push({ role: 'tool_call', content: args, timestamp: ts, toolName });
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
else if (typeof content === 'string' && content) {
|
|
478
|
+
messages.push({ role: 'assistant', content, timestamp: ts });
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
else if (msg.role === 'toolResult') {
|
|
482
|
+
const resultMsg = msg;
|
|
483
|
+
const toolName = resultMsg.toolName || 'unknown';
|
|
484
|
+
let resultText = '';
|
|
485
|
+
if (Array.isArray(resultMsg.content)) {
|
|
486
|
+
resultText = resultMsg.content
|
|
487
|
+
.filter((c) => c.type === 'text')
|
|
488
|
+
.map((c) => c.text || '')
|
|
489
|
+
.join('\n');
|
|
490
|
+
}
|
|
491
|
+
else if (typeof resultMsg.content === 'string') {
|
|
492
|
+
resultText = resultMsg.content;
|
|
493
|
+
}
|
|
494
|
+
messages.push({ role: 'tool_result', content: resultText, timestamp: ts, toolName, isError: !!resultMsg.isError });
|
|
495
|
+
}
|
|
496
|
+
else if (msg.role === 'bashExecution') {
|
|
497
|
+
const bashMsg = msg;
|
|
498
|
+
messages.push({
|
|
499
|
+
role: 'tool_call',
|
|
500
|
+
content: bashMsg.command || '',
|
|
501
|
+
timestamp: ts,
|
|
502
|
+
toolName: 'bash',
|
|
503
|
+
});
|
|
504
|
+
if (bashMsg.output) {
|
|
505
|
+
messages.push({
|
|
506
|
+
role: 'tool_result',
|
|
507
|
+
content: bashMsg.output,
|
|
508
|
+
timestamp: ts,
|
|
509
|
+
toolName: 'bash',
|
|
510
|
+
isError: bashMsg.exitCode !== undefined && bashMsg.exitCode !== 0,
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
return messages;
|
|
517
|
+
}
|
|
518
|
+
async listSessions() {
|
|
519
|
+
const diskSessions = await SessionManager.listAll();
|
|
520
|
+
const folderMap = new Map();
|
|
521
|
+
for (const s of diskSessions) {
|
|
522
|
+
const rawCwd = s.cwd || '';
|
|
523
|
+
let cwd = rawCwd;
|
|
524
|
+
if (rawCwd.startsWith('~')) {
|
|
525
|
+
cwd = path.join(os.homedir(), rawCwd.slice(1));
|
|
526
|
+
}
|
|
527
|
+
else if (!path.isAbsolute(rawCwd)) {
|
|
528
|
+
cwd = path.join(os.homedir(), rawCwd);
|
|
529
|
+
}
|
|
530
|
+
cwd = normalizePath(cwd);
|
|
531
|
+
if (!folderMap.has(cwd)) {
|
|
532
|
+
folderMap.set(cwd, []);
|
|
533
|
+
}
|
|
534
|
+
const active = this.sessions.get(s.path);
|
|
535
|
+
folderMap.get(cwd).push({
|
|
536
|
+
path: s.path,
|
|
537
|
+
id: s.id,
|
|
538
|
+
name: s.name,
|
|
539
|
+
created: s.created.toISOString(),
|
|
540
|
+
modified: s.modified.toISOString(),
|
|
541
|
+
messageCount: s.messageCount,
|
|
542
|
+
firstMessage: s.firstMessage,
|
|
543
|
+
isActive: !!active,
|
|
544
|
+
clientCount: active ? active.clients.size : 0,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
const folders = [];
|
|
548
|
+
for (const [cwdPath, sessions] of folderMap.entries()) {
|
|
549
|
+
const name = path.basename(cwdPath) || cwdPath;
|
|
550
|
+
folders.push({ path: cwdPath, name, sessions: sessions.sort((a, b) => b.modified.localeCompare(a.modified)) });
|
|
551
|
+
}
|
|
552
|
+
return folders.sort((a, b) => {
|
|
553
|
+
const aTime = a.sessions[0]?.modified || '';
|
|
554
|
+
const bTime = b.sessions[0]?.modified || '';
|
|
555
|
+
return bTime.localeCompare(aTime);
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
getActiveSessions() {
|
|
559
|
+
return Array.from(this.sessions.values()).map(s => ({
|
|
560
|
+
sessionId: s.sessionId,
|
|
561
|
+
sessionFile: s.sessionFile,
|
|
562
|
+
cwd: s.cwd,
|
|
563
|
+
model: s.model,
|
|
564
|
+
clientCount: s.clients.size,
|
|
565
|
+
isIdle: s.isIdle,
|
|
566
|
+
createdAt: s.createdAt,
|
|
567
|
+
lastActivity: s.lastActivity,
|
|
568
|
+
}));
|
|
569
|
+
}
|
|
570
|
+
async takeOver(cwd, targetSessionId) {
|
|
571
|
+
const existing = this.findActiveSessionByCwd(cwd);
|
|
572
|
+
const interruptedClientIds = new Set();
|
|
573
|
+
if (existing && existing.sessionId !== targetSessionId) {
|
|
574
|
+
try {
|
|
575
|
+
if (existing.type === 'server') {
|
|
576
|
+
await existing.agentSession.abort();
|
|
577
|
+
}
|
|
578
|
+
else if (existing.type === 'cli') {
|
|
579
|
+
existing.cliWs.send(JSON.stringify({ type: 'cli_abort' }));
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
catch (err) {
|
|
583
|
+
console.error(`Failed to abort session ${existing.sessionId} during takeover:`, err);
|
|
584
|
+
}
|
|
585
|
+
const interruptedClients = Array.from(existing.clients);
|
|
586
|
+
for (const clientId of interruptedClients) {
|
|
587
|
+
existing.clients.delete(clientId);
|
|
588
|
+
interruptedClientIds.add(clientId);
|
|
589
|
+
}
|
|
590
|
+
this.scheduleIdleCheck(existing.sessionFile);
|
|
591
|
+
}
|
|
592
|
+
return interruptedClientIds;
|
|
593
|
+
}
|
|
594
|
+
async sendUserMessage(sessionFileOrId, text, streamingBehavior) {
|
|
595
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
596
|
+
if (!tracked)
|
|
597
|
+
return;
|
|
598
|
+
tracked.lastActivity = Date.now();
|
|
599
|
+
this.cancelIdleCheck(tracked.sessionFile);
|
|
600
|
+
const isBash = text.trimStart().startsWith('!');
|
|
601
|
+
if (isBash) {
|
|
602
|
+
const isExcluded = text.trimStart().startsWith('!!');
|
|
603
|
+
const command = isExcluded ? text.trimStart().slice(2).trim() : text.trimStart().slice(1).trim();
|
|
604
|
+
if (command) {
|
|
605
|
+
if (tracked.type === 'server') {
|
|
606
|
+
if (this.onEvent) {
|
|
607
|
+
this.onEvent(tracked.sessionFile, {
|
|
608
|
+
type: 'tool_execution_start',
|
|
609
|
+
toolName: 'bash',
|
|
610
|
+
args: { command },
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
try {
|
|
614
|
+
const result = await tracked.agentSession.executeBash(command, (chunk) => {
|
|
615
|
+
if (this.onEvent) {
|
|
616
|
+
this.onEvent(tracked.sessionFile, {
|
|
617
|
+
type: 'tool_execution_update',
|
|
618
|
+
toolName: 'bash',
|
|
619
|
+
delta: chunk,
|
|
620
|
+
});
|
|
621
|
+
}
|
|
622
|
+
}, { excludeFromContext: isExcluded });
|
|
623
|
+
if (this.onEvent) {
|
|
624
|
+
this.onEvent(tracked.sessionFile, {
|
|
625
|
+
type: 'tool_execution_end',
|
|
626
|
+
toolName: 'bash',
|
|
627
|
+
result: result.output,
|
|
628
|
+
isError: result.exitCode !== 0,
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
catch (err) {
|
|
633
|
+
if (this.onEvent) {
|
|
634
|
+
this.onEvent(tracked.sessionFile, {
|
|
635
|
+
type: 'tool_execution_end',
|
|
636
|
+
toolName: 'bash',
|
|
637
|
+
result: err.message,
|
|
638
|
+
isError: true,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
else if (tracked.type === 'cli') {
|
|
644
|
+
tracked.cliWs.send(JSON.stringify({
|
|
645
|
+
type: 'cli_bash',
|
|
646
|
+
command,
|
|
647
|
+
excludeFromContext: isExcluded,
|
|
648
|
+
}));
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
if (tracked.type === 'server') {
|
|
654
|
+
await tracked.agentSession.sendUserMessage(text, { deliverAs: streamingBehavior });
|
|
655
|
+
}
|
|
656
|
+
else if (tracked.type === 'cli') {
|
|
657
|
+
tracked.cliWs.send(JSON.stringify({
|
|
658
|
+
type: 'cli_message',
|
|
659
|
+
message: text,
|
|
660
|
+
streamingBehavior,
|
|
661
|
+
}));
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async abortSession(sessionFileOrId) {
|
|
665
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
666
|
+
if (!tracked)
|
|
667
|
+
return;
|
|
668
|
+
if (tracked.type === 'server') {
|
|
669
|
+
await tracked.agentSession.abort();
|
|
670
|
+
}
|
|
671
|
+
else if (tracked.type === 'cli') {
|
|
672
|
+
tracked.cliWs.send(JSON.stringify({ type: 'cli_abort' }));
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
async changeModel(sessionFileOrId, modelStr) {
|
|
676
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
677
|
+
if (!tracked)
|
|
678
|
+
return { error: 'Session not found' };
|
|
679
|
+
if (tracked.type === 'server') {
|
|
680
|
+
const parsed = this.parseModelStr(modelStr);
|
|
681
|
+
if (!parsed)
|
|
682
|
+
return { error: `Invalid model format: ${modelStr}` };
|
|
683
|
+
const model = this.modelRegistry.find(parsed.provider, parsed.id);
|
|
684
|
+
if (!model)
|
|
685
|
+
return { error: `Model not found: ${modelStr}` };
|
|
686
|
+
try {
|
|
687
|
+
await tracked.agentSession.setModel(model);
|
|
688
|
+
tracked.model = modelStr;
|
|
689
|
+
return {};
|
|
690
|
+
}
|
|
691
|
+
catch (err) {
|
|
692
|
+
return { error: err.message };
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
tracked.cliWs.send(JSON.stringify({ type: 'cli_model_change', model: modelStr }));
|
|
697
|
+
tracked.model = modelStr;
|
|
698
|
+
return {};
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
isStreaming(sessionFileOrId) {
|
|
702
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
703
|
+
if (!tracked)
|
|
704
|
+
return false;
|
|
705
|
+
return tracked.type === 'server' ? tracked.agentSession.isStreaming : tracked.isStreaming;
|
|
706
|
+
}
|
|
707
|
+
scheduleIdleCheck(sessionFileOrId) {
|
|
708
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
709
|
+
if (!tracked)
|
|
710
|
+
return;
|
|
711
|
+
this.cancelIdleCheck(tracked.sessionFile);
|
|
712
|
+
if (tracked.clients.size === 0 && tracked.isIdle) {
|
|
713
|
+
tracked.idleTimer = setTimeout(() => {
|
|
714
|
+
this.destroySession(tracked.sessionFile, 'idle timeout');
|
|
715
|
+
}, this.idleTimeoutMs);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
cancelIdleCheck(sessionFileOrId) {
|
|
719
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
720
|
+
if (!tracked || !tracked.idleTimer)
|
|
721
|
+
return;
|
|
722
|
+
clearTimeout(tracked.idleTimer);
|
|
723
|
+
tracked.idleTimer = null;
|
|
724
|
+
}
|
|
725
|
+
destroySession(sessionFileOrId, reason) {
|
|
726
|
+
const tracked = this.getSession(sessionFileOrId);
|
|
727
|
+
if (!tracked)
|
|
728
|
+
return;
|
|
729
|
+
this.cancelIdleCheck(tracked.sessionFile);
|
|
730
|
+
if (tracked.type === 'server') {
|
|
731
|
+
tracked.eventUnsubscribe();
|
|
732
|
+
tracked.agentSession.dispose();
|
|
733
|
+
}
|
|
734
|
+
else {
|
|
735
|
+
try {
|
|
736
|
+
tracked.cliWs.close();
|
|
737
|
+
}
|
|
738
|
+
catch (err) { }
|
|
739
|
+
}
|
|
740
|
+
this.sessions.delete(tracked.sessionFile);
|
|
741
|
+
}
|
|
742
|
+
async registerCliSession(sessionFile, cwd, modelStr, cliWs) {
|
|
743
|
+
const existing = this.sessions.get(sessionFile);
|
|
744
|
+
let clients = new Set();
|
|
745
|
+
if (existing) {
|
|
746
|
+
clients = existing.clients;
|
|
747
|
+
this.cancelIdleCheck(sessionFile);
|
|
748
|
+
if (existing.type === 'server') {
|
|
749
|
+
try {
|
|
750
|
+
existing.eventUnsubscribe();
|
|
751
|
+
existing.agentSession.dispose();
|
|
752
|
+
}
|
|
753
|
+
catch (err) { }
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
let sessionId = existing?.sessionId;
|
|
757
|
+
if (!sessionId) {
|
|
758
|
+
try {
|
|
759
|
+
const sessionManager = SessionManager.open(sessionFile);
|
|
760
|
+
sessionId = sessionManager.getSessionId();
|
|
761
|
+
}
|
|
762
|
+
catch (err) {
|
|
763
|
+
// Fallback 1: Extract from filename (e.g. some_path/TIMESTAMP_UUID.jsonl)
|
|
764
|
+
const baseName = path.basename(sessionFile);
|
|
765
|
+
const match = baseName.match(/_(.+)\.jsonl$/);
|
|
766
|
+
if (match) {
|
|
767
|
+
sessionId = match[1];
|
|
768
|
+
}
|
|
769
|
+
else {
|
|
770
|
+
return { tracked: null, error: `Could not determine a persistent session ID from file path: ${sessionFile}` };
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
const normalizedCwd = normalizePath(cwd);
|
|
775
|
+
const tracked = {
|
|
776
|
+
type: 'cli',
|
|
777
|
+
sessionId,
|
|
778
|
+
sessionFile,
|
|
779
|
+
cwd: normalizedCwd,
|
|
780
|
+
model: modelStr || '',
|
|
781
|
+
clients,
|
|
782
|
+
isIdle: true,
|
|
783
|
+
idleTimer: null,
|
|
784
|
+
createdAt: existing?.createdAt || Date.now(),
|
|
785
|
+
lastActivity: Date.now(),
|
|
786
|
+
cliWs,
|
|
787
|
+
isStreaming: false,
|
|
788
|
+
};
|
|
789
|
+
this.sessions.set(sessionFile, tracked);
|
|
790
|
+
return { tracked };
|
|
791
|
+
}
|
|
792
|
+
async unregisterCliSession(sessionFile) {
|
|
793
|
+
const tracked = this.sessions.get(sessionFile);
|
|
794
|
+
if (!tracked || tracked.type !== 'cli')
|
|
795
|
+
return;
|
|
796
|
+
this.cancelIdleCheck(sessionFile);
|
|
797
|
+
this.sessions.delete(sessionFile);
|
|
798
|
+
if (tracked.clients.size > 0) {
|
|
799
|
+
console.log(`CLI Bridge disconnected for ${sessionFile}. Restarting server-side agent session...`);
|
|
800
|
+
const result = await this.loadSession(sessionFile, tracked.cwd, tracked.model);
|
|
801
|
+
if (!result.error && result.tracked) {
|
|
802
|
+
result.tracked.clients = tracked.clients;
|
|
803
|
+
if (this.onEvent) {
|
|
804
|
+
this.onEvent(sessionFile, { type: 'agent_end' });
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
handleCliEvent(sessionFile, event) {
|
|
810
|
+
const tracked = this.sessions.get(sessionFile);
|
|
811
|
+
if (!tracked || tracked.type !== 'cli')
|
|
812
|
+
return;
|
|
813
|
+
tracked.lastActivity = Date.now();
|
|
814
|
+
if (event.type === 'agent_start') {
|
|
815
|
+
tracked.isIdle = false;
|
|
816
|
+
tracked.isStreaming = true;
|
|
817
|
+
this.cancelIdleCheck(sessionFile);
|
|
818
|
+
}
|
|
819
|
+
else if (event.type === 'agent_end') {
|
|
820
|
+
tracked.isIdle = true;
|
|
821
|
+
tracked.isStreaming = false;
|
|
822
|
+
this.scheduleIdleCheck(sessionFile);
|
|
823
|
+
}
|
|
824
|
+
else if (event.type === 'model_select') {
|
|
825
|
+
const modelStr = event.model;
|
|
826
|
+
if (modelStr) {
|
|
827
|
+
tracked.model = modelStr;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
if (this.onEvent) {
|
|
831
|
+
this.onEvent(sessionFile, event);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
async disposeAll() {
|
|
835
|
+
const sessionIds = Array.from(this.sessions.keys());
|
|
836
|
+
for (const id of sessionIds) {
|
|
837
|
+
this.destroySession(id, 'server shutdown');
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
setupEventListeners(sessionFile, agentSession) {
|
|
841
|
+
return agentSession.subscribe((event) => {
|
|
842
|
+
const tracked = this.sessions.get(sessionFile);
|
|
843
|
+
if (!tracked)
|
|
844
|
+
return;
|
|
845
|
+
if (this.onEvent) {
|
|
846
|
+
this.onEvent(sessionFile, event);
|
|
847
|
+
}
|
|
848
|
+
switch (event.type) {
|
|
849
|
+
case 'agent_start':
|
|
850
|
+
tracked.isIdle = false;
|
|
851
|
+
tracked.lastActivity = Date.now();
|
|
852
|
+
this.cancelIdleCheck(sessionFile);
|
|
853
|
+
break;
|
|
854
|
+
case 'agent_end':
|
|
855
|
+
tracked.isIdle = true;
|
|
856
|
+
tracked.lastActivity = Date.now();
|
|
857
|
+
this.scheduleIdleCheck(sessionFile);
|
|
858
|
+
break;
|
|
859
|
+
case 'message_update':
|
|
860
|
+
case 'message_end':
|
|
861
|
+
case 'tool_execution_start':
|
|
862
|
+
case 'tool_execution_end':
|
|
863
|
+
tracked.lastActivity = Date.now();
|
|
864
|
+
break;
|
|
865
|
+
case 'model_select': {
|
|
866
|
+
const evt = event;
|
|
867
|
+
const modelStr = evt.model ? `${evt.model.provider}:${evt.model.id}` : '';
|
|
868
|
+
if (modelStr) {
|
|
869
|
+
tracked.model = modelStr;
|
|
870
|
+
}
|
|
871
|
+
break;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
extractMessageText(msg) {
|
|
877
|
+
if (msg.role === 'user') {
|
|
878
|
+
if (typeof msg.content === 'string')
|
|
879
|
+
return msg.content;
|
|
880
|
+
if (Array.isArray(msg.content)) {
|
|
881
|
+
return msg.content
|
|
882
|
+
.filter((c) => c.type === 'text')
|
|
883
|
+
.map((c) => c.text)
|
|
884
|
+
.join('\n');
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
if (msg.role === 'assistant') {
|
|
888
|
+
if (typeof msg.content === 'string')
|
|
889
|
+
return msg.content;
|
|
890
|
+
if (Array.isArray(msg.content)) {
|
|
891
|
+
return msg.content
|
|
892
|
+
.filter((c) => c.type === 'text')
|
|
893
|
+
.map((c) => c.text)
|
|
894
|
+
.join('\n');
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
return '';
|
|
898
|
+
}
|
|
899
|
+
parseModelStr(modelStr) {
|
|
900
|
+
const colonIdx = modelStr.indexOf(':');
|
|
901
|
+
if (colonIdx === -1)
|
|
902
|
+
return null;
|
|
903
|
+
return {
|
|
904
|
+
provider: modelStr.slice(0, colonIdx),
|
|
905
|
+
id: modelStr.slice(colonIdx + 1),
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
//# sourceMappingURL=session-pool.js.map
|