-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathagentRuntime.ts
More file actions
437 lines (392 loc) · 13.9 KB
/
Copy pathagentRuntime.ts
File metadata and controls
437 lines (392 loc) · 13.9 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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/**
* AgentRuntime: shared agent lifecycle core for VS Code and standalone modes.
*
* Owns all infrastructure that both PixelAgentsViewProvider (VS Code) and the
* standalone CLI need: timer Maps, file watchers, HookEventHandler, DismissalTracker,
* session scanning, and agent removal. Adapters (VS Code, CLI) create an instance
* and register platform-specific lifecycle callbacks.
*
* This is the single source of truth for agent lifecycle wiring. No duplication.
*/
import * as fs from 'fs';
import * as path from 'path';
import type { HookProvider } from '../../core/src/provider.js';
import type { AgentStateStore } from './agentStateStore.js';
import { DismissalTracker } from './dismissalTracker.js';
import {
adoptExternalSessionFromHook,
ensureProjectScan,
isTrackedProjectDir,
reassignAgentToFile,
scanForTeammateFiles,
setAgentRemovalCallback,
setDismissalTracker,
setHookProvider as setFileWatcherHookProvider,
setTeammateRemovalCallback,
setTeamProvider,
startExternalSessionScanning,
startFileWatching,
startStaleExternalAgentCheck,
} from './fileWatcher.js';
import type { HookEvent } from './hookEventHandler.js';
import { HookEventHandler } from './hookEventHandler.js';
import { SessionRouter } from './sessionRouter.js';
import { cancelPermissionTimer, cancelWaitingTimer } from './timerManager.js';
import { setHookProvider } from './transcriptParser.js';
import type { AgentState } from './types.js';
/** Callbacks that adapters register for platform-specific behavior. */
export interface RuntimeLifecycleCallbacks {
/** Called after an agent is removed. Adapters use this to dismiss JSONL files, etc. */
onAgentRemoved?: (agentId: number, agent: AgentState) => void;
/** Called when a teammate is removed. */
onTeammateRemoved?: (teammateId: number, agent: AgentState, source: string) => void;
}
export class AgentRuntime {
// Per-agent timer Maps (shared by all fileWatcher/hookEventHandler operations)
readonly fileWatchers = new Map<number, fs.FSWatcher>();
readonly pollingTimers = new Map<number, ReturnType<typeof setInterval>>();
readonly waitingTimers = new Map<number, ReturnType<typeof setTimeout>>();
readonly permissionTimers = new Map<number, ReturnType<typeof setTimeout>>();
readonly jsonlPollTimers = new Map<number, ReturnType<typeof setInterval>>();
// Scanning state
readonly knownJsonlFiles = new Set<string>();
readonly projectScanTimer = { current: null as ReturnType<typeof setInterval> | null };
readonly activeAgentId = { current: null as number | null };
private externalScanTimer: ReturnType<typeof setInterval> | null = null;
private staleCheckTimer: ReturnType<typeof setInterval> | null = null;
// Configuration refs (mutable, shared with scanners)
readonly watchAllSessions = { current: false };
readonly hooksEnabled = { current: true };
// Dependencies
readonly dismissalTracker = new DismissalTracker();
private hookEventHandler: HookEventHandler;
private lifecycleCallbacks: RuntimeLifecycleCallbacks = {};
constructor(
private readonly store: AgentStateStore,
provider: HookProvider,
) {
// Wire module-level dependencies
setDismissalTracker(this.dismissalTracker);
setHookProvider(provider);
setFileWatcherHookProvider(provider);
if (provider.team) {
setTeamProvider(provider.team);
}
setAgentRemovalCallback((id) => this.removeAgent(id));
setTeammateRemovalCallback((id) => this.removeTeammate(id, 'team-config'));
this.hookEventHandler = new HookEventHandler(
store,
this.waitingTimers,
this.permissionTimers,
provider,
new SessionRouter(),
this.watchAllSessions,
);
// Wire hook lifecycle callbacks to shared agent operations
this.hookEventHandler.setLifecycleCallbacks({
onExternalSessionDetected: (sessionId, transcriptPath, cwd) => {
const projectDir = transcriptPath ? path.dirname(transcriptPath) : cwd;
if (!isTrackedProjectDir(projectDir) && !this.watchAllSessions.current) {
return;
}
adoptExternalSessionFromHook(
sessionId,
transcriptPath,
cwd,
this.knownJsonlFiles,
this.store.nextAgentId,
this.store,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
() => this.store.persist(),
(agent) => this.registerAgent(agent.sessionId, agent.id),
);
},
onSessionClear: (agentId, newSessionId, newTranscriptPath) => {
if (newTranscriptPath) {
this.knownJsonlFiles.add(newTranscriptPath);
reassignAgentToFile(
agentId,
newTranscriptPath,
this.store,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
() => this.store.persist(),
);
}
const agent = this.store.get(agentId);
if (agent) {
this.unregisterAgent(agent.sessionId);
agent.sessionId = newSessionId;
this.registerAgent(agent.sessionId, agent.id);
}
},
onSessionResume: (transcriptPath) => {
this.dismissalTracker.clearDismissal(transcriptPath);
this.dismissalTracker.clearSeededMtime(transcriptPath);
this.knownJsonlFiles.delete(transcriptPath);
},
onTeammateDetected: (parentAgentId, sessionId, _agentType) => {
const parentAgent = this.store.get(parentAgentId);
if (!parentAgent) return;
scanForTeammateFiles(
parentAgent.projectDir,
sessionId,
parentAgentId,
this.store.nextAgentId,
this.store,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
() => this.store.persist(),
(agent) => this.registerAgent(agent.sessionId, agent.id),
);
},
onTeammateRemoved: (teammateAgentId) => {
this.removeTeammate(teammateAgentId, 'hooks');
},
onSessionEnd: (agentId) => {
const agent = this.store.get(agentId);
if (!agent) return;
this.dismissalTracker.clearSeededMtime(agent.jsonlFile);
this.dismissalTracker.dismiss(agent.jsonlFile);
if (agent.isTeamLead) {
this.removeTeammates(agentId);
}
if (agent.isExternal) {
this.unregisterAgent(agent.sessionId);
this.removeAgent(agentId);
}
},
});
}
/** Register adapter-specific lifecycle callbacks. */
setLifecycleCallbacks(callbacks: RuntimeLifecycleCallbacks): void {
this.lifecycleCallbacks = callbacks;
}
// ── Hook event routing ──
/** Route an incoming hook event to the appropriate agent. */
handleHookEvent(providerId: string, event: Record<string, unknown>): void {
this.hookEventHandler.handleEvent(providerId, event as HookEvent);
}
/** Register an agent with the hook event handler for session->agent mapping. */
registerAgent(sessionId: string, agentId: number): void {
this.hookEventHandler.registerAgent(sessionId, agentId);
}
/** Unregister an agent from the hook event handler. */
unregisterAgent(sessionId: string): void {
this.hookEventHandler.unregisterAgent(sessionId);
}
// ── Agent removal (shared cleanup) ──
/** Remove an agent: stop watchers, cancel timers, delete from store. */
removeAgent(id: number): void {
const agent = this.store.get(id);
if (!agent) return;
// Stop JSONL poll timer
const jpTimer = this.jsonlPollTimers.get(id);
if (jpTimer) {
clearInterval(jpTimer);
}
this.jsonlPollTimers.delete(id);
// Stop file watching
this.fileWatchers.get(id)?.close();
this.fileWatchers.delete(id);
const pt = this.pollingTimers.get(id);
if (pt) {
clearInterval(pt);
}
this.pollingTimers.delete(id);
// Cancel timers
cancelWaitingTimer(id, this.waitingTimers);
cancelPermissionTimer(id, this.permissionTimers);
// Notify adapter before deleting from store
this.lifecycleCallbacks.onAgentRemoved?.(id, agent);
// Remove from store (fires agentRemoved event) and persist
this.store.delete(id);
this.store.persist();
}
/** Remove a single teammate agent. */
removeTeammate(teammateId: number, source: string): void {
const agent = this.store.get(teammateId);
if (!agent) return;
console.log(`[Pixel Agents] Removing teammate ${teammateId} (source: ${source})`);
this.dismissalTracker.dismiss(agent.jsonlFile);
this.unregisterAgent(agent.sessionId);
this.lifecycleCallbacks.onTeammateRemoved?.(teammateId, agent, source);
this.removeAgent(teammateId);
}
/** Remove all teammates of a lead agent. */
removeTeammates(leadId: number): void {
const teammates: number[] = [];
for (const [id, agent] of this.store) {
if (agent.leadAgentId === leadId) {
teammates.push(id);
}
}
for (const id of teammates) {
const agent = this.store.get(id);
if (agent) {
console.log(`[Pixel Agents] Removing teammate ${id} (lead ${leadId} closed)`);
this.dismissalTracker.dismiss(agent.jsonlFile);
this.unregisterAgent(agent.sessionId);
this.removeAgent(id);
}
}
}
// ── Scanning ──
/** Start project-level scanning for a directory. */
startProjectScan(projectDir: string, onAgentCreated?: (agent: AgentState) => void): void {
ensureProjectScan(
projectDir,
this.knownJsonlFiles,
this.projectScanTimer,
this.activeAgentId,
this.store.nextAgentId,
this.store,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
() => this.store.persist(),
onAgentCreated ?? ((agent) => this.registerAgent(agent.sessionId, agent.id)),
this.hooksEnabled,
);
}
/** Start external session scanning (detects sessions from other terminals). */
startExternalScanning(projectDir: string): void {
if (this.externalScanTimer) return;
this.externalScanTimer = startExternalSessionScanning(
projectDir,
this.knownJsonlFiles,
this.store.nextAgentId,
this.store,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
this.jsonlPollTimers,
() => this.store.persist(),
this.watchAllSessions,
this.hooksEnabled,
);
}
/** Start stale external agent check (removes agents whose JSONL files are deleted). */
startStaleCheck(): void {
if (this.staleCheckTimer) return;
this.staleCheckTimer = startStaleExternalAgentCheck(
this.store,
this.knownJsonlFiles,
this.hooksEnabled,
);
}
// ── Restore persisted external agents (standalone) ──
/**
* Re-create external agents from the adapter's persistence on startup.
* Only external agents are restorable here (no terminal to rebind).
* VS Code uses its own restoreAgents() in agentManager.ts to also handle
* terminal agents via vscode.window.terminals.
*/
restoreExternalAgents(): void {
const adapter = this.store.getAdapter();
if (!adapter) return;
const persisted = adapter.loadAgents();
if (persisted.length === 0) return;
let maxId = 0;
for (const p of persisted) {
if (!p.isExternal) continue;
try {
if (!fs.existsSync(p.jsonlFile)) continue;
} catch {
continue;
}
if (this.store.has(p.id)) {
this.knownJsonlFiles.add(p.jsonlFile);
if (p.id > maxId) maxId = p.id;
continue;
}
const agent: AgentState = {
id: p.id,
sessionId: p.sessionId || path.basename(p.jsonlFile, '.jsonl'),
terminalRef: undefined,
isExternal: true,
projectDir: p.projectDir,
jsonlFile: p.jsonlFile,
fileOffset: 0,
lineBuffer: '',
activeToolIds: new Set(),
activeToolStatuses: new Map(),
activeToolNames: new Map(),
activeSubagentToolIds: new Map(),
activeSubagentToolNames: new Map(),
backgroundAgentToolIds: new Set(),
isWaiting: false,
permissionSent: false,
hadToolsInTurn: false,
lastDataAt: 0,
linesProcessed: 0,
seenUnknownRecordTypes: new Set(),
folderName: p.folderName,
sessionName: p.sessionName,
hookDelivered: false,
inputTokens: 0,
outputTokens: 0,
teamName: p.teamName,
agentName: p.agentName,
isTeamLead: p.isTeamLead,
leadAgentId: p.leadAgentId,
teamUsesTmux: p.teamUsesTmux,
};
this.store.set(p.id, agent);
this.knownJsonlFiles.add(p.jsonlFile);
try {
const stat = fs.statSync(p.jsonlFile);
agent.fileOffset = stat.size;
startFileWatching(
p.id,
p.jsonlFile,
this.store,
this.fileWatchers,
this.pollingTimers,
this.waitingTimers,
this.permissionTimers,
);
} catch {
/* ignore stat errors on restore */
}
this.registerAgent(agent.sessionId, agent.id);
if (p.id > maxId) maxId = p.id;
console.log(
`[Pixel Agents] Restored external agent ${p.id} -> ${path.basename(p.jsonlFile)}`,
);
}
if (maxId >= this.store.nextAgentId.current) {
this.store.nextAgentId.current = maxId + 1;
}
this.store.persist();
}
// ── Cleanup ──
/** Clean up all scanners, timers, and agents. Called on shutdown. */
dispose(): void {
this.hookEventHandler.dispose();
if (this.projectScanTimer.current) {
clearInterval(this.projectScanTimer.current);
this.projectScanTimer.current = null;
}
if (this.externalScanTimer) {
clearInterval(this.externalScanTimer);
this.externalScanTimer = null;
}
if (this.staleCheckTimer) {
clearInterval(this.staleCheckTimer);
this.staleCheckTimer = null;
}
for (const id of [...this.store.keys()]) {
this.removeAgent(id);
}
}
}