UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

827 lines (826 loc) • 31.3 kB
import { t as asNonArrayRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { b as uniqueStrings } from "../../string-normalization-DLmfYZXI.mjs"; import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs"; import { o as racePromiseWithAbortSignal } from "../../src-BPmQBLJp.mjs"; import { t as formatErrorMessage } from "../../errors-BKzCeTYb.mjs"; import { _ as resolveDefaultAgentId } from "../../agent-scope-config-DmXgFGKP.mjs"; import "../../api-BztiQCYj.mjs"; import { t as ErrorCodes } from "../../gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "../../error-codes-BzF7aRQ0.mjs"; import { r as textResult } from "../../tool-results-CcV0sxnb.mjs"; import { u as readPositiveIntegerParam } from "../../common-njQNtpnW.mjs"; import { i as optionalFiniteNumberSchema } from "../../typebox-BwU4K8-3.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import { s as mapPluginConfigIssues } from "../../extension-shared-CJ4teJ7p.mjs"; import "../../text-utility-runtime-Ds8jsG0J.mjs"; import "../../time-runtime-DoAwjF0T.mjs"; import "../../error-runtime-BM740gJj.mjs"; import { a as WIKI_SEARCH_MODES, h as compareWikiClaimSummaries } from "../../query-pages-ByoZVAti.mjs"; import { n as buildPluginConfigSchema } from "../../config-schema-BjPebUmU.mjs"; import { t as definePluginEntry } from "../../plugin-entry-CiJdaHtx.mjs"; import "../../gateway-runtime-Du0olVch.mjs"; import "../../channel-actions-DxuDuzvg.mjs"; import "../../memory-host-core-BIEi4fjg.mjs"; import "../../param-readers-CVZN1591.mjs"; import { A as closeMemoryWikiQueryReader, C as searchMemoryWiki, F as deactivateMemoryWikiCompiledCacheOwnersExcept, I as loadMemoryWikiCompiledCache, L as loadMemoryWikiCompiledDashboards, M as activateMemoryWikiCompiledCacheOwner, N as configureMemoryWikiCompiledCacheStore, O as ensureMemoryWikiVaultGeneration, P as createMemoryWikiCompiledCacheStore, R as resolveMemoryWikiCompiledCacheOwnerId, S as getMemoryWikiPage, _ as compileMemoryWikiVault, a as renderMemoryWikiStatus, c as waitForMemoryWikiImportedSourceSyncs, d as probeObsidianCli, f as runObsidianAction, g as normalizeMemoryWikiMutationInput, h as applyMemoryWikiMutation, j as MemoryWikiDashboardUnavailableError, k as loadMemoryWikiValidatedVaultIdentity, l as OBSIDIAN_ACTIONS, m as ingestMemoryWikiSource, n as renderWikiSearchResults, o as resolveMemoryWikiStatus, p as lintMemoryWikiVault, r as buildMemoryWikiDoctorReport, s as syncMemoryWikiImportedSources, t as renderWikiMutationSummary, u as assertOfficialObsidianCliSupported, w as initializeMemoryWikiVault, z as setMemoryWikiDashboardState } from "../../presentation-DlSI_19M.mjs"; import { a as resolveMemoryWikiConfig, i as resolveMemoryWikiAgentConfig, n as WIKI_SEARCH_BACKENDS, o as resolveMemoryWikiConfiguredAgentIds, r as WIKI_SEARCH_CORPORA, t as MemoryWikiConfigSource } from "../../config-BbCc3-tw.mjs"; import { c as createMemoryWikiSourceSyncStateStore, i as getMemoryWikiImportRunStateStore, n as configureMemoryWikiImportRunStateStore, r as createMemoryWikiImportRunStateStore, s as configureMemoryWikiSourceSyncStateStore } from "../../import-runs-state-CdrnhnHo.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { Type } from "typebox"; //#region extensions/memory-wiki/src/config-schema.ts const memoryWikiConfigSchema = buildPluginConfigSchema(MemoryWikiConfigSource, { safeParse(e) { if (e === void 0) return { success: true, data: resolveMemoryWikiConfig(void 0) }; const t = MemoryWikiConfigSource.safeParse(e); if (t.success) return { success: true, data: resolveMemoryWikiConfig(t.data) }; return { success: false, error: { issues: mapPluginConfigIssues(t.error.issues) } }; } }); //#endregion //#region extensions/memory-wiki/src/corpus-supplement.ts function createWikiCorpusSupplement(e) { return { search: async (t) => { const n = e.getAppConfig(); const r = e.resolveConfig(t.agentId, n); return (await searchMemoryWiki({ config: r, appConfig: n, agentId: r.agentId ?? t.agentId, agentSessionKey: t.agentSessionKey, sandboxed: t.sandboxed, query: t.query, maxResults: t.maxResults, searchBackend: "local", searchCorpus: "wiki" })).filter((e) => e.corpus === "wiki"); }, get: async (t) => { const n = e.getAppConfig(); const r = e.resolveConfig(t.agentId, n); const i = await getMemoryWikiPage({ config: r, appConfig: n, agentId: r.agentId ?? t.agentId, agentSessionKey: t.agentSessionKey, sandboxed: t.sandboxed, lookup: t.lookup, fromLine: t.fromLine, lineCount: t.lineCount, searchBackend: "local", searchCorpus: "wiki" }); return i?.corpus === "wiki" ? i : null; } }; } //#endregion //#region extensions/memory-wiki/src/import-runs.ts function toImportRunSummary(e) { const { version: t, createdPaths: n, updatedPaths: r, ...i } = e; const a = uniqueStrings([...n, ...r].map((e) => e.path)); const o = Boolean(e.rollbackStartedAt || e.rollbackTargetsFinalizedAt); return { ...i, status: e.rolledBackAt ? "rolled_back" : o ? "rolling_back" : "applied", pagePaths: a, samplePaths: a.slice(0, 5) }; } async function listMemoryWikiImportRuns(e, t) { const n = Math.max(1, Math.floor(t?.limit ?? 10)); const r = (await getMemoryWikiImportRunStateStore().list(e.vault.path)).map(toImportRunSummary).toSorted((e, t) => t.appliedAt.localeCompare(e.appliedAt)); return { runs: r.slice(0, n), totalRuns: r.length, activeRuns: r.filter((e) => e.status !== "rolled_back").length, rolledBackRuns: r.filter((e) => e.status === "rolled_back").length }; } //#endregion //#region extensions/memory-wiki/src/gateway.ts const READ_SCOPE = "operator.read"; const WRITE_SCOPE = "operator.write"; const LOCAL_FILE_INGEST_SCOPE = "operator.admin"; function readStringParam(e, t, n) { const r = e[t]; if (typeof r === "string" && r.trim()) return r.trim(); if (n?.required) throw new Error(`${t} is required.`); } function readEnumParam(e, t, n) { const r = readStringParam(e, t); if (!r) return; if (n.includes(r)) return r; throw new Error(`${t} must be one of: ${n.join(", ")}.`); } function respondError(e, t) { if (t instanceof MemoryWikiDashboardUnavailableError) { const n = t.state === "rebuilding"; e(false, void 0, errorShape(t.state === "compile-required" ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE, t.message, { details: { state: t.state }, ...n ? { retryable: true, retryAfterMs: 500 } : {} })); return; } e(false, void 0, { code: "internal_error", message: formatErrorMessage(t) }); } function registerMemoryWikiGatewayMethods(e) { const { api: t } = e; const registerResultMethod = (e, n, r) => { t.registerGatewayMethod(e, async ({ params: t, respond: n, client: i, signal: a, hasCurrentClientAuthority: o }) => { let s = true; const c = { authority: i && o ? { kind: "operator", scopes: i.connect.scopes ?? [], connId: i.connId } : { kind: "host", operation: e }, signal: a, assertCurrent() { a?.throwIfAborted(); if (!s || o && !o()) throw new Error("Memory Wiki request authority is no longer current."); } }; try { n(true, await r(t, c)); } catch (e) { respondError(n, e); } finally { s = false; } }, { scope: n }); }; const syncImportedSourcesInBackground = (n, r) => { const i = e.resolveSourceSyncSignal?.(); if (e.resolveSourceSyncSignal && !i) return; syncMemoryWikiImportedSources({ config: n, appConfig: r, ...i ? { signal: i } : {} }).catch((e) => { if (i?.aborted) return; setMemoryWikiDashboardState(n, { state: "failed" }); t.logger.warn(`memory-wiki: background source sync failed: ${formatErrorMessage(e)}`); }); }; const resolveSourceSyncSignal = () => { const t = e.resolveSourceSyncSignal?.(); if (e.resolveSourceSyncSignal && !t) throw new Error("Memory Wiki service is not active."); return t; }; const resolveRequestContext = (t) => { const n = resolveSourceSyncSignal(); const r = e.getAppConfig(); const i = readStringParam(t, "agentId"); const a = e.resolveConfig(i, r); return { agentId: a.agentId ?? i ?? (r ? resolveDefaultAgentId(r) : void 0), appConfig: r, config: a, signal: n }; }; registerResultMethod("wiki.status", READ_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); await syncMemoryWikiImportedSources({ config: n, appConfig: t, ...r ? { signal: r } : {} }); return await resolveMemoryWikiStatus(n, { appConfig: t }); }); registerResultMethod("wiki.importRuns", READ_SCOPE, async (e) => { const { config: t } = resolveRequestContext(e); const n = readPositiveIntegerParam(e, "limit"); return await listMemoryWikiImportRuns(t, n !== void 0 ? { limit: n } : {}); }); registerResultMethod("wiki.importInsights", READ_SCOPE, async (e) => { const { appConfig: t, config: n } = resolveRequestContext(e); syncImportedSourcesInBackground(n, t); return (await loadMemoryWikiCompiledDashboards(n)).importInsights; }); registerResultMethod("wiki.overview", READ_SCOPE, async (e) => { const { appConfig: t, config: n } = resolveRequestContext(e); syncImportedSourcesInBackground(n, t); return (await loadMemoryWikiCompiledDashboards(n)).overview; }); registerResultMethod("wiki.init", WRITE_SCOPE, async (e) => { const { config: t, signal: n } = resolveRequestContext(e); return await initializeMemoryWikiVault(t, n ? { signal: n } : void 0); }); registerResultMethod("wiki.doctor", READ_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); await syncMemoryWikiImportedSources({ config: n, appConfig: t, ...r ? { signal: r } : {} }); const i = await resolveMemoryWikiStatus(n, { appConfig: t }); return buildMemoryWikiDoctorReport(i); }); registerResultMethod("wiki.compile", WRITE_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); await syncMemoryWikiImportedSources({ config: n, appConfig: t, deferIndexRefresh: true, ...r ? { signal: r } : {} }); return await compileMemoryWikiVault(n, r ? { signal: r } : void 0); }); registerResultMethod("wiki.ingest", LOCAL_FILE_INGEST_SCOPE, async (e) => { const { config: t, signal: n } = resolveRequestContext(e); const r = readStringParam(e, "inputPath", { required: true }); const i = readStringParam(e, "title"); return await ingestMemoryWikiSource({ config: t, inputPath: r, ...i ? { title: i } : {}, ...n ? { signal: n } : {} }); }); registerResultMethod("wiki.lint", WRITE_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); await syncMemoryWikiImportedSources({ config: n, appConfig: t, deferIndexRefresh: true, ...r ? { signal: r } : {} }); return await lintMemoryWikiVault(n, r ? { signal: r } : void 0); }); registerResultMethod("wiki.bridge.import", WRITE_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); return await syncMemoryWikiImportedSources({ config: { ...n, vaultMode: "bridge" }, appConfig: t, ...r ? { signal: r } : {} }); }); registerResultMethod("wiki.unsafeLocal.import", WRITE_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); if (n.vault.scope === "agent") throw new Error("Unsafe-local import does not support memory-wiki vault.scope=agent."); return await syncMemoryWikiImportedSources({ config: { ...n, vaultMode: "unsafe-local" }, appConfig: t, ...r ? { signal: r } : {} }); }); registerResultMethod("wiki.search", READ_SCOPE, async (e, t) => { const { agentId: n, appConfig: r, config: i, signal: a } = resolveRequestContext(e); await syncMemoryWikiImportedSources({ config: i, appConfig: r, ...a ? { signal: a } : {} }); const o = readStringParam(e, "query", { required: true }); const s = readPositiveIntegerParam(e, "maxResults"); const c = readEnumParam(e, "backend", WIKI_SEARCH_BACKENDS); const l = readEnumParam(e, "corpus", WIKI_SEARCH_CORPORA); const u = readEnumParam(e, "mode", WIKI_SEARCH_MODES); return await searchMemoryWiki({ memoryContext: t, config: i, appConfig: r, ...n ? { agentId: n } : {}, query: o, maxResults: s, searchBackend: c, searchCorpus: l, mode: u }); }); registerResultMethod("wiki.apply", WRITE_SCOPE, async (e) => { const { appConfig: t, config: n, signal: r } = resolveRequestContext(e); const i = normalizeMemoryWikiMutationInput(e); await syncMemoryWikiImportedSources({ config: n, appConfig: t, ...r ? { signal: r } : {} }); return await applyMemoryWikiMutation({ config: n, mutation: i, ...r ? { signal: r } : {} }); }); registerResultMethod("wiki.get", READ_SCOPE, async (e, t) => { const { agentId: n, appConfig: r, config: i, signal: a } = resolveRequestContext(e); await syncMemoryWikiImportedSources({ config: i, appConfig: r, ...a ? { signal: a } : {} }); const o = readStringParam(e, "lookup", { required: true }); const s = readPositiveIntegerParam(e, "fromLine"); const c = readPositiveIntegerParam(e, "lineCount"); const l = readEnumParam(e, "backend", WIKI_SEARCH_BACKENDS); const u = readEnumParam(e, "corpus", WIKI_SEARCH_CORPORA); return await getMemoryWikiPage({ memoryContext: t, config: i, appConfig: r, ...n ? { agentId: n } : {}, lookup: o, fromLine: s, lineCount: c, searchBackend: l, searchCorpus: u }); }); registerResultMethod("wiki.obsidian.status", READ_SCOPE, () => probeObsidianCli()); for (const e of OBSIDIAN_ACTIONS) registerResultMethod(`wiki.obsidian.${e.command}`, WRITE_SCOPE, async (t) => { const { config: n } = resolveRequestContext(t); assertOfficialObsidianCliSupported(n); const r = e.argument ? readStringParam(t, e.argument.name, { required: true }) : void 0; return await runObsidianAction({ config: n, action: e, value: r }); }); } //#endregion //#region extensions/memory-wiki/src/prompt-section.ts const DIGEST_MAX_PAGES = 4; const DIGEST_MAX_CLAIMS_PER_PAGE = 2; const DIGEST_MAX_PAGE_TITLE_CHARS = 160; const DIGEST_MAX_CLAIM_CHARS = 700; const DIGEST_MAX_PROMPT_CHARS = 2800; function rankPromptDigestPage(e) { return (e.contradictions?.length ?? 0) * 6 + (e.questions?.length ?? 0) * 4 + Math.min(e.claimCount ?? 0, 6) * 2 + Math.min(e.topClaims?.length ?? 0, 3); } function formatPromptClaim(e) { const t = [ e.status?.trim() ? `status ${e.status.trim()}` : null, e.confidence !== void 0 ? `confidence ${e.confidence.toFixed(2)}` : null, e.freshnessLevel?.trim() ? `freshness ${e.freshnessLevel.trim()}` : null ].filter(Boolean); if (t.length === 0) return e.text; return `${e.text} (${t.join(", ")})`; } function buildDigestPromptSection(e) { if (!e?.pages?.length) return []; const t = e.pages.filter((e) => (e.claimCount ?? 0) > 0 || (e.questions?.length ?? 0) > 0 || (e.contradictions?.length ?? 0) > 0).toSorted((e, t) => { const n = rankPromptDigestPage(e); const r = rankPromptDigestPage(t); if (n !== r) return r - n; return e.title.localeCompare(t.title); }).slice(0, DIGEST_MAX_PAGES); if (t.length === 0) return []; const n = ["## Compiled Wiki Snapshot", `Compiled wiki currently tracks ${e.claimCount ?? 0} claims across ${t.length} high-signal pages.`]; n.push(`Contradiction clusters: ${e.contradictionCount}.`); for (const e of t) { const t = [ e.kind, `${e.claimCount} claims`, (e.questions?.length ?? 0) > 0 ? `${e.questions?.length} open questions` : null, (e.contradictions?.length ?? 0) > 0 ? `${e.contradictions?.length} contradiction notes` : null ].filter(Boolean); n.push(`- ${truncateUtf16Safe(e.title, DIGEST_MAX_PAGE_TITLE_CHARS)}: ${t.join(", ")}`); for (const t of (e.topClaims ?? []).toSorted(compareWikiClaimSummaries).slice(0, DIGEST_MAX_CLAIMS_PER_PAGE)) n.push(` - ${truncateUtf16Safe(formatPromptClaim(t), DIGEST_MAX_CLAIM_CHARS)}`); } n.push(""); return truncateUtf16Safe(n.join("\n"), DIGEST_MAX_PROMPT_CHARS).split("\n"); } function buildWikiToolGuidance(e) { const t = e.has("wiki_search"); const n = e.has("wiki_get"); const r = [ e.has("memory_search") ? "Prefer `memory_search` with `corpus=all` for one recall pass across durable memory and the compiled wiki when both are relevant." : "", e.has("memory_get") ? "Use `memory_get` with `corpus=wiki` or `corpus=all` when you already know the page path and want a small excerpt without leaving the shared memory tool flow." : "", t && n ? "Workflow: `wiki_search` first, then `wiki_get` for the exact page or imported memory file you need. Use this when you want wiki-specific ranking or provenance details instead of the broader shared memory flow." : t ? "Use `wiki_search` before answering from stored knowledge when you want wiki-specific ranking or provenance details." : n ? "Use `wiki_get` to inspect specific wiki pages or imported memory files by path/id." : "", e.has("wiki_apply") ? "Use `wiki_apply` for narrow synthesis filing and metadata repair instead of rewriting managed markdown blocks by hand." : "", e.has("wiki_lint") ? "After meaningful wiki updates, run `wiki_lint` before trusting the vault." : "" ].filter(Boolean); return r.length > 0 ? [ "## Compiled Wiki", "Use the wiki when the answer depends on accumulated project knowledge, prior syntheses, entity pages, or source-backed notes that should survive beyond one conversation.", ...r, "" ] : []; } function createWikiPromptSectionBuilder() { return ({ availableTools: e }) => buildWikiToolGuidance(e); } function createWikiPromptSectionPreparer(e) { return async ({ agentId: t }) => { if (e.config.vault.scope === "agent" && !t) return []; const n = e.resolveConfig(t); if (!n.context.includeCompiledDigestPrompt) return []; return buildDigestPromptSection((await loadMemoryWikiCompiledCache(n))?.digest); }; } //#endregion //#region extensions/memory-wiki/src/tool.ts const WIKI_SEARCH_TIMEOUT_MS = 3e4; function formatWikiToolReportPath(e, t) { const n = path.resolve(e.vault.path); const r = path.resolve(t); const i = path.relative(n, r); if (!i || i.startsWith("..") || path.isAbsolute(i)) return t; return i.replace(/\\/g, "/"); } const WikiStatusSchema = Type.Object({}, { additionalProperties: false }); const WikiSearchBackendSchema = Type.Union(WIKI_SEARCH_BACKENDS.map((e) => Type.Literal(e))); const WikiSearchCorpusSchema = Type.Union(WIKI_SEARCH_CORPORA.map((e) => Type.Literal(e))); const WikiSearchModeSchema = Type.Union(WIKI_SEARCH_MODES.map((e) => Type.Literal(e))); const WikiSearchSchema = Type.Object({ query: Type.String({ minLength: 1 }), maxResults: Type.Optional(Type.Integer({ minimum: 1 })), backend: Type.Optional(WikiSearchBackendSchema), corpus: Type.Optional(WikiSearchCorpusSchema), mode: Type.Optional(WikiSearchModeSchema) }, { additionalProperties: false }); const WikiGetSchema = Type.Object({ lookup: Type.String({ minLength: 1 }), fromLine: Type.Optional(Type.Integer({ minimum: 1 })), lineCount: Type.Optional(Type.Integer({ minimum: 1 })), backend: Type.Optional(WikiSearchBackendSchema), corpus: Type.Optional(WikiSearchCorpusSchema) }, { additionalProperties: false }); const WikiClaimEvidenceSchema = Type.Object({ kind: Type.Optional(Type.String({ minLength: 1 })), sourceId: Type.Optional(Type.String({ minLength: 1 })), path: Type.Optional(Type.String({ minLength: 1 })), lines: Type.Optional(Type.String({ minLength: 1 })), weight: optionalFiniteNumberSchema({ minimum: 0 }), note: Type.Optional(Type.String({ minLength: 1 })), confidence: optionalFiniteNumberSchema({ minimum: 0, maximum: 1 }), privacyTier: Type.Optional(Type.String({ minLength: 1 })), updatedAt: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false }); const WikiClaimSchema = Type.Object({ id: Type.Optional(Type.String({ minLength: 1 })), text: Type.String({ minLength: 1 }), status: Type.Optional(Type.String({ minLength: 1 })), confidence: optionalFiniteNumberSchema({ minimum: 0, maximum: 1 }), evidence: Type.Optional(Type.Array(WikiClaimEvidenceSchema)), updatedAt: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false }); const WikiApplySchema = Type.Object({ op: Type.Union([ Type.Literal("create_synthesis"), Type.Literal("update_metadata"), Type.Literal("synthesis"), Type.Literal("metadata") ]), title: Type.Optional(Type.String({ minLength: 1 })), body: Type.Optional(Type.String({ minLength: 1 })), lookup: Type.Optional(Type.String({ minLength: 1 })), sourceIds: Type.Optional(Type.Array(Type.String({ minLength: 1 }))), claims: Type.Optional(Type.Array(WikiClaimSchema)), contradictions: Type.Optional(Type.Array(Type.String({ minLength: 1 }))), questions: Type.Optional(Type.Array(Type.String({ minLength: 1 }))), confidence: Type.Optional(Type.Union([Type.Number({ minimum: 0, maximum: 1 }), Type.Null()])), status: Type.Optional(Type.String({ minLength: 1 })) }, { additionalProperties: false }); function createWikiStatusTool(e, t, n = {}) { return { name: "wiki_status", label: "Wiki Status", description: "Inspect the current memory wiki vault mode, health, and Obsidian CLI availability.", parameters: WikiStatusSchema, execute: async () => { await syncMemoryWikiImportedSources({ config: e, appConfig: t, signal: n.signal }); const r = await resolveMemoryWikiStatus(e, { appConfig: t, callerAgentId: n.agentId }); return textResult(renderMemoryWikiStatus(r), r); } }; } function createWikiSearchTool(e, t, n = {}) { return { name: "wiki_search", label: "Wiki Search", description: "Search wiki pages and, when shared search is enabled, the active memory corpus by title, path, id, or body text.", parameters: WikiSearchSchema, execute: async (r, i, a) => { const o = i; const s = new AbortController(); const c = setTimeout(() => s.abort(/* @__PURE__ */ new Error(`wiki_search timed out after ${WIKI_SEARCH_TIMEOUT_MS / 1e3}s`)), WIKI_SEARCH_TIMEOUT_MS); c.unref?.(); const l = AbortSignal.any([ a, n.signal, s.signal ].filter((e) => e !== void 0)); try { return await racePromiseWithAbortSignal(async () => { await syncMemoryWikiImportedSources({ config: e, appConfig: t, signal: n.signal ?? l }); l.throwIfAborted(); const r = await searchMemoryWiki({ config: e, appConfig: t, ...n, signal: l, ...n.memoryContext ? { memoryContext: { ...n.memoryContext, signal: l } } : {}, query: o.query, maxResults: o.maxResults, ...o.backend ? { searchBackend: o.backend } : {}, ...o.corpus ? { searchCorpus: o.corpus } : {}, ...o.mode ? { mode: o.mode } : {} }); l.throwIfAborted(); return textResult(renderWikiSearchResults(r), { results: r }); }, l, (e) => e.reason instanceof Error ? e.reason : /* @__PURE__ */ new Error("wiki_search aborted")); } finally { clearTimeout(c); } } }; } function createWikiLintTool(e, t, { signal: n } = {}) { return { name: "wiki_lint", label: "Wiki Lint", description: "Lint the wiki vault and surface structural issues, provenance gaps, contradictions, and open questions.", parameters: WikiStatusSchema, execute: async () => { await syncMemoryWikiImportedSources({ config: e, appConfig: t, signal: n, deferIndexRefresh: true }); const r = await lintMemoryWikiVault(e, n ? { signal: n } : void 0); const i = r.issuesByCategory.contradictions.length; const a = r.issuesByCategory["open-questions"].length; const o = r.issuesByCategory.provenance.length; const s = r.issues.filter((e) => e.severity === "error").length; const c = r.issues.filter((e) => e.severity === "warning").length; const l = formatWikiToolReportPath(e, r.reportPath); const u = r.issueCount === 0 ? "No wiki lint issues." : [ `Issues: ${r.issueCount} total (${s} errors, ${c} warnings)`, `Contradictions: ${i}`, `Open questions: ${a}`, `Provenance gaps: ${o}`, `Report: ${l}` ].join("\n"); return textResult(u, { issueCount: r.issueCount, issues: r.issues, issuesByCategory: r.issuesByCategory, reportPath: l }); } }; } function createWikiApplyTool(e, t, { signal: n } = {}) { return { name: "wiki_apply", label: "Wiki Apply", description: "Apply narrow wiki mutations for syntheses and page metadata without freeform markdown surgery.", parameters: WikiApplySchema, execute: async (r, i) => { const a = normalizeMemoryWikiMutationInput(i); await syncMemoryWikiImportedSources({ config: e, appConfig: t, signal: n }); const o = await applyMemoryWikiMutation({ config: e, mutation: a, ...n ? { signal: n } : {} }); return textResult(renderWikiMutationSummary(o), o); } }; } function createWikiGetTool(e, t, n = {}) { return { name: "wiki_get", label: "Wiki Get", description: "Read a wiki page by id or relative path, or fall back to the active memory corpus when shared search is enabled.", parameters: WikiGetSchema, execute: async (r, i) => { const a = asNonArrayRecord(i); const o = typeof a.lookup === "string" ? a.lookup.trim() : ""; if (!o) return textResult("wiki_get requires a non-empty `lookup` path or id.", { found: false }); await syncMemoryWikiImportedSources({ config: e, appConfig: t, signal: n.signal }); const s = await getMemoryWikiPage({ config: e, appConfig: t, ...n, lookup: o, fromLine: a.fromLine, lineCount: a.lineCount, ...a.backend ? { searchBackend: a.backend } : {}, ...a.corpus ? { searchCorpus: a.corpus } : {} }); if (!s) return textResult(`Wiki page not found: ${o}`, { found: false }); return textResult(s.content, { found: true, ...s }); } }; } //#endregion //#region extensions/memory-wiki/index.ts async function loadConfiguredVaultIdentity(e) { const t = await loadMemoryWikiValidatedVaultIdentity(e); if (t.vaultGeneration) return { vaultGeneration: t.vaultGeneration, compiledCachePublicationId: t.compiledCachePublicationId }; try { if (!(await fs.stat(path.join(e, ".openclaw-wiki", "log.jsonl"))).isFile()) return null; } catch (e) { if (e instanceof Error && "code" in e && e.code === "ENOENT") return null; throw e; } return { vaultGeneration: await ensureMemoryWikiVaultGeneration(e), compiledCachePublicationId: null }; } var memory_wiki_default = definePluginEntry({ id: "memory-wiki", name: "Memory Wiki", description: "Persistent wiki compiler and Obsidian-friendly knowledge vault for OpenClaw.", configSchema: memoryWikiConfigSchema, register(e) { const t = resolveMemoryWikiConfig(e.pluginConfig); const getAppConfig = () => e.runtime.config.current(); const resolveConfig = (e, n = getAppConfig()) => resolveMemoryWikiAgentConfig({ config: t, appConfig: n, agentId: e }); const resolveToolContext = (e) => { const n = getAppConfig(); if (t.vault.scope === "agent" && !e && resolveMemoryWikiConfiguredAgentIds(n).length > 1) return null; return { appConfig: n, config: resolveConfig(e, n), ...r ? { signal: r.signal } : {} }; }; configureMemoryWikiSourceSyncStateStore(createMemoryWikiSourceSyncStateStore(e.runtime.state.openKeyedStore)); configureMemoryWikiImportRunStateStore(createMemoryWikiImportRunStateStore(e.runtime.state.openKeyedStore)); const n = createMemoryWikiCompiledCacheStore(e.runtime.state.openBlobStore, { onReadError(t) { e.logger.warn(`memory-wiki: compiled cache unavailable: ${String(t)}`); } }); configureMemoryWikiCompiledCacheStore(n); let r; e.registerService({ id: "memory-wiki-compiled-cache-owner-cleanup", async start() { r?.abort(); const e = new AbortController(); r = e; try { const e = getAppConfig(); const r = t.vault.scope === "global" ? [resolveConfig(void 0, e)] : resolveMemoryWikiConfiguredAgentIds(e).map((t) => resolveConfig(t, e)); deactivateMemoryWikiCompiledCacheOwnersExcept(/* @__PURE__ */ new Set()); const i = []; for (const e of r) { const t = await loadConfiguredVaultIdentity(e.vault.path); if (t) i.push({ config: e, identity: t }); } const a = /* @__PURE__ */ new Set(); for (const { config: e, identity: t } of i) { activateMemoryWikiCompiledCacheOwner(e, t.vaultGeneration, t.compiledCachePublicationId); a.add(resolveMemoryWikiCompiledCacheOwnerId(e)); } deactivateMemoryWikiCompiledCacheOwnersExcept(a); await n.deleteOwnersExcept(a); } catch (t) { e.abort(); if (r === e) r = void 0; deactivateMemoryWikiCompiledCacheOwnersExcept(/* @__PURE__ */ new Set()); throw t; } }, async stop() { r?.abort(); r = void 0; deactivateMemoryWikiCompiledCacheOwnersExcept(/* @__PURE__ */ new Set()); await waitForMemoryWikiImportedSourceSyncs(); deactivateMemoryWikiCompiledCacheOwnersExcept(/* @__PURE__ */ new Set()); await closeMemoryWikiQueryReader(); } }); e.registerMemoryPromptSupplement(createWikiPromptSectionBuilder()); e.registerMemoryPromptPreparation(createWikiPromptSectionPreparer({ config: t, resolveConfig })); e.registerMemoryCorpusSupplement(createWikiCorpusSupplement({ resolveConfig, getAppConfig })); registerMemoryWikiGatewayMethods({ api: e, getAppConfig, resolveConfig, resolveSourceSyncSignal: () => r?.signal }); for (const [t, n] of [ ["wiki_status", createWikiStatusTool], ["wiki_lint", createWikiLintTool], ["wiki_apply", createWikiApplyTool], ["wiki_search", createWikiSearchTool], ["wiki_get", createWikiGetTool] ]) e.registerTool({ contextVersion: 2, create: (e) => { const t = resolveToolContext(e.agentId); if (!t) return null; return n(t.config, t.appConfig, { agentId: t.config.agentId ?? e.agentId, agentSessionKey: e.sessionKey, sandboxed: e.sandboxed, conversationRecall: e.conversationRecall, memoryContext: { authority: e.sessionKey ? { kind: "session", conversationRecall: e.conversationRecall, sessionKey: e.sessionKey, sessionId: e.sessionId, sandboxed: e.sandboxed === true, audience: e.memoryAudience } : { kind: "host", operation: "memory-wiki.tool" }, assertCurrent() { e.assertInvocationCurrent(); e.assertMemoryAudienceCurrent?.(); }, ...t.signal ? { signal: t.signal } : {} }, ...t.signal ? { signal: t.signal } : {} }); } }, { name: t }); e.registerCli(async ({ program: e }) => { const { registerWikiCli: n } = await import("../../cli-BZzshkAE.mjs"); n(e, { config: t, resolveConfig, getAppConfig }); }, { descriptors: [{ name: "wiki", description: "Inspect and initialize the memory wiki vault", hasSubcommands: true }] }); } }); //#endregion export { memory_wiki_default as default };