UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

489 lines (488 loc) • 15 kB
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs"; import { t as killProcessTree } from "./kill-tree-DlMFq2XA.mjs"; import { n as canAccessSync } from "./path-existence-Co7-GyVr.mjs"; import "./utils-C8YECn2Q.mjs"; import { n as computeBackoff } from "./src-BPmQBLJp.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { i as resolveExecutable } from "./executable-path-D8oWZRS5.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { n as runCommandWithTimeout, s as releaseChildProcessOutputAfterExit } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import "./backoff-B-fIQi7C.mjs"; import { i as formatCommandResult, r as formatCommandOutput } from "./command-error-BbCvU7oG.mjs"; import { n as hasBinary } from "./config-eval-nIkprN5m.mjs"; import "./config-C4hfYsYF.mjs"; import { b as resolveGogServeInvocation, d as buildGogWatchStartArgs, h as normalizeServePath, l as buildGogWatchServeArgs, u as buildGogWatchServeLogArgs, v as resolveGmailHookRuntimeConfig, y as resolveGogExecutable } from "./gmail-B-kIMiKm.mjs"; import fs from "node:fs"; import process$1 from "node:process"; import path from "node:path"; import { spawn } from "node:child_process"; //#region src/hooks/gmail-setup-utils.ts let cachedPythonPath; let gcloudBin; function formatJsonParseFailure(e, t, n) { return `${e} returned invalid JSON: ${formatCommandOutput(formatErrorMessage(n))}\n${formatCommandResult(e, t)}`; } function findExecutablesOnPath(e) { const t = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean); const n = /* @__PURE__ */ new Set(); const r = []; for (const i of t) for (const t of e) { const e = path.join(i, t); if (n.has(e)) continue; if (canAccessSync(e, fs.constants.X_OK)) { r.push(e); n.add(e); } } return r; } function ensureGcloudOnPath() { if (hasBinary("gcloud")) return true; for (const e of [ "/opt/homebrew/share/google-cloud-sdk/bin/gcloud", "/usr/local/share/google-cloud-sdk/bin/gcloud", "/opt/homebrew/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud", "/usr/local/Caskroom/google-cloud-sdk/latest/google-cloud-sdk/bin/gcloud" ]) if (canAccessSync(e, fs.constants.X_OK)) { const t = path.dirname(e); const n = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean); if (!n.includes(t)) process.env.PATH = [...n, t].join(path.delimiter); return true; } return false; } const MIN_GCLOUD_PYTHON = [3, 10]; const MAX_GCLOUD_PYTHON = [3, 14]; function isSupportedGcloudPythonVersion(e, t) { if (e !== MIN_GCLOUD_PYTHON[0]) return false; return t >= MIN_GCLOUD_PYTHON[1] && t <= MAX_GCLOUD_PYTHON[1]; } async function resolvePythonExecutablePath() { if (cachedPythonPath !== void 0) return cachedPythonPath ?? void 0; const e = findExecutablesOnPath(["python3", "python"]); for (const t of e) { const e = await runCommandWithTimeout([ t, "-c", "import os, sys; print(os.path.realpath(sys.executable)); print('%d.%d' % sys.version_info[:2])" ], { timeoutMs: 2e3 }); if (e.code !== 0) continue; const n = e.stdout.trim().split(/\r?\n/); const r = n[0]?.trim(); if (!r) continue; const i = n[1]?.trim().match(/^(\d+)\.(\d+)/); if (!i) continue; if (!isSupportedGcloudPythonVersion(Number(i[1]), Number(i[2]))) continue; if (canAccessSync(r, fs.constants.X_OK)) { cachedPythonPath = r; return r; } } cachedPythonPath = null; } async function gcloudEnv() { return { CLOUDSDK_PYTHON: await resolvePythonExecutablePath(), CLOUDSDK_PYTHON_ARGS: void 0 }; } async function runGcloudCommand(e, t) { return await runCommandWithTimeout([gcloudBin ??= resolveExecutable("gcloud"), ...e], { timeoutMs: t, env: await gcloudEnv() }); } async function ensureDependency(e, t) { if (e === "gcloud" && ensureGcloudOnPath()) return; if (hasBinary(e)) return; if (process.platform !== "darwin") throw new Error(`${e} not installed; install it and retry`); if (!hasBinary("brew")) throw new Error("Homebrew not installed (install brew and retry)"); const n = e === "gcloud" ? await gcloudEnv() : void 0; const r = await runCommandWithTimeout([ "brew", "install", ...t ], { timeoutMs: 6e5, env: n }); if (r.code !== 0) throw new Error(formatCommandResult(`brew install for ${e}`, r)); if (!hasBinary(e)) throw new Error(`${e} still not available after brew install`); } async function ensureGcloudAuth() { const e = await runGcloudCommand([ "auth", "list", "--filter", "status:ACTIVE", "--format", "value(account)" ], 3e4); if (e.code === 0 && e.stdout.trim()) return; const t = await runGcloudCommand(["auth", "login"], 6e5); if (t.code !== 0) throw new Error(formatCommandResult("gcloud auth login", t)); } async function runGcloud(e) { const t = await runGcloudCommand(e, 12e4); if (t.code !== 0) throw new Error(formatCommandResult("gcloud command", t)); return t; } async function ensureTopic(e, t) { if ((await runGcloudCommand([ "pubsub", "topics", "describe", t, "--project", e ], 3e4)).code === 0) return; await runGcloud([ "pubsub", "topics", "create", t, "--project", e ]); } async function ensureSubscription(e, t, n, r) { const i = await runGcloudCommand([ "pubsub", "subscriptions", "describe", t, "--project", e ], 3e4); await runGcloud([ "pubsub", "subscriptions", i.code === 0 ? "update" : "create", t, "--project", e, ...i.code === 0 ? [] : ["--topic", n], "--push-endpoint", r ]); } async function ensureTailscaleEndpoint(e) { if (e.mode === "off") return ""; const t = resolveExecutable("tailscale"); const n = ["status", "--json"]; const r = "tailscale status --json"; const i = await runCommandWithTimeout([t, ...n], { timeoutMs: 3e4, signal: e.signal }); if (i.code !== 0) throw new Error(formatCommandResult(r, i)); let a; try { a = JSON.parse(i.stdout); } catch (e) { throw new Error(formatJsonParseFailure(r, i, e), { cause: e }); } const o = a.Self?.DNSName?.replace(/\.$/, ""); if (!o) throw new Error("tailscale DNS name missing; run tailscale up"); const s = typeof e.target === "string" && e.target.trim().length > 0 ? e.target.trim() : e.port ? String(e.port) : ""; if (!s) throw new Error("tailscale target missing; set a port or target URL"); const c = normalizeServePath(e.path); const l = [ e.mode, "--bg", "--set-path", c, "--yes", s ]; const u = await runCommandWithTimeout([t, ...l], { timeoutMs: 3e4, signal: e.signal }); if (u.code !== 0) throw new Error(formatCommandResult(`tailscale ${e.mode}`, u)); const d = `https://${o}${c}`; return e.token ? `${d}?token=${e.token}` : d; } async function resolveProjectIdFromGogCredentials() { const e = gogCredentialsPaths(); for (const t of e) try { const e = fs.readFileSync(t, "utf-8"); const n = extractGogClientId(JSON.parse(e))?.match(/^(\d+)-/)?.[1] ?? null; if (!n) continue; const r = await runGcloudCommand([ "projects", "list", "--filter", `projectNumber=${n}`, "--format", "value(projectId)" ], 3e4); if (r.code !== 0) continue; const i = r.stdout.trim().split(/\s+/)[0]; if (i) return i; } catch {} return null; } function gogCredentialsPaths() { const e = []; const t = process.env.XDG_CONFIG_HOME; if (t) e.push(path.join(t, "gogcli", "credentials.json")); e.push(resolveUserPath("~/.config/gogcli/credentials.json")); if (process.platform === "darwin") e.push(resolveUserPath("~/Library/Application Support/gogcli/credentials.json")); return e; } function extractGogClientId(e) { const t = e.installed; const n = e.web; const r = t?.client_id || n?.client_id || e.client_id || ""; return typeof r === "string" ? r : null; } //#endregion //#region src/hooks/gmail-watcher.ts const log = createSubsystemLogger("gmail-watcher"); const GMAIL_BIND_RETRY_LIMIT = 3; const GMAIL_BIND_BACKOFF = { initialMs: 5e3, maxMs: 2e4, factor: 2, jitter: 0 }; let watcherProcess = null; let renewalScope; let shuttingDown = false; let currentConfig = null; let respawnTimeout = null; async function startGmailWatch(e, t = {}) { const n = [resolveGogExecutable(), ...buildGogWatchStartArgs(e)]; try { const r = await runCommandWithTimeout(n, { timeoutMs: 12e4, signal: t.signal }); if (r.code !== 0) { log.error(formatCommandResult("gog gmail watch start", r)); return false; } log.info(`watch started for ${e.account}`); return true; } catch (e) { log.error(`watch start error: ${String(e)}`); return false; } } function spawnGogServe(e, t = 0) { const n = buildGogWatchServeArgs(e); log.info(`starting gog ${buildGogWatchServeLogArgs(e).join(" ")}`); let r = false; let i = false; let a = ""; const o = resolveGogServeInvocation(n); const s = spawn(o.command, o.args, { stdio: [ "ignore", "pipe", "pipe" ], detached: process$1.platform !== "win32", windowsHide: o.windowsHide, windowsVerbatimArguments: o.windowsVerbatimArguments }); s.stdout?.on("error", (e) => { log.error(`gog stdout error: ${String(e)}`); }); s.stdout?.on("data", (e) => { const t = e.toString().trim(); if (t) log.info(`[gog] ${t}`); }); s.stderr?.on("error", (e) => { log.error(`gog stderr error: ${String(e)}`); }); s.stderr?.on("data", (e) => { const t = e.toString(); const n = a + t; if (!r && /address already in use|EADDRINUSE/i.test(n)) r = true; a = n.slice(-512); const i = t.trim(); if (!i) return; log.warn(`[gog] ${i}`); }); s.on("error", (e) => { if (s.pid === void 0) i = true; log.error(`gog process error: ${String(e)}`); }); const c = releaseChildProcessOutputAfterExit(s); s.once("exit", () => { if (!shuttingDown && watcherProcess === s && process$1.platform !== "win32" && s.pid) killProcessTree(s.pid, { force: true, detached: true }); }); s.once("close", (e, n) => { c(); if (shuttingDown || watcherProcess !== s) return; if (i) { watcherProcess = null; return; } if (r && t >= GMAIL_BIND_RETRY_LIMIT) { log.error(`gog serve failed to bind after ${GMAIL_BIND_RETRY_LIMIT} retries (address already in use); stopping restarts. Stop the other process and restart the Gmail watcher, or set OPENCLAW_SKIP_GMAIL_WATCHER=1 if it is managed separately.`); watcherProcess = null; return; } const a = r ? t + 1 : 0; const o = r ? computeBackoff(GMAIL_BIND_BACKOFF, a) : 5e3; log.warn(r ? `gog serve failed to bind (address already in use); retry ${a}/${GMAIL_BIND_RETRY_LIMIT} in ${o / 1e3}s` : `gog exited (code=${e}, signal=${n}); restarting in 5s`); watcherProcess = null; respawnTimeout = setTimeout(() => { respawnTimeout = null; if (shuttingDown || !currentConfig) return; watcherProcess = spawnGogServe(currentConfig, a); }, o); }); return s; } /** * Signal the gog process tree to exit gracefully (SIGTERM, SIGKILL after 3 s) * and resolve on exit/close/error or a final 8 s safety timeout. */ function settleProcess(e) { if (process$1.platform === "win32" && (e.exitCode != null || e.signalCode != null)) return Promise.resolve(); return new Promise((t) => { let n = false; let r = false; let i = false; let a; const settle = () => { if (n) return; n = true; if (a) clearTimeout(a); if (o) clearTimeout(o); e.removeListener("exit", settleAfterEscalation); e.removeListener("close", settleAfterEscalation); e.removeListener("error", settleAfterEscalation); t(); }; const settleAfterEscalation = () => { r = true; if (i) settle(); }; const o = setTimeout(() => { if (!n) { log.warn("gog process did not exit after SIGKILL; giving up"); settle(); } }, 8e3); e.on("exit", settleAfterEscalation); e.on("close", settleAfterEscalation); e.on("error", settleAfterEscalation); if (typeof e.pid === "number") { killProcessTree(e.pid, { graceMs: 3e3, detached: process$1.platform !== "win32" }); a = setTimeout(() => { i = true; if (r) settle(); }, 3025); } else { try { e.kill("SIGTERM"); } catch {} i = true; } }); } async function stopWatcherResources(e) { shuttingDown = true; if (respawnTimeout) { clearTimeout(respawnTimeout); respawnTimeout = null; } const t = renewalScope; await t?.stop(); if (renewalScope === t) renewalScope = void 0; if (watcherProcess) { e?.(); const t = watcherProcess; watcherProcess = null; await settleProcess(t); } } function cancelledGmailWatcherStart(e) { if (currentConfig === e) currentConfig = null; return { started: false, reason: "startup cancelled" }; } async function startGmailWatcher(e, t) { if (!e.hooks?.enabled) return { started: false, reason: "hooks not enabled" }; if (!e.hooks?.gmail?.account) return { started: false, reason: "no gmail account configured" }; if (!hasBinary("gog")) return { started: false, reason: "gog binary not found" }; const n = resolveGmailHookRuntimeConfig(e, {}); if (!n.ok) return { started: false, reason: n.error }; return startGmailWatcherService(n.value, t); } /** Start the shared watcher lifecycle after the caller resolves config and prerequisites. */ async function startGmailWatcherService(e, t) { if (t.signal?.aborted) return cancelledGmailWatcherStart(e); currentConfig = e; if (watcherProcess || renewalScope || respawnTimeout) { await stopWatcherResources(); shuttingDown = false; } if (e.tailscale.mode !== "off") try { await ensureTailscaleEndpoint({ mode: e.tailscale.mode, path: e.tailscale.path, port: e.serve.port, signal: t.signal, target: e.tailscale.target }); log.info(`tailscale ${e.tailscale.mode} configured for port ${e.serve.port}`); if (t.signal?.aborted) return cancelledGmailWatcherStart(e); } catch (n) { if (t.signal?.aborted) return cancelledGmailWatcherStart(e); log.error(`tailscale setup failed: ${String(n)}`); return { started: false, reason: `tailscale setup failed: ${String(n)}` }; } const n = await startGmailWatch(e, { signal: t.signal }); if (t.signal?.aborted) return cancelledGmailWatcherStart(e); if (!n) log.warn("gmail watch start failed, but continuing with serve"); shuttingDown = false; watcherProcess = spawnGogServe(e); const r = e.renewEveryMinutes * 6e4; const i = t.scheduler.scope(); renewalScope = i; i.schedule({ id: "gmail-watch-renewal", delayMs: r, everyMs: r, run: () => startGmailWatch(e, { signal: i.signal }) }); log.info(`gmail watcher started for ${e.account} (renew every ${e.renewEveryMinutes}m)`); return { started: true }; } async function stopGmailWatcher() { await stopWatcherResources(() => log.info("stopping gmail watcher")); currentConfig = null; log.info("gmail watcher stopped"); } //#endregion export { ensureGcloudAuth as a, ensureTopic as c, ensureDependency as i, resolveProjectIdFromGogCredentials as l, startGmailWatcherService as n, ensureSubscription as o, stopGmailWatcher as r, ensureTailscaleEndpoint as s, startGmailWatcher as t, runGcloud as u };