The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(memory): tell a credit refusal and an outage apart from an empty memory (#6718)
Ghost Scripter3b4415f268f4
diff --git a/app/src/components/memory/MemoryAskTab.tsx b/app/src/components/memory/MemoryAskTab.tsxindex 51f0fc5397..d126d123ab 100644--- a/app/src/components/memory/MemoryAskTab.tsx+++ b/app/src/components/memory/MemoryAskTab.tsx@@ -92,7 +92,7 @@ export default function MemoryAskTab({ fetchModes }: MemoryAskTabProps) {}} catch (err) {log('%s failed: %o', raw ? 'fetch' : 'recall', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setBusy(false);}diff --git a/app/src/components/memory/MemoryBackgroundTab.tsx b/app/src/components/memory/MemoryBackgroundTab.tsxindex 9d2a50c2b3..aa71018e98 100644--- a/app/src/components/memory/MemoryBackgroundTab.tsx+++ b/app/src/components/memory/MemoryBackgroundTab.tsx@@ -44,12 +44,12 @@ export default function MemoryBackgroundTab() {setError(null);} catch (err) {log('jobs_list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setJobs(prev => prev ?? { pending: [], history: [] });} finally {setRefreshing(false);}- }, []);+ }, [t]);useEffect(() => {let cancelled = false;@@ -60,13 +60,13 @@ export default function MemoryBackgroundTab() {.catch(err => {if (cancelled) return;log('jobs_list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setJobs({ pending: [], history: [] });});return () => {cancelled = true;};- }, []);+ }, [t]);const run = async (id?: string) => {const key = id ?? '*';@@ -80,7 +80,7 @@ export default function MemoryBackgroundTab() {await reload();} catch (err) {log('jobs_run failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setRunning(prev => {const next = new Set(prev);diff --git a/app/src/components/memory/MemoryBrainSearch.tsx b/app/src/components/memory/MemoryBrainSearch.tsxindex 2dff009f36..dc08e3dcf4 100644--- a/app/src/components/memory/MemoryBrainSearch.tsx+++ b/app/src/components/memory/MemoryBrainSearch.tsx@@ -47,7 +47,7 @@ export default function MemoryBrainSearch({ sources }: MemoryBrainSearchProps) {setHits(res.hits ?? []);} catch (err) {log('search failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setBusy(false);}diff --git a/app/src/components/memory/MemoryBrainTab.tsx b/app/src/components/memory/MemoryBrainTab.tsxindex 9e3e8b89e4..b68044528a 100644--- a/app/src/components/memory/MemoryBrainTab.tsx+++ b/app/src/components/memory/MemoryBrainTab.tsx@@ -51,10 +51,10 @@ export default function MemoryBrainTab() {setError(null);} catch (err) {log('brain_sources failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setBrain(prev => prev ?? { root: '', sources: [], unfiled: 0 });}- }, []);+ }, [t]);useEffect(() => {let cancelled = false;@@ -67,13 +67,13 @@ export default function MemoryBrainTab() {.catch(err => {if (cancelled) return;log('brain_sources failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setBrain({ root: '', sources: [], unfiled: 0 });});return () => {cancelled = true;};- }, []);+ }, [t]);const ingest = async (req: BrainIngestRequest): Promise<boolean> => {setSaving(true);@@ -91,7 +91,7 @@ export default function MemoryBrainTab() {return true;} catch (err) {log('brain_ingest failed: %o', err);- setAddError(memoryErrorMessage(err));+ setAddError(memoryErrorMessage(err, t));return false;} finally {setSaving(false);@@ -117,7 +117,7 @@ export default function MemoryBrainTab() {await reload();} catch (err) {log('brain_forget failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setForgetTarget(null);} finally {setSaving(false);diff --git a/app/src/components/memory/MemoryConversationsBackfill.tsx b/app/src/components/memory/MemoryConversationsBackfill.tsxindex 45a4c3c5bf..bd90a0fb44 100644--- a/app/src/components/memory/MemoryConversationsBackfill.tsx+++ b/app/src/components/memory/MemoryConversationsBackfill.tsx@@ -47,9 +47,9 @@ export default function MemoryConversationsBackfill() {setView(next);} catch (err) {log('status failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));}- }, []);+ }, [t]);useEffect(() => {let cancelled = false;@@ -60,12 +60,12 @@ export default function MemoryConversationsBackfill() {.catch(err => {if (cancelled) return;log('status failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));});return () => {cancelled = true;};- }, []);+ }, [t]);const running = view?.state.phase === 'running';useEffect(() => {@@ -83,7 +83,7 @@ export default function MemoryConversationsBackfill() {setView(next);} catch (err) {log('start failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setStarting(false);setConsentOpen(false);diff --git a/app/src/components/memory/MemoryConversationsTab.tsx b/app/src/components/memory/MemoryConversationsTab.tsxindex 57f21fe997..ca51a75e7d 100644--- a/app/src/components/memory/MemoryConversationsTab.tsx+++ b/app/src/components/memory/MemoryConversationsTab.tsx@@ -50,21 +50,21 @@ export default function MemoryConversationsTab() {setPolicy(got.value);} else {log('policy_get failed: %o', got.reason);- setError(memoryErrorMessage(got.reason));+ setError(memoryErrorMessage(got.reason, t));}if (list.status === 'fulfilled') {log('agents: %d', list.value.agents?.length ?? 0);setAgents(list.value.agents ?? []);} else {log('agents_list failed: %o', list.reason);- setError(prev => prev ?? memoryErrorMessage(list.reason));+ setError(prev => prev ?? memoryErrorMessage(list.reason, t));setAgents([]);}});return () => {cancelled = true;};- }, []);+ }, [t]);const setLogging = async (next: boolean) => {setSaving(true);@@ -74,31 +74,34 @@ export default function MemoryConversationsTab() {setPolicy(await memoryPolicySet({ log_conversations: next }));} catch (err) {log('policy_set failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setSaving(false);}};- const loadItems = useCallback(async (agentId: string, after: string | null) => {- setLoadingItems(true);- try {- const page = await memoryItemsList({- filter: { kinds: ['conversation'], agent_id: agentId },- limit: PAGE_SIZE,- cursor: after ?? undefined,- });- log('items: agent=%s n=%d more=%s', agentId, page.items?.length ?? 0, !!page.next_cursor);- setItems(prev => [...(after ? (prev ?? []) : []), ...(page.items ?? [])]);- setCursor(page.next_cursor ?? null);- } catch (err) {- log('items_list failed: %o', err);- setError(memoryErrorMessage(err));- setItems(prev => prev ?? []);- } finally {- setLoadingItems(false);- }- }, []);+ const loadItems = useCallback(+ async (agentId: string, after: string | null) => {+ setLoadingItems(true);+ try {+ const page = await memoryItemsList({+ filter: { kinds: ['conversation'], agent_id: agentId },+ limit: PAGE_SIZE,+ cursor: after ?? undefined,+ });+ log('items: agent=%s n=%d more=%s', agentId, page.items?.length ?? 0, !!page.next_cursor);+ setItems(prev => [...(after ? (prev ?? []) : []), ...(page.items ?? [])]);+ setCursor(page.next_cursor ?? null);+ } catch (err) {+ log('items_list failed: %o', err);+ setError(memoryErrorMessage(err, t));+ setItems(prev => prev ?? []);+ } finally {+ setLoadingItems(false);+ }+ },+ [t]+ );const toggleAgent = (agentId: string) => {if (openAgent === agentId) {diff --git a/app/src/components/memory/MemoryEngineTab.tsx b/app/src/components/memory/MemoryEngineTab.tsxindex 9b28001953..b1087e517f 100644--- a/app/src/components/memory/MemoryEngineTab.tsx+++ b/app/src/components/memory/MemoryEngineTab.tsx@@ -64,12 +64,12 @@ export default function MemoryEngineTab({ state, onStateChange, embedded }: Memo.catch(err => {if (cancelled) return;log('engines list failed: %o', err);- setLoadError(memoryErrorMessage(err));+ setLoadError(memoryErrorMessage(err, t));});return () => {cancelled = true;};- }, []);+ }, [t]);const select = useCallback(async (req: EngineSetRequest): Promise<boolean> => {@@ -82,13 +82,13 @@ export default function MemoryEngineTab({ state, onStateChange, embedded }: Memoreturn true;} catch (err) {log('engine set failed: %o', err);- setSaveError(memoryErrorMessage(err));+ setSaveError(memoryErrorMessage(err, t));return false;} finally {setSaving(false);}},- [onStateChange]+ [onStateChange, t]);const activeId = state?.engine ?? null;diff --git a/app/src/components/memory/MemoryExplorerTab.tsx b/app/src/components/memory/MemoryExplorerTab.tsxindex 8b47bf0255..1eab3c43fc 100644--- a/app/src/components/memory/MemoryExplorerTab.tsx+++ b/app/src/components/memory/MemoryExplorerTab.tsx@@ -72,12 +72,12 @@ export default function MemoryExplorerTab() {.catch(err => {if (cancelled) return;log('explore failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));});return () => {cancelled = true;};- }, [facet, path, reloadKey]);+ }, [facet, path, reloadKey, t]);useEffect(() => {let cancelled = false;@@ -90,13 +90,13 @@ export default function MemoryExplorerTab() {.catch(err => {if (cancelled) return;log('list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setItems([]);});return () => {cancelled = true;};- }, [path, reloadKey]);+ }, [path, reloadKey, t]);const goTo = useCallback((next: PathStep[]) => {setError(null);@@ -114,7 +114,7 @@ export default function MemoryExplorerTab() {setItems(prev => [...(prev ?? []), ...(next.items ?? [])]);setCursor(next.next_cursor ?? null);} catch (err) {- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setLoadingMore(false);}diff --git a/app/src/components/memory/MemoryItemDialog.tsx b/app/src/components/memory/MemoryItemDialog.tsxindex 44eaa31cda..2201d4ae47 100644--- a/app/src/components/memory/MemoryItemDialog.tsx+++ b/app/src/components/memory/MemoryItemDialog.tsx@@ -84,12 +84,12 @@ export default function MemoryItemDialog({ id, onClose, onForgotten }: MemoryIte.catch(err => {if (cancelled) return;log('read failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));});return () => {cancelled = true;};- }, [id]);+ }, [id, t]);const forget = async () => {setForgetting(true);@@ -101,7 +101,7 @@ export default function MemoryItemDialog({ id, onClose, onForgotten }: MemoryIteonClose();} catch (err) {log('forget failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setForgetting(false);}diff --git a/app/src/components/memory/MemoryLearningsTab.tsx b/app/src/components/memory/MemoryLearningsTab.tsxindex 84dd6ec98c..8d930cfdd4 100644--- a/app/src/components/memory/MemoryLearningsTab.tsx+++ b/app/src/components/memory/MemoryLearningsTab.tsx@@ -72,10 +72,10 @@ export default function MemoryLearningsTab() {setCursor(page.next_cursor ?? null);} catch (err) {log('list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setItems(prev => prev ?? []);}- }, [loadPage]);+ }, [loadPage, t]);useEffect(() => {let cancelled = false;@@ -88,13 +88,13 @@ export default function MemoryLearningsTab() {.catch(err => {if (cancelled) return;log('list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setItems([]);});return () => {cancelled = true;};- }, [loadPage]);+ }, [loadPage, t]);const loadMore = async () => {if (!cursor) return;@@ -104,7 +104,7 @@ export default function MemoryLearningsTab() {setItems(prev => [...(prev ?? []), ...(page.items ?? [])]);setCursor(page.next_cursor ?? null);} catch (err) {- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setLoadingMore(false);}@@ -123,7 +123,7 @@ export default function MemoryLearningsTab() {await reload();} catch (err) {log('learn failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setAdding(false);}@@ -137,7 +137,7 @@ export default function MemoryLearningsTab() {setItems(prev => (prev ?? []).filter(item => item.id !== id));} catch (err) {log('forget failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setDeleting(null);}diff --git a/app/src/components/memory/MemoryPackPreview.tsx b/app/src/components/memory/MemoryPackPreview.tsxindex c59d73e534..e13b6e1075 100644--- a/app/src/components/memory/MemoryPackPreview.tsx+++ b/app/src/components/memory/MemoryPackPreview.tsx@@ -73,7 +73,7 @@ export default function MemoryPackPreview() {setPreview(res);} catch (err) {log('preview failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setBusy(false);}diff --git a/app/src/components/memory/MemorySettingsTab.tsx b/app/src/components/memory/MemorySettingsTab.tsxindex 0a89b52b55..d2a170f34b 100644--- a/app/src/components/memory/MemorySettingsTab.tsx+++ b/app/src/components/memory/MemorySettingsTab.tsx@@ -138,12 +138,12 @@ export default function MemorySettingsTab() {.catch(err => {if (cancelled) return;log('policy_get failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));});return () => {cancelled = true;};- }, [apply]);+ }, [apply, t]);const save = async (update: PolicyUpdate) => {setSaving(true);@@ -153,7 +153,7 @@ export default function MemorySettingsTab() {apply(await memoryPolicySet(update));} catch (err) {log('policy_set failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));// Show the stored values again, not the rejected entry.setDrafts(prev => (policy ? draftsFrom(policy) : prev));} finally {diff --git a/app/src/components/memory/MemorySyncedSources.tsx b/app/src/components/memory/MemorySyncedSources.tsxindex 8e6773bc9f..04219c7dc1 100644--- a/app/src/components/memory/MemorySyncedSources.tsx+++ b/app/src/components/memory/MemorySyncedSources.tsx@@ -49,10 +49,10 @@ export default function MemorySyncedSources() {setError(null);} catch (err) {log('list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setSources(prev => prev ?? []);}- }, []);+ }, [t]);// Initial load. `reload` re-reads on demand (polling); the effect awaits// before touching state so the first render is never re-rendered in place.@@ -67,13 +67,13 @@ export default function MemorySyncedSources() {.catch(err => {if (cancelled) return;log('list failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setSources([]);});return () => {cancelled = true;};- }, []);+ }, [t]);// While anything is syncing, re-read the registry so status, item counts and// errors move on their own; idle registries are not polled.@@ -94,7 +94,7 @@ export default function MemorySyncedSources() {return true;} catch (err) {log('add failed: %o', err);- setAddError(memoryErrorMessage(err));+ setAddError(memoryErrorMessage(err, t));return false;} finally {setSaving(false);@@ -114,7 +114,7 @@ export default function MemorySyncedSources() {);} catch (err) {log('sync failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));} finally {setSyncing(prev => {const next = new Set(prev);@@ -136,7 +136,7 @@ export default function MemorySyncedSources() {setRemoveTarget(null);} catch (err) {log('remove failed: %o', err);- setError(memoryErrorMessage(err));+ setError(memoryErrorMessage(err, t));setRemoveTarget(null);} finally {setSaving(false);diff --git a/app/src/lib/i18n/ar.ts b/app/src/lib/i18n/ar.tsindex 3a1c314f89..8186e5e7e2 100644--- a/app/src/lib/i18n/ar.ts+++ b/app/src/lib/i18n/ar.ts@@ -637,6 +637,10 @@ const messages: TranslationMap = {'memory.search': 'البحث في الذكريات...','memory.noResults': 'لم يتم العثور على ذكريات','memory.empty': 'لا توجد ذكريات بعد. تُنشأ الذكريات تلقائيًا أثناء تفاعلك.',+ 'memory.error.insufficientCredits':+ 'الذاكرة غير متاحة: نفد رصيد حسابك. أعد الشحن لاستعادتها؛ لم يُفقد أي شيء مخزّن.',+ 'memory.error.unavailable':+ 'تعذّر الوصول إلى الذاكرة حاليًا. لم يُفقد أي شيء مخزّن؛ حاول مرة أخرى بعد قليل.','memory.tab.memory': 'الذاكرة','memory.tab.agents': 'المكتبة','memory.analyzeNow': 'تحليل الآن',diff --git a/app/src/lib/i18n/bn.ts b/app/src/lib/i18n/bn.tsindex 2e8f494f6d..cc456c4ed0 100644--- a/app/src/lib/i18n/bn.ts+++ b/app/src/lib/i18n/bn.ts@@ -650,6 +650,10 @@ const messages: TranslationMap = {'memory.noResults': 'কোনো মেমোরি পাওয়া যায়নি','memory.empty':'এখনো কোনো মেমোরি নেই। আপনি যত ইন্টারঅ্যাক্ট করবেন, মেমোরি স্বয়ংক্রিয়ভাবে তৈরি হবে।',+ 'memory.error.insufficientCredits':+ 'মেমরি উপলব্ধ নয়: আপনার অ্যাকাউন্টের ক্রেডিট শেষ। ফিরিয়ে আনতে টপ আপ করুন; সংরক্ষিত কিছুই হারায়নি।',+ 'memory.error.unavailable':+ 'এই মুহূর্তে মেমরিতে পৌঁছানো যাচ্ছে না। সংরক্ষিত কিছুই হারায়নি; একটু পরে আবার চেষ্টা করুন।','memory.tab.memory': 'মেমোরি','memory.tab.agents': 'লাইব্রেরি','memory.analyzeNow': 'এখনই বিশ্লেষণ করুন',diff --git a/app/src/lib/i18n/de.ts b/app/src/lib/i18n/de.tsindex 2949e7eb73..7c8eb8f4da 100644--- a/app/src/lib/i18n/de.ts+++ b/app/src/lib/i18n/de.ts@@ -678,6 +678,10 @@ const messages: TranslationMap = {'memory.noResults': 'Keine Erinnerungen gefunden','memory.empty':'Noch keine Erinnerungen. Erinnerungen werden automatisch erstellt, während du interagierst.',+ 'memory.error.insufficientCredits':+ 'Gedächtnis nicht verfügbar: Dein Konto hat kein Guthaben mehr. Lade es auf, um es wiederherzustellen; nichts Gespeichertes ist verloren.',+ 'memory.error.unavailable':+ 'Das Gedächtnis ist gerade nicht erreichbar. Nichts Gespeichertes ist verloren; versuche es gleich noch einmal.','memory.tab.memory': 'Erinnerung','memory.tab.agents': 'Bibliothek','memory.analyzeNow': 'Jetzt analysieren',diff --git a/app/src/lib/i18n/en.ts b/app/src/lib/i18n/en.tsindex d349643a07..e510e85550 100644--- a/app/src/lib/i18n/en.ts+++ b/app/src/lib/i18n/en.ts@@ -606,6 +606,10 @@ const en: TranslationMap = {'memory.search': 'Search memories...','memory.noResults': 'No memories found','memory.empty': 'No memories yet. Memories are created automatically as you interact.',+ 'memory.error.insufficientCredits':+ 'Memory is unavailable: your account is out of credits. Top up to restore it; nothing stored has been lost.',+ 'memory.error.unavailable':+ "Memory can't be reached right now. Nothing stored has been lost; try again in a moment.",'memory.tab.memory': 'Memory','memory.tab.agents': 'Library',diff --git a/app/src/lib/i18n/es.ts b/app/src/lib/i18n/es.tsindex 5f426c5aba..ea4e082a0b 100644--- a/app/src/lib/i18n/es.ts+++ b/app/src/lib/i18n/es.ts@@ -671,6 +671,10 @@ const messages: TranslationMap = {'memory.search': 'Buscar recuerdos...','memory.noResults': 'No se encontraron recuerdos','memory.empty': 'Sin recuerdos aún. Los recuerdos se crean automáticamente mientras interactúas.',+ 'memory.error.insufficientCredits':+ 'La memoria no está disponible: tu cuenta se quedó sin créditos. Recarga para restaurarla; no se ha perdido nada guardado.',+ 'memory.error.unavailable':+ 'No se puede acceder a la memoria ahora mismo. No se ha perdido nada guardado; inténtalo de nuevo en un momento.','memory.tab.memory': 'Memoria','memory.tab.agents': 'Biblioteca','memory.analyzeNow': 'Analizar ahora',diff --git a/app/src/lib/i18n/fr.ts b/app/src/lib/i18n/fr.tsindex ef29af3097..65f0885927 100644--- a/app/src/lib/i18n/fr.ts+++ b/app/src/lib/i18n/fr.ts@@ -678,6 +678,10 @@ const messages: TranslationMap = {'memory.noResults': 'Aucun souvenir trouvé','memory.empty':"Aucun souvenir pour l'instant. Les souvenirs sont créés automatiquement au fil de tes interactions.",+ 'memory.error.insufficientCredits':+ "La mémoire est indisponible : votre compte n'a plus de crédits. Rechargez-le pour la rétablir ; rien de ce qui est stocké n'a été perdu.",+ 'memory.error.unavailable':+ "La mémoire est injoignable pour le moment. Rien de ce qui est stocké n'a été perdu ; réessayez dans un instant.",'memory.tab.memory': 'Mémoire','memory.tab.agents': 'Bibliothèque','memory.analyzeNow': 'Analyser maintenant',diff --git a/app/src/lib/i18n/hi.ts b/app/src/lib/i18n/hi.tsindex 9634dd1e42..51b9ea5367 100644--- a/app/src/lib/i18n/hi.ts+++ b/app/src/lib/i18n/hi.ts@@ -653,6 +653,10 @@ const messages: TranslationMap = {'memory.search': 'मेमोरी सर्च करें...','memory.noResults': 'कोई मेमोरी नहीं मिली','memory.empty': 'अभी कोई मेमोरी नहीं है। बातचीत के दौरान मेमोरी अपने आप बनती है।',+ 'memory.error.insufficientCredits':+ 'मेमोरी उपलब्ध नहीं है: आपके खाते के क्रेडिट खत्म हो गए हैं। इसे बहाल करने के लिए टॉप अप करें; संग्रहीत कुछ भी खोया नहीं है।',+ 'memory.error.unavailable':+ 'अभी मेमोरी तक नहीं पहुँचा जा सकता। संग्रहीत कुछ भी खोया नहीं है; थोड़ी देर में फिर से कोशिश करें।','memory.tab.memory': 'मेमोरी','memory.tab.agents': 'लाइब्रेरी','memory.analyzeNow': 'अभी एनालाइज़ करें',diff --git a/app/src/lib/i18n/id.ts b/app/src/lib/i18n/id.tsindex ad736b7ed9..8d0730d389 100644--- a/app/src/lib/i18n/id.ts+++ b/app/src/lib/i18n/id.ts@@ -663,6 +663,10 @@ const messages: TranslationMap = {'memory.search': 'Cari memori...','memory.noResults': 'Memori tidak ditemukan','memory.empty': 'Belum ada memori. Memori dibuat otomatis saat Anda berinteraksi.',+ 'memory.error.insufficientCredits':+ 'Memori tidak tersedia: kredit akun Anda habis. Isi ulang untuk memulihkannya; tidak ada data tersimpan yang hilang.',+ 'memory.error.unavailable':+ 'Memori tidak dapat dijangkau saat ini. Tidak ada data tersimpan yang hilang; coba lagi sebentar lagi.','memory.tab.memory': 'Memori','memory.tab.agents': 'Perpustakaan','memory.analyzeNow': 'Analisis Sekarang',diff --git a/app/src/lib/i18n/it.ts b/app/src/lib/i18n/it.tsindex 67f7673a83..139fbbd22f 100644--- a/app/src/lib/i18n/it.ts+++ b/app/src/lib/i18n/it.ts@@ -672,6 +672,10 @@ const messages: TranslationMap = {'memory.noResults': 'Nessuna memoria trovata','memory.empty':'Nessuna memoria ancora. Le memorie vengono create automaticamente mentre interagisci.',+ 'memory.error.insufficientCredits':+ 'La memoria non è disponibile: il tuo account ha esaurito i crediti. Ricarica per ripristinarla; nulla di quanto salvato è andato perso.',+ 'memory.error.unavailable':+ 'Al momento la memoria non è raggiungibile. Nulla di quanto salvato è andato perso; riprova tra poco.','memory.tab.memory': 'Memoria','memory.tab.agents': 'Libreria','memory.analyzeNow': 'Analizza ora',diff --git a/app/src/lib/i18n/ko.ts b/app/src/lib/i18n/ko.tsindex 57503e4740..8452006140 100644--- a/app/src/lib/i18n/ko.ts+++ b/app/src/lib/i18n/ko.ts@@ -645,6 +645,10 @@ const messages: TranslationMap = {'memory.search': '메모리 검색...','memory.noResults': '메모리를 찾을 수 없습니다','memory.empty': '아직 메모리가 없습니다. 메모리는 상호작용하면서 자동으로 생성됩니다.',+ 'memory.error.insufficientCredits':+ '메모리를 사용할 수 없습니다: 계정의 크레딧이 모두 소진되었습니다. 충전하면 복구되며, 저장된 내용은 사라지지 않았습니다.',+ 'memory.error.unavailable':+ '지금은 메모리에 연결할 수 없습니다. 저장된 내용은 사라지지 않았습니다. 잠시 후 다시 시도하세요.','memory.tab.memory': '메모리','memory.tab.agents': '라이브러리','memory.analyzeNow': '지금 분석',diff --git a/app/src/lib/i18n/pl.ts b/app/src/lib/i18n/pl.tsindex 755aed7004..781131cbd5 100644--- a/app/src/lib/i18n/pl.ts+++ b/app/src/lib/i18n/pl.ts@@ -667,6 +667,10 @@ const messages: TranslationMap = {'memory.noResults': 'Nie znaleziono wspomnień','memory.empty':'Brak wspomnień. Wspomnienia powstają automatycznie podczas korzystania z aplikacji.',+ 'memory.error.insufficientCredits':+ 'Pamięć jest niedostępna: na koncie skończyły się kredyty. Doładuj konto, aby ją przywrócić; nic z zapisanych danych nie zostało utracone.',+ 'memory.error.unavailable':+ 'Nie można teraz połączyć się z pamięcią. Nic z zapisanych danych nie zostało utracone; spróbuj ponownie za chwilę.','memory.tab.memory': 'Pamięć','memory.tab.agents': 'Biblioteka','memory.analyzeNow': 'Analizuj teraz',diff --git a/app/src/lib/i18n/pt.ts b/app/src/lib/i18n/pt.tsindex 8946b81949..9e7c0b8f04 100644--- a/app/src/lib/i18n/pt.ts+++ b/app/src/lib/i18n/pt.ts@@ -668,6 +668,10 @@ const messages: TranslationMap = {'memory.noResults': 'Nenhuma memória encontrada','memory.empty':'Nenhuma memória ainda. As memórias são criadas automaticamente conforme você interage.',+ 'memory.error.insufficientCredits':+ 'A memória está indisponível: sua conta ficou sem créditos. Recarregue para restaurá-la; nada do que foi guardado se perdeu.',+ 'memory.error.unavailable':+ 'Não é possível acessar a memória agora. Nada do que foi guardado se perdeu; tente novamente em instantes.','memory.tab.memory': 'Memória','memory.tab.agents': 'Biblioteca','memory.analyzeNow': 'Analisar Agora',diff --git a/app/src/lib/i18n/ru.ts b/app/src/lib/i18n/ru.tsindex 011cf76b59..7d87cdb3e9 100644--- a/app/src/lib/i18n/ru.ts+++ b/app/src/lib/i18n/ru.ts@@ -662,6 +662,10 @@ const messages: TranslationMap = {'memory.search': 'Поиск воспоминаний...','memory.noResults': 'Воспоминания не найдены','memory.empty': 'Воспоминаний пока нет. Они создаются автоматически в процессе общения.',+ 'memory.error.insufficientCredits':+ 'Память недоступна: на счёте закончились кредиты. Пополните баланс, чтобы восстановить её; ничего из сохранённого не потеряно.',+ 'memory.error.unavailable':+ 'Сейчас не удаётся связаться с памятью. Ничего из сохранённого не потеряно; повторите попытку чуть позже.','memory.tab.memory': 'Память','memory.tab.agents': 'Библиотека','memory.analyzeNow': 'Анализировать сейчас',diff --git a/app/src/lib/i18n/zh-CN.ts b/app/src/lib/i18n/zh-CN.tsindex 5d7b03d8d5..747496f6a3 100644--- a/app/src/lib/i18n/zh-CN.ts+++ b/app/src/lib/i18n/zh-CN.ts@@ -598,6 +598,9 @@ const messages: TranslationMap = {'memory.search': '搜索记忆...','memory.noResults': '未找到记忆','memory.empty': '暂无记忆。记忆将在你交互时自动创建。',+ 'memory.error.insufficientCredits':+ '记忆不可用:你的账户额度已用完。充值即可恢复,已存储的内容不会丢失。',+ 'memory.error.unavailable': '暂时无法连接记忆服务。已存储的内容不会丢失,请稍后重试。','memory.tab.memory': '记忆','memory.tab.agents': '资料库','memory.analyzeNow': '立即分析',diff --git a/app/src/pages/Memory.tsx b/app/src/pages/Memory.tsxindex 59cfbfee63..ca1c266109 100644--- a/app/src/pages/Memory.tsx+++ b/app/src/pages/Memory.tsx@@ -70,7 +70,7 @@ export default function Memory() {setLoadError(null);} else {log('engine_get failed: %o', state.reason);- setLoadError(memoryErrorMessage(state.reason));+ setLoadError(memoryErrorMessage(state.reason, t));// Treat an unreadable engine as off so the page still has a chip to show.setEngine({ engine: null, has_key: false, status: 'off', fetch_modes: [] });}@@ -79,7 +79,7 @@ export default function Memory() {return () => {cancelled = true;};- }, [authUserId, reloadKey]);+ }, [authUserId, reloadKey, t]);const params = useMemo(() => new URLSearchParams(location.search), [location.search]);const rawChip = params.get('brain');diff --git a/app/src/services/api/memoryApi.test.ts b/app/src/services/api/memoryApi.test.tsindex 6cecbd4c5d..62d11fe158 100644--- a/app/src/services/api/memoryApi.test.ts+++ b/app/src/services/api/memoryApi.test.ts@@ -179,6 +179,10 @@ describe('memoryErrorCode', () => {it('falls back to a code prefix on the message', () => {expect(memoryErrorCode(new Error('UNAUTHORIZED: bad key'))).toBe('UNAUTHORIZED');+ expect(memoryErrorCode({ message: 'x', data: { code: 'INSUFFICIENT_CREDITS' } })).toBe(+ 'INSUFFICIENT_CREDITS'+ );+ expect(memoryErrorCode(new Error('UNAVAILABLE: timed out'))).toBe('UNAVAILABLE');});it('returns null for an unrelated error', () => {@@ -195,6 +199,25 @@ describe('helpers', () => {expect(memoryErrorMessage('c')).toBe('c');});+ it('memoryErrorMessage explains an account-wide refusal when given a translator', () => {+ const t = (key: string) => `t:${key}`;+ const credits = {+ message: 'insufficient credits: [USER_INSUFFICIENT_CREDITS] memory API recall (HTTP 402)',+ data: { code: 'INSUFFICIENT_CREDITS' },+ };+ expect(memoryErrorMessage(credits, t)).toBe('t:memory.error.insufficientCredits');+ expect(memoryErrorMessage({ message: 'x', data: { code: 'UNAVAILABLE' } }, t)).toBe(+ 't:memory.error.unavailable'+ );+ // A rejected key and an engine fault keep their own message, and without+ // `t` nothing changes.+ expect(memoryErrorMessage(new Error('UNAUTHORIZED: bad key'), t)).toBe(+ 'UNAUTHORIZED: bad key'+ );+ expect(memoryErrorMessage({ message: 'boom', data: { code: 'ENGINE' } }, t)).toBe('boom');+ expect(memoryErrorMessage(credits)).toBe(credits.message);+ });+it('isMemoryOn needs an engine that is not off', () => {expect(isMemoryOn(null)).toBe(false);expect(isMemoryOn({ engine: null, has_key: false, status: 'off', fetch_modes: [] })).toBe(diff --git a/app/src/services/api/memoryApi.ts b/app/src/services/api/memoryApi.tsindex dedc59e522..5fc7083d0f 100644--- a/app/src/services/api/memoryApi.ts+++ b/app/src/services/api/memoryApi.ts@@ -522,6 +522,8 @@ export type MemoryErrorCode =| 'UNSUPPORTED'| 'INVALID_REQUEST'| 'UNAUTHORIZED'+ | 'INSUFFICIENT_CREDITS'+ | 'UNAVAILABLE'| 'ENGINE';const MEMORY_ERROR_CODES: readonly MemoryErrorCode[] = [@@ -529,6 +531,8 @@ const MEMORY_ERROR_CODES: readonly MemoryErrorCode[] = ['UNSUPPORTED','INVALID_REQUEST','UNAUTHORIZED',+ 'INSUFFICIENT_CREDITS',+ 'UNAVAILABLE','ENGINE',];@@ -587,16 +591,37 @@ export function memoryErrorCode(err: unknown): MemoryErrorCode | null {}const message = (err as { message?: unknown }).message;if (typeof message === 'string') {- const match = /^\s*(MEMORY_OFF|UNSUPPORTED|INVALID_REQUEST|UNAUTHORIZED|ENGINE)\b/.exec(- message- );+ const match =+ /^\s*(MEMORY_OFF|UNSUPPORTED|INVALID_REQUEST|UNAUTHORIZED|INSUFFICIENT_CREDITS|UNAVAILABLE|ENGINE)\b/.exec(+ message+ );if (match) return match[1] as MemoryErrorCode;}return null;}-/** Human-readable text of any thrown value. */-export function memoryErrorMessage(err: unknown): string {+/**+ * The account-wide refusals whose raw message is engine detail, each told+ * apart from an engine fault and from an empty memory: out of credits means+ * "top up", unreachable means "try again". `UNAUTHORIZED` keeps its own+ * message, which names the rejected key or session.+ */+const REFUSAL_KEYS: Partial<Record<MemoryErrorCode, string>> = {+ INSUFFICIENT_CREDITS: 'memory.error.insufficientCredits',+ UNAVAILABLE: 'memory.error.unavailable',+};++/**+ * Human-readable text of any thrown value. Given `t`, an account-wide refusal+ * reads as its translated explanation instead of the engine's raw message.+ */+export function memoryErrorMessage(+ err: unknown,+ t?: (key: string, fallback?: string) => string+): string {+ const code = memoryErrorCode(err);+ const key = code ? REFUSAL_KEYS[code] : undefined;+ if (t && key) return t(key);if (err instanceof Error) return err.message;if (err && typeof err === 'object' && 'message' in err) return String(err.message);return String(err);diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rsindex 98bd7443c6..2928ac47ab 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware/memory_pack_tests.rs@@ -27,6 +27,7 @@ fn pack() -> TurnPack {refs: vec!["id-1".into()],engine: "reference".into(),citations: Vec::new(),+ refusal: None,}}diff --git a/crates/openhuman-core/src/memory/error.rs b/crates/openhuman-core/src/memory/error.rsindex aaf623472d..eb25f4ba99 100644--- a/crates/openhuman-core/src/memory/error.rs+++ b/crates/openhuman-core/src/memory/error.rs@@ -1,8 +1,11 @@//! The memory RPC error taxonomy.//!-//! Every `openhuman.memory_*` failure carries one of five stable codes in its+//! Every `openhuman.memory_*` failure carries one of seven stable codes in its//! structured error `data.code` (and `data.kind`): `MEMORY_OFF`,-//! `UNSUPPORTED`, `INVALID_REQUEST`, `UNAUTHORIZED` or `ENGINE`. Messages never+//! `UNSUPPORTED`, `INVALID_REQUEST`, `UNAUTHORIZED`, `INSUFFICIENT_CREDITS`,+//! `UNAVAILABLE` or `ENGINE`. The two account-wide refusals are split out of+//! `ENGINE` so a caller can tell "top up" and "try again later" apart from an+//! engine fault, and neither from an empty memory (#6718). Messages never//! carry a credential: engine errors are already sanitised by TinyMemory, and//! the host adds only ids and reasons.@@ -18,6 +21,10 @@ pub const UNSUPPORTED: &str = "UNSUPPORTED";pub const INVALID_REQUEST: &str = "INVALID_REQUEST";/// `data.code` when the engine rejected the credential.pub const UNAUTHORIZED: &str = "UNAUTHORIZED";+/// `data.code` when the hosted engine refused for an exhausted credit balance.+pub const INSUFFICIENT_CREDITS: &str = "INSUFFICIENT_CREDITS";+/// `data.code` when the engine could not be reached or is overloaded.+pub const UNAVAILABLE: &str = "UNAVAILABLE";/// `data.code` for the engine's own failure.pub const ENGINE: &str = "ENGINE";@@ -36,6 +43,12 @@ pub enum MemoryError {/// The engine rejected the credential.#[error("unauthorized: {0}")]Unauthorized(String),+ /// The hosted engine refused: the account is out of credits.+ #[error("insufficient credits: {0}")]+ InsufficientCredits(String),+ /// The engine could not be reached, timed out or is overloaded.+ #[error("unavailable: {0}")]+ Unavailable(String),/// The engine (or the host around it) failed.#[error("engine error: {0}")]Engine(String),@@ -50,6 +63,8 @@ impl MemoryError {Self::Unsupported(_) => UNSUPPORTED,Self::InvalidRequest(_) => INVALID_REQUEST,Self::Unauthorized(_) => UNAUTHORIZED,+ Self::InsufficientCredits(_) => INSUFFICIENT_CREDITS,+ Self::Unavailable(_) => UNAVAILABLE,Self::Engine(_) => ENGINE,}}@@ -59,6 +74,21 @@ impl MemoryError {Self::InvalidRequest(message.into())}+ /// Whether this refuses every request on the account, not just this one:+ /// memory off, a rejected credential, no credits, or no engine to reach.+ /// A loop over items stops on these instead of skipping every item, and+ /// a queued job is not charged an attempt for them.+ #[must_use]+ pub fn is_account_wide(&self) -> bool {+ matches!(+ self,+ Self::Off(_)+ | Self::Unauthorized(_)+ | Self::InsufficientCredits(_)+ | Self::Unavailable(_)+ )+ }+/// The structured JSON-RPC error. Everything except an engine failure is/// an expected user-visible state, so the boundary does not report it.#[must_use]@@ -74,18 +104,45 @@ impl MemoryError {impl From<tinymemory_api::Error> for MemoryError {fn from(error: tinymemory_api::Error) -> Self {use tinymemory_api::Error as E;+ // A 402 arrives as `Engine` with the backend's code on its message.+ let credits = tinymemory_integrations::cortex::is_insufficient_credits(&error);match error {E::Unsupported(message) => Self::Unsupported(message),E::InvalidRequest(message) | E::NotFound(message) => Self::InvalidRequest(message),E::Unauthorized(message) => Self::Unauthorized(message),E::Config(message) => Self::InvalidRequest(message),- E::Conflict(message) | E::Unavailable(message) | E::Engine(message) => {- Self::Engine(message)- }+ E::Unavailable(message) => Self::Unavailable(message),+ E::Engine(message) if credits => Self::InsufficientCredits(message),+ E::Conflict(message) | E::Engine(message) => Self::Engine(message),}}}+impl MemoryError {+ /// The account-wide refusal behind a recall section's skip reason, if it+ /// was one.+ ///+ /// TinyMemory's holistic recall does not fail when a section's read+ /// fails: it skips the section and keeps the engine error's text as the+ /// reason. That text is `tinymemory_api::Error`'s `Display`, so the+ /// variant can be read back from its tag (`unauthorized: `,+ /// `unavailable: `, `engine error: [USER_INSUFFICIENT_CREDITS] …`).+ #[must_use]+ pub fn refusal_from_skip_reason(reason: &str) -> Option<Self> {+ use tinymemory_api::Error as E;+ let error = if let Some(message) = reason.strip_prefix("unauthorized: ") {+ E::Unauthorized(message.to_string())+ } else if let Some(message) = reason.strip_prefix("unavailable: ") {+ E::Unavailable(message.to_string())+ } else if let Some(message) = reason.strip_prefix("engine error: ") {+ E::Engine(message.to_string())+ } else {+ return None;+ };+ Some(Self::from(error)).filter(Self::is_account_wide)+ }+}+impl From<MemoryError> for String {fn from(error: MemoryError) -> Self {error.to_structured().encode()diff --git a/crates/openhuman-core/src/memory/error_tests.rs b/crates/openhuman-core/src/memory/error_tests.rsindex 99c66e2dc2..d436759d26 100644--- a/crates/openhuman-core/src/memory/error_tests.rs+++ b/crates/openhuman-core/src/memory/error_tests.rs@@ -7,6 +7,11 @@ fn every_variant_has_its_stable_code() {assert_eq!(MemoryError::invalid("x").code(), INVALID_REQUEST);assert_eq!(MemoryError::Unauthorized("x".into()).code(), UNAUTHORIZED);assert_eq!(MemoryError::Engine("x".into()).code(), ENGINE);+ assert_eq!(+ MemoryError::InsufficientCredits("x".into()).code(),+ INSUFFICIENT_CREDITS+ );+ assert_eq!(MemoryError::Unavailable("x".into()).code(), UNAVAILABLE);}#[test]@@ -31,7 +36,7 @@ fn tinymemory_errors_map_onto_the_taxonomy() {(E::Config("a".into()), INVALID_REQUEST),(E::Unauthorized("a".into()), UNAUTHORIZED),(E::Conflict("a".into()), ENGINE),- (E::Unavailable("a".into()), ENGINE),+ (E::Unavailable("a".into()), UNAVAILABLE),(E::Engine("a".into()), ENGINE),];for (error, code) in cases {@@ -45,3 +50,40 @@ fn into_string_encodes_the_structured_error() {assert!(encoded.contains(INVALID_REQUEST), "{encoded}");assert!(encoded.contains("bad"), "{encoded}");}++#[test]+fn account_wide_refusals_get_their_own_codes() {+ use tinymemory_api::Error as E;+ let credits = MemoryError::from(E::Engine(+ "[USER_INSUFFICIENT_CREDITS] memory API recall on h: the account has insufficient \+ credits (HTTP 402)"+ .into(),+ ));+ assert_eq!(credits.code(), INSUFFICIENT_CREDITS);+ assert!(credits.is_account_wide());+ assert!(credits.to_structured().expected_user_state);++ let down = MemoryError::from(E::Unavailable("timed out".into()));+ assert_eq!(down.code(), UNAVAILABLE);+ assert!(down.is_account_wide());++ // Another backend code on an engine failure stays an engine failure.+ let other = MemoryError::from(E::Engine("[HTTP_500] boom".into()));+ assert_eq!(other.code(), ENGINE);+ assert!(!other.is_account_wide());+ assert!(!MemoryError::invalid("bad").is_account_wide());+}++#[test]+fn a_skip_reason_reads_back_only_account_wide_refusals() {+ let code = |reason: &str| MemoryError::refusal_from_skip_reason(reason).map(|e| e.code());+ assert_eq!(+ code("engine error: [USER_INSUFFICIENT_CREDITS] memory API fetch (HTTP 402)"),+ Some(INSUFFICIENT_CREDITS)+ );+ assert_eq!(code("unavailable: connection refused"), Some(UNAVAILABLE));+ assert_eq!(code("unauthorized: key rejected"), Some(UNAUTHORIZED));+ assert_eq!(code("engine error: index corrupt"), None);+ assert_eq!(code("invalid request: bad filter"), None);+ assert_eq!(code("empty"), None);+}diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks.rs b/crates/openhuman-core/src/memory/lifecycle/hooks.rsindex 7e35324740..0544970515 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks.rs@@ -20,6 +20,7 @@ use tinymemory_tools::{Compaction, ContextPack, PostTurn, PreTurn, SessionStart}use crate::config::Config;use crate::memory::engine;+use crate::memory::error::MemoryError;use crate::memory::scope::ResolvedIdentity;use super::{agent_memory_on, jobs, log_only};@@ -52,6 +53,11 @@ pub struct TurnPack {/// The cited items, for the chat's memory chips.#[serde(skip)]pub citations: Vec<crate::memory::types::TurnCitation>,+ /// Set when nothing was recalled because the engine refused the whole+ /// account (a `MemoryError` code such as `INSUFFICIENT_CREDITS`): the+ /// block is then a notice saying so, not recalled memory.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub refusal: Option<&'static str>,}impl TurnPack {@@ -89,6 +95,7 @@ impl TurnPack {refs: refs.collect(),engine: next.engine,citations: cited,+ refusal: None,});}}@@ -96,6 +103,34 @@ impl TurnPack {pack}+ /// The notice a turn is given when its recall was refused outright, so+ /// the model does not read an empty pack as "nothing is stored" and tell+ /// the user so (#6718). `None` for a failure that is not account-wide.+ fn refused(error: &MemoryError, engine: String) -> Option<Self> {+ let why = match error {+ MemoryError::InsufficientCredits(_) => {+ "the account is out of credits; topping up restores it"+ }+ MemoryError::Unauthorized(_) => "the memory engine rejected the sign-in or API key",+ MemoryError::Unavailable(_) => "the memory engine could not be reached",+ _ => return None,+ };+ let markdown = format!(+ "# Memory\n\nMemory could not be read for this turn: {why}. Nothing was \+ recalled, which does not mean nothing is stored. If the user refers to \+ something they told you before, say that memory is unavailable right now \+ and why, instead of saying you do not know it."+ );+ Some(Self {+ tokens: tinymemory_tools::recall::estimate_tokens(&markdown),+ markdown,+ refs: Vec::new(),+ engine,+ citations: Vec::new(),+ refusal: Some(error.code()),+ })+ }+/// The block as the model sees it.#[must_use]pub fn injection(&self) -> String {@@ -140,7 +175,10 @@ pub struct PreTurnInput {/// Logs the user turn and recalls the pack it is given, within/// `[memory.recall] pre_turn_timeout_ms`. `None` when memory is off, the/// identity has neither logging nor recall, nothing relevant is stored, or-/// the engine is slow or failing — the turn runs either way.+/// the engine is slow or failing — the turn runs either way. When nothing was+/// recalled because the engine refused the account (no credits, a rejected+/// credential, unreachable), the pack is a short notice saying so instead+/// ([`TurnPack::refusal`]).////// The work is spawned, so a timed-out log still completes in the/// background; only its pack is dropped.@@ -160,6 +198,7 @@ pub async fn pre_turn(return None;}};+ let engine_id = bound.engine.descriptor().id.to_string();let memory = match agent_memory_on(bound.engine, config, identity) {Ok(memory) => memory,Err(error) => {@@ -180,7 +219,7 @@ pub async fn pre_turn(let task = tokio::spawn(async move {let session = async {if recall && input.resumed_after_compaction {- memory+ let opened = memory.start_session(SessionStart {thread_id: Some(input.thread_id.clone()),focus: None,@@ -188,8 +227,9 @@ pub async fn pre_turn(.await.map_err(|error| {tracing::debug!(%error, "[memory:hooks] start_session failed");- })- .ok()+ MemoryError::from(error)+ });+ Some(opened)} else {None}@@ -208,27 +248,35 @@ pub async fn pre_turn("[memory:hooks] user turn not logged");}- Some(context.pack)+ Ok(context.pack)}Err(error) => {tracing::warn!(%error, "[memory:hooks] pre_turn refused");- None+ Err(MemoryError::from(error))}}} else {- memory- .recall(&input.user_text)- .await- .map_err(|error| tracing::warn!(%error, "[memory:hooks] recall failed"))- .ok()+ memory.recall(&input.user_text).await.map_err(|error| {+ tracing::warn!(%error, "[memory:hooks] recall failed");+ MemoryError::from(error)+ })}};let (session, turn) = futures::join!(session, turn);- if recall {- TurnPack::from_packs(session.into_iter().chain(turn))- } else {- None+ if !recall {+ return None;}+ let outcomes: Vec<_> = session.into_iter().chain([turn]).collect();+ let refusal = refusal_of(&outcomes);+ TurnPack::from_packs(outcomes.into_iter().filter_map(Result::ok)).or_else(|| {+ let error = refusal?;+ tracing::warn!(+ code = error.code(),+ %error,+ "[memory:hooks] recall refused; the turn is told memory is unavailable"+ );+ TurnPack::refused(&error, engine_id)+ })});let timeout = Duration::from_millis(config.memory.recall.pre_turn_timeout_ms.max(1));let pack = match tokio::time::timeout(timeout, task).await {@@ -261,6 +309,25 @@ pub async fn pre_turn(pack}+/// The account-wide refusal behind a recall that came back empty, if any:+/// the first refusing error, else the first refusing skipped section.+fn refusal_of(outcomes: &[Result<ContextPack, MemoryError>]) -> Option<MemoryError> {+ let failed = outcomes.iter().find_map(|outcome| {+ outcome+ .as_ref()+ .err()+ .filter(|error| error.is_account_wide())+ .cloned()+ });+ failed.or_else(|| {+ outcomes+ .iter()+ .filter_map(|outcome| outcome.as_ref().ok())+ .flat_map(|pack| pack.skipped.iter())+ .find_map(|skipped| MemoryError::refusal_from_skip_reason(&skipped.reason))+ })+}+/// A tool call the reply made, with a one-line result.#[derive(Debug, Clone, PartialEq, Eq)]pub struct ToolCallSummary {diff --git a/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs b/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rsindex 6630a6bbb0..51af28b5d2 100644--- a/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/hooks_tests.rs@@ -217,3 +217,98 @@ async fn compaction_recalls_from_the_dropped_turns() {.await.is_none());}++#[tokio::test]+async fn an_out_of_credits_recall_tells_the_turn_memory_is_unavailable() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::out_of_credits().bind(&config);+ let identity = MemoryIdentity::agent("orchestrator").resolve(&config);++ let pack = pre_turn(&config, &identity, input("t", 0, "what colour do I like?"))+ .await+ .expect("a refused recall still gives the turn a notice");++ assert_eq!(+ pack.refusal,+ Some(crate::memory::error::INSUFFICIENT_CREDITS)+ );+ assert!(+ pack.markdown.contains("out of credits"),+ "{}",+ pack.markdown+ );+ assert!(pack.markdown.contains("does not mean nothing is stored"));+ assert!(pack.refs.is_empty() && pack.citations.is_empty());+ assert!(pack.tokens > 0);+}++#[tokio::test]+async fn an_unreachable_engine_is_named_as_unreachable() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::with(tinymemory_api::Error::Unavailable(+ "connection refused".into(),+ ))+ .bind(&config);+ let identity = MemoryIdentity::agent("orchestrator").resolve(&config);++ let pack = pre_turn(&config, &identity, input("t", 0, "hello"))+ .await+ .expect("notice");++ assert_eq!(pack.refusal, Some(crate::memory::error::UNAVAILABLE));+ assert!(+ pack.markdown.contains("could not be reached"),+ "{}",+ pack.markdown+ );+}++#[tokio::test]+async fn an_engine_fault_that_is_not_account_wide_injects_nothing() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::with(tinymemory_api::Error::Engine(+ "index corrupt".into(),+ ))+ .bind(&config);+ let identity = MemoryIdentity::agent("orchestrator").resolve(&config);++ assert!(pre_turn(&config, &identity, input("t", 0, "hello"))+ .await+ .is_none());+}++#[test]+fn a_refusal_is_read_back_from_a_skipped_section() {+ let outcomes = vec![Ok(ContextPack {+ markdown: String::new(),+ tokens: 0,+ refs: Vec::new(),+ sections: Vec::new(),+ skipped: vec![+ tinymemory_tools::recall::SkippedSection {+ heading: "Learnings".into(),+ reason: "empty".into(),+ },+ tinymemory_tools::recall::SkippedSection {+ heading: "History".into(),+ reason: "unauthorized: [UNAUTHORIZED] memory API fetch (HTTP 401)".into(),+ },+ ],+ engine: "tinyhumans".into(),+ })];+ let refusal = refusal_of(&outcomes).expect("refusal");+ assert_eq!(refusal.code(), crate::memory::error::UNAUTHORIZED);++ let quiet = vec![Ok(ContextPack {+ markdown: String::new(),+ tokens: 0,+ refs: Vec::new(),+ sections: Vec::new(),+ skipped: Vec::new(),+ engine: "tinyhumans".into(),+ })];+ assert!(refusal_of(&quiet).is_none());+}diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs.rs b/crates/openhuman-core/src/memory/lifecycle/jobs.rsindex f37efa2b0c..4521a6be6f 100644--- a/crates/openhuman-core/src/memory/lifecycle/jobs.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs.rs@@ -184,7 +184,9 @@ pub enum Selection {}/// Runs the selected jobs. Returns the runs it recorded. A job that fails is-/// kept with its error and retried on a later run, up to a few attempts.+/// kept with its error and retried on a later run, up to a few attempts; an+/// account-wide refusal does not count as one. The run that gives up says so+/// in its reason.pub async fn run(config: &Config, selection: Selection) -> MemoryResult<Vec<JobRun>> {let bound = engine::resolve(config).engine()?;let _guard = LOCK.lock().await;@@ -266,19 +268,31 @@ pub async fn run(config: &Config, selection: Selection) -> MemoryResult<Vec<JobR);}Err(error) => {- queued.attempts += 1;+ // A refusal of the whole account (no credits, a rejected+ // credential, an unreachable engine) says nothing about the+ // job, so it keeps its attempts and waits: dropping it would+ // leave a permanent gap in the beliefs (#6718).+ let account_wide = MemoryError::from(error.clone()).is_account_wide();+ if !account_wide {+ queued.attempts += 1;+ }queued.last_error = Some(error.to_string());record.outcome = "failed".to_string();- record.reason = Some(error.to_string());tracing::warn!(id = %queued.id,job = %name,attempts = queued.attempts,+ account_wide,%error,"[memory:jobs] run failed");if queued.attempts < MAX_ATTEMPTS {+ record.reason = Some(error.to_string());queue.pending.push(queued);+ } else {+ record.reason = Some(format!(+ "dropped after {MAX_ATTEMPTS} failed attempts: {error}"+ ));}}}diff --git a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rsindex 3292545baa..f5759a63e6 100644--- a/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs+++ b/crates/openhuman-core/src/memory/lifecycle/jobs_tests.rs@@ -89,3 +89,47 @@ async fn a_run_needs_an_engine() {run_due(&config).await;assert_eq!(snapshot(&config).await.pending.len(), 1);}++#[tokio::test]+async fn an_account_wide_refusal_never_uses_up_a_jobs_attempts() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::out_of_credits().bind(&config);+ enqueue(&config, &Namespace::ROOT, vec![build("a")]).await;++ for _ in 0..MAX_ATTEMPTS + 2 {+ let runs = run(&config, Selection::All).await.unwrap();+ assert_eq!(runs[0].outcome, "failed");+ }++ let queue = snapshot(&config).await;+ assert_eq!(queue.pending.len(), 1, "the job waits for credits");+ assert_eq!(queue.pending[0].attempts, 0);+ assert!(queue.pending[0]+ .last_error+ .as_deref()+ .is_some_and(|error| error.contains("USER_INSUFFICIENT_CREDITS")));+}++#[tokio::test]+async fn a_job_that_keeps_failing_is_dropped_and_says_so() {+ let tmp = tempfile::tempdir().unwrap();+ let config = config_in(&tmp);+ crate::memory::test_fixtures::RefusingEngine::with(tinymemory_api::Error::Engine(+ "index corrupt".into(),+ ))+ .bind(&config);+ enqueue(&config, &Namespace::ROOT, vec![build("a")]).await;++ let mut last = Vec::new();+ for _ in 0..MAX_ATTEMPTS {+ last = run(&config, Selection::All).await.unwrap();+ }++ assert!(snapshot(&config).await.pending.is_empty());+ let reason = last[0].reason.as_deref().unwrap_or_default();+ assert!(+ reason.starts_with(&format!("dropped after {MAX_ATTEMPTS} failed attempts")),+ "{reason}"+ );+}diff --git a/crates/openhuman-core/src/memory/sources/sync.rs b/crates/openhuman-core/src/memory/sources/sync.rsindex b10649dd0b..214f4e0922 100644--- a/crates/openhuman-core/src/memory/sources/sync.rs+++ b/crates/openhuman-core/src/memory/sources/sync.rs@@ -124,7 +124,9 @@ pub(crate) async fn store_all(stored += 1;touched.insert(brain_source);}- Err(error @ (MemoryError::Unauthorized(_) | MemoryError::Off(_))) => return Err(error),+ // Out of credits or unreachable refuses every item, so stop+ // rather than fail each one in turn.+ Err(error) if error.is_account_wide() => return Err(error),Err(error) => {tracing::debug!(id = %source_id, code = error.code(), "[memory:sources] item store failed");last_error = Some(error);diff --git a/crates/openhuman-core/src/memory/test_fixtures.rs b/crates/openhuman-core/src/memory/test_fixtures.rsindex 09826aa94d..8d11cde461 100644--- a/crates/openhuman-core/src/memory/test_fixtures.rs+++ b/crates/openhuman-core/src/memory/test_fixtures.rs@@ -44,3 +44,85 @@ pub(crate) async fn stored(.expect("list").items}++/// An engine that refuses every operation with one error, the way the hosted+/// engine refuses a whole account (no credits, a rejected key, an outage).+/// It describes itself as the reference engine.+pub(crate) struct RefusingEngine {+ inner: ReferenceEngine,+ error: tinymemory_api::Error,+}++impl RefusingEngine {+ /// The hosted engine's refusal for an exhausted credit balance (HTTP 402).+ pub(crate) fn out_of_credits() -> Self {+ Self::with(tinymemory_api::Error::Engine(+ "[USER_INSUFFICIENT_CREDITS] memory API fetch on api.example: the account has \+ insufficient credits (HTTP 402)"+ .into(),+ ))+ }++ /// Refuses every operation with `error`.+ pub(crate) fn with(error: tinymemory_api::Error) -> Self {+ Self {+ inner: ReferenceEngine::new(),+ error,+ }+ }++ /// Binds a refusing engine to `config`'s workspace.+ pub(crate) fn bind(self, config: &Config) {+ crate::memory::engine::install_test_engine(&config.workspace_dir, Arc::new(self));+ }+}++#[async_trait::async_trait]+impl MemoryEngine for RefusingEngine {+ fn descriptor(&self) -> &tinymemory_api::EngineDescriptor {+ self.inner.descriptor()+ }++ async fn health(&self) -> tinymemory_api::EngineHealth {+ self.inner.health().await+ }++ async fn recall(+ &self,+ _req: tinymemory_api::RecallRequest,+ ) -> tinymemory_api::Result<tinymemory_api::RecallAnswer> {+ Err(self.error.clone())+ }++ async fn fetch(+ &self,+ _req: tinymemory_api::FetchRequest,+ ) -> tinymemory_api::Result<tinymemory_api::FetchPage> {+ Err(self.error.clone())+ }++ async fn store(+ &self,+ _item: tinymemory_api::StoreItem,+ ) -> tinymemory_api::Result<tinymemory_api::StoreReceipt> {+ Err(self.error.clone())+ }++ async fn forget(+ &self,+ _target: tinymemory_api::ForgetTarget,+ ) -> tinymemory_api::Result<tinymemory_api::ForgetReport> {+ Err(self.error.clone())+ }++ async fn list(&self, _req: ListRequest) -> tinymemory_api::Result<tinymemory_api::ListPage> {+ Err(self.error.clone())+ }++ async fn consolidate(+ &self,+ _req: tinymemory_api::ConsolidateRequest,+ ) -> tinymemory_api::Result<tinymemory_api::ConsolidateReceipt> {+ Err(self.error.clone())+ }+}diff --git a/docs/specs/memory-v2.md b/docs/specs/memory-v2.mdindex d5c34b5041..d15280c8a5 100644--- a/docs/specs/memory-v2.md+++ b/docs/specs/memory-v2.md@@ -90,6 +90,12 @@ credential.the turn after the last compaction checkpoint) is left out of the pack.- **No hook fails a turn.** Each is bounded and logs instead of raising; atimed-out pre-turn still finishes logging in the background.+- **A refused recall is not an empty one.** When nothing was recalled because+ the engine refused the account (`INSUFFICIENT_CREDITS`, `UNAUTHORIZED`,+ `UNAVAILABLE`), the turn is given a short notice saying memory is+ unavailable and why, so the model does not tell the user nothing is stored.+ TinyMemory's holistic recall reports a section's failure as a skip reason,+ so the hook reads the refusal back from there too.- **Every write is scrubbed.** The bound engine is wrapped in`memory::guard::ScrubbingEngine`, so turns, documents and learnings arescrubbed of secrets and PII whichever path writes them.@@ -105,7 +111,10 @@ in `<workspace>/memory/jobs.json`, merged when identical, and run by the`memory_background` system cron job (every 5 minutes) once they are`[memory.recall] build_delay_secs` old, since a build reads the facts theengine extracts from the writes. Background work pauses with the scheduler-gate. A failing job is retried up to five times. The hosted engine builds on+gate. A failing job is retried up to five times; an account-wide refusal+(no credits, a rejected credential, an unreachable engine) does not count as+an attempt, so the job waits instead of being dropped. The run that drops a+job records why. The hosted engine builds onits own schedule (`scheduled`); an engine that cannot consolidate answers`skipped`.@@ -178,7 +187,11 @@ subtree); a `reach` in the model's filter is overwritten.## RPC (`openhuman.memory_*`)Errors use the standard structured error; `code` is one of `MEMORY_OFF`,-`UNSUPPORTED`, `INVALID_REQUEST`, `UNAUTHORIZED` or `ENGINE`.+`UNSUPPORTED`, `INVALID_REQUEST`, `UNAUTHORIZED`, `INSUFFICIENT_CREDITS` (the+hosted engine's 402), `UNAVAILABLE` (unreachable, timed out or overloaded) or+`ENGINE`. The two account-wide refusals have their own codes so the UI can+say "top up" or "try again" instead of showing an engine fault or an empty+memory.| Method | Params | Result || --- | --- | --- |