openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
316 lines (315 loc) • 11.7 kB
JavaScript
import { A as parseStrictPositiveInteger, a as resolveStateDir, d as resolveRequiredHomeDir, p as resolveUserPath, s as normalizeProfileName, u as resolveHomeRelativePath } from "./path-guards-quCEQx1i.mjs";
import fsSync from "node:fs";
import path from "node:path";
import { hasNodeErrorCode as hasErrnoCode, isNodeError as isErrno } from "@openclaw/fs-safe/path";
import os from "node:os";
//#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;
}
/** Preserves Error values and stringifies every other value into a new Error. */
function toStringifiedError(e) {
return e instanceof Error ? e : new Error(String(e));
}
/** 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 extractErrorCodeOrErrno(e) {
const t = extractErrorCode(e);
if (t) return t.trim().toUpperCase();
if (!e || typeof e !== "object") return;
const n = e.errno;
if (typeof n === "string" && n.trim()) return n.trim().toUpperCase();
if (typeof n === "number" && Number.isFinite(n)) return String(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/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/tcp-port.ts
const MAX_TCP_PORT = 65535;
/** Parse a positive TCP port or return null for absent/invalid input. */
function parseTcpPort(e) {
const t = parseStrictPositiveInteger(e);
if (t === void 0 || t > 65535) return null;
return 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 fsSync.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();
const DEFAULT_GATEWAY_PORT = 18789;
/**
* 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);
}
function parseGatewayPortEnvValue(e) {
const t = e?.trim();
if (!t) return null;
if (/^\d+$/.test(t)) return parseTcpPort(t);
const n = t.match(/^\[[^\]]+\]:(\d+)$/);
if (n?.[1]) return parseTcpPort(n[1]);
const r = t.indexOf(":");
const i = t.lastIndexOf(":");
if (r <= 0 || r !== i) return null;
const a = t.slice(r + 1);
if (!/^\d+$/.test(a)) return null;
return parseTcpPort(a);
}
function resolveGatewayPort(e, t = process.env) {
const n = t.OPENCLAW_GATEWAY_PORT?.trim();
const r = parseGatewayPortEnvValue(n);
if (r !== null) return r;
const i = e?.gateway?.port;
if (typeof i === "number" && Number.isFinite(i) && i > 0) return i;
const a = normalizeProfileName(t.OPENCLAW_PROFILE);
if (!a) return DEFAULT_GATEWAY_PORT;
let o = 2166136261;
for (const e of Buffer.from(a, "utf8")) o = Math.imul(o ^ e, 16777619) >>> 0;
return 2e4 + o % 4e4;
}
//#endregion
export { formatErrorMessage as _, resolveIncludeRoots as a, toStringifiedError as b, hasErrnoCode as c, isMissingPathError as d, coerceErrorMessage as f, extractErrorCodeOrErrno as g, extractErrorCode as h, resolveGatewayPort as i, ignoreMissingPath as l, collectNestedErrorCandidates as m, resolveGatewayLockDir as n, resolveIsNixMode as o, collectErrorGraphCandidates as p, resolveGatewayLockDirForCanonicalStateDir as r, parseTcpPort as s, resolveConfigPath as t, isErrno as u, formatErrorStackWithMessage as v, toErrorObject as y };