openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,018 lines (1,017 loc) • 36.6 kB
JavaScript
import "./runtime-process-manifest-D9nKAy2n.js";
import path from "node:path";
import fsPromises from "node:fs/promises";
import { hasNodeErrorCode as hasErrnoCode, isNodeError as isErrno, isPathInside as isPathInside$1, normalizeWindowsPathForComparison as normalizeWindowsPathForComparison$1 } from "@openclaw/fs-safe/path";
import fs from "node:fs";
import { canUseRootFileOpen, openRootFileSync, readFileDescriptorBoundedSync } from "@openclaw/fs-safe/advanced";
import { FsSafeError } from "@openclaw/fs-safe/errors";
import os from "node:os";
import { AsyncLocalStorage, AsyncResource } from "node:async_hooks";
//#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;
}
/** 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
/** Retains runtime string entries from arrays without normalizing their contents. */
function filterStringEntries(e) {
return Array.isArray(e) ? e.filter((e) => typeof e === "string") : [];
}
/** 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);
}
/** Lowercases normalized entries, removes empties/duplicates, and preserves first-seen order. */
function normalizeUniqueStringEntriesLower(e) {
return uniqueStrings(normalizeStringEntriesLower(e ? [...e] : void 0));
}
/** Normalizes array-backed string lists and rejects non-array input as empty. */
function normalizeTrimmedStringList(e) {
if (!Array.isArray(e)) return [];
return e.flatMap((e) => {
const t = normalizeOptionalString(e);
return t ? [t] : [];
});
}
/** Returns undefined for non-arrays but preserves an empty array for explicit arrays. */
function normalizeArrayBackedTrimmedStringList(e) {
if (!Array.isArray(e)) return;
return normalizeTrimmedStringList(e);
}
//#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");
}
/** Ignore only ENOENT; all other failures retain their original identity. */
function ignoreMissingPath(e) {
if (hasErrnoCode(e, "ENOENT")) return;
throw e;
}
//#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/utils/boolean.ts
/**
* Shared boolean coercion helpers for config, env, and plugin SDK runtime inputs.
*
* `asBoolean` is intentionally strict; string parsing is opt-in through
* `parseBooleanValue` so schema callers do not silently accept ambiguous text.
*/
const DEFAULT_TRUTHY = [
"true",
"1",
"yes",
"on"
];
const DEFAULT_FALSY = [
"false",
"0",
"no",
"off"
];
function asBoolean(e) {
return typeof e === "boolean" ? e : void 0;
}
function parseBooleanValue(e, t = {}) {
const n = asBoolean(e);
if (n !== void 0) return n;
const r = normalizeOptionalLowercaseString(e);
if (!r) return;
if ((t.truthy ?? DEFAULT_TRUTHY).includes(r)) return true;
if ((t.falsy ?? DEFAULT_FALSY).includes(r)) return false;
}
//#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 lifecycle-owned process-local Set singleton. */
function resolveGlobalSet(e, t) {
return resolveGlobalSingleton(e, () => /* @__PURE__ */ new Set(), (e) => e.clear(), t);
}
//#endregion
//#region packages/normalization-core/src/number-coercion.ts
function asFiniteNumber(e) {
return typeof e === "number" && Number.isFinite(e) ? e : void 0;
}
/** Returns a safe integer only when it satisfies the supplied inclusive bounds. */
function asSafeIntegerInRange(e, t) {
if (typeof e !== "number" || !Number.isSafeInteger(e)) return;
if (t.min !== void 0 && e < t.min) return;
if (t.max !== void 0 && e > t.max) return;
return e;
}
/** Conservative upper bound for Node timer delays. */
const MAX_TIMER_TIMEOUT_MS = 2147e6;
/** Timer bound expressed in whole seconds for env/config inputs. */
const MAX_TIMER_TIMEOUT_SECONDS = Math.floor(MAX_TIMER_TIMEOUT_MS / 1e3);
/** Resolves arbitrary timeout input with fallback and minimum timer bounds. */
function resolveTimerTimeoutMs(e, t, n = 1) {
const r = asFiniteNumber(e) ?? asFiniteNumber(t);
const i = Math.max(0, Math.floor(n));
if (r === void 0) return i;
return Math.min(Math.max(Math.floor(r), i), MAX_TIMER_TIMEOUT_MS);
}
//#endregion
//#region packages/normalization-core/src/error-coercion.ts
const PROVIDER_AUTH_PERSISTENCE_ERROR_BRAND = Symbol.for("openclaw.provider-auth-persistence-error");
function isProviderAuthPersistenceError(e) {
try {
return PROVIDER_AUTH_PERSISTENCE_ERROR_BRAND in e && e[PROVIDER_AUTH_PERSISTENCE_ERROR_BRAND] === true;
} catch {
return false;
}
}
function isErrorObject(e) {
try {
if (e instanceof Error) return true;
return Object.prototype.toString.call(e) === "[object Error]";
} catch {
return false;
}
}
function isAggregateErrorObject(e) {
try {
if (e instanceof AggregateError) return true;
for (let t = Object.getPrototypeOf(e); t; t = Object.getPrototypeOf(t)) {
const e = Object.getOwnPropertyDescriptor(t, "constructor")?.value;
if (typeof e === "function" && e.name === "AggregateError") return true;
}
} catch {}
return false;
}
function readProperty(e, t) {
try {
return e[t];
} catch {
return;
}
}
function readErrorText(e, t) {
const n = readProperty(e, t);
return typeof n === "string" ? n : void 0;
}
function formatStatusAndCode(e) {
if ((typeof e !== "object" || e === null) && typeof e !== "function") return;
try {
if (Object.keys(e).some((e) => e !== "status" && e !== "code")) return;
} catch {}
const t = readProperty(e, "status");
const n = readProperty(e, "code");
if (t === void 0 && n === void 0) return;
return `status=${typeof t === "string" || typeof t === "number" ? String(t) : "unknown"} code=${typeof n === "string" || typeof n === "number" ? String(n) : "unknown"}`;
}
function stringifyUnknown(e) {
if (e === null || typeof e !== "object" && typeof e !== "function") return String(e);
try {
const t = JSON.stringify(e);
if (t !== void 0) return t;
} catch {}
try {
return Object.prototype.toString.call(e);
} catch {
return "Unknown error";
}
}
function readErrorCauses(e) {
if (!isErrorObject(e)) return [];
const t = readProperty(e, "cause");
const n = isAggregateErrorObject(e) ? readProperty(e, "errors") : void 0;
const r = isProviderAuthPersistenceError(e) ? [readProperty(e, "persistenceError"), readProperty(e, "cleanupError")] : [];
const i = readErrorText(e, "name") === "SuppressedError" ? [readProperty(e, "error"), readProperty(e, "suppressed")].map((e) => e == null ? String(e) : e) : [];
return [
...r,
t || void 0,
...Array.isArray(n) ? n : [],
...i
];
}
/** Formats unknown errors with cause/aggregate details and optional diagnostic redaction. */
function formatErrorMessage(e, t = {}) {
let n;
if (isErrorObject(e)) {
n = readErrorText(e, "message") || readErrorText(e, "name") || "Error";
const r = /* @__PURE__ */ new Set([n]);
const appendCauseMessage = (e) => {
if (!e || r.has(e)) return;
n += ` | ${e}`;
r.add(e);
};
if (t.includeCode) {
const t = readProperty(e, "code");
if (typeof t === "string" || typeof t === "number") appendCauseMessage(String(t));
}
const i = collectErrorGraphCandidates(e, readErrorCauses);
for (const e of i.slice(1)) if (isErrorObject(e)) {
const t = readErrorText(e, "message");
if (t && n.includes(t)) r.add(t);
else appendCauseMessage(t);
const i = readProperty(e, "code");
if (typeof i === "string" || typeof i === "number") appendCauseMessage(String(i));
} else if (typeof e === "string") appendCauseMessage(e);
else appendCauseMessage(formatStatusAndCode(e) ?? stringifyUnknown(e));
} else n = formatStatusAndCode(e) ?? stringifyUnknown(e);
return t.redact ? t.redact(n) : n;
}
/**
* Formats an error's stack so it always names the error. Bun can materialize
* `stack` during garbage collection with a bare `Error` header, dropping the
* message that V8-style stacks carry.
*/
function formatErrorStackWithMessage(e) {
const t = readErrorText(e, "name") || "Error";
const n = readErrorText(e, "message") ?? "";
const r = readProperty(e, "stack");
if (typeof r !== "string" || !r) return n || t;
if (!n || r.includes(n)) return r;
const i = `${t}: ${n}`;
const a = r.indexOf("\n");
const o = a < 0 ? r : r.slice(0, a);
return o === t ? i + r.slice(o.length) : `${i}\n${r}`;
}
/**
* Normalizes an unknown thrown value into an Error. Non-Error objects become
* the `cause` and have their enumerable fields copied so structured details
* (codes, statuses) survive the coercion.
*/
function toErrorObject(e, t) {
if (e instanceof Error) return e;
if (typeof e === "string") return new Error(e);
const n = new Error(t, { cause: e });
if (typeof e === "object" && e !== null || typeof e === "function") Object.assign(n, e);
return n;
}
/** Reads Error messages unchanged and stringifies every other value. */
function coerceErrorMessage(e) {
return e instanceof Error ? e.message : String(e);
}
function extractErrorCode(e) {
if (!e || typeof e !== "object") return;
const t = readProperty(e, "code");
return typeof t === "string" || typeof t === "number" ? String(t) : void 0;
}
function collectErrorGraphCandidates(e, t) {
if (e == null) return [];
const n = [e];
const r = (/* @__PURE__ */ new Set()).add(e);
for (const e of n) {
if (!e || typeof e !== "object" || !t) continue;
for (const i of t(e)) if (i != null && !r.has(i)) {
r.add(i);
n.push(i);
}
}
return n;
}
function collectNestedErrorCandidates(e) {
return collectErrorGraphCandidates(e, (e) => {
const t = [
readProperty(e, "cause"),
readProperty(e, "reason"),
readProperty(e, "original"),
readProperty(e, "error"),
readProperty(e, "suppressed"),
readProperty(e, "data")
];
const n = readProperty(e, "errors");
if (Array.isArray(n)) t.push(...n);
return t;
});
}
//#endregion
//#region src/shared/detached-async-context.ts
const asyncHooks = typeof process === "undefined" ? void 0 : process.getBuiltinModule?.("node:async_hooks");
const detachedAsyncContext = asyncHooks ? resolveGlobalSingleton(Symbol.for("openclaw.detachedAsyncContext"), () => new asyncHooks.AsyncResource("openclaw.detached-async-context")) : void 0;
/** Runs under the context-free async root initialized before managed work can begin. */
function runInDetachedAsyncContext(e) {
return detachedAsyncContext ? detachedAsyncContext.runInAsyncScope(e) : e();
}
//#endregion
//#region src/shared/async-store.ts
function enterAsyncStore(e, t) {
this.enterWith(e);
return t();
}
/** Enter once; the resource restores the caller's frame without copying it again. */
function runWithAsyncStore(e, t, n) {
if (e.getStore() === t) return n();
return new AsyncResource("OpenClawAsyncStore").runInAsyncScope(enterAsyncStore, e, t, n);
}
//#endregion
//#region src/plugins/plugin-instance-invocation.ts
var InvocationFrame = class InvocationFrame {
constructor(e, t = e.invocation) {
this.retentionOwner = e.retentionOwner;
this.invocation = t;
this.metadataScope = e.metadataScope;
this.cacheScope = e.cacheScope;
this.sourceCaptureStorage = e.sourceCaptureStorage;
}
get runtimePluginId() {}
withScopes(e) {
return new InvocationFrame(e);
}
};
/** Copy core scopes through the current owner so runtime-only fields survive. */
function createPluginExecutionFrame(e, t) {
return t ? t.withScopes(e) : new InvocationFrame(e);
}
const pluginExecutionContext = resolveGlobalSingleton(Symbol.for("openclaw.pluginInstanceInvocation"), () => {
const e = new AsyncLocalStorage();
return {
invocation: {
getStore() {
return e.getStore()?.invocation;
},
run(t, n) {
const r = e.getStore();
return r?.invocation === t ? n() : runWithAsyncStore(e, createPluginExecutionFrame({
...r,
invocation: t
}, r), n);
},
exit(t) {
const n = e.getStore();
return n?.invocation ? runWithAsyncStore(e, n.withScopes({
...n,
invocation: void 0
}), t) : t();
}
},
getFrame() {
return e.getStore();
},
runFrame(t, n) {
return runWithAsyncStore(e, t, n);
}
};
});
const pluginInstanceInvocation = pluginExecutionContext.invocation;
const getPluginExecutionFrame = pluginExecutionContext.getFrame;
const runWithPluginExecutionFrame = pluginExecutionContext.runFrame;
//#endregion
//#region src/infra/fs-safe-env.ts
const nativeModeKey = "OPENCLAW_FS_SAFE_NATIVE_MODE";
const legacyModeKeys = ["FS_SAFE_PYTHON_MODE", "OPENCLAW_FS_SAFE_PYTHON_MODE"];
const legacyKeys = [
...legacyModeKeys,
"FS_SAFE_PYTHON",
"OPENCLAW_FS_SAFE_PYTHON",
"OPENCLAW_PINNED_PYTHON",
"OPENCLAW_PINNED_WRITE_PYTHON"
];
const fallbacks = /* @__PURE__ */ new WeakMap();
let warned = false;
function nativeModeIsValid(e) {
const t = e?.trim().toLowerCase() ?? "";
return /^(?:0|false|off|never|1|true|on|auto|required|require)$/u.test(t);
}
function currentFallback(e) {
const t = fallbacks.get(e);
return t && e[t.key] === t.value ? t : void 0;
}
/** Read the operator/config inputs without promoting a derived native fallback. */
function fsSafeEnvInput(e) {
const t = currentFallback(e);
if (!t) return e;
const n = {
...e,
[t.key]: t.previous
};
if (!t.existed) delete n[t.key];
return n;
}
/** Retire our unchanged projection before an environment owner writes real inputs. */
function clearFsSafeEnvFallback(e) {
const t = currentFallback(e);
fallbacks.delete(e);
if (!t) return;
if (!t.existed) delete e[t.key];
else e[t.key] = t.previous;
}
/** Preserve OpenClaw's retired Python mode env contract below both native names. */
function normalizeFsSafeNativeEnv(e = process.env) {
clearFsSafeEnvFallback(e);
const t = legacyKeys.filter((t) => e[t] !== void 0);
if (t.length && e === process.env && !warned) {
warned = true;
process.emitWarning(`${t.join(", ")} is deprecated. OpenClaw maps legacy mode values to native mode only when neither FS_SAFE_NATIVE_MODE nor OPENCLAW_FS_SAFE_NATIVE_MODE selects a mode. Replace Python mode variables with native mode variables; interpreter path settings are ignored.`, {
code: "FS_SAFE_PYTHON_DEPRECATED",
type: "DeprecationWarning"
});
}
if (nativeModeIsValid(e.FS_SAFE_NATIVE_MODE) || nativeModeIsValid(e[nativeModeKey])) return;
const n = legacyModeKeys.map((t) => e[t]).find((e) => e !== void 0);
if (n === void 0) return;
const r = Object.keys(e);
const i = !r.includes(nativeModeKey) && Object.hasOwn(e, nativeModeKey) ? r.find((e) => e.toUpperCase() === nativeModeKey) ?? nativeModeKey : nativeModeKey;
const a = Object.hasOwn(e, i);
const o = e[i];
e[i] = n;
fallbacks.set(e, {
key: i,
value: n,
previous: o,
existed: a
});
}
//#endregion
//#region src/infra/env.ts
/** Interprets common human/operator truthy env strings. */
function isTruthyEnvValue(e) {
return parseBooleanValue(e) === true;
}
//#endregion
//#region src/infra/path-guards.ts
/**
* Normalize a Windows path for boundary math whose result is handed back to callers.
*
* Unlike `normalizeWindowsPathForComparison`, this preserves case: `path.win32.relative`
* already matches roots case-insensitively, so lowercasing only corrupts the returned
* relative path — and callers create files from it on a case-preserving filesystem.
* Extended-length prefix stripping stays, or `\\?\`-prefixed inputs read as boundary escapes.
*/
function normalizeWindowsPathPreservingCase(e) {
const t = path.win32.normalize(e);
if (!t.startsWith("\\\\?\\")) return t;
const n = t.slice(4);
return n.toUpperCase().startsWith("UNC\\") ? `\\\\${n.slice(4)}` : n;
}
//#endregion
//#region src/infra/safe-cwd.ts
function tryProcessCwd() {
try {
return process.cwd();
} catch {
return;
}
}
//#endregion
//#region packages/normalization-core/src/home-dir.ts
function normalizeHomeDirValue(e) {
const t = e?.trim();
return t && t !== "undefined" && t !== "null" ? t : void 0;
}
function normalizeSafe(e) {
try {
return normalizeHomeDirValue(e());
} catch {
return;
}
}
function resolveTermuxHome(e) {
const t = normalizeHomeDirValue(e.PREFIX);
if (!t || !normalizeHomeDirValue(e.ANDROID_DATA)) return;
if (!/(?:^|\/)com\.termux\/files\/usr\/?$/u.test(t.replace(/\\/gu, "/"))) return;
return path.resolve(t, "..", "home");
}
function resolveRawOsHomeDir(e, t) {
return normalizeHomeDirValue(e.HOME) ?? normalizeHomeDirValue(e.USERPROFILE) ?? resolveTermuxHome(e) ?? normalizeSafe(t);
}
function resolveOsHomeDir(e = process.env, t = os.homedir) {
const n = resolveRawOsHomeDir(e, t);
return n ? path.resolve(n) : void 0;
}
function resolveEffectiveHomeDir(e = process.env, t = os.homedir, n) {
const r = normalizeHomeDirValue(e.OPENCLAW_HOME);
if (!r) return resolveOsHomeDir(e, t);
if (r === "~" || r.startsWith("~/") || r.startsWith("~\\")) {
const i = resolveRawOsHomeDir(e, t);
if (!i) return n?.preserveUnresolvedTilde ? path.resolve(r) : void 0;
return path.resolve(r.replace(/^~(?=$|[\\/])/, () => i));
}
return path.resolve(r);
}
//#endregion
//#region packages/terminal-core/src/ansi-sequences.ts
const ANSI_OSC_INTRODUCER_PATTERN = "(?:\\x1b\\]|\\x9d)";
const ANSI_STRING_TERMINATOR_PATTERN = "(?:\\x1b\\\\|\\x07|\\x9c)";
const ANSI_OSC_PATTERN = `${ANSI_OSC_INTRODUCER_PATTERN}[^\\x07\\x1b\\x9c]*${ANSI_STRING_TERMINATOR_PATTERN}`;
const ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN = "[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]";
const ansiOscAtIndexRegex = new RegExp(ANSI_OSC_PATTERN, "y");
function matchAnsiOscAt(e, t) {
ansiOscAtIndexRegex.lastIndex = t;
return ansiOscAtIndexRegex.exec(e)?.[0];
}
/** Scan one CSI parser pass, retaining independently executed C0 controls. */
function scanAnsiCsiAt(e, t) {
const n = e.charCodeAt(t);
if (n !== 155 && (n !== 27 || e.charCodeAt(t + 1) !== 91)) return;
let r = t + (n === 155 ? 1 : 2);
const i = [];
let a = false;
while (r < e.length) {
const t = e.charCodeAt(r);
if (t === 24 || t === 26) {
r += 1;
a = true;
break;
}
if (t === 27 || t === 155) {
a = true;
break;
}
if (t <= 31 || t === 127) {
i.push(e.charAt(r));
r += 1;
continue;
}
if (t >= 32 && t <= 63) {
r += 1;
continue;
}
if (t >= 64 && t <= 126) r += 1;
a = true;
break;
}
return {
controls: i,
ended: a,
value: e.slice(t, r)
};
}
//#endregion
//#region packages/terminal-core/src/ansi.ts
const ANSI_OSC_SEQUENCE_PATTERN = `${ANSI_OSC_INTRODUCER_PATTERN}[\\s\\S]*?${ANSI_STRING_TERMINATOR_PATTERN}`;
const ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX = new RegExp(`${ANSI_OSC_SEQUENCE_PATTERN}|${ANSI_COMPAT_CONTROL_SEQUENCE_PATTERN}`, "y");
const graphemeSegmenter = new Intl.Segmenter(void 0, { granularity: "grapheme" });
function hasAnsiIntroducer(e) {
return e.includes("\x1B") || e.includes("") || e.includes("");
}
/**
* Strip ANSI against original input positions so one removal cannot synthesize
* a second sequence. C0 controls execute without ending CSI, CAN/SUB cancel it,
* and ESC restarts escape parsing.
*/
function stripAnsiInternal(e, t) {
if (!hasAnsiIntroducer(e)) return e;
const n = [];
let r = 0;
let i = 0;
while (i < e.length) {
const a = e.charCodeAt(i);
if (a !== 27 && a !== 155 && a !== 157) {
i += 1;
continue;
}
const o = matchAnsiOscAt(e, i);
const s = o ? void 0 : scanAnsiCsiAt(e, i);
ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX.lastIndex = i;
const c = !o && t.compatibilityGrammar ? ANSI_COMPAT_SEQUENCE_AT_INDEX_REGEX.exec(e)?.[0] : void 0;
let l = o?.length ?? s?.value.length ?? c?.length;
if (l === void 0) {
i += 1;
continue;
}
if (s && !s.ended && t.preserveIncompleteCsi) break;
if (s?.controls.length === 0 && c) l = Math.max(l, c.length);
n.push(e.slice(r, i), ...s?.controls ?? []);
i += l;
r = i;
}
n.push(e.slice(r));
return n.join("");
}
function stripAnsi(e) {
return stripAnsiInternal(e, { compatibilityGrammar: false });
}
const LOG_CONTROL_CHARS_REGEX = new RegExp(`[${String.fromCharCode(0)}-${String.fromCharCode(31)}${String.fromCharCode(127)}-${String.fromCharCode(159)}]`, "g");
//#endregion
//#region packages/terminal-core/src/safe-text.ts
/**
* Normalize untrusted text for single-line rendering, including bidirectional controls.
*/
function sanitizeTerminalText(e) {
return stripAnsi(e).replace(/[\p{Cc}\p{Bidi_Control}]/gu, (e) => e === "\r" ? "\\r" : e === "\n" ? "\\n" : e === " " ? "\\t" : "");
}
//#endregion
//#region src/infra/home-dir.ts
function getUserPathBaseDirectory() {
return resolveGlobalSingleton(Symbol.for("openclaw.userPathBaseDirectory"), () => {
const { AsyncLocalStorage: e } = process.getBuiltinModule("async_hooks");
return new e();
});
}
/** Resolves the effective home or falls back to cwd when no home source exists. */
function resolveRequiredHomeDir(e = process.env, t = os.homedir) {
const n = resolveEffectiveHomeDir(e, t) ?? tryProcessCwd();
if (n) return path.resolve(n);
throw new Error("Unable to resolve an OpenClaw home: set OPENCLAW_HOME, HOME, or USERPROFILE, or run from an existing directory.");
}
/** Resolves the OS home or falls back to cwd when no OS home source exists. */
function resolveRequiredOsHomeDir(e = process.env, t = os.homedir) {
const n = resolveOsHomeDir(e, t) ?? tryProcessCwd();
if (n) return path.resolve(n);
throw new Error("Unable to resolve an OS home: set HOME or USERPROFILE, or run from an existing directory.");
}
/** Expands leading `~`, `~/`, or `~\` with the effective home when one is known. */
function expandHomePrefix(e, t) {
if (!e.startsWith("~")) return e;
const n = normalizeHomeDirValue(t?.home) ?? resolveEffectiveHomeDir(t?.env ?? process.env, t?.homedir ?? os.homedir);
if (!n) return e;
return e.replace(/^~(?=$|[\\/])/, () => n);
}
function resolveAgainstUserBase(e) {
const t = getUserPathBaseDirectory().getStore();
return t ? path.resolve(t, e) : path.resolve(e);
}
function resolvePathWithHome(e, t, n, r = resolveAgainstUserBase) {
const i = e.trim();
if (!i) return i;
return r(i.startsWith("~") ? expandHomePrefix(i, {
home: n(t?.env ?? process.env, t?.homedir ?? os.homedir),
env: t?.env,
homedir: t?.homedir
}) : i);
}
/** Resolves a user-supplied path after trimming and expanding against the effective home. */
function resolveHomeRelativePath(e, t) {
return resolvePathWithHome(e, t, resolveRequiredHomeDir);
}
/** Resolves a user path against the effective home, preserving an empty input. */
function resolveUserPath(e, t = process.env, n = os.homedir) {
if (!e) return "";
return resolveHomeRelativePath(e, {
env: t,
homedir: n
});
}
//#endregion
//#region src/cli/profile-utils.ts
const PROFILE_NAME_RE = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
function isValidProfileName(e) {
return PROFILE_NAME_RE.test(e);
}
function normalizeProfileName(e) {
const t = e?.trim();
if (!t) return null;
if (normalizeLowercaseStringOrEmpty(t) === "default") return null;
if (!isValidProfileName(t)) return null;
return t;
}
/** Resolve the canonical home-scoped state root for a validated CLI profile. */
function resolveProfileStateDir(e, t, n) {
const r = e.trim();
if (!isValidProfileName(r)) throw new Error(`Invalid profile name: ${JSON.stringify(e)}`);
const i = normalizeLowercaseStringOrEmpty(r) === "default" ? "" : `-${r}`;
return path.join(resolveRequiredHomeDir(t, n), `.openclaw${i}`);
}
//#endregion
//#region src/infra/lru-cache.ts
/** Process-local LRU storage; callers own freshness and lifecycle. */
var LruCache = class {
#e;
#t;
#n;
#r = /* @__PURE__ */ new Map();
#i = 0;
constructor(e, t) {
this.#e = Number.isFinite(e) && e > 0 ? Math.max(1, Math.floor(e)) : 1;
this.#t = t?.maxBytes ?? Number.POSITIVE_INFINITY;
this.#n = t?.sizeOf;
}
get size() {
return this.#r.size;
}
clear() {
this.#r.clear();
this.#i = 0;
}
keys() {
return this.#r.keys();
}
delete(e) {
if (!this.#r.has(e)) return false;
this.#i -= this.#n?.(this.#r.get(e)) ?? 0;
return this.#r.delete(e);
}
deleteValue(e) {
for (const [t, n] of this.#r) if (n === e) this.delete(t);
}
/** Reads without promoting a value whose revalidation is still pending. */
peek(e) {
return this.#r.get(e);
}
/** Returns a cached value and refreshes its recency when present. */
get(e) {
if (!this.#r.has(e)) return;
const t = this.#r.get(e);
this.#r.delete(e);
this.#r.set(e, t);
return t;
}
/** Stores a value as the newest entry and evicts oldest entries past capacity. */
set(e, t) {
this.delete(e);
this.#r.set(e, t);
this.#i += this.#n?.(t) ?? 0;
for (const e of this.#r.keys()) {
if (this.#r.size <= this.#e && this.#i <= this.#t) break;
this.delete(e);
}
}
};
//#endregion
//#region src/config/state-dir.ts
const absoluteStateDirs = new LruCache(64);
function resolveNewStateDir(e = resolveRequiredHomeDir) {
return path.join(e(), ".openclaw");
}
/**
* State directory for mutable data (sessions, logs, caches).
* Can be overridden via OPENCLAW_STATE_DIR.
* Default: ~/.openclaw, or ~/.openclaw-<profile> for a named profile.
*/
function resolveStateDir(e = process.env, t = os.homedir) {
const n = e.OPENCLAW_STATE_DIR?.trim();
if (n && process.platform !== "win32" && path.isAbsolute(n)) {
const e = absoluteStateDirs.peek(n);
if (e !== void 0) return e;
const t = path.resolve(n);
absoluteStateDirs.set(n, t);
return t;
}
if (n) return resolveHomeRelativePath(n, {
env: e,
homedir: t
});
return resolveStateDirFromHome(e, () => resolveRequiredHomeDir(e, t));
}
/** Select a default state directory from the caller's already resolved home. */
function resolveStateDirFromHome(e, t) {
const n = normalizeProfileName(e.OPENCLAW_PROFILE);
return n ? resolveProfileStateDir(n, e, t) : resolveNewStateDir(t);
}
//#endregion
//#region src/infra/config-dir.ts
/** Resolves the OpenClaw config directory from state/config env overrides or home. */
function resolveConfigDir(e = process.env, t = os.homedir) {
const n = e.OPENCLAW_STATE_DIR?.trim();
if (n) return resolveUserPath(n, e, t);
const r = e.OPENCLAW_CONFIG_PATH?.trim();
if (r) return path.dirname(resolveUserPath(r, e, t));
return resolveStateDir(e, t);
}
//#endregion
//#region src/infra/home-display.ts
/** Replace an absolute home path with its display prefix without clipping sibling paths. */
function shortenPathWithHome(e, { home: t, prefix: n }) {
if (e === t) return n;
if (e.startsWith(`${t}/`) || process.platform === "win32" && e.startsWith(`${t}\\`)) return `${n}${e.slice(t.length)}`;
if (process.platform === "win32" && path.win32.isAbsolute(e) && isPathInside$1(t, e)) {
const r = path.win32.relative(normalizeWindowsPathPreservingCase(t), normalizeWindowsPathPreservingCase(e));
return path.win32.join(n, r);
}
return e;
}
//#endregion
//#region src/infra/abort-signal.ts
function isAbortError(e) {
if (!e || typeof e !== "object") return false;
try {
if (("name" in e ? String(e.name) : "") === "AbortError") return true;
return ("message" in e && typeof e.message === "string" ? e.message : "") === "This operation was aborted";
} catch {
return false;
}
}
//#endregion
//#region src/utils.ts
/** Resolves the effective OpenClaw home directory, if one can be determined. */
function resolveHomeDir() {
return resolveEffectiveHomeDir(process.env, os.homedir);
}
const HOME_TEXT_START = String.raw`(?<=^|[\s"'\x60(\[{<=:;]|file://)`;
const HOME_TEXT_DELIMITER = String.raw`[\s"'\x60)\]}>]`;
const HOME_TEXT_LIST_NEXT = String.raw`[:;](?=[/\\~$]|[A-Za-z]:)`;
function resolveHomeDisplayPrefix() {
const e = resolveHomeDir();
if (!e) return;
if (normalizeHomeDirValue(process.env.OPENCLAW_HOME)) return {
home: e,
prefix: "$OPENCLAW_HOME"
};
return {
home: e,
prefix: "~"
};
}
/** Replaces the leading home directory in a path with `~` or `$OPENCLAW_HOME`. */
function shortenHomePath(e) {
const t = resolveHomeDisplayPrefix();
if (!t) return e;
return shortenPathWithHome(e, t);
}
let CONFIG_DIR = resolveConfigDir();
//#endregion
//#region src/infra/boundary-path.ts
const runInBoundaryPathContext = AsyncLocalStorage.snapshot();
function resolveIdentityPathViaExistingAncestorSync(e) {
const t = path.resolve(e);
return realpathExistingAncestorSync(t) ?? t;
}
async function resolveIdentityPathViaExistingAncestor(e) {
const t = path.resolve(e);
return await realpathExistingAncestor(t) ?? t;
}
//#endregion
//#region src/config/paths.ts
/**
* Nix mode detection: When OPENCLAW_NIX_MODE=1, the gateway is running under Nix.
* In this mode:
* - No auto-install flows should be attempted
* - Missing dependencies should produce actionable Nix-specific error messages
* - Config is managed externally (read-only from Nix perspective)
*/
function resolveIsNixMode(e = process.env) {
return e.OPENCLAW_NIX_MODE === "1";
}
let isNixMode = resolveIsNixMode();
const CONFIG_FILENAME = "openclaw.json";
/** Build a homedir thunk that respects OPENCLAW_HOME for the given env. */
function envHomedir(e) {
return () => resolveRequiredHomeDir(e, os.homedir);
}
function normalizePathForComparison(e) {
const t = path.resolve(e);
try {
return fs.realpathSync.native(t);
} catch {
return t;
}
}
/**
* Optional allowlist of directories that `$include` directives may resolve
* outside the config directory. Set via `OPENCLAW_INCLUDE_ROOTS` as a
* platform-delimited path list (`:` on POSIX, `;` on Windows).
*
* Each entry is tilde-expanded and resolved to an absolute path. Entries that
* cannot be resolved or that are not absolute after expansion are dropped.
*
* Returns an empty array when the var is unset or contains no usable entries,
* preserving the historical behavior where `$include` is confined to the
* directory containing `openclaw.json`.
*/
function resolveIncludeRoots(e = process.env, t = envHomedir(e)) {
const n = e.OPENCLAW_INCLUDE_ROOTS?.trim();
if (!n) return [];
const effectiveHomedir = () => resolveRequiredHomeDir(e, t);
const r = /* @__PURE__ */ new Set();
const i = [];
for (const t of n.split(path.delimiter)) {
const n = t.trim();
if (!n) continue;
const a = path.resolve(resolveHomeRelativePath(n, {
env: e,
homedir: effectiveHomedir
}));
if (r.has(a)) continue;
r.add(a);
i.push(a);
}
return i;
}
let STATE_DIR = resolveStateDir();
/**
* Resolve the explicitly selected or canonical config path.
*/
function resolveConfigPathCandidate(e = process.env, t = envHomedir(e)) {
return resolveConfigPath(e, void 0, t);
}
/**
* Active config path.
*/
function resolveConfigPath(e = process.env, t, n = envHomedir(e)) {
const r = e.OPENCLAW_CONFIG_PATH?.trim();
if (r) return resolveUserPath(r, e, n);
return path.join(t ?? resolveStateDir(e, n), CONFIG_FILENAME);
}
let CONFIG_PATH = resolveConfigPathCandidate();
/**
* Gateway lock directory inside the selected state tree.
* Default: $OPENCLAW_STATE_DIR/tmp/openclaw-<uid> (uid suffix when available).
*/
function resolveGatewayLockDir(e = resolveStateDir(), t = typeof process.getuid === "function" ? process.getuid() : void 0) {
return resolveGatewayLockDirForCanonicalStateDir(normalizePathForComparison(e), t);
}
/** Append the lock layout when the caller has already resolved the state directory. */
function resolveGatewayLockDirForCanonicalStateDir(e, t = typeof process.getuid === "function" ? process.getuid() : void 0) {
const n = t != null ? `openclaw-${t}` : "openclaw";
return path.join(e, "tmp", n);
}
//#endregion
export { isRecord as $, formatErrorMessage as A, hasErrnoCode as B, normalizeFsSafeNativeEnv as C, coerceErrorMessage as D, runInDetachedAsyncContext as E, resolveTimerTimeoutMs as F, normalizeArrayBackedTrimmedStringList as G, isErrno as H, readGlobalSingleton as I, normalizeOptionalLowercaseString as J, normalizeUniqueStringEntriesLower as K, resolveGlobalSet as L, toErrorObject as M, asFiniteNumber as N, collectNestedErrorCandidates as O, asSafeIntegerInRange as P, asOptionalRecord as Q, resolveGlobalSingleton as R, fsSafeEnvInput as S, runWithAsyncStore as T, isMissingPathError as U, ignoreMissingPath as V, filterStringEntries as W, asNullableRecord as X, normalizeOptionalString as Y, asOptionalObjectRecord as Z, tryProcessCwd as _, resolveIdentityPathViaExistingAncestor as a, normalizeWindowsPathPreservingCase as b, openRootFileSync as c, resolveConfigDir as d, isStringArray as et, resolveStateDir as f, sanitizeTerminalText as g, resolveRequiredOsHomeDir as h, resolveIncludeRoots as i, formatErrorStackWithMessage as j, extractErrorCode as k, shortenHomePath as l, expandHomePrefix as m, resolveGatewayLockDir as n, resolveIdentityPathViaExistingAncestorSync as o, LruCache as p, normalizeLowercaseStringOrEmpty as q, resolveGatewayLockDirForCanonicalStateDir as r, canUseRootFileOpen as s, resolveConfigPath as t, isAbortError as u, isPathInside$1 as v, getPluginExecutionFrame as w, isTruthyEnvValue as x, normalizeWindowsPathForComparison$1 as y, canAccessSync as z };