openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
273 lines (272 loc) • 11.4 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { r as isRootFileMissingFailure } from "./boundary-file-read-BfaFLDqt.mjs";
import "./utils-C8YECn2Q.mjs";
import { l as resolveAgentIdFromSessionKey } from "./session-key-CqAyZeVk.mjs";
import { _ as resolveDefaultAgentId, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { n as rememberBoundedKey } from "./dedupe-DxT0h2gR.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { a as hasMultipleSessionSharingIdentities, c as prepareUserProfileCatalog, o as isUserProfileCatalogReady, v as readUserProfileIdentity } from "./user-profile-list-D7DDbqt5.mjs";
import { t as prepareSessionTranscriptHydration } from "./session-transcript-hydration-B_Y3bole.mjs";
import { c as triggerInternalHook, n as createInternalHookEvent } from "./internal-hooks-D6nf-Q3g.mjs";
import { g as resolveWorkspaceBootstrapPath, i as DEFAULT_MEMORY_FILENAME, n as DEFAULT_BOOTSTRAP_FILENAME, s as DEFAULT_USER_FILENAME, t as DEFAULT_AGENTS_FILENAME } from "./workspace-bootstrap-policy-D7EJ00Ub.mjs";
import { i as getAgentWorkspaceAccess } from "./workspace-access-CnjZBg1i.mjs";
import { a as getWorkspaceFileSourceRelativePath, c as workspaceFilesShareSourceIdentity, i as createLoadedWorkspaceBootstrapFile, o as readWorkspaceFileWithGuards } from "./workspace-bootstrap-publish-Djm2I6pY.mjs";
import { c as loadWorkspaceBootstrapFiles, o as isWorkspaceSetupCompleted, r as filterBootstrapFilesForSession } from "./workspace-DLlXz3VE.mjs";
import { r as isMemoryOriginEligibleForAutomaticInjection } from "./types-Bo5s7TN4.mjs";
import { n as classifyActiveMemoryWorkspacePaths } from "./memory-runtime-C3z9zu-7.mjs";
import { r as buildBootstrapContextForFiles } from "./bootstrap-BoYamcpL.mjs";
import path from "node:path";
//#region src/agents/workspace-personal-bootstrap.ts
/** Optional personal overlay; the caller supplies the session-selected human profile. */
async function loadPersonalUserBootstrapFile(e, t, n) {
if (!t) return;
const r = isUserProfileCatalogReady() ? void 0 : await prepareUserProfileCatalog();
try {
if (!hasMultipleSessionSharingIdentities()) return;
const r = readUserProfileIdentity(t)?.profileId;
if (!r || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(r)) return;
const i = resolveUserPath(e);
const a = path.join(i, "users", r, DEFAULT_USER_FILENAME);
const o = await readWorkspaceFileWithGuards({
filePath: a,
workspaceDir: i,
rejectAliases: true
});
if (!o.ok) {
if (!isRootFileMissingFailure(o)) n?.("Personal USER.md could not be read safely; using shared defaults.");
return;
}
if (!hasMultipleSessionSharingIdentities() || readUserProfileIdentity(t)?.profileId !== r) return;
const s = createLoadedWorkspaceBootstrapFile(DEFAULT_USER_FILENAME, a, o, true);
s.origin = {
kind: "personal",
rootPath: path.dirname(a)
};
return s;
} finally {
r?.release();
}
}
//#endregion
//#region src/agents/bootstrap-files.ts
const CONTINUATION_SCAN_MAX_RECORDS = 500;
const FULL_BOOTSTRAP_COMPLETED_CUSTOM_TYPE = "openclaw:bootstrap-context:full";
const BOOTSTRAP_WARNING_DEDUPE_LIMIT = 1024;
const seenBootstrapWarnings = /* @__PURE__ */ new Set();
/** Resolves the effective bootstrap injection mode for a session agent. */
function resolveContextInjectionMode(e, t) {
const n = e && t ? resolveAgentConfig(e, t)?.contextInjection : void 0;
if (n === "always" || n === "continuation-skip" || n === "never") return n;
return e?.agents?.defaults?.contextInjection ?? "always";
}
/** Checks the active SQLite transcript branch for a valid full-bootstrap marker. */
async function hasCompletedBootstrapTurn(e) {
const { agentId: t, sessionId: n, sessionKey: r, storePath: i } = e ?? {};
if (!t || !n || !r || !i) return false;
try {
const e = prepareSessionTranscriptHydration({
agentId: t,
sessionId: n,
sessionKey: r,
storePath: i
});
const a = await e.readRecentActiveEvents(CONTINUATION_SCAN_MAX_RECORDS);
e.assertCurrent();
for (const e of a.toReversed()) {
const t = e;
if (t?.type === "compaction" || t?.type === "reset") return false;
if (t?.type === "custom" && t.customType === "openclaw:bootstrap-context:full") return true;
}
return false;
} catch {
return false;
}
}
/** Builds a session-scoped warning sink that dedupes repeated bootstrap warnings. */
function makeBootstrapWarn(e) {
const t = e.warn;
if (!t) return;
const n = e.workspaceDir ?? "";
return (r, i) => {
const a = i ?? `${n}\u0000${e.sessionLabel}\u0000${r}`;
if (!rememberBoundedKey(seenBootstrapWarnings, a, BOOTSTRAP_WARNING_DEDUPE_LIMIT)) return;
t(`${r} (sessionKey=${e.sessionLabel})`);
};
}
function filterCompletedWorkspaceBootstrapFile(e, t, n) {
if (!t) return e;
const r = resolveUserPath(n);
const i = path.join(r, DEFAULT_BOOTSTRAP_FILENAME);
return e.filter((e) => {
if (e.name !== "BOOTSTRAP.md") return true;
const t = normalizeOptionalString(e.path);
if (!t) return true;
return resolveWorkspaceBootstrapPath(r, t) !== i;
});
}
async function isWorkspaceSetupCompletedForContext(e, t = false) {
try {
return await isWorkspaceSetupCompleted(e, t ? { readOnly: true } : {});
} catch {
return false;
}
}
async function resolveIneligibleAutomaticMemoryFiles(e) {
const t = e.files.filter((e) => !e.missing && (e.name === DEFAULT_MEMORY_FILENAME || e.name === "USER.md"));
if (t.length === 0 || !e.config) return [];
let n;
try {
n = e.agentId ?? resolveDefaultAgentId(e.config);
} catch (n) {
e.warn?.(`excluding automatic memory context: ${String(n)}`);
return t;
}
const r = t.map((t) => path.relative(resolveUserPath(e.workspaceDir), t.path).replaceAll(path.sep, "/"));
let i;
try {
const a = getAgentWorkspaceAccess(e.workspaceDir);
i = await classifyActiveMemoryWorkspacePaths({
cfg: e.config,
agentId: n,
workspaceDir: e.workspaceDir,
relativePaths: r,
...a ? { readSources: t.map((e, t) => ({
relativePath: r[t],
canonicalRelativePath: getWorkspaceFileSourceRelativePath(e)
})) } : {}
});
if (a && getAgentWorkspaceAccess(e.workspaceDir) !== a) throw new Error("Workspace access changed during memory classification");
} catch (n) {
e.warn?.(`excluding automatic memory context: ${String(n)}`);
return t;
}
if (i.status === "unavailable") return [];
if (i.status === "unsupported") {
e.warn?.("excluding automatic memory context: selected memory runtime does not support provenance classification");
return t;
}
const a = new Map(i.classifications.map((e) => [e.relativePath, e.originClass]));
return t.filter((e, t) => !isMemoryOriginEligibleForAutomaticInjection(a.get(r[t])));
}
/** Prepare the same bounded workspace facts without invoking run-owned bootstrap hooks. */
async function resolveBootstrapFilesForPreparation(e) {
return resolveBootstrapFiles({
...e,
readOnlyState: true
}, "none");
}
async function resolveBootstrapFilesForRun(e) {
const t = await resolveBootstrapFiles(e, "registered");
const n = e.executionWorkspaceDir && resolveUserPath(e.executionWorkspaceDir);
if (n && n !== resolveUserPath(e.workspaceDir)) {
const r = path.join(n, DEFAULT_AGENTS_FILENAME);
for (const i of await resolveBootstrapFiles({
...e,
workspaceDir: n
}, "registered")) if (i.name === "AGENTS.md" && !i.missing && path.resolve(i.path) === r) {
i.origin = {
kind: "execution-project",
rootPath: n
};
t.push(i);
}
}
return t;
}
async function resolveBootstrapFiles(e, t) {
const n = getAgentWorkspaceAccess(e.workspaceDir);
const r = {
sessionKey: e.sessionKey ?? e.sessionId,
chatType: e.chatType,
workspaceDir: e.workspaceDir
};
const i = await isWorkspaceSetupCompletedForContext(e.workspaceDir, e.readOnlyState);
const a = await loadWorkspaceBootstrapFiles(e.workspaceDir);
for (const t of a) t.origin = {
kind: "agent-workspace",
rootPath: resolveUserPath(e.workspaceDir)
};
const o = await loadPersonalUserBootstrapFile(e.workspaceDir, e.bootstrapUserProfileId, e.warn);
const s = a.findIndex((e) => e.name === DEFAULT_USER_FILENAME);
if (o) a.splice(s < 0 ? a.length : s + 1, 0, o);
const c = await resolveIneligibleAutomaticMemoryFiles({
files: a,
workspaceDir: e.workspaceDir,
config: e.config,
agentId: e.agentId,
warn: e.warn
});
const l = a.find((e) => e.name === DEFAULT_MEMORY_FILENAME && !e.missing);
const u = l && filterBootstrapFilesForSession([l], r).length === 0 ? l : void 0;
const d = [...u ? [u] : [], ...c];
const f = filterCompletedWorkspaceBootstrapFile(filterBootstrapFilesForSession(a, r).filter((e) => !c.some((t) => workspaceFilesShareSourceIdentity(e, t))), i, e.workspaceDir);
const p = e.contextMode === "lightweight" ? [] : f;
let m = p;
if (t === "registered") {
const t = e.sessionKey ?? e.sessionId ?? "unknown";
const n = e.agentId ?? (e.sessionKey ? resolveAgentIdFromSessionKey(e.sessionKey) : void 0);
const r = {
workspaceDir: e.workspaceDir,
bootstrapFiles: p,
cfg: e.config,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
agentId: n
};
const i = createInternalHookEvent("agent", "bootstrap", t, r);
await triggerInternalHook(i);
const a = i.context.bootstrapFiles;
m = Array.isArray(a) ? a : p;
}
const h = typeof t === "object" ? [...m, ...t.projected] : m;
const g = filterBootstrapFilesForSession(h, r);
const _ = filterCompletedWorkspaceBootstrapFile(d.length === 0 ? g : g.filter((e) => !d.some((t) => {
if (workspaceFilesShareSourceIdentity(e, t)) return true;
const n = normalizeOptionalString(e.path);
const r = normalizeOptionalString(t.path);
return Boolean(n && r && path.resolve(n) === path.resolve(r));
})), i, e.workspaceDir);
if (getAgentWorkspaceAccess(e.workspaceDir) !== n) throw new Error("Workspace access changed while preparing bootstrap context");
const { workspaceDir: v, warn: y } = e;
const b = resolveUserPath(v);
const x = /* @__PURE__ */ new Set();
const S = [];
for (const e of _) {
const t = normalizeOptionalString(e.path) ?? "";
if (!t) {
y?.(`skipping bootstrap file "${e.name}" — missing or invalid "path" field (hook may have used "filePath" instead)`);
continue;
}
const n = resolveWorkspaceBootstrapPath(b, t);
const r = path.normalize(path.relative(b, n));
if (x.has(r)) continue;
x.add(r);
S.push({
...e,
path: n
});
}
return S;
}
/** Resolves both raw bootstrap metadata and bounded context files for a run. */
async function resolveBootstrapContextForRun(e) {
const t = await resolveBootstrapFilesForRun(e);
return {
bootstrapFiles: t,
contextFiles: buildBootstrapContextForFiles(t, e)
};
}
/** Applies declared additions through the normal bootstrap filters and budgets. */
async function resolveBootstrapContextWithProjectedHookFiles(e, t) {
const n = await resolveBootstrapFiles({
...e,
readOnlyState: true
}, { projected: t });
return {
bootstrapFiles: n,
contextFiles: buildBootstrapContextForFiles(n, e)
};
}
//#endregion
export { resolveBootstrapContextWithProjectedHookFiles as a, resolveContextInjectionMode as c, resolveBootstrapContextForRun as i, hasCompletedBootstrapTurn as n, resolveBootstrapFilesForPreparation as o, makeBootstrapWarn as r, resolveBootstrapFilesForRun as s, FULL_BOOTSTRAP_COMPLETED_CUSTOM_TYPE as t };