UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

417 lines (416 loc) • 16.8 kB
import { a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "../../agent-scope-config-DmXgFGKP.mjs"; import { n as createNormalizedPluginsConfig } from "../../config-state-B1JlHgba.mjs"; import { i as rethrowIncognitoSessionError } from "../../incognito-session-error-BxQdjUZa.mjs"; import { a as getMemoryCapabilityRegistration } from "../../memory-state-BAtmlQOR.mjs"; import { o as resolveRememberAcrossConversations } from "../../config-utils-sHBULYOF.mjs"; import "../../session-store-runtime-D5peOAR8.mjs"; import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs"; import { r as resolveLivePluginConfigObject } from "../../plugin-config-runtime-CFUaG6iN.mjs"; import "../../agent-runtime-DA4W1L0G.mjs"; import "../../memory-core-host-runtime-core-vt7Kf2j2.mjs"; import "../../memory-host-core-BIEi4fjg.mjs"; import { K as TRIGGER_LOOKUP_SETTLE_RESERVE_MS, L as MAX_SETUP_GRACE_TIMEOUT_MS, M as HOOK_TIMEOUT_RECOVERY_GRACE_MS, R as MAX_TIMEOUT_MS, l as ACTIVE_MEMORY_STATUS_PREFIX } from "../../types-DgEaE0BK.mjs"; import { a as normalizePluginConfig, n as hasDeprecatedModelFallbackPolicy, o as readActiveMemoryConfig, t as applyCliRuntimeRecallTimeoutDefault } from "../../config-wv3sOLSo.mjs"; import { n as resolveRecallEscalationDecision } from "../../escalation-C2bxODvo.mjs"; import { n as buildSearchQuery, o as getModelRef, r as extractRecentTurns, t as buildQuery } from "../../query-DWtvcnNd.mjs"; import { n as buildRecallOutcomePrefix, t as buildPromptPrefix } from "../../prompt-DPpwxhtv.mjs"; import { i as forgetActiveRecallRun, p as toSingleLineErrorMessage } from "../../recall-state-DrcDAUNj.mjs"; import { i as prepareActiveMemorySession, o as resolveStatusUpdateAgentId, r as persistPluginStatusLines } from "../../session-Ds1NndBH.mjs"; import { a as isAllowedChatId, c as isSessionActiveMemoryDisabled, d as resolveCommandSessionKey, f as setSessionActiveMemoryDisabled, i as isActiveMemoryPluginEnabled, l as lacksAdminToMutateActiveMemoryGlobal, m as updateActiveMemoryGlobalEnabledInConfig, n as formatActiveMemoryCommandHelp, o as isEligibleInteractiveSession, p as shouldSkipActiveMemoryForHarnessSession, r as isActiveMemoryGloballyEnabled, s as isEnabledForAgent, t as ACTIVE_MEMORY_GLOBAL_MUTATION_ADMIN_REQUIRED_TEXT, u as resolveChatType } from "../../session-policy-Dv6OUBLy.mjs"; import { t as createActiveMemoryHookDeadline } from "../../transcript-BVkcRGef.mjs"; import { i as resolveTriggerRecall, r as forgetTriggerRecallRun } from "../../trigger-recall-BQGGA-ad.mjs"; //#region extensions/active-memory/index.ts var active_memory_default = definePluginEntry({ id: "active-memory", name: "Active Memory", description: "Proactively surfaces relevant memory before eligible conversational replies.", register(e) { const readCurrentConfig = () => readActiveMemoryConfig(e); const resolveSelectedRecallToolNames = (e) => { const t = createNormalizedPluginsConfig(e.plugins).slots.memory; const n = getMemoryCapabilityRegistration(); if (!n || n.pluginId !== t) return; return n.capability.recallToolNames; }; const t = readCurrentConfig(); let n = normalizePluginConfig(e.pluginConfig, t, resolveSelectedRecallToolNames(t)); const warnDeprecatedModelFallbackPolicy = (t) => { if (hasDeprecatedModelFallbackPolicy(t)) e.logger.warn?.("active-memory: config.modelFallbackPolicy is deprecated and no longer changes runtime behavior. config.modelFallback is a chain-resolution last-resort (consulted only when config.model, the current run's model, and the agent's configured default all resolve to nothing) — it is NOT a runtime failover that substitutes a different model when the resolved model errors out."); }; warnDeprecatedModelFallbackPolicy(e.pluginConfig); const refreshLiveConfigFromRuntime = () => { const t = resolveLivePluginConfigObject(() => e.runtime.config.current(), "active-memory", e.pluginConfig); const r = readCurrentConfig(); const i = !isActiveMemoryPluginEnabled(r) ? { enabled: false } : t ?? {}; n = normalizePluginConfig(i, r, resolveSelectedRecallToolNames(r)); if (t) warnDeprecatedModelFallbackPolicy(t); }; e.registerCommand({ name: "active-memory", description: "Enable, disable, or inspect Active Memory for this session.", acceptsArgs: true, exposeSenderIsOwner: true, handler: async (t) => { const r = t.args?.trim().split(/\s+/).filter(Boolean) ?? []; const i = r.includes("--global"); const a = (r.find((e) => e !== "--global") ?? "status").toLowerCase(); if (a === "help") return { text: formatActiveMemoryCommandHelp() }; const o = [ "on", "enable", "enabled" ].includes(a) ? true : [ "off", "disable", "disabled" ].includes(a) ? false : void 0; refreshLiveConfigFromRuntime(); if (i) { const n = e.runtime.config.current(); if (a === "status") return { text: `Active Memory: ${isActiveMemoryGloballyEnabled(n) ? "on" : "off"} globally.` }; if (lacksAdminToMutateActiveMemoryGlobal({ senderIsOwner: t.senderIsOwner, gatewayClientScopes: t.gatewayClientScopes })) return { text: ACTIVE_MEMORY_GLOBAL_MUTATION_ADMIN_REQUIRED_TEXT }; if (o !== void 0) { await e.runtime.config.mutateConfigFile({ afterWrite: { mode: "auto" }, writeOptions: { assertCurrent: Array.isArray(t.gatewayClientScopes) ? void 0 : t.assertOwnerCurrent }, mutate: (e) => { const t = updateActiveMemoryGlobalEnabledInConfig(e, o); Object.assign(e, t); } }); refreshLiveConfigFromRuntime(); return { text: `Active Memory: ${o ? "on" : "off"} globally.` }; } } const s = await resolveCommandSessionKey({ api: e, config: n, sessionKey: t.sessionKey, sessionId: t.sessionId }); if (!s) return { text: "Active Memory: session toggle unavailable because this command has no session context." }; const c = resolveStatusUpdateAgentId({ sessionKey: s }); const l = readCurrentConfig(); const u = isEnabledForAgent(n, c); const d = n.enabled && resolveRememberAcrossConversations(l, c); if (!u && !d) return { text: "Active Memory: off for this session." }; if (a === "status") return { text: [ `Active Memory: ${await isSessionActiveMemoryDisabled({ api: e, sessionKey: s }) ? "off" : "on"} for this session.`, `Trigger recall configuration: ${u ? "on" : "off"} for agent ${c}.`, `Remember across conversations setting: ${d ? "on" : "off"}.` ].join("\n") }; if (o !== void 0) { await setSessionActiveMemoryDisabled({ api: e, sessionKey: s, disabled: !o }); if (!o) await persistPluginStatusLines({ api: e, agentId: c, sessionKey: s }); return { text: `Active Memory: ${o ? "on" : "off"} for this session.` }; } return { text: `Unknown Active Memory action: ${a}\n\n${formatActiveMemoryCommandHelp()}` }; } }); const r = MAX_TIMEOUT_MS + MAX_SETUP_GRACE_TIMEOUT_MS + HOOK_TIMEOUT_RECOVERY_GRACE_MS * 2; const logRecallSkipped = (t) => { e.logger.info?.(`active-memory: recall skipped reason=${t}`); }; e.on("before_prompt_build", async (t, r) => { const i = r.toolAuthority; if (!i) { e.logger.debug?.("active-memory: recall skipped because this prompt has no turn tool authority"); return; } i.assertActive(); refreshLiveConfigFromRuntime(); const a = readCurrentConfig(); const o = resolveStatusUpdateAgentId(r); const s = (o ? getModelRef(a, o, n, { modelProviderId: r.modelProviderId, modelId: r.modelId }) : { provider: r.modelProviderId, model: r.modelId }) ?? {}; const c = await e.runtime.agent.resolveCliBackendDispatchEligibilityAsync({ provider: s.provider, model: s.model, config: a, ...o ? { agentId: o, agentDir: resolveAgentDir(a, o), workspaceDir: resolveAgentWorkspaceDir(a, o) } : {} }); const l = applyCliRuntimeRecallTimeoutDefault(n, c !== void 0); const u = l.toolsAllow.filter((e) => i.allows(e)); const d = l.timeoutMs + l.setupGraceTimeoutMs + HOOK_TIMEOUT_RECOVERY_GRACE_MS; const f = new AbortController(); const p = createActiveMemoryHookDeadline(); const armHookDeadline = (t, n) => { p.arm(t, () => { f.abort(/* @__PURE__ */ new Error(`active-memory ${n} timeout after ${t}ms`)); e.logger.warn?.(`active-memory: before_prompt_build ${n} timed out after ${String(t)}ms; skipping memory lookup`); }); }; armHookDeadline(HOOK_TIMEOUT_RECOVERY_GRACE_MS, "preflight"); const m = (async () => { try { const n = resolveStatusUpdateAgentId(r); const o = e.runtime.agent.session.resolveStorePath(a.session?.store, { agentId: n || void 0 }); let s; let c = r.sessionKey?.trim() || void 0; if (!c && n) { s = await prepareActiveMemorySession({ api: e, agentId: n, sessionId: r.sessionId, storePath: o }); c = s.sessionKey; } const m = n || resolveStatusUpdateAgentId({ sessionKey: c }); const publishPrependContext = (e) => { const t = e.filter(Boolean).join("\n"); if (!t) return; f.signal.throwIfAborted(); i.assertActive(); r.hookInvocation?.assertActive(); r.assertMemoryAudienceCurrent?.(); return { prependContext: t }; }; if (u.length === 0) { await persistPluginStatusLines({ api: e, agentId: m, sessionKey: c, statusLine: `${ACTIVE_MEMORY_STATUS_PREFIX} status=policy-disabled` }); logRecallSkipped("policy-disabled"); i.assertActive(); return; } s ??= c ? await prepareActiveMemorySession({ api: e, agentId: m, sessionKey: c, storePath: o }) : { entry: void 0, readFailed: false }; if (shouldSkipActiveMemoryForHarnessSession(s)) { logRecallSkipped("harness-session"); return; } await persistPluginStatusLines({ api: e, agentId: m, sessionKey: c }); i.assertActive(); const h = await isSessionActiveMemoryDisabled({ api: e, sessionKey: c }); f.signal.throwIfAborted(); i.assertActive(); if (h) { logRecallSkipped("session-disabled"); return; } const g = { ...r, sessionKey: c ?? r.sessionKey }; if (!isEligibleInteractiveSession(g)) { logRecallSkipped("session-ineligible"); return; } const _ = { ...g, mainKey: a.session?.mainKey ?? e.config.session?.mainKey }; const v = t.currentUserMessage ?? t.prompt; if (t.currentUserMessage !== void 0 && !v.trim()) { e.logger.debug?.("active-memory: recall skipped reason=no-current-text"); return; } const y = t.currentUserMessage === void 0 ? void 0 : t.currentUserMessageId ? JSON.stringify({ message: v, messageId: t.currentUserMessageId }) : null; const b = extractRecentTurns(t.messages); const x = buildSearchQuery({ latestUserMessage: v, recentTurns: b }); const S = createNormalizedPluginsConfig(a.plugins).slots.memory; const C = getMemoryCapabilityRegistration(); const w = C && C.pluginId === S ? C.capability : void 0; const T = w?.deterministicRecallToolName; const E = resolveChatType(_); const D = E === "direct" || E === "explicit"; const O = isAllowedChatId(l, _); const k = isEnabledForAgent(l, m); let A = { hasStrongHit: false, injectedCount: 0 }; const j = w?.providerRuntime ? w.recallToolNames ?? [] : void 0; const M = j ? c && j.length > 0 && j.every((e) => i.allows(e)) ? { kind: "native", context: { authority: { kind: "session", sessionKey: c, sessionId: r.sessionId, sandboxed: r.sandboxed === true, audience: r.memoryAudience }, signal: f.signal, assertCurrent() { f.signal.throwIfAborted(); i.assertActive(); r.hookInvocation?.assertActive(); r.assertMemoryAudienceCurrent?.(); } } } : void 0 : T && u.includes(T) ? { kind: "legacy" } : void 0; if (k && m && M && D && O) { i.assertActive(); const t = p.remainingMs() - 50; if (t > 0) { A = await resolveTriggerRecall({ cfg: a, agentId: m, source: M, query: x, message: v, activeProjectKeys: r.activeProjectKeys, signal: AbortSignal.timeout(t), runId: r.runId, requestKey: y, authorityFingerprint: i.fingerprint, debug: (t) => e.logger.debug?.(t) }).catch((t) => { rethrowIncognitoSessionError(t); e.logger.debug?.(`active-memory: lane-1 trigger recall failed: ${toSingleLineErrorMessage(t)}`); return { hasStrongHit: false, injectedCount: 0 }; }); i.assertActive(); if (A.context && A.injectedCount > 0 && l.logging) e.logger.info?.(`active-memory: lane-1 injected ${A.injectedCount} trigger-matched entries`); } else e.logger.debug?.("active-memory: lane-1 trigger recall skipped: preflight budget exhausted"); } else if (l.enabled && m && !k) { const t = `active-memory: lane-1 skipped reason=agent-not-configured agent=${m}`; e.logger.debug?.(t); if (l.logging) e.logger.info?.(t); } const N = A.context; const P = k && E !== void 0 && l.allowedChatTypes.includes(E) && O; const F = Boolean(l.enabled && c && resolveRememberAcrossConversations(a, m) && D && O); const I = F && w?.supportsPrivateTranscriptRecall === true; if (F && !I) e.logger.warn?.("active-memory: the current memory provider does not support protected private transcript recall; skipping Remember across conversations"); const L = I && T && u.includes(T) ? T : void 0; const R = Boolean(L); if (I && !R) e.logger.warn?.(`active-memory: ${T ?? "the provider's direct recall tool"} is unavailable; skipping Remember across conversations private transcript recall`); if (!P && !R) { logRecallSkipped("destination-not-allowed"); return publishPrependContext([N]); } const z = resolveRecallEscalationDecision({ mode: l.mode, message: v, hasStrongLaneOneHit: A.hasStrongHit }); if (z !== "recall") { e.logger.debug?.(`active-memory: recall skipped reason=${z}`); return publishPrependContext([N, z === "no-recall-intent" ? buildRecallOutcomePrefix("skipped-no-recall-intent") : void 0]); } const B = R && c ? { anchorSessionKey: c, scope: "same-agent-private", corpus: P ? "configured" : "sessions" } : void 0; const V = L && !P ? { ...l, toolsAllow: [L] } : { ...l, toolsAllow: u }; const H = buildQuery({ latestUserMessage: v, recentTurns: b, config: V }); armHookDeadline(d, "recall"); const { maybeResolveActiveRecall: U } = await import("./recall.js"); f.signal.throwIfAborted(); i.assertActive(); const W = await U({ api: e, runtimeConfig: a, config: V, agentId: m, sessionKey: c, sessionId: r.sessionId, sessionEntry: s.entry, storePath: o, messageProvider: r.messageProvider, channelId: r.channelId, query: H, requestKey: y, searchQuery: x, currentModelProviderId: r.modelProviderId, currentModelId: r.modelId, conversationRecall: B, abortSignal: f.signal, runId: r.runId, authorityFingerprint: i.fingerprint, memorySlot: S ?? void 0, activeProjectKeys: r.activeProjectKeys, memoryAudience: r.memoryAudience, assertMemoryAudienceCurrent: r.assertMemoryAudienceCurrent }); return publishPrependContext([N, W.summary ? buildPromptPrefix(W.summary) : W.status === "unavailable" ? buildRecallOutcomePrefix(W.status) : void 0]); } catch (t) { rethrowIncognitoSessionError(t); if (f.signal.aborted) return; const n = toSingleLineErrorMessage(t); e.logger.warn?.(`active-memory: before_prompt_build failed, skipping memory lookup: ${n}`); return; } })(); try { const e = await Promise.race([m, p.promise]); return typeof e === "symbol" ? void 0 : e; } finally { p.stop(); } }, { timeoutMs: r, requiresToolAuthority: true }); e.on("agent_end", (e, t) => { const n = e.runId ?? t.runId; forgetActiveRecallRun(n); forgetTriggerRecallRun(n); }); } }); //#endregion export { active_memory_default as default };