forked from Lilly-Protocol/agentlily-runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemory-store.ts
More file actions
201 lines (168 loc) · 5.29 KB
/
Copy pathmemory-store.ts
File metadata and controls
201 lines (168 loc) · 5.29 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
import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
export interface MemoryEntry {
agentId: string;
taskId: string;
input: string;
output: unknown;
recordedAt: string;
}
export interface ListMemoryOptions {
limit?: number;
offset?: number;
}
export interface InMemoryMemoryStoreOptions {
/**
* Maximum total entries retained across all agents before FIFO eviction.
* Default: 10,000.
*/
maxEntries?: number;
/**
* Maximum entries retained per individual agent before FIFO eviction.
* Default: 1,000. Set to 0 for unbounded per-agent growth.
*/
maxEntriesPerAgent?: number;
}
export interface MemoryStore {
append(entry: MemoryEntry): Promise<void>;
listByAgent(
agentId: string,
options?: ListMemoryOptions
): Promise<MemoryEntry[]>;
countByAgent?(agentId: string): Promise<number>;
clear?(): Promise<void>;
}
export const DEFAULT_MAX_MEMORY_ENTRIES = 10_000;
export const DEFAULT_MAX_MEMORY_ENTRIES_PER_AGENT = 1_000;
export class InMemoryMemoryStore implements MemoryStore {
private readonly entries: MemoryEntry[] = [];
public readonly maxEntries: number;
public readonly maxEntriesPerAgent: number;
public constructor(options: InMemoryMemoryStoreOptions | number = {}) {
const resolved =
typeof options === "number" ? { maxEntries: options } : options;
const maxEntries = resolved.maxEntries ?? DEFAULT_MAX_MEMORY_ENTRIES;
if (!Number.isInteger(maxEntries) || maxEntries < 1) {
throw new RangeError("maxEntries must be a positive integer.");
}
this.maxEntries = maxEntries;
this.maxEntriesPerAgent =
resolved.maxEntriesPerAgent ?? DEFAULT_MAX_MEMORY_ENTRIES_PER_AGENT;
}
public get capacity(): number {
return this.maxEntries;
}
public get size(): number {
return this.entries.length;
}
public async append(entry: MemoryEntry): Promise<void> {
// Clone entry defensively so external mutation cannot corrupt store state.
const entryCopy: MemoryEntry = {
agentId: entry.agentId,
taskId: entry.taskId,
input: entry.input,
output: entry.output,
recordedAt: entry.recordedAt
};
// Enforce the per-agent limit by evicting that agent's oldest entry.
if (this.maxEntriesPerAgent > 0) {
let agentCount = 0;
let oldestAgentIndex = -1;
for (let i = 0; i < this.entries.length; i++) {
if (this.entries[i]?.agentId === entryCopy.agentId) {
if (oldestAgentIndex === -1) {
oldestAgentIndex = i;
}
agentCount++;
}
}
if (agentCount >= this.maxEntriesPerAgent && oldestAgentIndex !== -1) {
this.entries.splice(oldestAgentIndex, 1);
}
}
// Enforce the global capacity limit by evicting the oldest entry (FIFO).
if (this.entries.length >= this.maxEntries) {
this.entries.shift();
}
this.entries.push(entryCopy);
}
public async listByAgent(
agentId: string,
options?: ListMemoryOptions
): Promise<MemoryEntry[]> {
const matching = this.entries.filter((entry) => entry.agentId === agentId);
const offset = options?.offset ?? 0;
const limit = options?.limit ?? matching.length;
const slice = matching.slice(offset, offset + limit);
return slice.map((entry) => ({ ...entry }));
}
public async countByAgent(agentId: string): Promise<number> {
let count = 0;
for (const entry of this.entries) {
if (entry.agentId === agentId) {
count++;
}
}
return count;
}
public async clear(): Promise<void> {
this.entries.length = 0;
}
}
export class JsonFileMemoryStore implements MemoryStore {
private readonly filePath: string;
private memoryCache: MemoryEntry[] | null = null;
public constructor(filePath: string) {
this.filePath = filePath;
}
public getFilePath(): string {
return this.filePath;
}
private async loadEntries(): Promise<MemoryEntry[]> {
if (this.memoryCache !== null) {
return this.memoryCache;
}
if (!existsSync(this.filePath)) {
this.memoryCache = [];
return this.memoryCache;
}
try {
const raw = await readFile(this.filePath, "utf-8");
if (raw.trim().length === 0) {
this.memoryCache = [];
return this.memoryCache;
}
const parsed: unknown = JSON.parse(raw);
if (Array.isArray(parsed)) {
this.memoryCache = parsed as MemoryEntry[];
} else {
this.memoryCache = [];
}
} catch {
this.memoryCache = [];
}
return this.memoryCache;
}
private async flush(): Promise<void> {
const dir = dirname(this.filePath);
if (dir && dir !== "." && !existsSync(dir)) {
await mkdir(dir, { recursive: true });
}
const data = JSON.stringify(this.memoryCache ?? [], null, 2);
await writeFile(this.filePath, data, "utf-8");
}
public async append(entry: MemoryEntry): Promise<void> {
const entries = await this.loadEntries();
entries.push(entry);
await this.flush();
}
public async listByAgent(agentId: string): Promise<MemoryEntry[]> {
const entries = await this.loadEntries();
return entries.filter((entry) => entry.agentId === agentId);
}
public async clear(): Promise<void> {
this.memoryCache = [];
await this.flush();
}
}