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
285 lines (242 loc) · 7.72 KB
/
Copy pathmemory-store.ts
File metadata and controls
285 lines (242 loc) · 7.72 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
import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { RuntimeError } from "../errors/runtime-errors.js";
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 interface JsonFileMemoryStoreOptions {
/**
* Maximum total entries retained across all agents before FIFO eviction.
* Default: unbounded (undefined).
*/
maxEntries?: number;
/**
* Maximum entries retained per individual agent before FIFO eviction.
* Default: unbounded (undefined).
*/
maxEntriesPerAgent?: number;
}
export class JsonFileMemoryStore implements MemoryStore {
private readonly filePath: string;
private memoryCache: MemoryEntry[] | null = null;
public readonly maxEntries: number;
public constructor(filePath: string, options: { maxEntries?: number } = {}) {
this.filePath = filePath;
this.maxEntries = options.maxEntries ?? DEFAULT_MAX_MEMORY_ENTRIES;
if (!Number.isInteger(this.maxEntries) || this.maxEntries < 1) {
throw new RangeError("maxEntries must be a positive integer.");
}
}
public getFilePath(): string {
return this.filePath;
}
public get capacity(): number {
return this.maxEntries;
}
public async size(): Promise<number> {
const entries = await this.loadEntries();
return entries.length;
}
private async loadEntries(): Promise<MemoryEntry[]> {
if (this.memoryCache !== null) {
return this.memoryCache;
}
if (!existsSync(this.filePath)) {
return [];
}
const raw = await readFile(this.filePath, "utf-8");
if (raw.trim().length === 0) {
this.memoryCache = [];
return this.memoryCache;
}
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch (error) {
throw new RuntimeError(
"STORAGE_CORRUPTED",
`Corrupted memory storage file at ${this.filePath}: invalid JSON.`,
{
filePath: this.filePath,
cause: error instanceof Error ? error.message : String(error)
}
);
}
if (!Array.isArray(parsed)) {
throw new RuntimeError(
"STORAGE_CORRUPTED",
`Corrupted memory storage file at ${this.filePath}: expected a JSON array of entries.`,
{
filePath: this.filePath,
receivedType: typeof parsed
}
);
}
this.memoryCache = parsed as MemoryEntry[];
return this.memoryCache;
}
private async flush(): Promise<void> {
if (this.memoryCache === null) {
return;
}
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 entryCopy: MemoryEntry = {
agentId: entry.agentId,
taskId: entry.taskId,
input: entry.input,
output: entry.output,
recordedAt: entry.recordedAt
};
const entries = await this.loadEntries();
const entryCopy: MemoryEntry = {
agentId: entry.agentId,
taskId: entry.taskId,
input: entry.input,
output: entry.output,
recordedAt: entry.recordedAt
};
if (entries.length >= this.maxEntries) {
entries.shift();
}
entries.push(entryCopy);
await this.flush();
}
public async listByAgent(
agentId: string,
options?: ListMemoryOptions
): Promise<MemoryEntry[]> {
const entries = await this.loadEntries();
const matching = entries.filter((entry) => entry.agentId === agentId);
const offset = options?.offset ?? 0;
const limit = options?.limit ?? matching.length;
return matching.slice(offset, offset + limit).map((entry) => ({ ...entry }));
}
public async countByAgent(agentId: string): Promise<number> {
const entries = await this.loadEntries();
return entries.filter((entry) => entry.agentId === agentId).length;
}
public async clear(): Promise<void> {
this.memoryCache = [];
// Remove the backing file to match the "empty or removed backing file" acceptance criterion
try {
const { rm } = await import("node:fs/promises");
await rm(this.filePath, { force: true });
} catch {
// Ignore removal errors (file may not exist)
}
}
}