forked from Lilly-Protocol/agentlily-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent-instance-manager.ts
More file actions
67 lines (52 loc) · 1.54 KB
/
Copy pathagent-instance-manager.ts
File metadata and controls
67 lines (52 loc) · 1.54 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
import { assertNonEmptyValue } from "../guards/runtime-guards.js";
export interface AgentInstance {
agentId: string;
createdAt: string;
}
export interface AgentInstanceManagerOptions {
maxInstances?: number;
}
export class AgentInstanceManager {
private readonly instances = new Map<string, AgentInstance>();
private readonly maxInstances: number;
public constructor(options: AgentInstanceManagerOptions = {}) {
this.maxInstances = options.maxInstances ?? 5_000;
}
public getOrCreate(agentId: string): AgentInstance {
assertNonEmptyValue(agentId, "agentId");
const existing = this.instances.get(agentId);
if (existing) {
return existing;
}
if (this.maxInstances > 0 && this.instances.size >= this.maxInstances) {
const oldestId = this.instances.keys().next().value;
if (oldestId !== undefined) {
this.instances.delete(oldestId);
}
}
const created: AgentInstance = {
agentId,
createdAt: new Date().toISOString()
};
this.instances.set(agentId, created);
return created;
}
public get(agentId: string): AgentInstance | undefined {
return this.instances.get(agentId);
}
public has(agentId: string): boolean {
return this.instances.has(agentId);
}
public delete(agentId: string): boolean {
return this.instances.delete(agentId);
}
public clear(): void {
this.instances.clear();
}
public size(): number {
return this.instances.size;
}
public list(): AgentInstance[] {
return Array.from(this.instances.values());
}
}