openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,299 lines (1,298 loc) • 42 kB
JavaScript
import fsPromises from "node:fs/promises";
import { hasNodeErrorCode as hasErrnoCode, isNodeError as isErrno } from "@openclaw/fs-safe/path";
import path from "node:path";
import fs from "node:fs";
import { isDeepStrictEqual } from "node:util";
import "@openclaw/fs-safe/root";
import { sameFileIdentity } from "@openclaw/fs-safe/advanced";
import "@openclaw/fs-safe/durability";
import { FsSafeError } from "@openclaw/fs-safe/errors";
import { createHash, randomUUID } from "node:crypto";
import "@openclaw/fs-safe/config";
//#region packages/normalization-core/src/record-coerce.ts
/** Type guard for non-array object records at browser-safe boundaries. */
function isRecord(e) {
return e !== null && typeof e === "object" && !Array.isArray(e);
}
function isStringArray(e) {
return Array.isArray(e) && e.every((e) => typeof e === "string");
}
/** Returns a non-array record or undefined. */
function asOptionalRecord(e) {
return isRecord(e) ? e : void 0;
}
/** Returns a non-array record or null. */
function asNullableRecord(e) {
return isRecord(e) ? e : null;
}
/** Returns any object-backed record, including arrays, or undefined. */
function asOptionalObjectRecord(e) {
return e && typeof e === "object" ? e : void 0;
}
//#endregion
//#region packages/normalization-core/src/string-coerce.ts
/** Trims string input and returns null for non-strings or empty strings. */
function normalizeNullableString(e) {
if (typeof e !== "string") return null;
const t = e.trim();
return t ? t : null;
}
/** Trims string input and returns undefined for non-strings or empty strings. */
function normalizeOptionalString(e) {
return normalizeNullableString(e) ?? void 0;
}
/** Requires non-blank string input while preserving its original whitespace. */
function readNonBlankString(e) {
return typeof e === "string" && e.trim() ? e : void 0;
}
/** Lowercases a normalized optional string. */
function normalizeOptionalLowercaseString(e) {
return normalizeOptionalString(e)?.toLowerCase();
}
/** Lowercases a normalized string or returns an empty string when absent. */
function normalizeLowercaseStringOrEmpty(e) {
return normalizeOptionalLowercaseString(e) ?? "";
}
//#endregion
//#region packages/normalization-core/src/string-normalization.ts
/** Coerces entries to strings, trims them, and drops empty results. */
function normalizeStringEntries(e) {
return (e ?? []).map((e) => String(e).trim()).filter(Boolean);
}
/** Normalizes string entries and lowercases each retained value. */
function normalizeStringEntriesLower(e) {
return normalizeStringEntries(e).map((e) => e.toLowerCase());
}
/** Returns first-seen unique values while preserving insertion order. */
function uniqueValues(e) {
return [...new Set(e)];
}
/** Returns first-seen unique strings while preserving insertion order. */
function uniqueStrings(e) {
return uniqueValues(e);
}
/** Normalizes entries, removes duplicates, and preserves first-seen order. */
function normalizeUniqueStringEntries(e) {
return uniqueStrings(normalizeStringEntries(e ? [...e] : void 0));
}
/** Lowercases normalized entries, removes empties/duplicates, and preserves first-seen order. */
function normalizeUniqueStringEntriesLower(e) {
return uniqueStrings(normalizeStringEntriesLower(e ? [...e] : void 0));
}
//#endregion
//#region src/channels/plugins/dm-access.ts
function allowFromListsMatch(e, t) {
if (!Array.isArray(e) || !Array.isArray(t)) return false;
const n = normalizeStringEntries(e);
const r = normalizeStringEntries(t);
if (n.length !== r.length) return false;
return n.every((e, t) => e === r[t]);
}
function normalizeLegacyDmAliases(e) {
const t = asNullableRecord(e.entry.dm);
if (!t) return {
entry: e.entry,
changed: false
};
const n = { ...t };
let r = { ...e.entry };
let i = false;
for (const [t, a] of [["dmPolicy", "policy"], ["allowFrom", "allowFrom"]]) {
if (t === "allowFrom" && e.promoteAllowFrom === false) continue;
const o = r[t];
const s = n[a];
if (s === void 0) continue;
if (o === void 0) {
r[t] = s;
e.changes.push(`Moved ${e.pathPrefix}.dm.${a} → ${e.pathPrefix}.${t}.`);
} else if (t === "dmPolicy" ? o === s : allowFromListsMatch(o, s)) e.changes.push(`Removed ${e.pathPrefix}.dm.${a} (${t} already set).`);
else continue;
delete n[a];
i = true;
}
if (!i) return {
entry: e.entry,
changed: false
};
if (Object.keys(n).length === 0) {
const { dm: t, ...n } = r;
r = n;
e.changes.push(`Removed empty ${e.pathPrefix}.dm after migration.`);
} else r = {
...r,
dm: n
};
return {
entry: r,
changed: true
};
}
//#endregion
//#region src/config/channel-config-normalization.ts
/** Applies one channel-specific doctor migration to every object-shaped account. */
function normalizeChannelAccounts(e) {
const t = asNullableRecord(e.entry.accounts);
if (!t) return {
entry: e.entry,
changed: false
};
let n = false;
const r = { ...t };
for (const [i, a] of Object.entries(t)) {
const t = asNullableRecord(a);
if (!t) continue;
const o = e.normalizeAccount({
account: t,
accountId: i,
pathPrefix: `${e.pathPrefix}.accounts.${i}`,
changes: e.changes
});
if (o.changed) {
r[i] = o.entry;
n = true;
}
}
return n ? {
entry: {
...e.entry,
accounts: r
},
changed: true
} : {
entry: e.entry,
changed: false
};
}
/** Applies the same channel-specific doctor migration at root and account scope. */
function normalizeChannelConfigEntries(e) {
const t = e.changes ?? [];
const n = e.cfg.channels;
const r = asNullableRecord(n?.[e.channelId]);
if (!r) return {
config: e.cfg,
changes: t
};
const i = `channels.${e.channelId}`;
const a = e.normalizeEntry({
entry: r,
pathPrefix: i,
changes: t
});
const o = normalizeChannelAccounts({
entry: a.entry,
pathPrefix: i,
changes: t,
normalizeAccount: (t) => e.normalizeEntry({
entry: t.account,
accountId: t.accountId,
pathPrefix: t.pathPrefix,
changes: t.changes
})
});
if (!a.changed && !o.changed) return {
config: e.cfg,
changes: t
};
return {
config: {
...e.cfg,
channels: {
...n,
[e.channelId]: o.entry
}
},
changes: t
};
}
//#endregion
//#region src/infra/prototype-keys.ts
const BLOCKED_OBJECT_KEYS = /* @__PURE__ */ new Set([
"__proto__",
"prototype",
"constructor"
]);
/** Return true when assigning `key` could mutate an object prototype. */
function isBlockedObjectKey(e) {
return BLOCKED_OBJECT_KEYS.has(e);
}
//#endregion
//#region src/config/merge-missing.ts
/** Fill undefined fields in place; newly assigned values retain their source references. */
function mergeMissing(e, t) {
for (const [n, r] of Object.entries(t)) {
if (r === void 0 || isBlockedObjectKey(n)) continue;
const t = e[n];
if (t === void 0) {
e[n] = r;
continue;
}
if (isRecord(t) && isRecord(r)) mergeMissing(t, r);
}
}
//#endregion
//#region src/config/channel-compat-normalization.ts
function parseAliasStreamingMode(e) {
if (typeof e !== "string") return null;
const t = e.trim().toLowerCase();
return t === "off" || t === "partial" || t === "block" || t === "progress" ? t : null;
}
/**
* Doctor-only stream mode resolution across nested and legacy alias keys.
*
* Runtime helpers no longer read `streamMode`, so doctor contracts use this to
* preserve legacy intent (nested mode > scalar string > streamMode > scalar
* boolean) while migrating flat aliases into `streaming.mode`.
*/
function resolveLegacyAliasStreamingMode(e, t) {
const n = asNullableRecord(e.streaming)?.mode;
const r = parseAliasStreamingMode(n ?? e.streaming) ?? parseAliasStreamingMode(e.streamMode);
if (r) return r;
if (typeof e.streaming === "boolean") return e.streaming ? "partial" : "off";
return t;
}
/** Checks whether any account entry still carries a channel-specific legacy alias. */
function hasLegacyAccountStreamingAliases(e, t) {
return Object.values(asNullableRecord(e) ?? {}).some((e) => t(e));
}
/**
* Moves legacy flat streaming aliases into the nested `streaming` config shape.
*
* Existing nested values win over legacy aliases, matching doctor migration rules
* that preserve explicit modern config while removing stale compatibility keys.
*/
function normalizeLegacyStreamingAliases(e) {
const t = e.entry.streaming;
const n = e.entry.streamMode !== void 0;
const r = e.entry.chunkMode !== void 0 || e.entry.blockStreaming !== void 0 || e.entry.blockStreamingCoalesce !== void 0 || e.includePreviewChunk === true && e.entry.draftChunk !== void 0 || e.entry.nativeStreaming !== void 0;
if (!(n || typeof t === "boolean" || typeof t === "string" || r)) return {
entry: e.entry,
changed: false
};
const i = { ...e.entry };
let a = false;
const o = { ...asNullableRecord(i.streaming) };
const s = { ...asNullableRecord(o.block) };
const c = { ...asNullableRecord(o.preview) };
let l = false;
if ((n || typeof t === "boolean" || typeof t === "string") && o.mode === void 0) {
o.mode = e.resolvedMode;
l = n;
const r = n ? "streamMode" : `streaming (${typeof t === "boolean" ? "boolean" : "scalar"})`;
e.changes.push(`Moved ${e.pathPrefix}.${r} → ${e.pathPrefix}.streaming.mode (${e.resolvedMode}).`);
a = true;
}
if (n) {
if (!l) e.changes.push(`Removed ${e.pathPrefix}.streamMode (${e.pathPrefix}.streaming.mode already set).`);
delete i.streamMode;
a = true;
}
const moveOrRemoveAlias = (t, n, r, o, s = i[t]) => {
if (i[t] === void 0) return;
const c = `${e.pathPrefix}.streaming.${o}`;
if (n[r] === void 0) {
n[r] = s;
e.changes.push(`Moved ${e.pathPrefix}.${t} → ${c}.`);
} else e.changes.push(`Removed ${e.pathPrefix}.${t} (${c} already set).`);
delete i[t];
a = true;
};
moveOrRemoveAlias("chunkMode", o, "chunkMode", "chunkMode");
moveOrRemoveAlias("blockStreaming", s, "enabled", "block.enabled");
if (e.includePreviewChunk === true) moveOrRemoveAlias("draftChunk", c, "chunk", "preview.chunk");
moveOrRemoveAlias("blockStreamingCoalesce", s, "coalesce", "block.coalesce");
if (i.nativeStreaming !== void 0 && e.resolvedNativeTransport !== void 0) moveOrRemoveAlias("nativeStreaming", o, "nativeTransport", "nativeTransport", e.resolvedNativeTransport);
else if (typeof t === "boolean" && o.nativeTransport === void 0 && e.resolvedNativeTransport !== void 0) {
o.nativeTransport = e.resolvedNativeTransport;
e.changes.push(`Moved ${e.pathPrefix}.streaming (boolean) → ${e.pathPrefix}.streaming.nativeTransport.`);
a = true;
}
if (a && t === void 0 && o.mode === void 0 && e.aliasOnlyMode !== void 0) {
o.mode = e.aliasOnlyMode;
e.changes.push(`Set ${e.pathPrefix}.streaming.mode (${e.aliasOnlyMode}) to keep the previous default while migrating flat streaming keys.`);
}
if (Object.keys(c).length > 0) o.preview = c;
if (Object.keys(s).length > 0) o.block = s;
i.streaming = o;
return {
entry: i,
changed: a
};
}
/** Capture flat inheritance before root migration removes its aliases. */
function buildRootFlatDeliverySeed(e, t) {
const n = {};
if (e.chunkMode !== void 0) n.chunkMode = e.chunkMode;
const r = {};
if (e.blockStreaming !== void 0) r.enabled = e.blockStreaming;
if (e.blockStreamingCoalesce !== void 0) r.coalesce = e.blockStreamingCoalesce;
if (Object.keys(r).length > 0) n.block = r;
if (t === true && e.draftChunk !== void 0) n.preview = { chunk: e.draftChunk };
return Object.keys(n).length > 0 ? n : null;
}
/**
* Preserve pre-migration precedence: merged-entry mode/block.enabled/preview.chunk
* prefer root nested values, chunkMode prefers the account, and coalesce merges
* account fields over root fields. Preview chunks remain atomic. Materialization
* freezes inheritance at fix time so replacing the root object loses no settings.
*/
function seedMaterializedAccountStreaming(e) {
const { created: t } = e;
const n = e.rootNestedBefore ?? {};
const r = e.rootFlat ?? {};
const i = structuredClone(n);
for (const n of [
t,
r,
e.rootAfter
]) mergeMissing(i, structuredClone(n));
if (t.chunkMode !== void 0) i.chunkMode = t.chunkMode;
const a = asNullableRecord(asNullableRecord(t.block)?.coalesce);
if (a) {
const e = asNullableRecord(asNullableRecord(n.block)?.coalesce) ?? asNullableRecord(asNullableRecord(r.block)?.coalesce);
i.block = {
...asNullableRecord(i.block),
coalesce: {
...structuredClone(e ?? {}),
...structuredClone(a)
}
};
}
const o = asNullableRecord(n.preview)?.chunk;
if (o !== void 0 && asNullableRecord(t.preview)?.chunk !== void 0) i.preview = {
...asNullableRecord(i.preview),
chunk: structuredClone(o)
};
return i;
}
/**
* Runs generic channel doctor alias migration for the root entry and accounts.
*
* Channel plugins provide streaming resolution and optional account-specific
* migrations so core can keep one compatibility path for all channel shapes.
*/
function normalizeLegacyChannelAliases(e) {
let t = e.entry;
let n = false;
const r = e.seedAccountStreamingFromRoot === true ? buildRootFlatDeliverySeed(e.entry, e.resolveStreamingOptions(e.entry).includePreviewChunk) : null;
const i = e.seedAccountStreamingFromRoot === true ? asNullableRecord(e.entry.streaming) : null;
if (e.normalizeDm === true) {
const r = normalizeLegacyDmAliases({
entry: t,
pathPrefix: e.pathPrefix,
changes: e.changes,
promoteAllowFrom: e.rootDmPromoteAllowFrom
});
t = r.entry;
n = r.changed;
}
const a = normalizeLegacyStreamingAliases({
entry: t,
pathPrefix: e.pathPrefix,
changes: e.changes,
...e.resolveStreamingOptions(t)
});
t = a.entry;
n = n || a.changed;
const o = asNullableRecord(t.streaming);
const s = normalizeChannelAccounts({
entry: t,
pathPrefix: e.pathPrefix,
changes: e.changes,
normalizeAccount: ({ account: t, accountId: n, pathPrefix: a }) => {
let s = t;
let c = false;
if (e.normalizeAccountDm === true) {
const t = normalizeLegacyDmAliases({
entry: s,
pathPrefix: a,
changes: e.changes
});
s = t.entry;
c = t.changed;
}
const l = { ...e.resolveStreamingOptions(s) };
if (o) delete l.aliasOnlyMode;
const u = s.streaming;
const d = normalizeLegacyStreamingAliases({
entry: s,
pathPrefix: a,
changes: e.changes,
...l
});
s = d.entry;
c = c || d.changed;
if (e.seedAccountStreamingFromRoot === true && d.changed && u === void 0 && o) {
const t = asNullableRecord(s.streaming);
if (t) {
const n = seedMaterializedAccountStreaming({
created: t,
rootNestedBefore: i,
rootFlat: r,
rootAfter: o
});
if (JSON.stringify(n) !== JSON.stringify(t)) {
s = {
...s,
streaming: n
};
e.changes.push(`Copied ${e.pathPrefix}.streaming into ${a}.streaming to keep inherited settings while migrating flat streaming keys.`);
}
}
} else if (r && u !== void 0) {
const t = asNullableRecord(s.streaming);
if (t) {
let n = t;
const setNestedSlot = (e, t, r) => {
n = {
...n,
[e]: {
...asNullableRecord(n[e]),
[t]: r
}
};
};
if (r.chunkMode !== void 0 && n.chunkMode === void 0) n = {
...n,
chunkMode: r.chunkMode
};
const i = asNullableRecord(r.block);
const o = i?.enabled;
if (o !== void 0 && asNullableRecord(n.block)?.enabled === void 0) setNestedSlot("block", "enabled", o);
const l = asNullableRecord(i?.coalesce);
if (l) {
const e = asNullableRecord(asNullableRecord(n.block)?.coalesce);
const t = {
...structuredClone(l),
...structuredClone(e ?? {})
};
if (JSON.stringify(t) !== JSON.stringify(e ?? {})) setNestedSlot("block", "coalesce", t);
}
const u = asNullableRecord(r.preview)?.chunk;
if (u !== void 0 && asNullableRecord(n.preview)?.chunk === void 0) setNestedSlot("preview", "chunk", structuredClone(u));
if (n !== t) {
s = {
...s,
streaming: n
};
c = true;
e.changes.push(`Copied flat ${e.pathPrefix} delivery keys into ${a}.streaming to keep inherited settings while migrating flat streaming keys.`);
}
}
}
const f = e.normalizeAccountExtra?.({
account: s,
accountId: n,
pathPrefix: a,
changes: e.changes
});
if (f) {
s = f.entry;
c = c || f.changed;
}
return {
entry: s,
changed: c
};
}
});
return {
entry: s.entry,
changed: n || s.changed
};
}
/** Detects legacy streaming aliases on one channel or account config entry. */
function hasLegacyStreamingAliases(e, t) {
const n = asNullableRecord(e);
if (!n) return false;
return n.streamMode !== void 0 || typeof n.streaming === "boolean" || typeof n.streaming === "string" || n.chunkMode !== void 0 || n.blockStreaming !== void 0 || n.blockStreamingCoalesce !== void 0 || t?.includePreviewChunk === true && n.draftChunk !== void 0 || t?.includeNativeTransport === true && n.nativeStreaming !== void 0;
}
//#endregion
//#region src/infra/errno.ts
/** Classifies missing filesystem paths across Node and fs-safe boundaries. */
function isMissingPathError(e) {
return hasErrnoCode(e, "ENOENT") || hasErrnoCode(e, "ENOTDIR") || hasErrnoCode(e, "not-found");
}
//#endregion
//#region src/infra/utf8-input.ts
const createUtf8Decoder = () => new TextDecoder("utf-8", {
fatal: true,
ignoreBOM: true
});
const inputDecoder = createUtf8Decoder();
//#endregion
//#region src/infra/path-existence.ts
/** Resolve an absolute path through a readable ancestor; this is not a containment check. */
function realpathExistingAncestorSync(e) {
const t = [];
let n = e;
while (true) try {
return path.join(fs.realpathSync.native(n), ...t.toReversed());
} catch {
const e = path.dirname(n);
if (e === n) return;
t.push(path.basename(n));
n = e;
}
}
/** Async counterpart for runtime identity capture, including unreadable intermediate paths. */
async function realpathExistingAncestor(e) {
const t = [];
let n = e;
while (true) try {
return path.join(await fsPromises.realpath(n), ...t.toReversed());
} catch {
const e = path.dirname(n);
if (e === n) return;
t.push(path.basename(n));
n = e;
}
}
function canAccessSync(e, t) {
try {
fs.accessSync(e, t);
return true;
} catch {
return false;
}
}
//#endregion
//#region src/infra/plain-object.ts
/**
* Config merge/patch uses the object tag, not prototype identity: class instances
* and custom prototypes remain accepted, while Date/Map/Set values are excluded.
*/
function isPlainObject(e) {
return typeof e === "object" && e !== null && !Array.isArray(e) && Object.prototype.toString.call(e) === "[object Object]";
}
//#endregion
//#region src/infra/deep-merge.ts
function sanitizePlainObject(e) {
const t = {};
for (const [n, r] of Object.entries(e)) {
if (isBlockedObjectKey(n)) continue;
t[n] = isPlainObject(r) ? sanitizePlainObject(r) : r;
}
return t;
}
/** Merge plain objects while preserving OpenClaw's null, undefined, and array policies. */
function mergeDeep(e, t, n = {}) {
const r = n.arrays ?? "replace";
const i = n.undefinedValues ?? "skip";
if (Array.isArray(e) && Array.isArray(t)) return r === "concat" ? [...e, ...t] : t;
if (!isPlainObject(e) || !isPlainObject(t)) return t === void 0 && i === "skip" ? e : t;
const a = sanitizePlainObject(e);
for (const [e, o] of Object.entries(t)) {
if (isBlockedObjectKey(e) || o === void 0 && i === "skip") continue;
const t = a[e];
if (isPlainObject(o)) a[e] = isPlainObject(t) ? mergeDeep(t, o, n) : sanitizePlainObject(o);
else if (r === "concat" && Array.isArray(t) && Array.isArray(o)) a[e] = [...t, ...o];
else a[e] = o;
}
return a;
}
//#endregion
//#region src/shared/global-singleton.ts
/**
* Process-local singleton helpers for registries, caches, and SDK-visible shared state.
* Keys must be symbols so unrelated modules cannot collide on `globalThis` property names.
*/
const GLOBAL_SINGLETON_RESETS_KEY = Symbol.for("openclaw.globalSingletonLifecycleResets");
function resolveGlobalSingletonResetRegistry() {
const e = globalThis;
const t = e[GLOBAL_SINGLETON_RESETS_KEY];
if (t instanceof Map) return t;
const n = /* @__PURE__ */ new Map();
e[GLOBAL_SINGLETON_RESETS_KEY] = n;
return n;
}
/** Observe an existing owner's state without initializing it or registering cleanup. */
function readGlobalSingleton(e) {
const t = globalThis;
return Object.hasOwn(t, e) ? t[e] : void 0;
}
/** Resolves a process-local singleton for caches and registries that tolerate helper lookup. */
function resolveGlobalSingleton(e, t, n, r = "close-and-restart") {
const i = globalThis;
let a;
if (Object.hasOwn(i, e)) a = i[e];
else {
a = t();
i[e] = a;
}
if (n) resolveGlobalSingletonResetRegistry().set(e, {
lifecycle: r,
reset: () => n(a)
});
return a;
}
/** Resolves a process-local Map singleton for keyed caches backed by globalThis. */
function resolveGlobalMap(e, t, n) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Map(), typeof t === "string" ? (e) => e.clear() : t, typeof t === "string" ? t : n);
}
/** Resolves a lifecycle-owned process-local Set singleton. */
function resolveGlobalSet(e, t) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Set(), (e) => e.clear(), t);
}
//#endregion
//#region src/plugins/plugin-metadata-snapshot-readers.ts
const readerLifetime = resolveGlobalSingleton(Symbol.for("openclaw.pluginMetadataSnapshotReaderCustody"), () => ({ owners: 0 }));
const readerKeys = [
"adoptCurrentPluginMetadataSnapshotIfAbsent",
"getCurrentPluginMetadataSnapshot",
"resolvePluginMetadataSnapshot",
"loadPluginMetadataSnapshot",
"listOpenClawPluginManifestMetadata",
"listKnownProviderAuthEnvVarNamesCore"
];
const snapshotReaderSlot = resolveGlobalSingleton(Symbol.for("openclaw.pluginMetadataSnapshotReaders"), () => ({}), (e) => {
if (!readerLifetime.owners) for (const t of readerKeys) delete e[t];
}, "close-only");
//#endregion
//#region packages/normalization-core/src/result.ts
/** Create a successful {@link Result}. */
function ok(e) {
return {
ok: true,
value: e
};
}
/** Create a failed {@link Result}. */
function err(e) {
return {
ok: false,
error: e
};
}
//#endregion
//#region packages/normalization-core/src/agent-id.ts
const DEFAULT_AGENT_ID = "main";
const VALID_ID_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
const INVALID_CHARS_RE = /[^a-z0-9_-]+/g;
const LEADING_DASH_RE = /^-+/;
const TRAILING_DASH_RE = /-+$/;
/** Normalizes an OpenClaw agent id to its filesystem-safe canonical form. */
function normalizeAgentId(e) {
const t = normalizeAgentIdStrict(e);
return t.ok ? t.value : DEFAULT_AGENT_ID;
}
/** Normalizes an explicitly supplied agent id without falling back to the default agent. */
function normalizeAgentIdStrict(e) {
const t = (e ?? "").trim();
const n = t.toLowerCase();
if (VALID_ID_RE.test(t)) return ok(n);
const r = n.replace(INVALID_CHARS_RE, "-").replace(LEADING_DASH_RE, "").replace(TRAILING_DASH_RE, "").slice(0, 64);
return r ? ok(r) : err("unrepresentable");
}
//#endregion
//#region src/routing/account-id.ts
const DEFAULT_ACCOUNT_ID = "default";
function normalizeAccountId(e) {
return normalizeOptionalAccountId(e) ?? "default";
}
function normalizeOptionalAccountId(e) {
const t = (e ?? "").trim();
if (!t) return;
const n = normalizeAgentIdStrict(t);
return n.ok && !isBlockedObjectKey(n.value) ? n.value : void 0;
}
//#endregion
//#region src/routing/account-lookup.ts
function resolveChannelAccountKey(e, t, n, r, i, a) {
return resolveAccountKey(e, t, r, i, {
...a,
channelId: n
});
}
function resolveNormalizedAccountEntry(e, t, n, r) {
const i = resolveAccountKey(e, t, n, r);
return i === void 0 ? void 0 : e?.[i];
}
/** Select the stored spelling once for account readers and writers; exact keys win. */
function resolveAccountKey(e, t, n, r, i) {
const a = r ?? (i?.channelId ? snapshotReaderSlot.getCurrentPluginMetadataSnapshot?.({
allowScopedSnapshot: true,
allowWorkspaceScopedSnapshot: true
})?.owners.channelAccountKeyPolicies?.get(i.channelId) : void 0);
const o = a ? normalizeAccountId : n;
const s = o ?? normalizeLowercaseStringOrEmpty;
if (i?.allowMissing && (isBlockedObjectKey(normalizeLowercaseStringOrEmpty(t)) || isBlockedObjectKey(s(t)))) throw new Error(`Account id "${t}" is reserved. Choose a different account id.`);
const c = a ? s(t) : t;
const l = i?.allowMissing ? c : void 0;
if (!e || typeof e !== "object") return l;
if (Object.hasOwn(e, c) && (!o || !isBlockedObjectKey(c))) return c;
const u = s(c);
const d = normalizeLowercaseStringOrEmpty(c);
let f;
for (const t of Object.keys(e)) {
if (o && isBlockedObjectKey(t)) continue;
if (a && normalizeLowercaseStringOrEmpty(t) === d) return t;
const n = s(t);
if ((!o || Boolean(normalizeOptionalAccountId(t)) && !isBlockedObjectKey(n)) && n === u) {
if (!a) return t;
const n = asOptionalRecord(e[t]);
if (f === void 0 && n && Object.hasOwn(n, a.canonicalAliasesRequireOwnField) && normalizeOptionalString(n[a.canonicalAliasesRequireOwnField])) f = t;
}
}
return f ?? l;
}
//#endregion
//#region src/config/channel-doctor-helpers.ts
function stripRetiredKeys(e) {
if (e.recursive && Array.isArray(e.value)) {
let t = false;
const n = e.value.map((n, r) => {
const i = stripRetiredKeys({
...e,
value: n,
pathPrefix: `${e.pathPrefix}[${r}]`
});
t = t || i.changed;
return i.value;
});
return {
value: t ? n : e.value,
changed: t
};
}
const t = asNullableRecord(e.value);
if (!t) return {
value: e.value,
changed: false
};
let n = false;
const r = {};
for (const [i, a] of Object.entries(t)) {
if (e.keys.has(i)) {
e.onRemove?.({
key: i,
pathPrefix: e.pathPrefix
});
n = true;
continue;
}
if (!e.recursive) {
r[i] = a;
continue;
}
const t = stripRetiredKeys({
...e,
value: a,
pathPrefix: `${e.pathPrefix}.${i}`
});
n = n || t.changed;
r[i] = t.value;
}
return {
value: n ? r : e.value,
changed: n
};
}
/** Removes retired keys recursively or from a channel root and its accounts. */
function stripRetiredChannelKeys(e) {
const t = e.cfg.channels;
const n = asNullableRecord(t?.[e.channelId]);
if (!n) return {
config: e.cfg,
changed: false
};
const r = `channels.${e.channelId}`;
if (e.scope === "recursive") {
const i = stripRetiredKeys({
value: n,
keys: e.keys,
pathPrefix: r,
recursive: true,
onRemove: e.onRemove
});
return i.changed ? {
config: {
...e.cfg,
channels: {
...t,
[e.channelId]: i.value
}
},
changed: true
} : {
config: e.cfg,
changed: false
};
}
const i = normalizeChannelConfigEntries({
cfg: e.cfg,
channelId: e.channelId,
normalizeEntry: (t) => {
const n = stripRetiredKeys({
value: t.entry,
keys: e.keys,
pathPrefix: t.pathPrefix,
recursive: false,
onRemove: e.onRemove
});
return {
entry: n.value,
changed: n.changed
};
}
});
return {
config: i.config,
changed: i.config !== e.cfg
};
}
/** Materializes root/default-account inheritance after aliases create streaming. */
function materializeInheritedAccountStreaming(e) {
const t = e.cfg.channels;
const n = asNullableRecord(t?.[e.channelId]);
const r = asNullableRecord(n?.accounts);
if (!n || !r) return e.cfg;
const i = asNullableRecord(n.streaming);
const a = resolveChannelAccountKey(r, "default", e.channelId, (e) => e.trim().toLowerCase());
let o = false;
const s = { ...r };
const c = Object.keys(r).toSorted((e, t) => e === a ? -1 : t === a ? 1 : e.localeCompare(t));
for (const t of c) {
if (asNullableRecord(e.accountsBefore?.[t])?.streaming !== void 0) continue;
const n = asNullableRecord(s[t]);
const r = asNullableRecord(n?.streaming);
if (!n || !r) continue;
const c = a ? asNullableRecord(asNullableRecord(s[a])?.streaming) : null;
const l = t === a ? i : c ?? i;
if (!l) continue;
const u = asNullableRecord(mergeDeep(l, r));
if (!u || isDeepStrictEqual(u, r)) continue;
s[t] = {
...n,
streaming: u
};
o = true;
const d = t !== a && a && c ? `channels.${e.channelId}.accounts.${a}.streaming` : `channels.${e.channelId}.streaming`;
e.changes.push(`Copied ${d} into channels.${e.channelId}.accounts.${t}.streaming to keep inherited settings while migrating flat streaming keys.`);
}
return o ? {
...e.cfg,
channels: {
...t,
[e.channelId]: {
...n,
accounts: s
}
}
} : e.cfg;
}
//#endregion
//#region src/config/channel-alias-migration.ts
function buildAliasRuleMessage(e) {
const { streaming: t, prefix: n } = e;
const r = t.resolveNativeTransport !== void 0;
const i = [
...t.deliveryOnly ? [] : ["streamMode", "streaming (scalar)"],
"chunkMode",
"blockStreaming",
...t.includePreviewChunk ? ["draftChunk"] : [],
"blockStreamingCoalesce",
...r ? ["nativeStreaming"] : []
];
const a = [
...t.deliveryOnly ? [] : ["mode"],
"chunkMode",
...t.includePreviewChunk ? ["preview.chunk"] : [],
"block.enabled",
"block.coalesce",
...r ? ["nativeTransport"] : []
];
const o = e.root && !t.deliveryOnly ? 2 : 1;
const s = i.map((e, t) => t < o ? `${n}.${e}` : e);
return `${`${s.slice(0, -1).join(", ")}, and ${s.at(-1)}`} are legacy; use ${n}.streaming.{${a.join(",")}}. Run "openclaw doctor --fix".`;
}
function hasLegacyDmAliases(e) {
const t = asNullableRecord(asNullableRecord(e)?.dm);
return t !== null && (Object.hasOwn(t, "policy") || Object.hasOwn(t, "allowFrom"));
}
/**
* Builds the standard channel doctor alias-migration surface from a small spec:
* detection rules (root + accounts), the per-entry matcher, and the config
* normalizer. Channels with additional migrations compose around these pieces.
*/
function defineChannelAliasMigration(e) {
const { streaming: t } = e;
const n = `channels.${e.channelId}`;
const hasLegacyAliases = (e) => {
if (t.deliveryOnly === true) {
const t = asNullableRecord(e);
return t !== null && (t.chunkMode !== void 0 || t.blockStreaming !== void 0 || t.blockStreamingCoalesce !== void 0);
}
return hasLegacyStreamingAliases(e, {
includePreviewChunk: t.includePreviewChunk,
includeNativeTransport: t.resolveNativeTransport !== void 0
});
};
const resolveStreamingOptions = (e) => ({
resolvedMode: t.resolveMode?.(e) ?? resolveLegacyAliasStreamingMode(e, t.defaultMode),
aliasOnlyMode: t.absentObjectDefault,
includePreviewChunk: t.includePreviewChunk,
resolvedNativeTransport: t.resolveNativeTransport?.(e)
});
const normalizeChannelConfig = (r) => {
const i = r.changes ?? [];
const a = r.cfg.channels;
const o = asNullableRecord(a?.[e.channelId]);
if (!o) return {
config: r.cfg,
changes: i
};
const s = e.accountStreamingInheritsDefaultAccount ? asNullableRecord(o.accounts) : null;
if (t.deliveryOnly === true && !hasLegacyAliases(o) && !hasLegacyAccountStreamingAliases(o.accounts, hasLegacyAliases) && !(e.dm?.root && hasLegacyDmAliases(o)) && !(e.dm?.accounts && hasLegacyAccountStreamingAliases(o.accounts, hasLegacyDmAliases))) return {
config: r.cfg,
changes: i
};
const c = normalizeLegacyChannelAliases({
entry: o,
pathPrefix: n,
changes: i,
normalizeDm: e.dm?.root,
rootDmPromoteAllowFrom: e.dm?.rootPromoteAllowFrom,
normalizeAccountDm: e.dm?.accounts,
seedAccountStreamingFromRoot: e.accountStreamingReplacesRoot,
resolveStreamingOptions,
normalizeAccountExtra: e.normalizeAccountExtra
});
if (!c.changed) return {
config: r.cfg,
changes: i
};
const l = {
...r.cfg,
channels: {
...a,
[e.channelId]: c.entry
}
};
return {
config: e.accountStreamingInheritsDefaultAccount ? materializeInheritedAccountStreaming({
cfg: l,
channelId: e.channelId,
accountsBefore: s,
changes: i
}) : l,
changes: i
};
};
const r = [{
path: ["channels", e.channelId],
message: buildAliasRuleMessage({
streaming: t,
prefix: n,
root: true
}),
match: hasLegacyAliases
}, {
path: [
"channels",
e.channelId,
"accounts"
],
message: buildAliasRuleMessage({
streaming: t,
prefix: `${n}.accounts.<id>`,
root: false
}),
match: (e) => hasLegacyAccountStreamingAliases(e, hasLegacyAliases)
}];
if (e.dm?.root) r.push({
path: ["channels", e.channelId],
message: `${n}.dm.policy and ${n}.dm.allowFrom are legacy; use ${n}.dmPolicy and ${n}.allowFrom. Run "openclaw doctor --fix".`,
match: hasLegacyDmAliases
});
if (e.dm?.accounts) r.push({
path: [
"channels",
e.channelId,
"accounts"
],
message: `${n}.accounts.<id>.dm.policy and dm.allowFrom are legacy; use ${n}.accounts.<id>.dmPolicy and allowFrom. Run "openclaw doctor --fix".`,
match: (e) => hasLegacyAccountStreamingAliases(e, hasLegacyDmAliases)
});
return {
legacyConfigRules: r,
hasLegacyAliases,
normalizeChannelConfig
};
}
//#endregion
//#region src/config/legacy-private-network-migration.ts
/** Detects the retired flat `allowPrivateNetwork` key before doctor migration. */
function hasLegacyFlatAllowPrivateNetworkAlias(e) {
const t = asNullableRecord(e);
return Boolean(t && Object.hasOwn(t, "allowPrivateNetwork"));
}
/** Moves flat private-network config into `network.dangerouslyAllowPrivateNetwork`. */
function migrateLegacyFlatAllowPrivateNetworkAlias(e) {
if (!hasLegacyFlatAllowPrivateNetworkAlias(e.entry)) return {
entry: e.entry,
changed: false
};
const t = e.entry.allowPrivateNetwork;
const n = asNullableRecord(e.entry.network);
const r = n ? { ...n } : {};
const i = r.dangerouslyAllowPrivateNetwork;
const a = typeof i !== "boolean" && (typeof t === "boolean" || i === void 0) ? t : i;
delete r.dangerouslyAllowPrivateNetwork;
if (a !== void 0) r.dangerouslyAllowPrivateNetwork = a;
const o = { ...e.entry };
delete o.allowPrivateNetwork;
if (Object.keys(r).length > 0) o.network = r;
else delete o.network;
e.changes.push(`Moved ${e.pathPrefix}.allowPrivateNetwork → ${e.pathPrefix}.network.dangerouslyAllowPrivateNetwork (${String(a)}).`);
return {
entry: o,
changed: true
};
}
function hasLegacyAllowPrivateNetworkInAccounts(e) {
const t = asNullableRecord(e);
return Boolean(t && Object.values(t).some(hasLegacyFlatAllowPrivateNetworkAlias));
}
/** Build doctor rules that migrate legacy private-network aliases for one channel config. */
function createLegacyPrivateNetworkDoctorContract(e) {
const t = `channels.${e.channelKey}`;
return {
legacyConfigRules: [{
path: ["channels", e.channelKey],
message: `${t}.allowPrivateNetwork is legacy; use ${t}.network.dangerouslyAllowPrivateNetwork instead. Run "openclaw doctor --fix".`,
match: hasLegacyFlatAllowPrivateNetworkAlias
}, {
path: [
"channels",
e.channelKey,
"accounts"
],
message: `${t}.accounts.<id>.allowPrivateNetwork is legacy; use ${t}.accounts.<id>.network.dangerouslyAllowPrivateNetwork instead. Run "openclaw doctor --fix".`,
match: hasLegacyAllowPrivateNetworkInAccounts
}],
normalizeCompatibilityConfig: ({ cfg: t }) => {
if (!asNullableRecord(t.channels)) return {
config: t,
changes: []
};
return normalizeChannelConfigEntries({
cfg: t,
channelId: e.channelKey,
normalizeEntry: migrateLegacyFlatAllowPrivateNetworkAlias
});
}
};
}
//#endregion
//#region src/plugin-sdk/runtime-doctor-migrations.ts
/** Collects a channel's root config and object-shaped account overrides in config order. */
function collectChannelAccountScopes(e) {
const t = [];
const n = ["channels", e.channelId];
const r = asNullableRecord(e.cfg.channels);
const i = asNullableRecord(r?.[e.channelId]);
if (!i) return t;
t.push({
prefix: n.join("."),
pathSegments: n,
account: i
});
const a = asNullableRecord(i.accounts);
if (!a) return t;
for (const [e, r] of Object.entries(a)) {
const i = asNullableRecord(r);
if (i) {
const r = [
...n,
"accounts",
e
];
t.push({
prefix: r.join("."),
pathSegments: r,
account: i
});
}
}
return t;
}
function readKeyMovePath(e, t, n = true) {
let r = e;
for (const e of t.slice(0, -1)) {
const t = asNullableRecord(r[e]);
if (!t) return null;
r = t;
}
const i = t.at(-1);
return i && (n ? Object.hasOwn(r, i) : i in r) ? { value: r[i] } : null;
}
function setKeyMovePath(e, t, n) {
const [r, ...i] = t;
if (!r) return e;
if (i.length === 0) return {
...e,
[r]: n
};
return {
...e,
[r]: setKeyMovePath(asNullableRecord(e[r]) ?? {}, i, n)
};
}
function deleteKeyMovePath(e, t, n) {
const [r, ...i] = t;
if (!r) return e;
const a = { ...e };
if (i.length === 0) {
delete a[r];
return a;
}
const o = asNullableRecord(e[r]);
if (!o) return e;
const s = deleteKeyMovePath(o, i, n);
if (n && Object.keys(s).length === 0) delete a[r];
else a[r] = s;
return a;
}
/** Defines an immutable legacy-key move across fixed or `*`-mapped object paths. */
function defineKeyMoveMigration(e) {
const visitScopes = (t, n) => {
const [r, ...i] = n;
if (!r) {
const n = readKeyMovePath(t, e.from, e.sourceOwn);
return Boolean(n && (e.match?.(n.value) ?? true));
}
if (r === "*") return Object.values(t).some((e) => {
const t = asNullableRecord(e);
return t ? visitScopes(t, i) : false;
});
const a = asNullableRecord(t[r]);
return a ? visitScopes(a, i) : false;
};
const hasLegacy = (t) => {
const n = asNullableRecord(t);
return n ? visitScopes(n, e.scope ?? []) : false;
};
const normalizeScope = (t, n, r, i) => {
const a = readKeyMovePath(t, e.from, e.sourceOwn);
if (!a || !(e.match?.(a.value) ?? true)) return {
entry: t,
changed: false
};
const o = readKeyMovePath(t, e.to);
const s = e.map ? e.map(a.value) : { value: a.value };
const c = {
sourcePath: [
r,
...n,
...e.from
].join("."),
targetPath: [
r,
...n,
...e.to
].join("."),
sourceValue: a.value,
targetValue: o?.value,
mappedValue: s?.value
};
const l = e.targetIsSet?.(o?.value) ?? o?.value !== void 0;
let u = t;
if (l) i.push(e.existingMessage?.(c) ?? `Removed ${c.sourcePath} (${c.targetPath} already set).`);
else if (s) {
u = setKeyMovePath(u, e.to, s.value);
i.push(e.movedMessage?.(c) ?? `Moved ${c.sourcePath} → ${c.targetPath}.`);
} else i.push(e.invalidMessage?.(c) ?? `Removed invalid ${c.sourcePath} value.`);
return {
entry: deleteKeyMovePath(u, e.from, e.pruneEmptySource ?? false),
changed: true
};
};
const normalizeScopes = (e, t, n, r, i = []) => {
const [a, ...o] = t;
if (!a) return normalizeScope(e, i, n, r);
let s = false;
const c = { ...e };
const l = a === "*" ? Object.keys(e) : [a];
for (const t of l) {
const a = asNullableRecord(e[t]);
if (!a) continue;
const l = normalizeScopes(a, o, n, r, [...i, t]);
if (l.changed) {
c[t] = l.entry;
s = true;
}
}
return s ? {
entry: c,
changed: true
} : {
entry: e,
changed: false
};
};
return {
hasLegacy,
normalize: ({ entry: t, pathPrefix: n, changes: r }) => normalizeScopes(t, e.scope ?? [], n, r)
};
}
/**
* Defines the repair for channel config parked under `plugins.entries.<id>.config`.
* Channel plugins read `channels.<channelId>` only, but retired rich plugin-entry
* schemas let config UIs park values in the unread plugin-entry location.
*/
function defineStrayPluginEntryConfigMigration(e) {
const { pluginId: t, channelId: n } = e;
const r = `plugins.entries.${t}.config`;
const readStrayEntryConfig = (e) => {
const n = asNullableRecord(asNullableRecord(e.plugins)?.entries);
const r = asNullableRecord(asNullableRecord(n?.[t])?.config);
return r && Object.keys(r).length > 0 ? r : null;
};
return {
legacyConfigRule: {
path: [
"plugins",
"entries",
t,
"config"
],
message: `${r} is not read by the ${n} channel; run "openclaw doctor --fix" to move its keys to channels.${n}.`,
match: (e) => {
const t = asNullableRecord(e);
return Boolean(t && Object.keys(t).length > 0);
}
},
normalizeConfig: ({ cfg: i }) => {
const a = readStrayEntryConfig(i);
if (!a) return {
config: i,
changes: []
};
const o = structuredClone(i);
const s = asNullableRecord(asNullableRecord(o.channels)?.[n]) ?? {};
const c = [];
const l = [];
const u = { ...s };
for (const [e, t] of Object.entries(a)) if (Object.hasOwn(s, e)) l.push(e);
else {
u[e] = t;
c.push(e);
}
if (!e.validateMergedChannelConfig(u)) return {
config: i,
changes: []
};
const d = asNullableRecord(o.channels) ?? {};
d[n] = u;
o.channels = d;
const f = asNullableRecord(asNullableRecord(asNullableRecord(o.plugins)?.entries)?.[t]);
if (f) delete f.config;
return {
config: o,
changes: [...c.map((e) => `Moved ${r}.${e} to channels.${n}.${e}.`), ...l.map((e) => `Removed ${r}.${e}; channels.${n}.${e} is authoritative.`)]
};
}
};
}
//#endregion
export { normalizeStringEntries as A, isRecord as B, hasErrnoCode as C, isBlockedObjectKey as D, hasLegacyAccountStreamingAliases as E, normalizeOptionalString as F, readNonBlankString as I, asNullableRecord as L, normalizeUniqueStringEntriesLower as M, normalizeLowercaseStringOrEmpty as N, normalizeChannelAccounts as O, normalizeOptionalLowercaseString as P, asOptionalObjectRecord as R, realpathExistingAncestorSync as S, isMissingPathError as T, isStringArray as V, resolveGlobalSingleton as _, defineChannelAliasMigration as a, canAccessSync as b, resolveChannelAccountKey as c, normalizeAccountId as d, normalizeOptionalAccountId as f, resolveGlobalSet as g, resolveGlobalMap as h, createLegacyPrivateNetworkDoctorContract as i, normalizeUniqueStringEntries as j, normalizeChannelConfigEntries as k, resolveNormalizedAccountEntry as l, readGlobalSingleton as m, defineKeyMoveMigration as n, stripRetiredChannelKeys as o, normalizeAgentId as p, defineStrayPluginEntryConfigMigration as r, resolveAccountKey as s, collectChannelAccountScopes as t, DEFAULT_ACCOUNT_ID as u, mergeDeep as v, isErrno as w, realpathExistingAncestor as x, isPlainObject as y, asOptionalRecord as z };