|
| 1 | +const DEFAULT_URL = 'http://localhost:8080' |
| 2 | + |
| 3 | +type MemoryAddResponse = { |
| 4 | + id: string |
| 5 | + primary_sector: string |
| 6 | + sectors: string[] |
| 7 | +} |
| 8 | + |
| 9 | +type MemoryMatch = { |
| 10 | + id: string |
| 11 | + content: string |
| 12 | + score: number |
| 13 | + sectors: string[] |
| 14 | + primary_sector: string |
| 15 | +} |
| 16 | + |
| 17 | +type MemoryQueryResponse = { |
| 18 | + query: string |
| 19 | + matches: MemoryMatch[] |
| 20 | +} |
| 21 | + |
| 22 | +const baseUrl = () => process.env.OPENMEMORY_URL?.trim() || DEFAULT_URL |
| 23 | + |
| 24 | +async function request<T>(path: string, init: RequestInit): Promise<T> { |
| 25 | + const url = `${baseUrl()}${path}` |
| 26 | + const headers = { |
| 27 | + 'content-type': 'application/json', |
| 28 | + ...(init.headers || {}) |
| 29 | + } |
| 30 | + const response = await fetch(url, { ...init, headers }) |
| 31 | + if (!response.ok) { |
| 32 | + const text = await response.text().catch(() => '') |
| 33 | + throw new Error(`OpenMemory request failed (${response.status}): ${text || response.statusText}`) |
| 34 | + } |
| 35 | + if (response.status === 204) return undefined as T |
| 36 | + return response.json() as Promise<T> |
| 37 | +} |
| 38 | + |
| 39 | +export async function remember(content: string, tags?: string[]): Promise<MemoryAddResponse> { |
| 40 | + if (!content || !content.trim()) { |
| 41 | + throw new Error('remember() requires non-empty content') |
| 42 | + } |
| 43 | + return request<MemoryAddResponse>('/memory/add', { |
| 44 | + method: 'POST', |
| 45 | + body: JSON.stringify({ content, tags }) |
| 46 | + }) |
| 47 | +} |
| 48 | + |
| 49 | +export async function recall(query: string, k = 8): Promise<MemoryQueryResponse> { |
| 50 | + if (!query || !query.trim()) { |
| 51 | + throw new Error('recall() requires a query string') |
| 52 | + } |
| 53 | + return request<MemoryQueryResponse>('/memory/query', { |
| 54 | + method: 'POST', |
| 55 | + body: JSON.stringify({ query, k }) |
| 56 | + }) |
| 57 | +} |
| 58 | + |
| 59 | +export async function forget(id: string): Promise<void> { |
| 60 | + if (!id) throw new Error('forget() requires a memory id') |
| 61 | + await request<void>(`/memory/${encodeURIComponent(id)}`, { method: 'DELETE' }) |
| 62 | +} |
| 63 | + |
| 64 | +export default { remember, recall, forget } |
0 commit comments