@nomyx/assistant
Version:
A powerful assistant library and cli for your AI projects. works with Vertex AI (Claude and Gemini)
52 lines (44 loc) • 1.38 kB
text/typescript
import fs from 'fs/promises';
import path from 'path';
import { ILogger } from './types';
export class PersistentState {
private state: Record<string, any> = {};
private persistenceDir: string | undefined;
constructor(
persistenceDir?: string,
private logger?: ILogger
) {
this.persistenceDir = persistenceDir;
if (this.persistenceDir) {
this.loadState();
}
}
getState(): Record<string, any> {
return { ...this.state };
}
setState(newState: Record<string, any>): void {
this.state = { ...this.state, ...newState };
this.saveState();
}
private async loadState(): Promise<void> {
if (!this.persistenceDir) return;
const filePath = path.join(this.persistenceDir, 'assistant_state.json');
try {
const data = await fs.readFile(filePath, 'utf8');
this.state = JSON.parse(data);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
this.logger?.error('Error loading persistent state:', error);
}
}
}
private async saveState(): Promise<void> {
if (!this.persistenceDir) return;
const filePath = path.join(this.persistenceDir, 'assistant_state.json');
try {
await fs.writeFile(filePath, JSON.stringify(this.state), 'utf8');
} catch (error) {
this.logger?.error('Error saving persistent state:', error);
}
}
}