openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
432 lines (431 loc) • 19.7 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { r as isErrno } from "./errno-DFcoqIT9.mjs";
import { r as terminalText, t as hasTerminalControl } from "./safe-text-C80HAQ2e.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { l as pathExists$1 } from "./utils-C8YECn2Q.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import "./paths-DAcAg5aV.mjs";
import "./errors-BKzCeTYb.mjs";
import { r as decodeUtf8Input, t as Utf8InputError } from "./utf8-input-BHczGT8v.mjs";
import { i as decodeWindowsTextFileBuffer } from "./windows-encoding-BGmFeZe1.mjs";
import { n as quotePowerShellArg } from "./quote-cli-arg-J7A9UE6m.mjs";
import { t as publishOutputFileAtomically } from "./output-file.runtime.js";
import { existsSync, realpathSync, statSync } from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import os from "node:os";
import { readRegularFile, readRegularFileSync, resolvePathPrefixSync, sameFileIdentity } from "@openclaw/fs-safe/advanced";
import { isPathInside } from "@openclaw/fs-safe/path";
import { replaceFileAtomic } from "@openclaw/fs-safe/atomic";
//#region src/cli/completion-runtime.ts
const COMPLETION_SHELLS = [
"zsh",
"bash",
"powershell",
"fish"
];
const COMPLETION_SKIP_PLUGIN_COMMANDS_ENV = "OPENCLAW_COMPLETION_SKIP_PLUGIN_COMMANDS";
var CompletionProfileEncodingError = class extends Utf8InputError {
constructor(e, t, n) {
super(t, { cause: n });
this.profilePath = e;
this.name = "CompletionProfileEncodingError";
}
};
function formatInvalidUtf8InstallMessage(e) {
const t = formatCompletionReloadCommand(e.shell, e.cachePath);
return [
`Shell profile must be valid UTF-8: ${e.profilePath}.`,
"The file was left untouched.",
`For this session, load the prepared cache with: ${t}.`,
"Persistent installation requires backing up the profile and correcting its encoding first."
].join(" ");
}
async function readCompletionProfile(e, t, n = "mutate") {
const r = await fs$1.realpath(e);
const { buffer: i, stat: a, exactIdentity: o } = await readRegularFile({ filePath: r });
let s = "utf8";
if (t === "powershell" && process.platform === "win32") {
const [e, t, n] = i;
if (e === 255 && t === 254 || e === 254 && t === 255) s = e === 255 ? "utf16le" : "utf16be";
else if (e === 239 && t === 187 && n === 191) s = "utf8bom";
}
const c = s === "utf8" || s === "utf8bom" ? n === "mutate" ? decodeUtf8Input(i, `Shell profile ${e}`) : i.toString("utf8") : decodeWindowsTextFileBuffer({ buffer: i });
return {
content: s === "utf8bom" ? c.slice(1) : c,
encoding: s,
filePath: r,
mode: a.mode & 4095,
buffer: i,
exactIdentity: o
};
}
function encodeCompletionProfile(e, t) {
if (t === "utf8") return Buffer.from(e, "utf8");
const n = Buffer.from(`\uFEFF${e}`, t === "utf8bom" ? "utf8" : "utf16le");
return t === "utf16be" ? n.swap16() : n;
}
function isCompletionShell(e) {
return COMPLETION_SHELLS.includes(e);
}
function resolveShellBasename(e) {
const t = process.platform === "win32" ? path.win32.basename(e) : path.basename(e);
const n = path.win32.basename(e);
const r = n.length < t.length ? n : t;
return normalizeLowercaseStringOrEmpty(r.replace(/\.(?:exe|cmd|bat)$/i, ""));
}
/** Resolves the active shell from environment paths, using the platform's native default. */
function resolveShellFromEnv() {
const e = normalizeOptionalString(process.env.SHELL) ?? "";
const t = e ? resolveShellBasename(e) : "";
if (isCompletionShell(t)) return t;
if (t === "pwsh") return "powershell";
return process.platform === "win32" ? "powershell" : "zsh";
}
/** Returns the per-shell cached completion script path for a sanitized CLI binary name. */
function resolveCompletionCachePath(e, t, n = resolveStateDir(process.env, os.homedir)) {
const r = (t.trim() || "openclaw").replace(/[^a-zA-Z0-9._-]/g, "-");
return path.join(n, "completions", `${r}.${e === "powershell" ? "ps1" : e}`);
}
async function completionCacheExists(e, t = "openclaw") {
const n = resolveCompletionCachePath(e, t);
return pathExists$1(n);
}
function quoteCompletionPath(e, t) {
if (e === "powershell") return quotePowerShellArg(t);
return `'${e === "fish" ? t.replace(/[\\']/gu, "\\$&") : t.replaceAll("'", "'\\''")}'`;
}
function formatCompletionSourceLine(e, t) {
const n = quoteCompletionPath(e, t);
if (e === "powershell") return `. ${n}`;
if (e === "fish") return `test -f ${n}; and source ${n}`;
return `[ -f ${n} ] && source ${n}`;
}
function appendCompletionProfilePath(e, t, ...n) {
const r = t.sep === "\\" ? e.replaceAll("/", t.sep) : e;
return `${r}${r.endsWith(t.sep) ? "" : t.sep}${n.join(t.sep)}`;
}
/** Formats a current-shell command to load a profile or cached completion script. */
function formatCompletionReloadCommand(e, t) {
if (e === "powershell") return `. ${quoteCompletionPath(e, t)}`;
if (/^[a-zA-Z0-9_./~+-]+$/u.test(t)) return `source ${t}`;
const n = t.startsWith("~/") ? "~/" : "";
return `source ${n}${quoteCompletionPath(e, t.slice(n.length))}`;
}
function isCompletionProfileLine(e, t, n) {
return isSlowDynamicCompletionLine(e, t) || cachedCompletionSourceLines(n).includes(e.trim());
}
function cachedCompletionSourceLines(e) {
return [
`source "${e}"`,
`[ -f "${e}" ] && source "${e}"`,
`test -f "${e}"; and source "${e}"`,
...COMPLETION_SHELLS.map((t) => formatCompletionSourceLine(t, e))
];
}
function isPreviousCompletionSourceLine(e, t, n) {
const r = e.trim();
const i = /^(?:\[\s+-f|test\s+-f)\s+(.+?)\s*(?:\]\s*&&|;\s*and)\s+source\s+\1$/u.exec(r);
const a = /^(source|\.)\s+(.+)$/u.exec(r);
const o = i?.[1] ?? a?.[2];
if (!o) return false;
const s = a?.[1] === "." ? "powershell" : n;
const c = i ? /^"(.+)"$/u.exec(o)?.[1] : /^source\s+"([^"]+)"$/u.exec(r)?.[1];
const l = o.slice(1, -1);
const u = c ?? (s === "powershell" ? l.replace(/(['‘-‛])\1/gu, "$1") : s === "fish" ? l.replace(/\\([\\'])/gu, "$1") : l.replaceAll("'\\''", "'"));
const d = s === "powershell" && `'${u.replaceAll("'", "''")}'` === o;
if (!c && !d && quoteCompletionPath(s, u) !== o) return false;
const f = u.includes("\\") ? path.win32 : path;
return f.isAbsolute(u) && f.basename(f.dirname(u)) === "completions" && f.basename(u) === path.basename(t);
}
const PORTABLE_HOOK_SHELLS = /* @__PURE__ */ new Set([
"bash",
"zsh",
"fish"
]);
/** Characters that would change meaning if a literal shell operand were expanded or globbed. */
const PORTABLE_PATH_UNSAFE = /[\s"'`$\\|&;<>()*?[\]{}]/u;
/**
* Expands a guarded-source operand that is a portable `$HOME`-rooted path, or returns undefined
* when the operand is not one of the supported safe forms. The operand may be double-quoted or
* unquoted; single quotes prevent expansion and are never treated as portable. Expansion is
* purely textual (`${HOME}`/`$HOME` token + literal suffix); nothing is evaluated.
*/
function expandPortableHomeOperand(e, t, n) {
const r = e.length >= 2 && e.startsWith("\"") && e.endsWith("\"");
const i = r ? e.slice(1, -1) : e;
if (r ? i.includes("\"") : /["'`]/u.test(i)) return;
if (!r && PORTABLE_PATH_UNSAFE.test(t)) return;
const a = n === "fish" ? "$HOME" : i.startsWith("${HOME}") ? "${HOME}" : "$HOME";
if (!i.startsWith(a)) return;
const o = i.slice(a.length);
if (PORTABLE_PATH_UNSAFE.test(o)) return;
return o.startsWith("/") ? `${t}${o}` : void 0;
}
/**
* Recognizes a user-managed portable completion hook such as
* `[[ -f "${HOME}/.openclaw/completions/openclaw.bash" ]] && source "${HOME}/.openclaw/completions/openclaw.bash"`.
* Dotfile managers own these lines, so recognition is kept separate from rewrite ownership:
* portable hooks are never deleted or rewritten by the installer. The anchored parser only
* accepts guarded forms whose guard and source operands both expand to the current cache path;
* compound commands and mismatched paths are left alone.
*/
function isPortableCompletionSourceLine(e, t, n, r) {
if (!PORTABLE_HOOK_SHELLS.has(t)) return false;
const i = r.endsWith(path.sep) ? r : `${r}${path.sep}`;
if (!n.startsWith(i)) return false;
const a = n.slice(i.length);
if (PORTABLE_PATH_UNSAFE.test(a) || a === "") return false;
const o = e.replace(/^[ \t]+|[ \t]+$/gu, "");
const s = t === "fish" ? /^test[ \t]+-f[ \t]+(.+?)[ \t]*;[ \t]*and[ \t]+source[ \t]+(.+)$/u.exec(o) : /^\[[ \t]+-f[ \t]+(.+?)[ \t]+\][ \t]*&&[ \t]+source[ \t]+(.+)$/u.exec(o) ?? /^\[\[[ \t]+-f[ \t]+(.+?)[ \t]+\]\][ \t]*&&[ \t]+source[ \t]+(.+)$/u.exec(o);
const c = s?.[1];
const l = s?.[2];
return c !== void 0 && l !== void 0 && expandPortableHomeOperand(c, r, t) === n && expandPortableHomeOperand(l, r, t) === n;
}
function isOwnedCompletionInvocation(e, t) {
const [n, r, ...i] = e.trim().split(/\s+/u);
if (n !== t || r !== "completion") return false;
if (i.length === 2 && (i[0] === "--shell" || i[0] === "-s")) return isCompletionShell(i[1] ?? "");
return i.length === 0 || i.length === 1 && isCompletionShell((i[0] ?? "").replace(/^(?:--shell=|-s=?)/u, ""));
}
/** Check if a line uses an owned slow dynamic completion pattern (source <(...)). */
function isSlowDynamicCompletionLine(e, t) {
const n = e.trim();
const r = `<(${t} completion`;
const i = n.indexOf(r);
if (i >= 0) {
const e = n.slice(i);
return /^(?:(?:\[\s+-f\s+[^\]]+\]\s*&&\s*)?(?:source|\.))\s*$/u.test(n.slice(0, i).trimEnd()) && e.endsWith(")") && isOwnedCompletionInvocation(e.slice(2, -1), t);
}
const a = n.indexOf(`${t} completion`);
if (a < 0) return false;
const o = n.slice(0, a).trimEnd();
const s = /^eval\s+(["']?)\$\($/u.exec(o);
if (s) {
const e = n.slice(a);
const r = `)${s[1] ?? ""}`;
return e.endsWith(r) && isOwnedCompletionInvocation(e.slice(0, -r.length), t);
}
if (a !== 0 || /[;&]/u.test(n)) return false;
const c = n.split("|").map((e) => e.trim());
const l = c.at(-1) ?? "";
return isOwnedCompletionInvocation(c[0] ?? "", t) && /^(?:source|Invoke-Expression|iex)$/iu.test(l) && (c.length === 2 || c.length === 3 && /^Out-String$/iu.test(c[1] ?? ""));
}
async function resolveCompletionProfileWritePath(e) {
const { existingPath: t, unresolvedSegments: n } = resolvePathPrefixSync(e);
const r = [t, ...n].join(path.sep);
const i = path.dirname(r);
await fs$1.mkdir(i, { recursive: true });
return path.join(await fs$1.realpath(i), path.basename(r));
}
/** Resolves the shell startup profile path that should contain the OpenClaw completion block. */
function resolveCompletionProfilePath(e) {
const t = process.env;
const n = process.platform;
const r = n === "win32" ? path.win32 : path.posix;
const i = t.HOME || os.homedir();
if (e === "zsh") return appendCompletionProfilePath(t.ZDOTDIR === void 0 ? i : t.ZDOTDIR || r.sep, r, ".zshrc");
if (e === "bash") {
const e = appendCompletionProfilePath(i, r, ".bashrc");
return existsSync(e) ? e : appendCompletionProfilePath(i, r, ".bash_profile");
}
if (e === "fish") {
const e = t.XDG_CONFIG_HOME;
return appendCompletionProfilePath(e && r.isAbsolute(e) ? e : appendCompletionProfilePath(i, r, ".config"), r, "fish", "config.fish");
}
if (n === "win32") {
const e = normalizeOptionalString(t.SHELL) ?? "";
const n = (e ? resolveShellBasename(e) : "") === "powershell" ? "WindowsPowerShell" : "PowerShell";
return appendCompletionProfilePath(t.USERPROFILE || i, r, "Documents", n, "Microsoft.PowerShell_profile.ps1");
}
return appendCompletionProfilePath(i, r, ".config", "powershell", "Microsoft.PowerShell_profile.ps1");
}
/** Remove only literal cache registrations owned by state being uninstalled. */
async function removeCompletionRegistrations(e) {
const t = [];
const n = /* @__PURE__ */ new Set();
const r = process.platform === "win32" ? path.win32 : path.posix;
const i = process.env.HOME || os.homedir();
const a = COMPLETION_SHELLS.flatMap((t) => e.stateDirs.map((e) => resolveCompletionCachePath(t, "openclaw", e))).filter((t) => !e.preservePaths.some((e) => isPathInside(e, t)));
const o = [...new Set(a.flatMap(cachedCompletionSourceLines))];
if (o.length === 0) return t;
for (const a of COMPLETION_SHELLS) {
const s = a === "bash" ? [".bashrc", ".bash_profile"].map((e) => appendCompletionProfilePath(i, r, e)) : a === "powershell" && process.platform === "win32" ? ["PowerShell", "WindowsPowerShell"].map((e) => appendCompletionProfilePath(process.env.USERPROFILE || i, r, "Documents", e, "Microsoft.PowerShell_profile.ps1")) : [resolveCompletionProfilePath(a)];
for (const r of s) {
let i;
try {
i = await readCompletionProfile(r, a, "inspect");
} catch (e) {
if (isErrno(e) && e.code === "ENOENT") continue;
throw e;
}
if (n.has(i.filePath)) continue;
const s = i.encoding === "utf16le" || i.encoding === "utf16be";
const c = s ? i.content : i.buffer.toString("latin1");
const l = o.map((e) => escapeRegExp(s ? e : Buffer.from(e).toString("latin1"))).join("|");
const u = new RegExp(`${s ? "^" : "(?:^|(?<=^\\xEF\\xBB\\xBF))"}(?:[\\t ]*# OpenClaw Completion[\\t ]*\\r?\\n)?[\\t ]*(?:${l})[\\t ]*(?:\\r?\\n|$)`, "gm");
const d = c.replace(u, "");
if (d === c) continue;
if (s && !encodeCompletionProfile(c, i.encoding).equals(i.buffer)) throw new Error(terminalText`Cannot safely update malformed PowerShell profile ${r}. Repair its encoding and retry uninstall.`);
n.add(i.filePath);
if (!e.dryRun) {
const t = await fs$1.stat(path.dirname(i.filePath));
await replaceFileAtomic({
filePath: i.filePath,
content: s ? encodeCompletionProfile(d, i.encoding) : Buffer.from(d, "latin1"),
mode: i.mode,
dirMode: t.mode & 4095,
tempPrefix: ".openclaw-completion-profile",
syncTempFile: true,
syncParentDir: true,
assertBeforeMutation: () => {
const n = realpathSync(r);
const a = readRegularFileSync({ filePath: n });
if (n !== i.filePath || !sameFileIdentity(a.exactIdentity, i.exactIdentity) || !a.buffer.equals(i.buffer) || (a.stat.mode & 4095) !== i.mode || (statSync(path.dirname(n)).mode & 4095) !== (t.mode & 4095)) throw new Error("Completion profile changed during cleanup; retry uninstall.");
e.assertCurrent();
}
});
}
t.push(r);
}
}
return t;
}
/** Formats the resolved startup profile relative to HOME when that preserves its actual location. */
function resolveCompletionProfileHint(e) {
const t = resolveCompletionProfilePath(e);
if (e === "powershell") return t;
if (!path.isAbsolute(t)) return t.startsWith(`.${path.sep}`) || t.startsWith(`..${path.sep}`) ? t : `.${path.sep}${t}`;
const n = process.env.HOME;
return n && t.startsWith(`${n}${path.sep}`) ? `~/${t.slice(n.length + 1)}` : t;
}
/** Returns whether a shell profile already contains an OpenClaw completion block or source line. */
async function isCompletionInstalled(e, t = "openclaw") {
const n = resolveCompletionProfilePath(e);
if (!await pathExists$1(n)) return false;
const r = resolveCompletionCachePath(e, t);
const i = process.env.HOME || os.homedir();
const { content: a } = await readCompletionProfile(n, e, "inspect");
return a.split("\n").some((n) => isCompletionProfileLine(n, t, r) || isPortableCompletionSourceLine(n, e, r, i));
}
/**
* Returns true if profile has `source <(openclaw completion ...)` instead of cached file.
*/
async function usesSlowDynamicCompletion(e, t = "openclaw") {
const n = resolveCompletionProfilePath(e);
if (!await pathExists$1(n)) return false;
const r = resolveCompletionCachePath(e, t);
const { content: i } = await readCompletionProfile(n, e, "inspect");
return i.split("\n").some((e) => isSlowDynamicCompletionLine(e, t) && !e.includes(r));
}
const PROFILE_WRITE_ERROR_CODES = /* @__PURE__ */ new Set([
"EACCES",
"EPERM",
"EROFS"
]);
var CompletionCacheMissingError = class extends Error {
constructor(e) {
super(e);
this.name = "CompletionCacheMissingError";
}
};
function findCompletionProfileWriteError(e) {
if (isErrno(e) && PROFILE_WRITE_ERROR_CODES.has(e.code ?? "")) return e;
return e instanceof Error ? findCompletionProfileWriteError(e.cause) : void 0;
}
/** Optional setup/Doctor paths may skip install on write or encoding failures. */
function findOptionalCompletionInstallFailure(e) {
const t = findCompletionProfileWriteError(e);
if (t) return {
kind: "write",
error: t
};
let n = e;
while (n instanceof Error) {
if (n instanceof Utf8InputError && "profilePath" in n && typeof n.profilePath === "string") return {
kind: "encoding",
message: n.message,
profilePath: n.profilePath
};
n = n.cause;
}
}
async function installCompletion(e, t, n = "openclaw") {
if (!isCompletionShell(e)) throw new Error(`Automated installation not supported for ${e} yet.`);
const r = resolveCompletionCachePath(e, n);
if (!await pathExists$1(r)) throw new CompletionCacheMissingError(`Completion cache not found at ${r}. Run \`${n} completion --write-state\` first.`);
const i = resolveCompletionProfilePath(e);
const a = process.env.HOME || os.homedir();
try {
let o;
let s = "utf8";
try {
({content: o, encoding: s} = await readCompletionProfile(i, e, "mutate"));
} catch (n) {
if (n instanceof Utf8InputError) throw new CompletionProfileEncodingError(i, formatInvalidUtf8InstallMessage({
profilePath: i,
shell: e,
cachePath: r
}), n);
if (n.code !== "ENOENT") throw n;
if (!t) console.warn(terminalText`Profile not found at ${i}. Creating a new one.`);
o = "";
}
const c = o.split("\n");
const l = [];
let u = false;
let d = false;
for (let t = 0; t < c.length; t += 1) {
const i = c[t] ?? "";
if (i.trim() === "# OpenClaw Completion") {
const o = c[t + 1] ?? "";
if (isPortableCompletionSourceLine(o, e, r, a)) {
l.push(i);
continue;
}
u = true;
if (isCompletionProfileLine(o, n, r) || isPreviousCompletionSourceLine(o, r, e)) t += 1;
continue;
}
if (isCompletionProfileLine(i, n, r)) {
u = true;
continue;
}
if (isPortableCompletionSourceLine(i, e, r, a)) {
u = true;
d = true;
}
l.push(i);
}
let f;
if (d) f = l.join("\n");
else {
const t = l.join("\n").replace(/(?<!\n)\n+$/u, "");
const n = `# OpenClaw Completion\n${formatCompletionSourceLine(e, r)}`;
f = t ? `${t}\n\n${n}\n` : `${n}\n`;
}
if (f === o) {
if (!t) console.log(terminalText`Completion already installed in ${i}`);
return;
}
if (!t) console.log(terminalText`${u ? "Updating" : "Installing"} completion in ${i}...`);
await publishOutputFileAtomically({
filePath: await resolveCompletionProfileWritePath(i),
tempPrefix: ".openclaw-completion-profile",
durable: true,
writeTemp: async (e) => {
await fs$1.writeFile(e, encodeCompletionProfile(f, s), { flag: "wx" });
}
});
if (!t) {
const t = resolveCompletionProfileHint(e);
console.log(hasTerminalControl(t) ? "Completion installed. Restart your shell to load it." : `Completion installed. Restart your shell or run: ${formatCompletionReloadCommand(e, t)}`);
}
} catch (e) {
if (e instanceof CompletionProfileEncodingError) throw e;
const t = e instanceof Error ? e.message : String(e);
throw new Error(`Failed to install completion: ${t}`, { cause: e });
}
}
//#endregion
export { formatCompletionReloadCommand as a, isCompletionShell as c, resolveCompletionProfileHint as d, resolveCompletionProfilePath as f, findOptionalCompletionInstallFailure as i, removeCompletionRegistrations as l, usesSlowDynamicCompletion as m, COMPLETION_SKIP_PLUGIN_COMMANDS_ENV as n, installCompletion as o, resolveShellFromEnv as p, completionCacheExists as r, isCompletionInstalled as s, COMPLETION_SHELLS as t, resolveCompletionCachePath as u };