openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
638 lines (637 loc) • 19.6 kB
JavaScript
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { f as watch } from "./file-access-runtime-BD2Fjfbw.mjs";
import { i as observationPrefixKind, n as readObservationSnapshot, o as resolveFsObservationIntervalMs, r as admitObservationRoot, s as resolveFsObservationMode, t as ObservationSampleCloseError } from "./fs-observation-snapshot-75D5ef0W.mjs";
import "./error-runtime-BM740gJj.mjs";
import { c as matchesExtraMemoryPathEntry, l as normalizeExtraMemoryPathEntries } from "./read-file-_FfN9cuw.mjs";
import { n as classifyMemoryMultimodalPath } from "./multimodal-CD7YKC3g.mjs";
import "./runtime-env-D-Pa5lD6.mjs";
import "./setup-tools-NrA1nFHA.mjs";
import "./diagnostic-runtime-By09gTPa.mjs";
import "./memory-core-host-engine-fs-Bgn0bHTy.mjs";
import path from "node:path";
import fs from "node:fs/promises";
//#region extensions/memory-core/src/memory/watch-policy.ts
const IGNORED = /* @__PURE__ */ new Set([
".git",
"node_modules",
".pnpm-store",
".venv",
"venv",
".tox",
"__pycache__"
]);
async function firstLink(e, t, n) {
let r = ".";
const i = t.split(path.sep).filter((e) => e && e !== ".");
for (const t of i) {
n.throwIfAborted();
r = path.join(r, t);
const i = await observationPrefixKind(e, r, n);
if (i === "symlink") return r;
if (i !== "directory") return;
}
}
var MemoryWatchPolicy = class {
constructor(e, t) {
this.settings = t;
this.roots = /* @__PURE__ */ new Map();
this.extras = normalizeExtraMemoryPathEntries(e, t.extraPaths);
this.targets = [
{
path: path.resolve(e, "MEMORY.md"),
kind: "entry",
core: true
},
{
path: path.resolve(e, "USER.md"),
kind: "entry",
core: true
},
{
path: path.resolve(e, "memory"),
kind: "tree",
core: true
},
...this.extras.map((e) => ({
path: e.path,
kind: "tree",
core: false
}))
];
}
async admit(e, t) {
const n = this.roots.get(e);
if (n) return n;
const r = await admitObservationRoot(e, "allow");
const { exactIdentity: i } = await r.stat(".");
t.throwIfAborted();
if (!i) throw new Error("Memory observation root has no exact filesystem identity");
const a = {
root: r,
identity: `${i.dev}:${i.ino}`
};
this.roots.set(e, a);
return a;
}
async observations(e) {
const t = /* @__PURE__ */ new Map();
const add = (e, n) => {
const r = t.get(e.root) ?? {
...e,
selections: []
};
r.selections.push(n);
t.set(e.root, r);
};
for (const t of this.targets) {
e.throwIfAborted();
let n = t.core ? path.dirname(path.dirname(t.path)) : path.dirname(t.path);
let r = t.path;
for (let i = 0;; i++) {
if (i >= 40) throw new Error("Memory watch target has too many symbolic links");
const a = await this.admit(n, e);
const o = a.root;
e.throwIfAborted();
const s = path.relative(o.rootDir, r) || ".";
const c = await firstLink(o, s, e);
e.throwIfAborted();
add(a, {
scope: c ? {
path: c,
kind: "entry"
} : {
path: s,
kind: t.kind,
depth: 128
},
resolved: path.resolve(o.rootDir, c ?? s),
lexical: t.path,
core: t.core,
alias: c !== void 0
});
if (!c || path.normalize(c) === path.normalize(s)) break;
const l = path.resolve(o.rootDir, c);
const u = await fs.readlink(l);
e.throwIfAborted();
r = path.resolve(path.dirname(l), u, path.relative(l, r));
n = path.dirname(r);
}
}
return [...t.values()];
}
scopes(e) {
return [...new Map(e.selections.map(({ scope: e }) => [JSON.stringify(e), e])).values()];
}
selectionKeys(e) {
const t = this.settings.multimodal.enabled ? this.settings.multimodal.modalities : [];
return e.selections.flatMap(({ scope: e, resolved: n, lexical: r, alias: i }) => ["text", ...t].map((t) => JSON.stringify([
e,
n,
r,
i,
t
])));
}
ignored(e, t, n) {
if (e.split(path.sep).some((e) => IGNORED.has(e.toLowerCase()))) return true;
if (n === "directory") return false;
if (n === "symlink") return true;
const r = path.extname(t).toLowerCase();
return r !== "" && r !== ".md" && classifyMemoryMultimodalPath(t, this.settings.multimodal) === null;
}
exclude(e, t) {
const n = path.resolve(e.root.rootDir, t.path);
for (const r of e.selections) {
const e = r.resolved;
if (n === e || r.scope.kind === "tree" && isPathInside(e, n)) {
if (r.alias && n === e) return false;
const i = path.relative(e, n);
const a = path.join(r.lexical, i);
if (!this.ignored(i, a, t.kind)) return false;
} else if (isPathInside(n, e)) return false;
}
return true;
}
select(e, t, n) {
const r = path.resolve(e.root.rootDir, t);
for (const i of e.selections) {
const a = i.resolved;
if (n && isPathInside(r, a) && r !== a) return {
root: e.root,
relative: t,
sample: false
};
if (r !== a && (i.scope.kind !== "tree" || !isPathInside(a, r))) continue;
if (i.alias) return {
root: e.root,
relative: i.scope.path,
sample: false
};
const o = path.relative(a, r);
const s = path.join(i.lexical, o);
if (this.ignored(o, s, n ? "directory" : "file")) continue;
if (!i.core && !this.extras.some((e) => isPathInside(e.path, s) && (!this.ignored(o, s, "file") && matchesExtraMemoryPathEntry(e, s) || n && matchesExtraMemoryPathEntry(e, s, { directory: true })))) continue;
return {
root: e.root,
relative: t,
sample: true
};
}
}
};
//#endregion
//#region extensions/memory-core/src/memory/watch-settle.ts
const MEMORY_WATCH_MAX_PATHS = 1024;
const MEMORY_WATCH_SETTLE_RECHECK_MS = 100;
function snapshotsMatch(e, t) {
return e === null || t === null ? e === t : e.size === t.size && e.mtimeMs === t.mtimeMs;
}
async function snapshotPath(e) {
return e.sample ? await readObservationSnapshot(e.root, e.relative) ?? null : null;
}
function recordMemoryWatchEventPath(e, t) {
const n = path.resolve(t.root.rootDir, t.relative);
e.set(n, {
file: t,
snapshot: null
});
if (e.size > 1024) e.clear();
}
async function settleMemoryWatchEventPaths(e, t) {
t?.throwIfAborted();
const n = [...e];
e.clear();
const r = [];
const retain = (t, n) => {
if (!e.has(t) && e.size < 1024) e.set(t, n);
};
for (const [e, i] of n) {
t?.throwIfAborted();
const n = await snapshotPath(i.file);
t?.throwIfAborted();
if (i.snapshot === null) {
if (n !== null) r.push([e, {
file: i.file,
snapshot: n
}]);
} else if (!snapshotsMatch(i.snapshot, n)) retain(e, {
file: i.file,
snapshot: n
});
}
if (r.length) {
await sleepWithAbort(MEMORY_WATCH_SETTLE_RECHECK_MS, t);
for (const [e, n] of r) {
t?.throwIfAborted();
const r = await snapshotPath(n.file);
t?.throwIfAborted();
if (!snapshotsMatch(n.snapshot, r)) retain(e, {
file: n.file,
snapshot: r
});
}
}
return e.size === 0;
}
//#endregion
//#region extensions/memory-core/src/memory/file-watcher.ts
const log = createSubsystemLogger("memory");
const RETRY_DELAYS_MS = [
500,
2e3,
5e3
];
const DEFAULT_POLL_INTERVAL_MS = 3e4;
const RECONCILE_INTERVAL_MS = 3e5;
const sharedObservations = /* @__PURE__ */ new Map();
function failShared(e, t, n) {
e.shareable = false;
const r = e.members.size > 1;
if (r) for (const t of e.members) t.isolate();
for (const i of e.members) i.unavailable(t, r ? void 0 : n);
}
function sharedScopes(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) for (const e of n.scopes) t.set(JSON.stringify(e), e);
return [...t.values()];
}
function sharedSelectionKey(e) {
return JSON.stringify([...new Set([...e].flatMap((e) => e.policy.selectionKeys(e.group)))].toSorted());
}
function refreshShared(e) {
e.refreshRequested = true;
return e.refreshing ??= e.subscription.ready.then(async () => {
while (e.refreshRequested && e.members.size) {
e.refreshRequested = false;
await e.subscription.setScopes(sharedScopes(e.members));
}
}).catch((t) => {
failShared(e, t);
}).finally(() => {
e.refreshing = void 0;
}).then(() => e.refreshRequested && e.members.size ? refreshShared(e) : void 0);
}
function acquireObservation(e, t, n, r) {
const i = JSON.stringify([
e.group.root.rootDir,
e.group.identity,
t,
n
]);
const a = sharedObservations.get(i) ?? /* @__PURE__ */ new Set();
for (const t of a) if (r && t.shareable && sharedScopes([...t.members, e]).length <= 128) {
const n = sharedSelectionKey(t.members);
t.members.add(e);
if (n !== sharedSelectionKey(t.members)) return {
shared: t,
ready: refreshShared(t)
};
const r = t.refreshing ?? t.subscription.ready;
return {
shared: t,
ready: !t.refreshing && t.subscription.health().state === "ready" ? r.then(() => {
e.invalidate({ reason: "reconcile" });
e.health(t.subscription.health());
}) : r
};
}
const o = /* @__PURE__ */ new Set([e]);
const s = {
key: i,
members: o,
mode: t,
pollIntervalMs: n,
shareable: r,
refreshRequested: false,
subscription: watch(e.group.root, {
scopes: e.scopes,
mode: t,
intervalMs: RECONCILE_INTERVAL_MS,
pollIntervalMs: n,
maxDirectories: 1e6,
maxEntries: 1e6,
maxPendingPaths: MEMORY_WATCH_MAX_PATHS,
exclude: (e) => {
for (const t of o) if (!t.policy.exclude(t.group, e)) return false;
return true;
},
onInvalidate: (e) => {
for (const t of o) t.invalidate(e);
},
onHealth: (e) => {
if (e.state === "unavailable") {
const t = e.failure?.operation === "watch" && e.failure.code === "watch-limit" ? "watch-limit" : void 0;
failShared(s, e.failure?.error, t);
return;
}
for (const t of o) t.health(e);
}
})
};
a.add(s);
sharedObservations.set(i, a);
return {
shared: s,
ready: s.subscription.ready
};
}
function releaseObservation({ member: e, shared: t }) {
const n = sharedSelectionKey(t.members);
t.members.delete(e);
if (t.members.size) {
if (n !== sharedSelectionKey(t.members)) refreshShared(t);
return Promise.resolve();
}
const r = sharedObservations.get(t.key);
r?.delete(t);
if (!r?.size) sharedObservations.delete(t.key);
return t.subscription.close();
}
var MemoryFileWatcher = class {
constructor(e) {
this.options = e;
this.lifetime = new AbortController();
this.observations = /* @__PURE__ */ new Map();
this.rootIds = /* @__PURE__ */ new WeakMap();
this.isolatedRoots = /* @__PURE__ */ new WeakSet();
this.nextRootId = 0;
this.pendingPaths = /* @__PURE__ */ new Map();
this.pressureWarningShown = false;
this.pollingWarningShown = false;
this.closeErrors = [];
this.closed = false;
this.degraded = false;
this.retries = 0;
this.retryExhausted = false;
this.refreshRequested = false;
this.pendingChange = false;
this.revision = 0;
this.policy = new MemoryWatchPolicy(e.workspaceDir, e.settings);
}
get capacityDegraded() {
return this.degraded;
}
health() {
return [...this.observations.values()].map(({ shared: { subscription: e, mode: t, pollIntervalMs: n } }) => {
const r = e.health();
return {
state: r.state,
mode: r.mode,
directories: r.directories,
failure: r.failure ? {
operation: r.failure.operation,
code: r.failure.code,
error: String(r.failure.error)
} : void 0,
pollingFallback: t === "auto" && r.mode === "poll",
pollIntervalMs: n
};
});
}
start() {
return this.starting ??= this.options.runInBackgroundContext(() => this.refresh());
}
publishState() {
this.options.onState?.({
health: this.health(),
capacityDegraded: this.degraded
});
}
get canObserve() {
return !(this.closed || this.degraded || this.closeErrors.length || this.recovering || this.retryTimer || this.retryExhausted);
}
refresh() {
if (!this.canObserve) return Promise.resolve();
this.refreshRequested = true;
return this.refreshing ??= Promise.resolve().then(async () => {
while (this.refreshRequested && this.canObserve) {
this.refreshRequested = false;
const e = (await this.policy.observations(this.lifetime.signal)).flatMap((e) => {
let t = this.rootIds.get(e.root);
if (t === void 0) {
t = ++this.nextRootId;
this.rootIds.set(e.root, t);
}
const n = [];
for (let r = 0; r < e.selections.length; r += 128) n.push({
id: String(t) + ":" + r,
group: {
...e,
selections: e.selections.slice(r, r + 128)
}
});
return n;
});
if (!this.canObserve) return;
const t = new Set(e.map((e) => e.id));
const n = [...this.observations.values()].filter((e) => !t.has(e.id));
await this.retire(n);
if (!this.canObserve) return;
const r = [];
for (const { id: t, group: n } of e) {
if (!this.canObserve) return;
const e = this.policy.scopes(n);
const i = this.observations.get(t);
if (i) {
if (JSON.stringify(i.member.scopes) === JSON.stringify(e)) {
i.member.group = n;
continue;
}
await this.retire([i]);
if (!this.canObserve) return;
}
const a = resolveFsObservationMode();
const o = resolveFsObservationIntervalMs(process.env, DEFAULT_POLL_INTERVAL_MS);
const s = {
group: n,
scopes: e,
policy: this.policy,
invalidate: (e) => {
this.deliver(() => this.dirty(s.group, e));
},
health: (e) => {
this.deliver(() => this.onHealth(e, a, o));
},
isolate: () => {
if (!this.isolatedRoots.has(n.root)) {
this.isolatedRoots.add(n.root);
this.retries = 0;
}
},
unavailable: (e, t) => {
this.deliver(() => this.unavailable(e, t));
}
};
const { shared: c, ready: l } = acquireObservation(s, a, o, !this.isolatedRoots.has(n.root));
this.observations.set(t, {
id: t,
member: s,
shared: c
});
r.push(l);
}
this.publishState();
await Promise.all(r);
}
}).catch((e) => {
if (!this.closed) this.unavailable(e);
}).finally(() => {
this.refreshing = void 0;
if (this.refreshRequested && !this.retryTimer) this.refresh();
});
}
deliver(e) {
let t = false;
try {
this.options.runInBackgroundContext(() => {
t = true;
e();
});
} catch (e) {
if (t) throw e;
this.retryExhausted = true;
this.unavailable(e);
clearTimeout(this.watchTimer);
this.watchTimer = void 0;
this.pendingChange = false;
}
}
dirty(e, t) {
if (!t.changes) {
this.markDirty();
this.refresh();
return;
}
let n = false;
for (const r of t.changes) {
const i = this.policy.select(e, r.path, r.type === "structural");
if (i) {
n ||= r.type === "structural";
if (t.reason === "event" || t.reason === "reconcile") this.retries = 0;
this.markDirty(i);
}
}
if (n) this.refresh();
}
onHealth(e, t, n) {
this.publishState();
if (e.state !== "ready") return;
if (t === "auto" && e.mode === "poll" && !this.pollingWarningShown) {
this.pollingWarningShown = true;
const t = e.failure ? `${e.failure.code ?? e.failure.operation}: ${String(e.failure.error)}` : "native watch events are unavailable; fs-safe did not report a reason";
log.warn(`memory watcher using fallback polling every ${n} ms: ${t}. Native watching will not be retried until the watcher restarts.`);
}
const r = [...this.observations.values()].reduce((e, t) => e + t.shared.subscription.health().directories, 0);
if (this.pressureWarningShown || r <= 2e3) return;
this.pressureWarningShown = true;
const i = e.mode === "poll" ? "Large memory folders or extraPaths increase metadata polling work." : "Large memory folders or extraPaths can exhaust file-watch/open-file limits.";
log.warn(`Memory file watching is tracking ${r} observed directories. ${i} Remove unnecessary memory.search.extraPaths entries or narrow their roots. After changes, restart the Gateway. To refresh the index, run in the Gateway's environment: ` + formatCliCommand("openclaw memory index --force --agent " + this.options.agentId) + ".");
}
unavailable(e, t) {
if (this.closed || this.recovering || this.retryTimer || this.degraded) return;
this.degraded ||= Boolean(t);
this.publishState();
this.options.onUnavailable();
this.markDirty();
log.warn(t ? "memory watcher capacity exhausted (" + t + "); watching disabled, memory will refresh on search" : "memory watcher unavailable; memory will refresh on search: " + String(e));
const n = this.retire([...this.observations.values()]);
this.recovering = n.finally(() => {
this.recovering = void 0;
if (this.closed || this.degraded || this.closeErrors.length || this.retryExhausted) return;
const e = RETRY_DELAYS_MS[this.retries++];
if (e === void 0) {
this.retryExhausted = true;
return;
}
this.retryTimer = setTimeout(() => {
this.retryTimer = void 0;
this.refresh();
}, e);
this.retryTimer.unref();
});
}
async retire(e) {
for (const t of e) this.observations.delete(t.id);
if (e.length) this.publishState();
const t = await Promise.allSettled(e.map(releaseObservation));
for (const e of t) {
if (e.status !== "rejected") continue;
materializeErrorStack(e.reason);
this.closeErrors.push(e.reason);
if (!this.closed) this.options.onUnavailable();
log.warn("memory watcher close failed; observation will not restart: " + String(e.reason));
}
}
markDirty(e) {
if (this.closed) return;
this.revision++;
this.pendingChange = true;
if (e) recordMemoryWatchEventPath(this.pendingPaths, e);
this.options.onDirty?.();
this.scheduleSync();
}
scheduleSync(e = false) {
if (this.closed || this.settling) return;
clearTimeout(this.watchTimer);
this.watchTimer = setTimeout(() => {
this.watchTimer = void 0;
let e = false;
const t = this.revision;
this.settling = Promise.resolve().then(async () => {
if (this.closed) return;
if (!await settleMemoryWatchEventPaths(this.pendingPaths, this.lifetime.signal)) {
e = true;
return;
}
if (this.closed) return;
this.pendingChange = this.revision !== t;
await this.options.runInBackgroundContext(() => this.options.onChange());
}).catch((e) => {
if (e instanceof ObservationSampleCloseError) {
materializeErrorStack(e.cause);
this.closeErrors.push(e.cause);
this.unavailable(e);
}
if (!this.closed) {
this.pendingChange = this.revision !== t;
log.warn("memory sync failed (watch): " + String(e));
}
}).finally(() => {
this.settling = void 0;
if (this.pendingChange) this.scheduleSync(e);
});
}, Math.max(e ? 100 : 0, this.options.settings.sync.watchDebounceMs));
this.watchTimer.unref();
}
close() {
if (this.closing) return this.closing;
this.closing = this.options.runInBackgroundContext(async () => {
this.closed = true;
this.lifetime.abort();
clearTimeout(this.watchTimer);
clearTimeout(this.retryTimer);
const e = this.retire([...this.observations.values()]);
await Promise.allSettled([
this.starting,
this.refreshing,
this.recovering,
this.settling,
e
]);
this.pendingPaths.clear();
this.publishState();
if (this.closeErrors.length) {
const e = new AggregateError(this.closeErrors, "Memory watcher cleanup failed");
materializeErrorStack(e);
throw e;
}
});
return this.closing;
}
};
//#endregion
export { MemoryFileWatcher as t };