openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
271 lines (270 loc) • 9 kB
JavaScript
import { ni as NEVER } from "./json-schema-processors-CIhP-F53.mjs";
import { Et as _enum, Jn as string, Nt as array, Pn as number, Sn as looseObject, Yt as discriminatedUnion, sr as unknown, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { r as sha256HexPrefixCore } from "./node-crypto-B6yuTjmm.mjs";
import { c as resolveWorkspaceStateIdentity } from "./workspace-state-identity-Ce50CSIn.mjs";
//#region src/memory-host-sdk/event-store.ts
const MEMORY_HOST_EVENTS_PLUGIN_ID = "memory-core";
const MEMORY_HOST_EVENTS_NAMESPACE = "memory-host.events";
const MEMORY_HOST_EVENT_CURSORS_NAMESPACE = "memory-host.event-cursors";
const MAX_MEMORY_HOST_EVENTS = 1e4;
const MAX_MEMORY_HOST_EVENT_CURSORS = 1e3;
const MAX_MEMORY_HOST_EVENT_JSON_BYTES = 8192;
const MAX_MEMORY_HOST_EVENT_ITEMS = 10;
const MAX_MEMORY_HOST_EVENT_TEXT_BYTES = 2048;
const MAX_MEMORY_HOST_EVENT_PATH_BYTES = 256;
const WORKSPACE_HASH_BYTES = 24;
let maxMemoryHostEventsForTests;
const memoryHostFiniteNumberSchema = number().finite();
const memoryHostRecallResultSchema = looseObject({
path: string(),
startLine: memoryHostFiniteNumberSchema,
endLine: memoryHostFiniteNumberSchema,
score: memoryHostFiniteNumberSchema
});
const memoryHostSkippedRecallResultSchema = memoryHostRecallResultSchema.extend({ reason: literal("non-short-term-memory-path") });
const memoryHostPromotionCandidateSchema = looseObject({
key: string(),
path: string(),
startLine: memoryHostFiniteNumberSchema,
endLine: memoryHostFiniteNumberSchema,
score: memoryHostFiniteNumberSchema,
recallCount: memoryHostFiniteNumberSchema
});
function boundedEventItems(e, t) {
const n = array(e);
return array(unknown()).transform((e, r) => {
const i = n.safeParse(e.slice(0, MAX_MEMORY_HOST_EVENT_ITEMS));
if (!i.success) {
r.addIssue({
code: "custom",
message: t
});
return NEVER;
}
return {
items: i.data,
truncated: e.length > MAX_MEMORY_HOST_EVENT_ITEMS
};
});
}
const memoryHostEventRecordSchema = discriminatedUnion("type", [
looseObject({
type: literal("memory.recall.recorded"),
timestamp: string(),
storageTruncated: unknown().optional(),
query: string(),
resultCount: memoryHostFiniteNumberSchema,
results: boundedEventItems(memoryHostRecallResultSchema, "invalid recall result")
}),
looseObject({
type: literal("memory.recall.skipped"),
timestamp: string(),
storageTruncated: unknown().optional(),
query: string(),
reason: literal("non-short-term-memory-path"),
eligibleResultCount: memoryHostFiniteNumberSchema,
skippedResultCount: memoryHostFiniteNumberSchema,
results: boundedEventItems(memoryHostSkippedRecallResultSchema, "invalid skipped recall result")
}),
looseObject({
type: literal("memory.promotion.applied"),
timestamp: string(),
storageTruncated: unknown().optional(),
memoryPath: string(),
applied: memoryHostFiniteNumberSchema,
candidates: boundedEventItems(memoryHostPromotionCandidateSchema, "invalid promotion candidate")
}),
looseObject({
type: literal("memory.dream.completed"),
timestamp: string(),
storageTruncated: unknown().optional(),
phase: _enum([
"light",
"deep",
"rem"
]),
outcome: _enum(["completed", "failed"]).optional(),
error: string().optional(),
inlinePath: string().optional(),
reportPath: string().optional(),
lineCount: memoryHostFiniteNumberSchema,
storageMode: _enum([
"inline",
"separate",
"both"
])
})
]);
function normalizeMemoryHostWorkspaceKey(e) {
const t = resolveWorkspaceStateIdentity(e).workspacePath.replace(/\\/g, "/");
return process.platform === "win32" ? t.toLowerCase() : t;
}
function memoryHostWorkspacePrefix(e) {
return sha256HexPrefixCore(normalizeMemoryHostWorkspaceKey(e), WORKSPACE_HASH_BYTES);
}
function truncateUtf8(e, t) {
if (Buffer.byteLength(e, "utf8") <= t) return {
value: e,
truncated: false
};
let n = 0;
let r = e.length;
while (n < r) {
const i = Math.ceil((n + r) / 2);
if (Buffer.byteLength(e.slice(0, i), "utf8") <= t - 3) n = i;
else r = i - 1;
}
const i = n > 0 && /[\uD800-\uDBFF]/u.test(e.charAt(n - 1)) ? n - 1 : n;
return {
value: `${e.slice(0, i)}…`,
truncated: true
};
}
/** Validate and bound one diagnostic event before storing it in plugin state. */
function normalizeMemoryHostEventRecordForStorage(e) {
const t = memoryHostEventRecordSchema.safeParse(e);
if (!t.success) return null;
const n = t.data;
let r = n.storageTruncated === true;
const boundText = (e, t) => {
const n = truncateUtf8(e, t);
r ||= n.truncated;
return n.value;
};
const i = boundText(n.timestamp, 128);
if (n.type === "memory.recall.recorded" || n.type === "memory.recall.skipped") {
const e = boundText(n.query, MAX_MEMORY_HOST_EVENT_TEXT_BYTES);
r ||= n.results.truncated;
const t = n.results.items.map((e) => {
return {
path: boundText(e.path, MAX_MEMORY_HOST_EVENT_PATH_BYTES),
startLine: e.startLine,
endLine: e.endLine,
score: e.score
};
});
const a = n.type === "memory.recall.recorded" ? {
type: "memory.recall.recorded",
timestamp: i,
query: e,
resultCount: n.resultCount,
results: t,
...r ? { storageTruncated: true } : {}
} : {
type: "memory.recall.skipped",
timestamp: i,
query: e,
reason: "non-short-term-memory-path",
eligibleResultCount: n.eligibleResultCount,
skippedResultCount: n.skippedResultCount,
results: t.map((e) => Object.assign(e, { reason: "non-short-term-memory-path" })),
...r ? { storageTruncated: true } : {}
};
return Buffer.byteLength(JSON.stringify(a), "utf8") <= MAX_MEMORY_HOST_EVENT_JSON_BYTES ? a : {
...a,
results: [],
storageTruncated: true
};
}
if (n.type === "memory.promotion.applied") {
const e = boundText(n.memoryPath, MAX_MEMORY_HOST_EVENT_PATH_BYTES);
r ||= n.candidates.truncated;
const t = n.candidates.items.map((e) => {
return {
key: boundText(e.key, MAX_MEMORY_HOST_EVENT_PATH_BYTES),
path: boundText(e.path, MAX_MEMORY_HOST_EVENT_PATH_BYTES),
startLine: e.startLine,
endLine: e.endLine,
score: e.score,
recallCount: e.recallCount
};
});
const a = {
type: "memory.promotion.applied",
timestamp: i,
memoryPath: e,
applied: n.applied,
candidates: t,
...r ? { storageTruncated: true } : {}
};
return Buffer.byteLength(JSON.stringify(a), "utf8") <= MAX_MEMORY_HOST_EVENT_JSON_BYTES ? a : {
...a,
candidates: [],
storageTruncated: true
};
}
const a = n.error ? boundText(n.error, MAX_MEMORY_HOST_EVENT_TEXT_BYTES) : void 0;
const o = n.inlinePath ? boundText(n.inlinePath, MAX_MEMORY_HOST_EVENT_PATH_BYTES) : void 0;
const s = n.reportPath ? boundText(n.reportPath, MAX_MEMORY_HOST_EVENT_PATH_BYTES) : void 0;
return {
type: n.type,
timestamp: i,
phase: n.phase,
...n.outcome ? { outcome: n.outcome } : {},
...a ? { error: a } : {},
...o ? { inlinePath: o } : {},
...s ? { reportPath: s } : {},
lineCount: n.lineCount,
storageMode: n.storageMode,
...r ? { storageTruncated: true } : {}
};
}
async function registerMemoryHostEvent(e) {
const t = normalizeMemoryHostEventRecordForStorage(e.event);
if (!t) throw new TypeError("Memory host event is invalid");
const n = memoryHostWorkspacePrefix(e.workspaceDir);
const r = `${n}:event:`;
const i = Date.now();
const a = {
pluginId: MEMORY_HOST_EVENTS_PLUGIN_ID,
cursorOptions: {
namespace: MEMORY_HOST_EVENT_CURSORS_NAMESPACE,
maxEntries: MAX_MEMORY_HOST_EVENT_CURSORS,
...e.env ? { env: e.env } : {}
},
cursorKey: `${n}:cursor`,
journalOptions: {
namespace: MEMORY_HOST_EVENTS_NAMESPACE,
maxEntries: maxMemoryHostEventsForTests ?? MAX_MEMORY_HOST_EVENTS,
...e.env ? { env: e.env } : {}
},
journalKeyPrefix: `${r}1:`,
journalKeyRange: {
keyStartInclusive: r,
keyEndExclusive: `${n}:event;`,
valueKind: "event"
},
journalValue: {
kind: "event",
event: t,
recordedAt: i
}
};
await (await import("./plugin-state-store-IvBZXpzM.mjs")).registerPluginStateSequencedJournalEntry(a);
}
async function listStoredMemoryHostEvents(e) {
const t = Number.isFinite(e.limit) ? Math.max(1, Math.min(maxMemoryHostEventsForTests ?? MAX_MEMORY_HOST_EVENTS, Math.floor(e.limit))) : maxMemoryHostEventsForTests ?? MAX_MEMORY_HOST_EVENTS;
const n = memoryHostWorkspacePrefix(e.workspaceDir);
const r = {
pluginId: MEMORY_HOST_EVENTS_PLUGIN_ID,
namespace: MEMORY_HOST_EVENTS_NAMESPACE,
keyStartInclusive: `${n}:event:`,
keyEndExclusive: `${n}:event;`,
limit: t,
order: "desc",
...e.type ? { valueFilter: {
path: "$.event.type",
equals: e.type
} } : {},
...e.env ? { env: e.env } : {}
};
return (await (await import("./plugin-state-store-IvBZXpzM.mjs")).pluginStateEntriesInKeyRange(r)).flatMap((e) => {
const t = e.value;
return t.kind === "event" ? [{
...e,
value: t
}] : [];
}).toReversed();
}
//#endregion
export { normalizeMemoryHostEventRecordForStorage as n, registerMemoryHostEvent as r, listStoredMemoryHostEvents as t };