UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

200 lines (199 loc) • 7.55 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { _ as resolveDefaultAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { f as prepareSystemAgentRunAdmission } from "./admitted-run-context-D3Jvk_f_.mjs"; import { o as resolveSessionStorePathForScope } from "./session-store-path-BIJyO4vM.mjs"; import { n as resolveInternalSessionEffectsIdentity } from "./internal-session-key-DySyL5iT.mjs"; import { a as withSessionContextAdmission } from "./session-transcript-read-fence-Bl-ZY3_t.mjs"; import { i as MAX_VISIBLE_MESSAGE_MAX_MESSAGES, r as MAX_VISIBLE_MESSAGE_MAX_BYTES } from "./session-accessor.sqlite-visible-cursor-BKIsjRgi.mjs"; import { l as waitForSessionTranscriptProjection } from "./session-transcript-reconcile-CtdkqWN1.mjs"; import { s as getMemoryProviderRuntime } from "./memory-state-BAtmlQOR.mjs"; import { c as resolveMemoryAudienceFromEntry, i as delegateMemoryAudience } from "./memory-audience-RRQiHS6M.mjs"; import { t as SessionManager } from "./session-manager-DuaaMI5O.mjs"; import { i as resolveModelFallbackOptions } from "./agent-runner-run-params-CiEn1JED.mjs"; import { t as createSessionMaintenanceFollowup } from "./run-pgKf8cOO.mjs"; import "./agent-runner-utils-D8POqd9a.mjs"; import { t as isToolsMemoryFlushPlan } from "./memory-flush-plan-DHRW29i4.mjs"; import fs from "node:fs"; import path from "node:path"; import crypto from "node:crypto"; //#region src/auto-reply/reply/memory-flush-session.ts /** * Derive one UUID-shaped mutation identity from the source session incarnation * (session ID and lifecycle revision) and its pre-compaction count. The count * advances after each completed compaction, so retries within one cycle reuse * the ID and later cycles do not. A reset keeps the session ID and restarts the * count but rotates the lifecycle revision, so a new incarnation never reuses an ID. */ function deriveMemoryFlushId(e) { const t = crypto.createHash("sha256").update(`openclaw-memory-flush\0${e.sourceSessionId}\0${e.sourceLifecycleRevision ?? ""}\0${e.compactionCount}`).digest().subarray(0, 16); t[6] = (t[6] ?? 0) & 15 | 128; t[8] = (t[8] ?? 0) & 63 | 128; const n = t.toString("hex"); return `${n.slice(0, 8)}-${n.slice(8, 12)}-${n.slice(12, 16)}-${n.slice(16, 20)}-${n.slice(20)}`; } /** Memory inference owns a detached view; an admission excludes its waiting user. */ async function prepareMemoryFlushSession(e) { e.signal?.throwIfAborted(); await waitForSessionTranscriptProjection(e.source, e.signal); e.signal?.throwIfAborted(); const t = await withSessionContextAdmission(e.source, e.admission, () => SessionManager.openDetachedBoundedAsync(e.source, { signal: e.signal, cwd: e.workspaceDir, maxBytes: MAX_VISIBLE_MESSAGE_MAX_BYTES, maxEvents: MAX_VISIBLE_MESSAGE_MAX_MESSAGES, onTruncated: () => { throw new Error("Memory flush exceeds the bounded conversation view."); } })); const n = resolveInternalSessionEffectsIdentity({ agentId: e.source.agentId, runId: e.runId }); return { ...n, sessionFile: n.sessionKey, sessionTarget: { agentId: e.source.agentId, storePath: e.source.storePath, ...n }, sessionManager: t, sessionPersistence: "detached", cleanupBundleMcpOnRunEnd: true }; } async function ensureMemoryFlushTargetFile(e) { const t = normalizeOptionalString(e.workspaceDir); const n = normalizeOptionalString(e.relativePath); if (!t || !n || path.isAbsolute(n)) throw new Error("Invalid memory flush target path"); const r = path.resolve(t); const i = path.resolve(r, n); const a = path.relative(r, i); if (!a || a.startsWith("..") || path.isAbsolute(a)) throw new Error("Memory flush target path must stay inside the workspace"); e.assertCurrent(); await fs.promises.mkdir(path.dirname(i), { recursive: true }); e.assertCurrent(); const o = await fs.promises.open(i, "a"); try { e.assertCurrent(); } finally { await o.close(); } } //#endregion //#region src/auto-reply/reply/memory-flush-prepare.ts const log = createSubsystemLogger("auto-reply/memory-flush"); async function prepareMemoryFlushAttempt(e) { e.assertCurrent(); const { resolution: t } = e; const { plan: n } = t; const { sessionKey: r, sessionEntry: i, followupRun: a } = e; if (!r || !i) throw new Error("Memory flush has no current transcript target."); const o = a.run.agentId ?? resolveDefaultAgentId(e.cfg); const s = resolveSessionStorePathForScope({ agentId: o, sessionKey: r, storePath: e.storePath }, e.cfg); const c = isToolsMemoryFlushPlan(n) && getMemoryProviderRuntime() ? await resolveMemoryAudienceFromEntry({ agentId: o, sessionKey: r, sessionId: i.sessionId, senderIsOwner: a.memoryAudienceSenderIsOwner ?? a.run.senderIsOwner, storePath: s, resolveAgentStorePath: (t) => resolveSessionStorePathForScope({ agentId: t }, e.cfg), assertCallerCurrent: e.assertCurrent }, i) : void 0; if (c?.status === "denied") { log.debug("memory flush skipped: source turn has no memory audience", { event: "memory_flush_no_audience", sourceSessionKey: r, sourceSessionId: i.sessionId, pluginId: t.pluginId, kind: c.kind, reason: c.reason }); return null; } let l; const release = () => { l?.release(); c?.release(); }; try { e.assertCurrent(); const u = await prepareMemoryFlushSession({ admission: e.preflightAdmission, source: { agentId: o, sessionId: i.sessionId, sessionKey: r, storePath: s }, runId: e.flushRunId, workspaceDir: a.run.workspaceDir, signal: e.abortSignal }); if (!isToolsMemoryFlushPlan(n)) await ensureMemoryFlushTargetFile({ workspaceDir: a.run.workspaceDir, relativePath: n.relativePath, assertCurrent: e.assertCurrent }); const d = [a.run.extraSystemPrompt, n.systemPrompt].filter(Boolean).join("\n\n"); const f = resolveModelFallbackOptions(a.run, e.cfg); const p = e.runtimePolicySessionKey ?? a.run.runtimePolicySessionKey ?? r; const m = createSessionMaintenanceFollowup({ run: a.run, sessionEntry: { sessionId: u.sessionId, updatedAt: Date.now() }, cfg: e.cfg, sessionKey: u.sessionKey, runtimePolicySessionKey: p, provider: f.provider, model: f.model, auth: a.run }).run; e.assertCurrent(); l = c ? await delegateMemoryAudience(c.audience, { sessionKey: u.sessionKey, storePath: u.sessionTarget.storePath, detached: true, assertCallerCurrent: e.assertCurrent }) : void 0; const h = isToolsMemoryFlushPlan(n) ? { flushId: deriveMemoryFlushId({ sourceSessionId: i.sessionId, sourceLifecycleRevision: i.lifecycleRevision, compactionCount: i.compactionCount ?? 0 }), ownerPluginId: t.pluginId, persistenceToolNames: n.persistenceToolNames, lookupToolNames: n.lookupToolNames, recordPersistenceToolSuccess: e.recordPersistenceToolSuccess } : void 0; const g = prepareSystemAgentRunAdmission(e.cfg, e.flushRunId, a.run.agentId, "auto-reply.memory-flush", void 0, a.operatorAuthority); return { writePath: isToolsMemoryFlushPlan(n) ? void 0 : n.relativePath, systemPrompt: d, selection: f, preparedRunAdmission: g, memorySession: { ...u, ...e.recoveryContextTokenBudget !== void 0 ? { disableCompactionRecovery: true } : {} }, memoryAudience: l?.audience, memoryFlushTools: h, maintenanceRun: m, sourcePolicySessionKey: p, release }; } catch (e) { release(); throw e; } } //#endregion export { prepareMemoryFlushAttempt };