UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

494 lines (493 loc) • 17.4 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { L as resolvePositiveTimerTimeoutMs, P as resolveIntegerOption } from "./number-coercion-D6u-4YD8.mjs"; import { m as toStringifiedError, n as coerceErrorMessage } from "./error-coercion-hDrHOSGy.mjs"; import { t as clearActiveProgressLine } from "./progress-line-DLpSyB1i.mjs"; import { r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs"; import { o as redactSensitiveLines, p as resolveRedactOptions } from "./redact-Mj7pppxC.mjs"; import { n as computeBackoff } from "./src-BPmQBLJp.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { n as formatTimestamp } from "./timestamps-CX4IhE2n.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import "./backoff-B-fIQi7C.mjs"; import { s as isLoopbackHost } from "./net-BgRayX-P.mjs"; import { f as readConnectPairingRequiredMessage } from "./connect-error-details-BdhXf496.mjs"; import { n as isRich, r as theme, t as colorize } from "./theme-BOI0xyRZ.mjs"; import { r as projectGatewayConnectionDetailsForDiagnostics } from "./connection-details-BWzGtdxz.mjs"; import { s as isGatewayTransportError } from "./transport-error-BL_kuysc.mjs"; import { d as throwExpectedCliError } from "./failure-output-DVVDqwuu.mjs"; import { n as resolveGatewayLocalPortOverride } from "./gateway-port-option-D-9uSBm2.mjs"; import { n as callGatewayFromCli, t as addGatewayClientOptions } from "./gateway-rpc-CxUN2f1a.mjs"; import { t as readGatewayDispatchConfig } from "./gateway-dispatch-config-NmsdoFuC.mjs"; import { t as buildGatewayConnectionDetails } from "./call-DVCK1deJ.mjs"; import { t as createSafeStreamWriter } from "./stream-writer-mG29506x.mjs"; import { t as formatDocsHelp } from "./help-format-D2ytHW5E.mjs"; import { r as parseLogLine, t as readConfiguredLogTail } from "./log-tail-CKSM_qfb.mjs"; import { t as parseLogsPositiveInt } from "./logs-cli.options-DAFf8S0V.mjs"; import { setTimeout } from "node:timers/promises"; //#region src/cli/logs-cli.ts const LOCAL_FALLBACK_NOTICE = "Local Gateway RPC unavailable; reading configured file log instead."; const JOURNAL_FALLBACK_NOTICE = "Local Gateway RPC unavailable; reading active systemd gateway journal instead."; const JOURNAL_CURSOR_PREFIX = "-- cursor: "; const JOURNAL_MAX_LIMIT = 5e3; const JOURNAL_MAX_BYTES = 1e6; async function fetchGatewayLogs(e, t, n, r) { r.signal?.throwIfAborted(); const i = e.url?.trim() || !isImplicitLoopbackGatewayConnection(e.connection) ? { progress: n } : { progress: n, clientName: GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT, mode: GATEWAY_CLIENT_MODES.BACKEND, deviceIdentity: null }; const a = await callGatewayFromCli("logs.tail", e, { cursor: t, limit: r.limit, maxBytes: r.maxBytes }, r.signal ? { ...i, signal: r.signal } : i); r.signal?.throwIfAborted(); if (!a || typeof a !== "object") throw new Error("Unexpected logs.tail response"); return a; } function shouldUseLocalLogsFallback(e, t) { if (!isLocalGatewayRpcUnavailableError(t)) return false; if (typeof e.url === "string" && e.url.trim().length > 0) return false; return isImplicitLoopbackGatewayConnection(isGatewayTransportError(t) ? t.connectionDetails : e.connection); } function isImplicitLoopbackGatewayConnection(e) { if (e.urlSource !== "local loopback") return false; try { return isLoopbackHost(new URL(e.url).hostname); } catch { return false; } } function isLocalGatewayRpcUnavailableError(e) { if (isGatewayTransportError(e)) return e.kind === "closed" || e.kind === "timeout"; const t = normalizeLowercaseStringOrEmpty(coerceErrorMessage(e)); if (readConnectPairingRequiredMessage(t)) return true; return isPlainGatewayRequestUnavailableError(t); } function isPlainGatewayRequestUnavailableError(e) { return e.startsWith("gateway closed (") || /^gateway timeout after \d+ms\b/u.test(e); } async function readSystemdJournalFallback(e) { e.signal?.throwIfAborted(); if (process.platform !== "linux") return null; const t = await import("./logs-cli.runtime.js"); e.signal?.throwIfAborted(); const n = await t.readSystemdServiceRuntime(process.env); e.signal?.throwIfAborted(); if (n.status !== "running" || typeof n.pid !== "number") return null; const r = resolveIntegerOption(e.limit, 1, { min: 1, max: JOURNAL_MAX_LIMIT }); const i = resolveIntegerOption(e.maxBytes, 1, { min: 1, max: JOURNAL_MAX_BYTES }); const a = process.env.OPENCLAW_SYSTEMD_UNIT?.trim(); const o = a ? a.endsWith(".service") ? a : `${a}.service` : `${t.resolveGatewaySystemdServiceName(process.env.OPENCLAW_PROFILE)}.service`; const s = `journalctl --user --boot --user-unit=${o} _PID=${n.pid}`; const c = [ "--user", "--boot", `--user-unit=${o}`, `_PID=${n.pid}`, "--no-pager", "--output=cat", "--show-cursor" ]; if (typeof e.cursor === "string" && e.cursor.trim().length > 0) c.push(`--after-cursor=${e.cursor}`); else if (e.since) c.push(`--since=${e.since.replace("T", " ").replace("Z", " UTC")}`); else c.push("-n", String(r)); const l = await t.execFileUtf8Tail("journalctl", c, { env: process.env, maxBytes: i }); e.signal?.throwIfAborted(); if (l.code !== 0) return null; const u = l.truncated ? l.stdout.indexOf("\n") : -1; const d = l.truncated ? u < 0 ? "" : l.stdout.slice(u + 1) : l.stdout; const f = []; let p; for (const e of d.split(/\r?\n/u)) { if (!e) continue; if (e.startsWith(JOURNAL_CURSOR_PREFIX)) { p = e.slice(11).trim() || p; continue; } f.push(e); } const m = f.length > r ? f.slice(-r) : f; const h = resolveRedactOptions(); return { source: s, sourceKind: "journal", service: { pid: n.pid, unit: o }, cursor: p ?? e.cursor, lines: redactSensitiveLines(m, h), truncated: l.truncated || f.length > r, localFallback: true }; } function formatLogResetNotice(e) { return e !== void 0 && e > 0 ? `Log cursor re-anchored (skipped ${e} bytes).` : "Log cursor reset (file rotated)."; } const MAX_FOLLOW_RETRIES = 8; const FOLLOW_BACKOFF_POLICY = { initialMs: 1e3, maxMs: 3e4, factor: 2, jitter: .2 }; function isTransientFollowError(e) { if (isGatewayTransportError(e)) { if (e.kind === "timeout") return true; const t = e.code ?? 0; return t !== 1008 && !(t >= 4e3 && t <= 4999); } const t = normalizeLowercaseStringOrEmpty(coerceErrorMessage(e)); if (readConnectPairingRequiredMessage(t)) return false; return isPlainGatewayRequestUnavailableError(t); } function registerLogsCli(e) { const t = e.command("logs").description("Tail gateway file logs via RPC").option("--limit <n>", "Max lines to return", "200").option("--max-bytes <n>", "Max bytes to read", "250000").option("--follow", "Follow log output", false).option("--interval <ms>", "Polling interval in ms", "1000").option("--json", "Emit JSON log lines", false).option("--plain", "Plain text output (no ANSI styling)", false).option("--no-color", "Disable ANSI colors").option("--local-time", "Display timestamps in local timezone (default)", false).option("--utc", "Display timestamps in UTC", false).addHelpText("after", () => formatDocsHelp("/cli/logs")); addGatewayClientOptions(t); t.action(async (e) => { const t = getAsyncWorkSignal(); const n = resolveGatewayLocalPortOverride(e); let r; let i = false; try { r = readGatewayDispatchConfig(); } catch { r = {}; i = true; } const a = buildGatewayConnectionDetails({ config: r, url: e.url, localPortOverride: n }); const o = { ...e, localPortOverride: n, connection: a, ...i ? { config: r } : {}, localConfigUnavailable: i && isImplicitLoopbackGatewayConnection(a) }; let s = { kind: "idle" }; const abortGatewayRecoveryProbe = () => { if (s.kind === "probing") { s.abortController.abort(); return s.promise; } }; const c = createSafeStreamWriter((e, t) => { abortGatewayRecoveryProbe(); const n = e.code ?? "EPIPE"; const r = `openclaw logs: output ${t === process.stdout ? "stdout" : "stderr"} closed (${n}). Stopping tail.`; try { clearActiveProgressLine(); process.stderr.write(`${r}\n`); } catch {} }); const logLine = (e) => c.writeLine(process.stdout, e); const errorLine = (e) => c.writeLine(process.stderr, e); const emitJsonLine = (e, t = false) => c.write(t ? process.stderr : process.stdout, `${JSON.stringify(e)}\n`); const l = resolvePositiveTimerTimeoutMs(parseLogsPositiveInt(o.interval, 1e3, "--interval"), 1e3); const u = parseLogsPositiveInt(o.limit, 200, "--limit"); const d = parseLogsPositiveInt(o.maxBytes, 25e4, "--max-bytes"); let f; let p; let m; let h; let g = false; let _ = true; let v; const y = Boolean(o.json); const emitNotice = (e) => y ? emitJsonLine({ type: "notice", message: e }) : errorLine(e); const b = !y && process.stdout.isTTY && !o.plain; const x = isRich() && o.color !== false && !o.plain; if (o.localTime && o.utc) throwExpectedCliError("Pass only one of --local-time or --utc."); const S = !o.utc; const formatLogLine = (e) => { const t = parseLogLine(e); if (!t) return e; const n = t.subsystem ?? t.module ?? t.plugin ?? ""; let r = t.time ?? ""; if (r) { const e = new Date(r); if (!Number.isNaN(e.getTime())) r = b ? formatTimestamp(e, { style: "short", timeZone: S ? void 0 : "UTC" }) : S ? formatTimestamp(e, { style: "long" }) : e.toISOString(); } const i = t.level ?? ""; const a = t.message || t.raw; if (!b) return [ r, i, n, a ].filter(Boolean).join(" ").trim(); const o = i === "error" || i === "fatal" ? theme.error : i === "warn" ? theme.warn : i === "debug" || i === "trace" ? theme.muted : theme.info; return [[ colorize(x, theme.muted, r), colorize(x, o, i), colorize(x, theme.accent, n) ].filter(Boolean).join(" "), colorize(x, o, a)].filter(Boolean).join(" ").trim(); }; const emitConnectionNotice = (e, t) => y ? emitJsonLine({ type: "notice", message: e }, true) : errorLine(colorize(x, t, e)); if (i) emitConnectionNotice(`Warning: Configuration could not be read. ${o.localConfigUnavailable ? "Reading local file logs. " : ""}Run \`${formatCliCommand("openclaw doctor --fix")}\`.`, theme.warn); const startGatewayRecoveryProbe = () => { if (t?.aborted || !g || s.kind !== "idle") return; const e = (/* @__PURE__ */ new Date()).toISOString(); const n = new AbortController(); const r = fetchGatewayLogs(o, f, false, { limit: u, maxBytes: d, signal: t ? AbortSignal.any([t, n.signal]) : n.signal }).then((t) => ({ ok: true, payload: t, startedAt: e }), (e) => ({ ok: false, error: e })); s = { kind: "probing", promise: r, abortController: n }; r.then((e) => { s = { kind: "settled", result: e }; }); }; const readJournalWhileProbingRecovery = async () => { let e; if (s.kind === "settled") { const t = s.result; s = { kind: "idle" }; if (t.ok) return { payload: t.payload, gatewayPollStartedAt: t.startedAt }; if (!shouldUseLocalLogsFallback(o, t.error)) throw toStringifiedError(t.error); e = toStringifiedError(t.error); } const n = s.kind === "probing" ? s.promise : void 0; const r = await readSystemdJournalFallback({ cursor: m, since: h, limit: u, maxBytes: d, signal: t }); if (r) return { payload: r }; if (n) { const e = await n; s = { kind: "idle" }; if (e.ok) return { payload: e.payload, gatewayPollStartedAt: e.startedAt }; throw toStringifiedError(e.error); } throw e ?? /* @__PURE__ */ new Error("Active systemd journal unavailable for logs follow"); }; let C = 0; try { for (;;) { if (t?.aborted) break; let e; const n = _ && !o.follow; let r = (/* @__PURE__ */ new Date()).toISOString(); try { if (o.localConfigUnavailable) e = { ...await readConfiguredLogTail({ cursor: f, limit: u, maxBytes: d }), sourceKind: "file", localFallback: true }; else if (g) { startGatewayRecoveryProbe(); const t = await readJournalWhileProbingRecovery(); e = t.payload; r = t.gatewayPollStartedAt ?? r; } else try { e = await fetchGatewayLogs(o, f, n, { limit: u, maxBytes: d, signal: t }); } catch (n) { t?.throwIfAborted(); if (!shouldUseLocalLogsFallback(o, n)) throw n; if (o.follow) { const r = await readSystemdJournalFallback({ cursor: m, since: h, limit: u, maxBytes: d, signal: t }); if (!r) throw n; e = r; } else e = { ...await readConfiguredLogTail({ cursor: f, limit: u, maxBytes: d }), sourceKind: "file", localFallback: true }; } if (f !== void 0 && p !== void 0 && e.file !== void 0 && e.file !== p) { f = void 0; r = (/* @__PURE__ */ new Date()).toISOString(); e = o.localConfigUnavailable ? { ...await readConfiguredLogTail({ limit: u, maxBytes: d }), sourceKind: "file", localFallback: true } : await fetchGatewayLogs(o, f, false, { limit: u, maxBytes: d, signal: t }); } } catch (e) { t?.throwIfAborted(); if (o.follow && C < MAX_FOLLOW_RETRIES && isTransientFollowError(e)) { C += 1; const e = computeBackoff(FOLLOW_BACKOFF_POLICY, C); if (!emitConnectionNotice(`[logs] gateway disconnected, reconnecting in ${Math.round(e / 1e3)}s...`, theme.warn)) return; await setTimeout(e, void 0, { signal: t }); continue; } const n = `Hint: run \`${formatCliCommand("openclaw doctor")}\`.`; const r = redactSensitiveUrlLikeString(formatErrorMessage(e)); const i = projectGatewayConnectionDetailsForDiagnostics(isGatewayTransportError(e) ? e.connectionDetails : o.connection); if (y) emitJsonLine({ type: "error", message: r, error: r, details: i, hint: n }, true); else if (errorLine(colorize(x, theme.error, r)) && errorLine(i.message)) errorLine(colorize(x, theme.muted, n)); defaultRuntime.exit(1, { resetStream: y ? process.stderr : void 0 }); return; } t?.throwIfAborted(); if (C > 0 && !emitConnectionNotice("[logs] gateway reconnected", theme.muted)) return; C = 0; const i = e.sourceKind ?? (e.file ? "file" : void 0); let a; if (i || e.file || e.source) a = JSON.stringify({ file: e.file, source: e.source, sourceKind: i, servicePid: e.service?.pid, serviceUnit: e.service?.unit, localFallback: e.localFallback === true ? true : void 0 }); const c = _ || a !== void 0 && a !== v; const S = Array.isArray(e.lines) ? e.lines : []; if (y) { if (c) { if (!emitJsonLine({ type: "meta", file: e.file, source: e.source, sourceKind: e.sourceKind ?? (e.file ? "file" : void 0), service: e.service, cursor: e.cursor, size: e.size, localFallback: e.localFallback === true ? true : void 0 })) return; } for (const e of S) { const t = parseLogLine(e); if (!emitJsonLine(t ? { type: "log", ...t } : { type: "raw", raw: e })) return; } } else { if (c && e.localFallback === true) { const t = e.sourceKind === "journal" ? JOURNAL_FALLBACK_NOTICE : LOCAL_FALLBACK_NOTICE; if (!errorLine(colorize(x, theme.warn, t))) return; } if (c) { if (e.sourceKind === "journal" && e.source) { if (!logLine(`${b ? colorize(x, theme.muted, "Log source:") : "Log source:"} ${e.source}`)) return; if (e.service?.pid !== void 0 && !logLine(`Service PID: ${e.service.pid}`)) return; if (e.service?.unit && !logLine(`Service Unit: ${e.service.unit}`)) return; } else if (e.file) { if (!logLine(`${b ? colorize(x, theme.muted, "Log file:") : "Log file:"} ${e.file}`)) return; } } for (const e of S) if (!logLine(formatLogLine(e))) return; } if (e.truncated && !emitNotice("Log tail truncated (increase --limit or --max-bytes).")) return; if (e.reset && !emitNotice(formatLogResetNotice(e.skippedBytes))) return; if (e.sourceKind === "journal") { g = true; if (typeof e.cursor === "string" && e.cursor.trim().length > 0) m = e.cursor; startGatewayRecoveryProbe(); } else { g = false; s = { kind: "idle" }; if (typeof e.cursor === "number" && Number.isFinite(e.cursor)) { f = e.cursor; p = e.file; if (o.follow) { m = void 0; h = r; } } else if (typeof e.cursor === "string" && e.cursor.trim().length > 0) m = e.cursor; } if (a !== void 0) v = a; _ = false; if (!o.follow) return; await setTimeout(l, void 0, { signal: t }); } } catch (e) { if (!t?.aborted) throw e; } finally { await abortGatewayRecoveryProbe(); } }); } //#endregion export { registerLogsCli };