-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.ts
More file actions
71 lines (63 loc) · 2.07 KB
/
Copy pathstore.ts
File metadata and controls
71 lines (63 loc) · 2.07 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
import { atomicWrite, ensureDir, readTextOrEmpty } from "../fs-utils.js";
import { memoryDir, memoryFile, userFile } from "../paths.js";
export type MemoryStore = "memory" | "user";
const MAX_BYTES: Record<MemoryStore, number> = {
memory: 4096,
user: 2048,
};
function fileFor(store: MemoryStore): string {
return store === "memory" ? memoryFile() : userFile();
}
export async function readMemory(store: MemoryStore): Promise<string> {
return await readTextOrEmpty(fileFor(store));
}
export async function writeMemory(
store: MemoryStore,
content: string,
): Promise<void> {
await ensureDir(memoryDir());
const trimmed = content.replace(/\s+$/g, "") + "\n";
if (Buffer.byteLength(trimmed, "utf8") > MAX_BYTES[store]) {
throw new Error(
`memory "${store}" exceeds ${MAX_BYTES[store]} bytes. Trim or split entries.`,
);
}
await atomicWrite(fileFor(store), trimmed);
}
export async function appendMemory(
store: MemoryStore,
entry: string,
): Promise<void> {
const current = await readMemory(store);
const sep = current && !current.endsWith("\n") ? "\n" : "";
await writeMemory(store, `${current}${sep}- ${entry.trim()}`);
}
export async function replaceInMemory(
store: MemoryStore,
oldString: string,
newString: string,
): Promise<void> {
const current = await readMemory(store);
if (!current.includes(oldString)) {
throw new Error(`old_string not found in ${store} memory`);
}
const occurrences = current.split(oldString).length - 1;
if (occurrences > 1) {
throw new Error(
`old_string matches ${occurrences} places in ${store} memory. Add more context.`,
);
}
await writeMemory(store, current.replace(oldString, newString));
}
export async function removeFromMemory(
store: MemoryStore,
fragment: string,
): Promise<void> {
const current = await readMemory(store);
const lines = current.split(/\r?\n/);
const kept = lines.filter((line) => !line.includes(fragment));
if (kept.length === lines.length) {
throw new Error(`fragment not found in ${store} memory`);
}
await writeMemory(store, kept.join("\n"));
}