src/memory/memory-store.ts
9 KB - Открыть исходный файл
// Long-term memory on disk (lab 06): the backend of the API's memory tool.
//
// The model sees a virtual folder, /memories. It views, creates, edits, renames, and deletes
// files there with the memory tool's commands. This class maps that folder to
// <dataDir>/memory and enforces the rules the model cannot be trusted to follow:
// - every path stays inside /memories (no "..", no hidden files, plain names only),
// - files are small and few (memory is a notebook of facts, not a document store),
// - nothing that looks like a secret is ever written.
//
// Memory is separate from sessions: `/new` starts a new conversation, but memory stays.
import { mkdir, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';
import path from 'node:path';
export class MemoryError extends Error {}
export const VIRTUAL_ROOT = '/memories';
const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
export interface MemoryLimits {
maxFileChars: number;
maxFiles: number;
}
const DEFAULT_LIMITS: MemoryLimits = { maxFileChars: 8_000, maxFiles: 100 };
const SECRET_PATTERNS: { name: string; pattern: RegExp }[] = [
{ name: 'an Anthropic API key', pattern: /sk-ant-[A-Za-z0-9_-]{10,}/ },
{ name: 'an API key', pattern: /\bsk-[A-Za-z0-9]{20,}/ },
{ name: 'an AWS access key', pattern: /\b(AKIA|ASIA)[0-9A-Z]{16}\b/ },
{ name: 'a private key', pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
{ name: 'a GitHub token', pattern: /\bgh[pousr]_[A-Za-z0-9]{30,}/ },
{ name: 'a password', pattern: /\b(password|passwd|pwd)\s*[:=]\s*\S+/i },
];
/** Returns what kind of secret the text seems to contain, or undefined. */
export function findSecret(text: string): string | undefined {
return SECRET_PATTERNS.find(({ pattern }) => pattern.test(text))?.name;
}
export class MemoryStore {
readonly dir: string;
private readonly limits: MemoryLimits;
constructor(dataDir: string, limits: MemoryLimits = DEFAULT_LIMITS) {
this.dir = path.join(dataDir, 'memory');
this.limits = limits;
}
/** Maps /memories/... to a real path inside the memory folder, or throws. */
toReal(virtualPath: string): string {
const clean = virtualPath.trim().replace(/\/+$/, '');
if (clean !== VIRTUAL_ROOT && !clean.startsWith(`${VIRTUAL_ROOT}/`)) {
throw new MemoryError(`The path ${virtualPath} is outside ${VIRTUAL_ROOT}.`);
}
const segments = clean.slice(VIRTUAL_ROOT.length).split('/').filter(Boolean);
for (const segment of segments) {
if (!NAME.test(segment)) {
throw new MemoryError(
`Invalid name "${segment}": use letters, digits, ".", "_" and "-" (no hidden files).`,
);
}
}
return path.join(this.dir, ...segments);
}
async view(virtualPath: string, viewRange?: number[]): Promise<string> {
const real = this.toReal(virtualPath);
await mkdir(this.dir, { recursive: true });
const info = await statOrNull(real);
if (!info) throw new MemoryError(`The path ${virtualPath} does not exist.`);
if (info.isDirectory()) {
const lines = [`Directory ${this.toVirtual(real)}:`];
const walk = async (dir: string, depth: number): Promise<void> => {
const entries = (await readdir(dir, { withFileTypes: true })).sort((a, b) =>
a.name.localeCompare(b.name),
);
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
lines.push(`${' '.repeat(depth)}- ${entry.name}/`);
if (depth < 2) await walk(full, depth + 1);
} else {
const size = (await stat(full)).size;
lines.push(`${' '.repeat(depth)}- ${entry.name} (${size} bytes)`);
}
}
};
await walk(real, 0);
if (lines.length === 1) lines.push('(empty)');
return lines.join('\n');
}
const all = (await readFile(real, 'utf8')).split('\n');
const [from = 1, to = -1] = viewRange ?? [];
const end = to === -1 ? all.length : Math.min(to, all.length);
return all
.slice(from - 1, end)
.map((line, i) => `${String(from + i).padStart(6)}\t${line}`)
.join('\n');
}
async create(virtualPath: string, text: string): Promise<string> {
const real = this.toReal(virtualPath);
if (real === this.dir) throw new MemoryError('Cannot write to the memory folder itself.');
await this.checkContent(text);
const existing = await statOrNull(real);
if (existing?.isDirectory()) throw new MemoryError(`${virtualPath} is a folder.`);
if (!existing && (await this.countFiles()) >= this.limits.maxFiles) {
throw new MemoryError(
`Memory is full (${this.limits.maxFiles} files). Merge or delete old entries first.`,
);
}
await mkdir(path.dirname(real), { recursive: true });
await writeFile(real, text, 'utf8');
return `File ${existing ? 'overwritten' : 'created'}: ${virtualPath}`;
}
async strReplace(virtualPath: string, oldText: string, newText: string): Promise<string> {
const real = await this.existingFile(virtualPath);
const content = await readFile(real, 'utf8');
const count = content.split(oldText).length - 1;
if (count === 0) throw new MemoryError(`The text to replace was not found in ${virtualPath}.`);
if (count > 1) {
throw new MemoryError(
`The text to replace appears ${count} times in ${virtualPath}; include more context.`,
);
}
// A replacer function: a plain string would expand "$&" and "$$" in the new text.
const updated = content.replace(oldText, () => newText);
await this.checkContent(updated);
await writeFile(real, updated, 'utf8');
return `File ${virtualPath} has been edited.`;
}
async insert(virtualPath: string, line: number, text: string): Promise<string> {
const real = await this.existingFile(virtualPath);
const lines = (await readFile(real, 'utf8')).split('\n');
if (line < 0 || line > lines.length) {
throw new MemoryError(`Line ${line} is out of range (0-${lines.length}).`);
}
// The model usually ends insert_text with "\n"; that newline ends the inserted line, it is
// not an extra empty line.
lines.splice(line, 0, ...text.replace(/\n$/, '').split('\n'));
const updated = lines.join('\n');
await this.checkContent(updated);
await writeFile(real, updated, 'utf8');
return `Text inserted at line ${line} in ${virtualPath}.`;
}
async delete(virtualPath: string): Promise<string> {
const real = this.toReal(virtualPath);
if (real === this.dir) throw new MemoryError('Cannot delete the memory folder itself.');
if (!(await statOrNull(real))) throw new MemoryError(`The path ${virtualPath} does not exist.`);
await rm(real, { recursive: true });
return `Deleted ${virtualPath}`;
}
async rename(oldPath: string, newPath: string): Promise<string> {
const from = this.toReal(oldPath);
const to = this.toReal(newPath);
if (from === this.dir || to === this.dir) throw new MemoryError('Cannot rename the root.');
if (!(await statOrNull(from))) throw new MemoryError(`The path ${oldPath} does not exist.`);
if (await statOrNull(to)) throw new MemoryError(`The path ${newPath} already exists.`);
await mkdir(path.dirname(to), { recursive: true });
await rename(from, to);
return `Renamed ${oldPath} to ${newPath}`;
}
/** All files as virtual paths, for `steward memory`. */
async listFiles(): Promise<string[]> {
const out: string[] = [];
const walk = async (dir: string): Promise<void> => {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) await walk(full);
else out.push(this.toVirtual(full));
}
};
await walk(this.dir);
return out.sort();
}
private toVirtual(real: string): string {
const relative = path.relative(this.dir, real).split(path.sep).join('/');
return relative ? `${VIRTUAL_ROOT}/${relative}` : VIRTUAL_ROOT;
}
private async existingFile(virtualPath: string): Promise<string> {
const real = this.toReal(virtualPath);
const info = await statOrNull(real);
if (!info) throw new MemoryError(`The path ${virtualPath} does not exist.`);
if (!info.isFile()) throw new MemoryError(`${virtualPath} is not a file.`);
return real;
}
private async checkContent(text: string): Promise<void> {
if (text.length > this.limits.maxFileChars) {
throw new MemoryError(
`Too long (${text.length} characters, limit ${this.limits.maxFileChars}). ` +
'Keep memory entries short: facts, not documents.',
);
}
const secret = findSecret(text);
if (secret) {
throw new MemoryError(`Not saved: the text looks like it contains ${secret}.`);
}
}
private async countFiles(): Promise<number> {
return (await this.listFiles()).length;
}
}
async function statOrNull(p: string) {
try {
return await stat(p);
} catch {
return null;
}
}