UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

534 lines (533 loc) • 18.1 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { S as parseDateStringTimestampMs } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import "./session-key-CqAyZeVk.mjs"; import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs"; import { O as tryResolveAmbientOwnerAgentId, _ as resolveDefaultAgentId, f as resolveAgentWorkspaceDir, t as AgentSelectionRequiredError } from "./agent-scope-config-DmXgFGKP.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { E as resolveMemoryRemDreamingConfig, b as resolveMemoryDreamingConfig, g as MEMORY_DREAMING_SYSTEM_EVENT_TEXT, h as MANAGED_MEMORY_DREAMING_CRON_TAG, m as MANAGED_MEMORY_DREAMING_CRON_NAME, w as resolveMemoryDreamingWorkspaces, x as resolveMemoryDreamingPluginConfig } from "./dreaming-C72ZWZJr.mjs"; import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs"; import { t as sortAndLimitBy } from "./sort-and-limit-Cu1yDP2e.mjs"; import { i as getAgentWorkspaceAccess, t as WorkspaceAccessUnavailableError } from "./workspace-access-CnjZBg1i.mjs"; import { i as readMemorySearchManagerStatus } from "./types-Bo5s7TN4.mjs"; import { a as getActiveMemoryProviderCore, l as resolveActiveMemoryBackendConfig, o as getActiveMemorySearchManagerCore } from "./memory-runtime-C3z9zu-7.mjs"; import { c as removeBackfillDiaryEntries, f as writeBackfillDiaryEntries, i as dedupeDreamDiaryEntries, l as removeGroundedShortTermCandidates, o as loadShortTermPromotionDreamingStats, s as previewGroundedRemMarkdown, u as repairDreamingArtifacts } from "./memory-core-bundled-runtime-C30jyiwB.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/gateway/server-methods/doctor-memory-files.ts const DREAM_DIARY_FILE_NAMES = ["DREAMS.md", "dreams.md"]; function getWorkspaceMemoryMaintenance(e) { const t = getAgentWorkspaceAccess(e, "memoryFiles"); if (!t?.memoryFiles) return; const n = t.memoryFiles.maintenance; if (!n) throw new WorkspaceAccessUnavailableError("Remote Memory maintenance is unavailable"); return n; } async function listWorkspaceDailyFiles(e) { const t = path.join(e, "memory"); const n = getWorkspaceMemoryMaintenance(e); let r; try { r = n ? (await n.listDirectory(t)).map((e) => e.name) : await fs.readdir(t); } catch (e) { if (extractErrorCode(e) === "ENOENT") return []; throw e; } return r.filter((e) => /^\d{4}-\d{2}-\d{2}(?:-[^/]+)?\.md$/i.test(e)).map((e) => path.join(t, e)).toSorted((e, t) => e.localeCompare(t)); } async function readDreamDiary(e) { const t = getWorkspaceMemoryMaintenance(e); for (const n of DREAM_DIARY_FILE_NAMES) { const r = path.join(e, n); let i; try { if (t) i = await t.stat(r, false); else { const e = await fs.lstat(r); i = { isSymbolicLink: e.isSymbolicLink(), isFile: e.isFile(), mtimeMs: e.mtimeMs }; } } catch (e) { if (extractErrorCode(e) === "ENOENT") continue; return { found: false, path: n }; } if (i.isSymbolicLink || !i.isFile) continue; try { return { found: true, path: n, content: t ? (await t.readFile(r)).toString("utf-8") : await fs.readFile(r, "utf-8"), updatedAtMs: Math.floor(i.mtimeMs) }; } catch { return { found: false, path: n }; } } return { found: false, path: DREAM_DIARY_FILE_NAMES[0] }; } //#endregion //#region src/gateway/server-methods/doctor-memory-provider-status.ts const SKIPPED_MEMORY_EMBEDDING_PROBE = { ok: false, checked: false, error: "memory embedding readiness not checked; run `openclaw memory status --deep` to check" }; /** Reads provider-native memory health under the current operator request authority. */ async function respondProviderMemoryStatus(e) { const respondHealth = (t, n = e.providerId) => e.respond(true, { agentId: e.agentId, provider: n, health: t, embedding: SKIPPED_MEMORY_EMBEDDING_PROBE }, void 0); let t = true; const assertRequestCurrent = () => { e.signal?.throwIfAborted(); e.client?.connectionSignal?.throwIfAborted(); if (!t || e.client?.invalidated || e.hasCurrentClientAuthority?.() === false) throw new Error("Memory status authority is no longer active"); }; let n = void 0; let r = null; try { n = await captureGatewayOperatorRunAuthority({ client: e.client, context: e.context, hasCurrentClientAuthority: e.hasCurrentClientAuthority, invocationAuthority: { assertCurrent: assertRequestCurrent, signal: e.signal } }); if (!n) throw new Error("Memory provider status requires authenticated operator authority"); const t = n.authority; const assertCurrent = () => { assertRequestCurrent(); t.assertCurrent(); }; assertCurrent(); const i = await getActiveMemoryProviderCore({ cfg: e.cfg, agentId: e.agentId, purpose: "status", context: { authority: { kind: "operator", scopes: t.scopes, connId: e.client?.connId }, assertCurrent, signal: e.signal } }); r = i.provider; if (!r) throw new Error(i.error ?? `memory plugin "${e.providerId}" unavailable`); const a = await r.health(); assertCurrent(); respondHealth(a, i.providerId ?? e.providerId); } catch (e) { respondHealth({ status: "unavailable", message: formatErrorMessage(e) }); } finally { t = false; try { await r?.close(); } finally { n?.release(); } } } //#endregion //#region src/gateway/server-methods/doctor-memory-target.ts /** Resolves and validates the agent targeted by a Doctor memory request. */ function resolveDoctorMemoryAgent(e, t, n) { const r = e.getRuntimeConfig(); const i = asOptionalRecord(t)?.agentId; if (i !== void 0 && typeof i !== "string") { n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "agentId must be a string")); return null; } const a = typeof i === "string" ? normalizeAgentId(i) : void 0; let o = a ?? tryResolveAmbientOwnerAgentId(r); if (!o) try { o = resolveDefaultAgentId(r, { surface: "doctor memory", hint: "Pass agentId to select a configured agent." }); } catch (e) { if (!(e instanceof AgentSelectionRequiredError)) throw e; n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, e.message)); return null; } if (a && !listAgentIds(r).includes(o)) { n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, `unknown agent id "${a}"`)); return null; } return { cfg: r, agentId: o, ...a ? { requestedAgentId: a } : {} }; } function resolveDoctorMemoryTarget(e, t, n) { const r = resolveDoctorMemoryAgent(e, t, n); if (!r) return null; return { cfg: r.cfg, agentId: r.agentId, workspaceDir: resolveAgentWorkspaceDir(r.cfg, r.agentId) }; } /** Builds a Doctor memory action handler with shared target validation. */ function memoryActionHandler(e, t) { return async ({ respond: n, context: r, params: i }) => { const a = resolveDoctorMemoryTarget(r, i, n); if (!a) return; n(true, { agentId: a.agentId, action: e, ...await t(a) }, void 0); }; } //#endregion //#region src/gateway/server-methods/doctor.ts function extractIsoDayFromPath(e) { return e.replaceAll("\\", "/").match(/(\d{4}-\d{2}-\d{2})(?:-[^/]+)?\.md$/i)?.[1] ?? null; } function groundedMarkdownToDiaryLines(e) { return e.split("\n").map((e) => e.replace(/^##\s+/, "").trimEnd()).filter((e, t, n) => e.length > 0 || t > 0 && expectDefined(n[t - 1], "lines entry at index 1")?.length > 0); } function resolveDreamingConfig(e) { const t = resolveMemoryDreamingConfig({ pluginConfig: resolveMemoryDreamingPluginConfig(e), cfg: e }); const { light: n, deep: r, rem: i } = t.phases; const a = { managedCronPresent: false }; return { enabled: t.enabled, ...t.timezone ? { timezone: t.timezone } : {}, verboseLogging: t.verboseLogging, storageMode: t.storage.mode, separateReports: t.storage.separateReports, phases: { light: { enabled: t.enabled && n.enabled, cron: n.cron, lookbackDays: n.lookbackDays, limit: n.limit, ...a }, deep: { enabled: t.enabled && r.enabled, cron: r.cron, limit: r.limit, minScore: r.minScore, minRecallCount: r.minRecallCount, minUniqueQueries: r.minUniqueQueries, recencyHalfLifeDays: r.recencyHalfLifeDays, ...a, ...typeof r.maxAgeDays === "number" ? { maxAgeDays: r.maxAgeDays } : {} }, rem: { enabled: t.enabled && i.enabled, cron: i.cron, lookbackDays: i.lookbackDays, limit: i.limit, minPatternStrength: i.minPatternStrength, ...a } } }; } const DREAMING_ENTRY_LIST_LIMIT = 8; function compareDreamingTimestamp(e, t) { const n = parseDateStringTimestampMs(e) ?? Number.NEGATIVE_INFINITY; const r = parseDateStringTimestampMs(t) ?? Number.NEGATIVE_INFINITY; return n === r ? 0 : r > n ? 1 : -1; } function compareDreamingEntryByRecency(e, t) { return compareDreamingTimestamp(e.lastRecalledAt, t.lastRecalledAt) || t.totalSignalCount - e.totalSignalCount || e.path.localeCompare(t.path); } function compareDreamingEntryBySignals(e, t) { return t.totalSignalCount - e.totalSignalCount || t.phaseHitCount - e.phaseHitCount || compareDreamingEntryByRecency(e, t); } function compareDreamingEntryByPromotion(e, t) { return compareDreamingTimestamp(e.promotedAt, t.promotedAt) || compareDreamingEntryBySignals(e, t); } async function loadDreamingStoreStats(e, t, n) { try { return await loadShortTermPromotionDreamingStats({ workspaceDir: e, nowMs: t, timezone: n }); } catch (e) { return { ...mergeDreamingStoreStats([]), storeError: formatErrorMessage(e) }; } } function mergeDreamingStoreStats(e) { const t = { shortTermCount: 0, recallSignalCount: 0, dailySignalCount: 0, groundedSignalCount: 0, totalSignalCount: 0, phaseSignalCount: 0, lightPhaseHitCount: 0, remPhaseHitCount: 0, promotedTotal: 0, promotedToday: 0 }; let n = Number.NEGATIVE_INFINITY; let r; const i = new Set(e.flatMap((e) => e.storePath ? [e.storePath] : [])); const a = new Set(e.flatMap((e) => e.phaseSignalPath ? [e.phaseSignalPath] : [])); const o = e.flatMap((e) => e.storeError ? [e.storeError] : []); const s = e.flatMap((e) => e.phaseSignalError ? [e.phaseSignalError] : []); for (const i of e) { t.shortTermCount += i.shortTermCount; t.recallSignalCount += i.recallSignalCount; t.dailySignalCount += i.dailySignalCount; t.groundedSignalCount += i.groundedSignalCount; t.totalSignalCount += i.totalSignalCount; t.phaseSignalCount += i.phaseSignalCount; t.lightPhaseHitCount += i.lightPhaseHitCount; t.remPhaseHitCount += i.remPhaseHitCount; t.promotedTotal += i.promotedTotal; t.promotedToday += i.promotedToday; const e = i.lastPromotedAt ? Date.parse(i.lastPromotedAt) : NaN; if (Number.isFinite(e) && e > n) { n = e; r = i.lastPromotedAt; } } return { ...t, shortTermEntries: sortAndLimitBy(e.flatMap((e) => e.shortTermEntries), DREAMING_ENTRY_LIST_LIMIT, compareDreamingEntryByRecency), signalEntries: sortAndLimitBy(e.flatMap((e) => e.signalEntries), DREAMING_ENTRY_LIST_LIMIT, compareDreamingEntryBySignals), promotedEntries: sortAndLimitBy(e.flatMap((e) => e.promotedEntries), DREAMING_ENTRY_LIST_LIMIT, compareDreamingEntryByPromotion), ...i.size === 1 ? { storePath: [...i][0] } : {}, ...a.size === 1 ? { phaseSignalPath: [...a][0] } : {}, ...r ? { lastPromotedAt: r } : {}, ...o.length === 1 ? { storeError: o[0] } : o.length > 1 ? { storeError: `${o.length} dreaming stores had read errors.` } : {}, ...s.length === 1 ? { phaseSignalError: s[0] } : s.length > 1 ? { phaseSignalError: `${s.length} phase signal stores had read errors.` } : {} }; } function isManagedDreamingJob(e) { if (normalizeOptionalString(e.description)?.includes("[managed-by=memory-core.short-term-promotion]")) return true; return normalizeOptionalString(e.name) === "Memory Dreaming Promotion" && e.payload.kind === "systemEvent" && normalizeOptionalString(e.payload.text) === "__openclaw_memory_core_short_term_promotion_dream__"; } async function resolveManagedDreamingCronStatus(e) { try { const t = (await e.cron.list({ includeDisabled: true })).filter(isManagedDreamingJob); let n; for (const e of t) { if (!e.enabled) continue; const t = e.state?.nextRunAtMs; if (typeof t !== "number" || !Number.isFinite(t)) continue; if (n === void 0 || t < n) n = t; } return { managedCronPresent: t.length > 0, ...n !== void 0 ? { nextRunAtMs: n } : {} }; } catch { return { managedCronPresent: false }; } } const createDoctorHandlers = () => ({ "doctor.memory.status": async ({ respond: e, context: t, params: n, client: r, signal: i, hasCurrentClientAuthority: a }) => { const o = resolveDoctorMemoryAgent(t, n, e); if (!o) return; const { cfg: s, agentId: c, requestedAgentId: l } = o; const u = resolveActiveMemoryBackendConfig({ cfg: s, agentId: c }); if (u?.backend === "provider-runtime") { await respondProviderMemoryStatus({ cfg: s, agentId: c, providerId: u.providerId, respond: e, context: t, client: r, signal: i, hasCurrentClientAuthority: a }); return; } const { manager: d, error: f, searchRuntimeRegistered: p } = await getActiveMemorySearchManagerCore({ cfg: s, agentId: c, purpose: "status" }); if (!d) { e(true, { agentId: c, searchRuntimeRegistered: p, embedding: { ok: false, error: f ?? "memory search unavailable" } }, void 0); return; } try { let r = await readMemorySearchManagerStatus(d); const i = n.probe === true || n.deep === true; let a = i ? await d.probeEmbeddingAvailability() : d.getCachedEmbeddingAvailability?.() ?? SKIPPED_MEMORY_EMBEDDING_PROBE; if (i) r = await readMemorySearchManagerStatus(d); if (!a.ok && !a.error) a = { ok: false, error: "memory embeddings unavailable" }; const o = Date.now(); const u = resolveDreamingConfig(s); const f = normalizeOptionalString(r.workspaceDir); const p = l ? f ? [f] : [] : resolveMemoryDreamingWorkspaces(s, { primaryWorkspaceDir: f, primaryAgentId: c }).map((e) => e.workspaceDir); const m = mergeDreamingStoreStats(p.length === 0 ? [] : await Promise.all(p.map((e) => loadDreamingStoreStats(e, o, u.timezone)))); const h = await resolveManagedDreamingCronStatus(t); for (const e of Object.values(u.phases)) Object.assign(e, h); e(true, { agentId: c, provider: r.provider, embedding: a, embeddingRuntime: (() => { const e = asOptionalRecord(asOptionalRecord(r.custom)?.llamaCppRuntime); return e?.engine === "llama.cpp" ? e : void 0; })(), dreaming: { ...u, ...m } }, void 0); } catch (t) { e(true, { agentId: c, embedding: { ok: false, error: `gateway memory check failed: ${formatErrorMessage(t)}` } }, void 0); } finally { await d.close?.().catch(() => {}); } }, "doctor.memory.dreamDiary": async ({ respond: e, context: t, params: n }) => { const r = resolveDoctorMemoryTarget(t, n, e); if (!r) return; const { agentId: i, workspaceDir: a } = r; e(true, { agentId: i, ...await readDreamDiary(a) }, void 0); }, "doctor.memory.backfillDreamDiary": memoryActionHandler("backfill", async ({ cfg: e, workspaceDir: t }) => { const n = await listWorkspaceDailyFiles(t); if (n.length === 0) { const e = await readDreamDiary(t); return { path: e.path, found: e.found, scannedFiles: 0, written: 0, replaced: 0 }; } const r = await previewGroundedRemMarkdown({ workspaceDir: t, inputPaths: n }); const i = resolveMemoryRemDreamingConfig({ pluginConfig: resolveMemoryDreamingPluginConfig(e), cfg: e }); const a = r.files.map((e) => { const t = extractIsoDayFromPath(e.path); if (!t) return null; return { isoDay: t, sourcePath: e.path, bodyLines: groundedMarkdownToDiaryLines(e.renderedMarkdown) }; }).filter((e) => e !== null); const o = await writeBackfillDiaryEntries({ workspaceDir: t, entries: a, timezone: i.timezone }); const s = await readDreamDiary(t); return { path: s.path, found: s.found, scannedFiles: r.scannedFiles, written: o.written, replaced: o.replaced }; }), "doctor.memory.resetDreamDiary": memoryActionHandler("reset", async ({ workspaceDir: e }) => { const t = await removeBackfillDiaryEntries({ workspaceDir: e }); const n = await readDreamDiary(e); return { path: n.path, found: n.found, removedEntries: t.removed }; }), "doctor.memory.resetGroundedShortTerm": memoryActionHandler("resetGroundedShortTerm", async ({ workspaceDir: e }) => { return { removedShortTermEntries: (await removeGroundedShortTermCandidates({ workspaceDir: e })).removed }; }), "doctor.memory.repairDreamingArtifacts": memoryActionHandler("repairDreamingArtifacts", async ({ workspaceDir: e }) => { const t = await repairDreamingArtifacts({ workspaceDir: e }); return { changed: t.changed, archiveDir: t.archiveDir, archivedDreamsDiary: t.archivedDreamsDiary, archivedSessionCorpus: t.archivedSessionCorpus, archivedSessionIngestion: t.archivedSessionIngestion, warnings: t.warnings }; }), "doctor.memory.dedupeDreamDiary": memoryActionHandler("dedupeDreamDiary", async ({ workspaceDir: e }) => { const t = await dedupeDreamDiaryEntries({ workspaceDir: e }); const n = await readDreamDiary(e); return { path: n.path, found: n.found, removedEntries: t.removed, dedupedEntries: t.removed, keptEntries: t.kept }; }) }); //#endregion export { createDoctorHandlers };