UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

385 lines (384 loc) • 13.8 kB
import { h as extractErrorCode } from "./paths-0xDagtub.mjs"; import { p as isRecord } from "./utils-BclMknzT.mjs"; import { L as normalizeLowercaseStringOrEmpty } from "./path-guards-quCEQx1i.mjs"; import { n as resolveDiagnosticProcessEnv } from "./process-env-Bx8i77R6.mjs"; import { v as resolveIdentityPathViaExistingAncestorSync } from "./redact-BRF0hr6G.mjs"; import { n as sha256HexPrefixCore } from "./node-crypto-CWAQhBWK.mjs"; import { n as isNodeRuntime, r as resolveRuntimeScriptPosition, t as isBunRuntime } from "./runtime-binary-QwVVJ9cA.mjs"; import { spawnSync } from "node:child_process"; import fsSync, { closeSync, openSync } from "node:fs"; import path from "node:path"; import { createHash, hash } from "node:crypto"; import { sha256FileSync } from "@openclaw/fs-safe/durability"; //#region src/infra/crypto-digest.ts function sha256Base64Url(e) { return hash("sha256", e, "base64url"); } /** Matches the streaming helper's symlink-following path contract. */ function sha256FileSync$1(e) { const t = openSync(e, "r"); try { return sha256FileSync(t).digest; } finally { closeSync(t); } } //#endregion //#region cli-root-options.mjs /** CLI token that stops root option scanning and leaves following args positional. */ const FLAG_TERMINATOR = "--"; const ROOT_BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--dev", "--no-color"]); const ROOT_VALUE_FLAGS = /* @__PURE__ */ new Set([ "--profile", "--log-level", "--container" ]); /** Returns whether a token can be consumed as a root option value. */ function isValueToken(e) { if (!e || e === "--") return false; if (!e.startsWith("-")) return true; return /^-\d+(?:\.\d+)?$/.test(e); } /** Count root-option tokens conservatively for route matching. */ function consumeRootOptionToken(e, t) { const n = e[t]; if (!n) return 0; if (ROOT_BOOLEAN_FLAGS.has(n)) return 1; if (n.startsWith("--profile=") || n.startsWith("--log-level=") || n.startsWith("--container=")) return 1; if (ROOT_VALUE_FLAGS.has(n)) return isValueToken(e[t + 1]) ? 2 : 1; return 0; } /** Consume required root values by their Commander role before startup policy is selected. */ function consumeRootCommandOptionToken(e, t) { return consumeKnownOptionToken(e, t, ROOT_BOOLEAN_FLAGS, ROOT_VALUE_FLAGS, "command-path"); } /** Read positional command tokens while accepting root options at any pre-terminator position. */ function getRootOptionAwareCommandPath(e, t) { const n = e.slice(2); const r = []; let i = false; for (let e = 0; e < n.length; e += 1) { const a = n[e]; if (!a) break; if (!i && a === "--") { if (r.length > 0) break; i = true; continue; } const o = i ? 0 : consumeRootCommandOptionToken(n, e); if (o > 0) { e += o - 1; continue; } if (!i && a.startsWith("-")) continue; r.push(a); if (r.length >= t) break; } return r; } function rewriteUpdateFlagArgv(e) { const t = e.indexOf("--update"); if (t === -1) return e; for (let n = 2; n < e.length; n++) { const r = e[n]; if (!r || r === "--") return e; if (n === t) return [ ...e.slice(0, t), "update", ...e.slice(t + 1) ]; const i = consumeRootOptionToken(e, n); if (i > 0) { n += i - 1; continue; } if (!r.startsWith("-")) return e; } return e; } /** Launchers choose their signal budget before the CLI parses, so accept both spellings. */ function isUpdateCommandArgv(e) { return getRootOptionAwareCommandPath(rewriteUpdateFlagArgv(e), 1)[0] === "update"; } function consumeKnownOptionToken(e, t, n, r, i) { const a = e[t]; if (!a || a === "--" || !a.startsWith("-")) return 0; const o = a.indexOf("="); const s = o === -1 ? a : a.slice(0, o); if (n.has(s)) return o === -1 ? 1 : 0; if (!r.has(s)) return 0; if (o !== -1) return i === "command-path" || a.slice(o + 1).trim() ? 1 : 0; if (i === "command-path") return e[t + 1] !== void 0 ? 2 : 0; return isValueToken(e[t + 1]) ? 2 : 0; } /** Parse command positionals while consuming known root and command options. */ function getCommandPositionalsWithRootOptions(e, t) { return parseCommandArgsWithRootOptions(e, t, false); } function parseCommandArgsWithRootOptions(e, t, n, r = false) { const i = e.slice(2); const a = new Set(t.booleanFlags ?? []); const o = new Set(t.valueFlags ?? []); const s = []; const c = []; const l = []; let u = 0; let d = false; for (let e = 0; e < i.length; e += 1) { const f = i[e]; if (f === void 0) break; if (!d && f === "--") { if (t.mode !== "command-path") break; d = true; continue; } const p = d ? 0 : t.mode === "command-path" ? consumeRootCommandOptionToken(i, e) : consumeRootOptionToken(i, e); if (p > 0) { (u > 0 && a.has(f) ? l : c).push(...i.slice(e, e + p)); e += p - 1; continue; } if (!d && f.startsWith("-")) { const n = consumeKnownOptionToken(i, e, a, o, t.mode); if (n === 0 || u === 0) return null; l.push(f); e += n - 1; continue; } if (u < t.commandPath.length) { if (f !== t.commandPath[u]) return null; u += 1; if (n && u === t.commandPath.length) { const t = i.slice(e + 1); return d ? ["--", ...t] : t; } continue; } s.push(f); if (!r && s.length === t.maxPositionals) return s; } return u < t.commandPath.length ? null : r ? { rootOptions: c, commandOptions: l } : s; } //#endregion //#region src/plugins/plugin-source-capture-path.ts const PLUGIN_SOURCE_CAPTURE_PREFIX = "openclaw-plugin-build-"; function resolvePluginSourceCapturesDirectory(e) { return path.join(e, "tmp", "plugin-captures"); } function resolvePluginSourceCaptureFallbackPrefix(e) { const t = resolveIdentityPathViaExistingAncestorSync(e); return `openclaw-plugin-captures-${sha256HexPrefixCore(t, 32)}-`; } function isLegacyPluginSourceCaptureName(e) { return e.startsWith("openclaw-plugin-build-") || e.startsWith("openclaw-model-catalog-"); } //#endregion //#region src/infra/gateway-process-argv.ts function normalizeProcArg(e) { return normalizeLowercaseStringOrEmpty(e.replaceAll("\\", "/")); } const ENTRY_CANDIDATES = [ "openclaw.mjs", "dist/index.js", "dist/entry.js", "scripts/run-node.mjs", "src/entry.ts", "src/index.ts" ]; function referencesRetainedArtifact(e) { return e.split(/[\\/=]/u).some((e) => isLegacyPluginSourceCaptureName(e) || /^openclaw-update-runtime-[A-Za-z0-9]{6}$/u.test(e)); } /** Exhausted lookup proves absence; unreadable identities stay unresolved. */ function readProcessPackageIdentity(e, t = false) { for (let n = e;;) { let e; try { e = JSON.parse(fsSync.readFileSync(path.join(n, "package.json"), "utf8")); } catch (e) { const r = path.dirname(n); if (t && extractErrorCode(e) === "ENOENT") { if (r === n) return { kind: "absent" }; if (path.basename(n) === "node_modules") return { kind: "unknown", reason: "could not read package identity" }; n = r; continue; } return { kind: "unknown", reason: "could not read package identity" }; } if (!isRecord(e) || typeof e.name !== "string" || !e.name.trim() || e.name !== e.name.trim()) return { kind: "unknown", reason: "package identity has no valid name" }; return { kind: "package", name: e.name, scripts: isRecord(e.scripts) ? e.scripts : {} }; } } function readProcessWorkingDirectories(e) { const t = new Set(e.filter((e) => Number.isSafeInteger(e) && e > 0)); const n = /* @__PURE__ */ new Map(); if (t.size === 0) return n; if (process.platform === "linux") { for (const e of t) try { n.set(e, fsSync.readlinkSync(`/proc/${e}/cwd`)); } catch {} return n; } try { if (process.platform === "darwin") { const e = spawnSync("/usr/sbin/lsof", [ "-a", "-p", [...t].join(","), "-d", "cwd", "-F0pn" ], { encoding: "utf8", timeout: 5e3, maxBuffer: 4194304, env: resolveDiagnosticProcessEnv() }); if (e.error || e.status !== 0 && e.status !== 1) return n; const r = e.stdout.split("\0"); r.pop(); const i = /* @__PURE__ */ new Set(); let a; for (const e of r) { const r = e.replace(/^\n/, ""); if (r.startsWith("p")) { const e = /^p(\d+)$/.exec(r); a = e && t.has(Number(e[1])) ? Number(e[1]) : void 0; } else if (a !== void 0 && r.startsWith("n") && path.isAbsolute(r.slice(1))) { if (n.delete(a)) i.add(a); else if (!i.has(a)) n.set(a, r.slice(1)); } } } } catch {} return n; } /** Generic script names identify OpenClaw only inside a verified package root. */ function classifyEntrypoint(e, t = {}) { const n = normalizeProcArg(e[0] ?? "").replace(/\.(bat|cmd|exe)$/i, ""); if (!t.requirePackageIdentity && (n.endsWith("/openclaw") || n === "openclaw")) return { kind: "openclaw", entryIndex: 0 }; const r = /(?:^|\/)openclaw\.mjs$/.test(n) ? 0 : resolveRuntimeScriptPosition(e).position; if (typeof r !== "number") return r.kind === "unclassified" ? { kind: "unclassified", cause: "runtime-syntax", reason: r.reason } : { kind: "other" }; const i = e[r]; if (t.inspectPackage && !t.requirePackageIdentity && t.cwd && path.isAbsolute(t.cwd) && isBunRuntime(e[0] ?? "") && !/[\\/]/u.test(i) && !path.extname(i)) { const e = readProcessPackageIdentity(t.cwd, true); if (e.kind === "unknown") return { kind: "unclassified", cause: "package-identity", reason: e.reason }; const n = e.kind === "package" ? e.scripts[i] : void 0; if (typeof n === "string" && n.trim()) return e.kind === "package" && e.name === "openclaw" ? { kind: "openclaw" } : { kind: "other" }; } const a = classifyOpenClawEntrypointPath(i, t); return a.kind === "openclaw" ? { ...a, entryIndex: r } : a; } /** Path evidence is shared with cleanup even when launcher syntax is unfamiliar. */ function classifyOpenClawEntrypointPath(e, t = {}) { const n = normalizeProcArg(e); if (!t.requirePackageIdentity && !t.inspectPackage && /(?:^|\/)openclaw\.mjs$/.test(n)) return { kind: "openclaw" }; const r = [...ENTRY_CANDIDATES, ...t.additionalEntrypoints ?? []]; let i = e; if (!path.isAbsolute(e)) { const n = t.cwd ?? (t.pid === void 0 ? void 0 : readProcessWorkingDirectories([t.pid]).get(t.pid)); if (!n || !path.isAbsolute(n)) return { kind: "unclassified", cause: "cwd", reason: "working directory is unavailable" }; i = path.resolve(n, e); } let a; let o; try { a = fsSync.realpathSync(i); if (t.inspectPackage && !t.requirePackageIdentity && referencesRetainedArtifact(a)) return { kind: "openclaw", artifactPath: a }; const n = t.requirePackageIdentity || t.inspectPackage ? fsSync.statSync(a) : void 0; if (t.requirePackageIdentity && !n?.isFile()) return { kind: "unclassified", cause: "script", reason: `entrypoint is not a regular file: ${e}` }; o = n?.isDirectory() ?? false; } catch { return { kind: "unclassified", cause: "script", reason: "could not resolve script" }; } const s = normalizeProcArg(a); if (!t.requirePackageIdentity && /(?:^|\/)openclaw\.mjs$/.test(n)) return { kind: "openclaw" }; const c = o ? void 0 : r.find((e) => s.endsWith(`/${e}`)); if (!c && (!t.inspectPackage || t.requirePackageIdentity)) return { kind: "other" }; const l = c ? a.slice(0, -c.length) : o ? a : path.dirname(a); const u = readProcessPackageIdentity(l, t.inspectPackage && !t.requirePackageIdentity || !c && !o); if (u.kind === "unknown") return { kind: "unclassified", cause: "package-identity", reason: u.reason }; return u.kind === "package" && u.name === "openclaw" ? { kind: "openclaw", ...t.requirePackageIdentity ? { packageIdentity: { root: path.resolve(l), entrypoint: a } } : {} } : { kind: "other" }; } /** One classification for process owners, command consumers, and diagnostics. */ function classifyOpenClawArgv(e, t = {}) { const { command: n, owner: r, pid: i, port: a } = t; if (!t.requirePackageIdentity && n === "gateway" && r?.pid === i && r?.state === "live" && (a === void 0 || r.port === a)) return { kind: "openclaw" }; const o = normalizeProcArg(e[0] ?? "").split("/").at(-1)?.replace(/\.(exe|cmd|bat)$/, "") ?? ""; if (!t.requirePackageIdentity && /^openclaw-[a-z0-9-]+$/.test(o)) return !n || o === `openclaw-${n}` ? { kind: "openclaw" } : { kind: "other" }; const s = classifyEntrypoint(e, t); if (n) return s.kind === "openclaw" && normalizeProcArg(getRootOptionAwareCommandPath(["node", ...e.slice(s.entryIndex)], 1)[0] ?? "") !== n ? { kind: "other" } : s; if (s.kind === "openclaw" || !t.requirePackageIdentity && e.some((e) => e.replaceAll("\\", "/").split("/").some(isLegacyPluginSourceCaptureName))) return s.kind === "openclaw" ? s : { kind: "openclaw" }; if (t.serviceMarkerUnavailable && !t.requirePackageIdentity) return { kind: "unclassified", cause: "service-marker", reason: "process environment is unreadable" }; let c = t.serviceMarker; if (i !== void 0 && process.platform === "linux" && (isNodeRuntime(o) || isBunRuntime(o) || o === "tsx")) try { c = fsSync.readFileSync(`/proc/${i}/environ`, "utf8").split("\0").find((e) => e.startsWith("OPENCLAW_SERVICE_MARKER="))?.slice(24); } catch (e) { return { kind: "unclassified", cause: "service-marker", reason: `process identity inspection failed (${extractErrorCode(e) ?? "unavailable"})` }; } return !t.requirePackageIdentity && c === "openclaw" ? { kind: "openclaw" } : s; } //#endregion export { referencesRetainedArtifact as a, resolvePluginSourceCapturesDirectory as c, isUpdateCommandArgv as d, rewriteUpdateFlagArgv as f, readProcessWorkingDirectories as i, getCommandPositionalsWithRootOptions as l, sha256FileSync$1 as m, classifyOpenClawEntrypointPath as n, isLegacyPluginSourceCaptureName as o, sha256Base64Url as p, readProcessPackageIdentity as r, resolvePluginSourceCaptureFallbackPrefix as s, classifyOpenClawArgv as t, getRootOptionAwareCommandPath as u };