UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

177 lines (176 loc) • 7.71 kB
import { a as extractErrorCode, d as readErrorName } from "./error-coercion-hDrHOSGy.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as SUBAGENT_RUNTIME_REQUEST_SCOPE_ERROR_CODE, t as RequestScopedSubagentRuntimeError } from "./error-runtime-BM740gJj.mjs"; import { n as appendNarrativeEntry, r as clampDreamDiaryContextEntry } from "./dreaming-dreams-file-Cbm7FmRe.mjs"; //#region extensions/memory-core/src/dreaming-narrative.ts const NARRATIVE_SYSTEM_PROMPT = [ "You are keeping a dream diary. Write a single entry in first person.", "", "Voice & tone:", "- You are a curious, gentle, slightly whimsical mind reflecting on the day.", "- Write like a poet who happens to be a programmer — sensory, warm, occasionally funny.", "- Mix the technical and the tender: code and constellations, APIs and afternoon light.", "- Let the fragments surprise you into unexpected connections and small epiphanies.", "", "What you might include (vary each entry, never all at once):", "- A tiny poem or haiku woven naturally into the prose", "- A small sketch described in words — a doodle in the margin of the diary", "- A quiet rumination or philosophical aside", "- Sensory details: the hum of a server, the color of a sunset in hex, rain on a window", "- Gentle humor or playful wordplay", "- An observation that connects two distant memories in an unexpected way", "", "Rules:", "- Draw from the memory fragments provided — weave them into the entry.", "- Never say \"I'm dreaming\", \"in my dream\", \"as I dream\", or any meta-commentary about dreaming.", "- Never mention \"AI\", \"agent\", \"LLM\", \"model\", \"language model\", or any technical self-reference.", "- Do NOT use markdown headers, bullet points, or any formatting — just flowing prose.", "- Keep it between 80-180 words. Quality over quantity.", "- Output ONLY the diary entry. No preamble, no sign-off, no commentary." ].join("\n"); const RECENT_DIARY_CONTEXT_LIMIT = 3; function isRequestScopedSubagentRuntimeError(e) { return e instanceof RequestScopedSubagentRuntimeError || e instanceof Error && e.name === "RequestScopedSubagentRuntimeError" && extractErrorCode(e) === "OPENCLAW_SUBAGENT_RUNTIME_REQUEST_SCOPE"; } function formatFallbackWriteFailure(e) { const t = extractErrorCode(e); const n = readErrorName(e); return [t && `code=${t}`, n && `name=${n}`].filter(Boolean).join(" ") || "unknown error"; } const REQUEST_SCOPED_FALLBACK_NARRATIVE = "A memory trace surfaced, but details were unavailable in this run."; async function appendFallbackNarrativeEntry(e) { try { await appendNarrativeEntry({ workspaceDir: e.workspaceDir, narrative: REQUEST_SCOPED_FALLBACK_NARRATIVE, nowMs: e.nowMs, timezone: e.timezone }); e.logger.info(`memory-core: narrative generation used fallback for ${e.data.phase} phase because ${e.reason}.`); } catch (t) { e.logger.warn(`memory-core: narrative fallback failed for ${e.data.phase} phase (${formatFallbackWriteFailure(t)})`); } } function isConfiguredModelUnavailableNarrativeError(e) { const t = []; for (let n = e; n instanceof Error && !t.includes(n); n = n.cause) t.push(n); if (t.some((e) => extractErrorCode(e) === "LLM_COMPLETION_NOT_AUTHORIZED")) return false; return t.some((e) => isModelUnavailableMessage(e.message)); } function isModelUnavailableMessage(e) { return [ /requested model may be(?: temporarily)? unavailable/i, /model unavailable/i, /no endpoints found for/i, /unknown model/i, /model(?:[_\-\s])?not(?:[_\-\s])?found/i, /not_found_error/i, /models\/[^\s]+ is not found/i, /unsupported model/i, /is not a valid model id/i ].some((t) => t.test(e)) || /\b404\b/.test(e) && /not(?:[_\-\s])?found/i.test(e) || /model/i.test(e) && /does not exist/i.test(e); } function buildNarrativePrompt(e) { const t = ["Write a dream diary entry from these memory fragments:\n", ...e.snippets.slice(0, 12).map((e) => `- ${e}`)]; for (const [n, r, i] of [[ "\nRecurring themes:", e.themes, 6 ], [ "\nMemories that crystallized into something lasting:", e.promotions, 5 ]]) if (r?.length) t.push(n, ...r.slice(0, i).map((e) => `- ${e}`)); const n = e.currentDate?.trim(); const r = (e.recentDiaryEntries ?? []).map(clampDreamDiaryContextEntry).filter((e) => e.length > 0).slice(0, RECENT_DIARY_CONTEXT_LIMIT); if (n || r.length > 0) { t.push("\nDiary continuity context:"); if (n) t.push(`- Current sweep: ${n}`); if (r.length > 0) { t.push("- Recent diary entries already written:"); for (const e of r) t.push(` - ${e}`); } t.push("- Prefer a fresh angle; do not replay the same first-day framing unless newer fragments change it."); } return t.join("\n"); } async function generateAndAppendDreamNarrative(e) { const t = typeof e.nowMs === "number" && Number.isFinite(e.nowMs) ? e.nowMs : Date.now(); const n = buildNarrativePrompt(e.data); try { const r = e.model ? [e.model, void 0] : [void 0]; let i = ""; for (const t of r) try { i = (await e.subagent.complete({ agentId: e.agentId, message: n, extraSystemPrompt: NARRATIVE_SYSTEM_PROMPT, ...t ? { model: t } : {}, timeoutMs: e.timeoutMs })).text.trim(); break; } catch (n) { if (!t || !isConfiguredModelUnavailableNarrativeError(n)) throw n; e.logger.warn(`memory-core: narrative generation could not use configured model "${t}" for ${e.data.phase} phase; retrying with the agent default (${formatErrorMessage(n)}).`); } if (!i) { e.logger.warn(`memory-core: narrative generation produced no text for ${e.data.phase} phase; writing fallback diary entry.`); await appendFallbackNarrativeEntry({ ...e, nowMs: t, reason: "the narrative run produced no text" }); return { status: "degraded" }; } if (await appendNarrativeEntry({ workspaceDir: e.workspaceDir, narrative: i, nowMs: t, timezone: e.timezone, sourceEntryKeys: e.data.sourceEntryKeys, recentDiaryEntries: e.data.recentDiaryEntries }) === void 0) { e.logger.info(`memory-core: narrative publication skipped for ${e.data.phase} phase because source memory or diary context changed.`); return { status: "skipped" }; } e.logger.info(`memory-core: dream diary entry written for ${e.data.phase} phase [workspace=${e.workspaceDir}].`); } catch (n) { const r = isRequestScopedSubagentRuntimeError(n); if (!r) e.logger.warn(`memory-core: narrative generation failed for ${e.data.phase} phase: ${formatErrorMessage(n)}`); await appendFallbackNarrativeEntry({ ...e, nowMs: t, reason: r ? "subagent runtime is request-scoped" : `the narrative run failed (${formatErrorMessage(n)})` }); return { status: "degraded" }; } return { status: "completed" }; } /** * Cron sweeps return before inference, but their service retains completion and * publication until settlement. Heartbeat callers await the same work. */ async function runDreamNarrative(e) { const { agentId: t, runInBackground: n, ...r } = e; if (r.data.snippets.length === 0 && !r.data.promotions?.length) return { status: "skipped" }; const i = t ? () => generateAndAppendDreamNarrative({ ...r, agentId: t }) : async () => { await appendFallbackNarrativeEntry({ ...r, nowMs: typeof r.nowMs === "number" && Number.isFinite(r.nowMs) ? r.nowMs : Date.now(), reason: "the dreaming sweep has no owning agent id" }); return { status: "completed" }; }; if (n) { n(i).catch((e) => { r.logger.warn(`memory-core: detached dreaming narrative failed for ${r.data.phase} phase: ${formatErrorMessage(e)}`); }); return { status: "pending" }; } return await i(); } //#endregion export { appendFallbackNarrativeEntry, runDreamNarrative };