UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 6.72 kB
import{a as extractErrorCode,d as readErrorName}from"./error-coercion-DlKnt6w-.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{n as SUBAGENT_RUNTIME_REQUEST_SCOPE_ERROR_CODE,t as RequestScopedSubagentRuntimeError}from"./error-runtime-DW-sj0iq.mjs";import{i as clampDreamDiaryContextEntry,n as FALLBACK_NARRATIVE,r as appendNarrativeEntry}from"./dreaming-dreams-file-ILfImmSq.mjs"; //!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(` `);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`}async function appendFallbackNarrativeEntry(e){try{await appendNarrativeEntry({workspaceDir:e.workspaceDir,workspaceFileMode:e.workspaceFileMode,narrative: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: `,...e.snippets.slice(0,12).map(e=>`- ${e}`)];for(const[n,r,i]of[[` Recurring themes:`,e.themes,6],[` Memories 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(` Diary 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(` `)}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,workspaceFileMode:e.workspaceFileMode,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`}}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()}export{appendFallbackNarrativeEntry,runDreamNarrative};