UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

557 lines (556 loc) • 19.5 kB
import { N as normalizeLowercaseStringOrEmpty, _ as resolveGlobalSingleton, c as resolveChannelAccountKey, d as normalizeAccountId, f as normalizeOptionalAccountId, j as normalizeUniqueStringEntries, s as resolveAccountKey, u as DEFAULT_ACCOUNT_ID, z as asOptionalRecord } from "./runtime-doctor-migrations-JGL9tD-z.js"; import "./number-coercion-BtnBjAcf.js"; import "./src-CSCqKRHJ.js"; import { isPathInside as isPathInside$1, normalizeWindowsPathForComparison as normalizeWindowsPathForComparison$1 } from "@openclaw/fs-safe/path"; import path from "node:path"; import fs from "node:fs"; import "@openclaw/fs-safe/advanced"; import os from "node:os"; //#region src/config/channel-account-config.ts /** Merge authored account overrides over channel defaults, with owner-selected collection rules. */ function mergeAccountConfig(e) { const t = /* @__PURE__ */ new Set(["accounts", ...e.omitKeys ?? []]); const n = Object.fromEntries(Object.entries(e.channelConfig ?? {}).filter(([e]) => !t.has(e))); const r = e.accountConfig; const i = { ...n, ...r }; const a = i; for (const [t, i] of Object.entries(e.inheritEmptyKeys ?? {})) { const e = r?.[t]; const o = i === "array" ? Array.isArray(e) ? e : void 0 : asOptionalRecord(e); if (o && Object.keys(o).length === 0) a[t] = n[t]; } for (const t of e.nestedObjectKeys ?? []) { const e = asOptionalRecord(n[t]); const i = asOptionalRecord(r?.[t]); if (e && i) a[t] = { ...e, ...i }; } if (e.preserveRootAllowFrom && Array.isArray(n.allowFrom) && Array.isArray(r?.allowFrom)) { if (n.allowFrom.some((e) => { const t = String(e).trim(); return t.length > 0 && t !== "*"; }) && r.allowFrom.some((e) => String(e).trim() === "*")) { const e = r.allowFrom.filter((e) => String(e).trim() !== "*"); a.allowFrom = e.length > 0 ? e : n.allowFrom; } } return i; } /** Resolve a named account before applying the shared channel inheritance rules. */ function resolveMergedAccountConfig(e) { const t = e.channelId ? resolveChannelAccountKey(e.accounts, e.accountId, e.channelId, e.normalizeAccountId, e.accountKeyPolicy) : resolveAccountKey(e.accounts, e.accountId, e.normalizeAccountId, e.accountKeyPolicy); const n = t === void 0 ? void 0 : e.accounts?.[t]; return mergeAccountConfig({ ...e, accountConfig: n }); } //#endregion //#region packages/session-url-contract/src/share.ts const CONTROL_UI_RESERVED_ROUTE_SEGMENTS = Object.freeze([ "activity", "ai-agents", "appearance", "approve", "apps", "ask", "automation", "automations", "channels", "chat", "templates", "communications", "config", "cron", "custodian", "dashboard", "dashboards", "debug", "focus", "infrastructure", "lobsterdex", "logs", "mcp", "meetings", "memory-import", "model-providers", "model-setup", "new", "nodes", "plugin", "plugins", "portals", "profile", "sessions", "settings", "share", "skills", "systems", "terminal", "usage", "workboard", "worktrees" ]); //#endregion //#region src/channels/plugins/account-helpers.ts function createAccountListHelpers(e, t) { function hasImplicitDefaultAccount(n) { const r = n.channels?.[e]; return Boolean(t?.hasImplicitDefaultAccount?.(n) || t?.implicitDefaultAccount?.channelKeys?.some((e) => hasConfiguredAccountValue(r?.[e])) || t?.implicitDefaultAccount?.envVars?.some((e) => hasConfiguredAccountValue(process.env[e]))); } function resolveConfiguredDefaultAccountId(t) { const n = t.channels?.[e]; return normalizeOptionalAccountId(typeof n?.defaultAccount === "string" ? n.defaultAccount : void 0); } function listConfiguredAccountIds(n) { const r = (n.channels?.[e])?.accounts; if (!r || typeof r !== "object") return []; const i = Object.keys(r).filter(Boolean); const a = t?.normalizeAccountId; if (!a) return i; return normalizeUniqueStringEntries(i.map((e) => a(e))); } function listAccountIds(e) { return listCombinedAccountIds({ configuredAccountIds: listConfiguredAccountIds(e), additionalAccountIds: t?.additionalAccountIds?.(e), implicitAccountId: t?.resolveImplicitAccountId ? t.resolveImplicitAccountId(e) : hasImplicitDefaultAccount(e) ? DEFAULT_ACCOUNT_ID : void 0, fallbackAccountIdWhenEmpty: t?.fallbackAccountIdWhenEmpty === false ? void 0 : t?.fallbackAccountIdWhenEmpty ?? "default" }); } function resolveDefaultAccountId(e) { return resolveListedDefaultAccountId({ accountIds: listAccountIds(e), configuredDefaultAccountId: resolveConfiguredDefaultAccountId(e), allowUnlistedDefaultAccount: t?.allowUnlistedDefaultAccount }); } return { listConfiguredAccountIds, listAccountIds, resolveDefaultAccountId, resolveAccountConfig: (n, r) => { const i = n.channels?.[e]; const a = i?.accounts; return resolveMergedAccountConfig({ channelConfig: i, channelId: e, accounts: a, accountId: r, omitKeys: t?.omitKeys, normalizeAccountId: t?.normalizeAccountId, nestedObjectKeys: t?.nestedObjectKeys }); } }; } function hasConfiguredAccountValue(e) { if (typeof e === "string") return e.trim().length > 0; return e !== void 0 && e !== null; } function listCombinedAccountIds(e) { const t = new Set([ ...e.configuredAccountIds, ...e.additionalAccountIds ?? [], ...e.implicitAccountId ? [e.implicitAccountId] : [] ].filter(Boolean)); if (t.size === 0 && e.fallbackAccountIdWhenEmpty) return [e.fallbackAccountIdWhenEmpty]; return [...t].toSorted((e, t) => e.localeCompare(t)); } function resolveListedDefaultAccountId(e) { const t = e.configuredDefaultAccountId; const n = e.normalizeListedAccountId ?? normalizeAccountId; if (t && (e.allowUnlistedDefaultAccount || e.accountIds.some((e) => n(e) === t))) return t; if (e.accountIds.includes("default")) return DEFAULT_ACCOUNT_ID; if (e.ambiguousFallbackAccountId && e.accountIds.length > 1) return e.ambiguousFallbackAccountId; return e.accountIds[0] ?? "default"; } //#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/safe-cwd.ts function tryProcessCwd() { try { return process.cwd(); } catch { return; } } //#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/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/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 export { createAccountListHelpers as _, normalizeWindowsPathPreservingCase as a, LruCache as c, resolveHomeRelativePath as d, resolveRequiredHomeDir as f, sanitizeTerminalText as g, tryProcessCwd as h, normalizeWindowsPathForComparison$1 as i, resolveProfileStateDir as l, resolveUserPath as m, isAbortError as n, resolveConfigDir as o, resolveRequiredOsHomeDir as p, isPathInside$1 as r, resolveStateDir as s, shortenHomePath as t, expandHomePrefix as u, hasConfiguredAccountValue as v, mergeAccountConfig as y };