UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

855 lines (854 loc) • 28.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs"; import { a as asOptionalRecord, l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { n as loggingState, t as APPLIED_LOGGING_CONFIG_UNOWNED } from "./state-Bg-ugveB.mjs"; import { F as invalidateLoggingConfigCache, I as readLoggingConfig, P as serializeFileLogRecord, i as redactSecrets, s as redactSensitiveText, u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs"; import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { I as hasInternalDiagnosticEventInterest, i as emitDiagnosticEventWithTrustedTraceContext, r as emitDiagnosticEvent, t as areDiagnosticsEnabledForProcess } from "./diagnostic-events-BjAH1Kbx.mjs"; import { C as isValidDiagnosticTraceId, S as isValidDiagnosticTraceFlags, b as getActiveDiagnosticTraceContext, x as isValidDiagnosticSpanId } from "./diagnostics-timeline-CSwiG24r.mjs"; import { n as formatTimestamp } from "./timestamps-CX4IhE2n.mjs"; import { n as formatConsoleDiagnosticLine } from "./json-console-line-DwSBR0na.mjs"; import { a as tryParseLogLevel, i as normalizeLogLevel, n as isLogLevelEnabled, r as levelToMinLevel, t as ALLOWED_LOG_LEVELS } from "./levels-BFNaKUFS.mjs"; import { n as resolvePreferredOpenClawTmpDir, t as DEFAULT_POSIX_TMP_ROOT } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { n as readParsedField } from "./string-readers-BtMVaphq.mjs"; import fs from "node:fs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs$1 from "node:fs/promises"; import os from "node:os"; import { appendRegularFile, appendRegularFileSync } from "@openclaw/fs-safe/advanced"; import { Logger } from "tslog"; //#region src/logging/env-log-level.ts /** Resolves OPENCLAW_LOG_LEVEL once per value, warning only when the invalid value changes. */ function resolveEnvLogLevelOverride() { const e = normalizeOptionalString(process.env.OPENCLAW_LOG_LEVEL) ?? ""; if (!e) { loggingState.invalidEnvLogLevelValue = null; return; } const t = tryParseLogLevel(e); if (t) { loggingState.invalidEnvLogLevelValue = null; return t; } if (loggingState.invalidEnvLogLevelValue !== e) { loggingState.invalidEnvLogLevelValue = e; const t = `[openclaw] Ignoring invalid OPENCLAW_LOG_LEVEL="${redactToolPayloadText(e)}" (allowed: ${ALLOWED_LOG_LEVELS.join("|")}).`; process.stderr.write(`${formatConsoleDiagnosticLine({ level: "warn", message: t })}\n`); } } //#endregion //#region src/logging/log-directory.ts /** * Creates a log directory and its missing parents with a bounded number of mkdir calls. * Node's recursive mkdirSync retries forever when a parent exists but refuses new * children (a deleted directory that is still mounted, such as a stale systemd * PrivateTmp), which would block the event loop inside the logger. */ function ensureLogDirectorySync(e, t = true, n = 511) { try { fs.mkdirSync(e, { mode: n }); } catch (r) { const i = extractErrorCode(r); if (i === "EEXIST" && fs.statSync(e).isDirectory()) return; const a = path.dirname(e); if (!t || i !== "ENOENT" || a === e) throw r; ensureLogDirectorySync(a, true, n); ensureLogDirectorySync(e, false, n); } } //#endregion //#region src/logging/log-file-shared.ts const LOG_PREFIX = "openclaw"; const LOG_SUFFIX = ".log"; function canUseNodeFs() { try { return process.getBuiltinModule?.("fs") !== void 0; } catch { return false; } } function formatLocalDate(e) { return `${e.getFullYear()}-${String(e.getMonth() + 1).padStart(2, "0")}-${String(e.getDate()).padStart(2, "0")}`; } //#endregion //#region src/logging/log-file-path.ts const ROLLING_LOG_FILE_RE = /^(openclaw(?:-[a-z0-9-]+)?)-(\d{4}-\d{2}-\d{2})\.log$/u; const MAX_LOG_PROFILE_SEGMENT_LENGTH = 220; function encodeLogProfileSegment(e) { let t = ""; for (const n of e) if (/^[a-z0-9]$/u.test(n)) t += n; else if (n === "-") t += "--"; else if (n === "_") t += "-0"; else if (/^[A-Z]$/u.test(n)) t += `-1${n.toLowerCase()}`; else t += `-2${n.codePointAt(0)?.toString(16) ?? "0"}-`; return t; } function resolveLogProfileSegment() { const e = process.env.OPENCLAW_PROFILE?.trim(); if (!e || e.toLowerCase() === "default") return null; const t = encodeLogProfileSegment(e); if (t.length <= MAX_LOG_PROFILE_SEGMENT_LENGTH) return t; return `-3${createHash("sha256").update(e).digest("hex")}`; } /** Resolves today's default rolling log path for the active CLI profile. */ function resolveDefaultRollingLogFile(e) { const t = /* @__PURE__ */ new Date(); let n = DEFAULT_POSIX_TMP_ROOT; if (canUseNodeFs()) { const t = resolveStateDir(); n = path.join(t, "logs"); if (e?.prepare !== false) { ensureLogDirectorySync(t, true, 448); n = resolvePreferredOpenClawTmpDir({ preferredDir: n, tmpdir: () => path.join(t, "tmp") }); } } const r = resolveLogProfileSegment(); const i = r ? `-${r}` : ""; return path.join(n, `${LOG_PREFIX}${i}-${formatLocalDate(t)}${LOG_SUFFIX}`); } /** Resolves the configured log file or today's rolling default log path. */ function resolveConfiguredLogFilePath(e) { return e?.logging?.file ?? resolveDefaultRollingLogFile(); } /** Returns whether a configured path had the legacy default rolling filename shape. */ function isLegacyRollingLogFilePath(e) { const t = path.basename(e); return t === `${"openclaw"}-YYYY-MM-DD${".log"}` || ROLLING_LOG_FILE_RE.exec(t)?.[1] === "openclaw"; } /** Advances a rolling log path to the requested date while preserving its profile family. */ function resolveRollingLogFilePathForDate(e, t) { const n = ROLLING_LOG_FILE_RE.exec(path.basename(e)); if (!n) return isLegacyRollingLogFilePath(e) ? path.join(path.dirname(e), `${LOG_PREFIX}-${formatLocalDate(t)}${LOG_SUFFIX}`) : e; return path.join(path.dirname(e), `${n[1]}-${formatLocalDate(t)}${LOG_SUFFIX}`); } /** Returns whether two dated rolling paths belong to the same profile family. */ function isSameRollingLogFileFamily(e, t) { const n = ROLLING_LOG_FILE_RE.exec(path.basename(e)); const r = ROLLING_LOG_FILE_RE.exec(path.basename(t)); return Boolean(n && r && n[1] === r[1]); } //#endregion //#region src/logging/logger-file-transport.ts const DEFAULT_MAX_QUEUED_RECORDS = 4096; const MAX_APPEND_BATCH_BYTES = 65536; const MAX_ROTATED_LOG_FILES = 5; const MAX_TRACKED_APPEND_FAILURE_FILES = 64; let queue = []; let queueStart = 0; let activeBatch = null; let activeIndex = 0; let droppedCount = 0; let droppedTarget = null; let scheduledFlush = null; let flushPromise = null; let processExiting = false; let processHooksInstalled = false; const warnedRotationFiles = /* @__PURE__ */ new Map(); const warnedAppendFiles = /* @__PURE__ */ new Set(); let appendFailureTrackingSaturated = false; function rotatedLogPath(e, t) { const n = path.extname(e); return `${e.slice(0, e.length - n.length)}.${t}${n}`; } function rotateLogFile(e) { try { ensureLogDirectorySync(path.dirname(e)); fs.rmSync(rotatedLogPath(e, MAX_ROTATED_LOG_FILES), { force: true }); for (let t = 4; t >= 1; t -= 1) { const n = rotatedLogPath(e, t); if (fs.existsSync(n)) fs.renameSync(n, rotatedLogPath(e, t + 1)); } if (fs.existsSync(e)) fs.renameSync(e, rotatedLogPath(e, 1)); return true; } catch { return false; } } async function getCurrentLogFileBytes(e) { try { return (await fs$1.stat(e)).size; } catch { return 0; } } function getCurrentLogFileBytesSync(e) { try { return fs.statSync(e).size; } catch { return 0; } } function buildDroppedMarker(e, t) { const n = /* @__PURE__ */ new Date(); const r = `[openclaw] file log queue overflow; dropped ${t} oldest record${t === 1 ? "" : "s"}`; const i = { 0: r, _meta: { date: n, hostname: e.hostname, logLevelName: "WARN", name: "openclaw" }, time: formatTimestamp(n, { style: "long" }), hostname: e.hostname, message: r, dropped: t }; return { ...e, payload: `${JSON.stringify(i)}\n` }; } function writeFileTransportWarning(e, t) { try { const n = redactSensitiveText(e); const r = `${formatConsoleDiagnosticLine({ level: "warn", message: n })}\n`; if (t) fs.writeSync(process.stderr.fd, r); else process.stderr.write(r); return true; } catch { return false; } } function warnAboutRotationFailure(e, t) { if (warnedRotationFiles.get(e.file) === e.maxFileBytes) return; warnedRotationFiles.set(e.file, e.maxFileBytes); writeFileTransportWarning(`[openclaw] log file rotation failed; continuing writes file=${e.file} maxFileBytes=${e.maxFileBytes}`, t); } function warnAboutAppendFailure(e, t) { if (warnedAppendFiles.has(e.file)) return; const n = warnedAppendFiles.size >= MAX_TRACKED_APPEND_FAILURE_FILES; if (n && appendFailureTrackingSaturated) return; if (!writeFileTransportWarning(n ? "[openclaw] log file append failure diagnostics saturated; suppressing new file targets" : `[openclaw] log file append failed; records dropped; check that the path is a writable regular file; file=${e.file}`, t)) return; if (n) appendFailureTrackingSaturated = true; else warnedAppendFiles.add(e.file); } function clearAppendFailure(e) { if (warnedAppendFiles.delete(e.file)) appendFailureTrackingSaturated = false; } function claimQueuedEntries() { const e = queueStart === 0 ? queue : [...queue.slice(queueStart), ...queue.slice(0, queueStart)]; queue = []; queueStart = 0; if (droppedCount > 0 && droppedTarget) e.unshift(buildDroppedMarker(droppedTarget, droppedCount)); droppedCount = 0; droppedTarget = null; return e; } function prepareWrite(e, t, n, r, i) { let a = Buffer.byteLength(e.payload, "utf8"); if (t.bytes > 0 && t.bytes + a > e.maxFileBytes) { if (rotateLogFile(e.file)) { t.bytes = 0; warnedRotationFiles.delete(e.file); } else warnAboutRotationFailure(e, n); } let o = i + 1; if (n) return { payload: e.payload, payloadBytes: a, nextIndex: o }; const s = [e.payload]; for (; o < r.length; o += 1) { const n = r[o]; if (!n || n.file !== e.file || n.maxFileBytes !== e.maxFileBytes) break; const i = Buffer.byteLength(n.payload, "utf8"); if (a + i > MAX_APPEND_BATCH_BYTES || t.bytes + a + i > e.maxFileBytes) break; s.push(n.payload); a += i; } return { payload: s.join(""), payloadBytes: a, nextIndex: o }; } async function writeEntries(e) { const t = /* @__PURE__ */ new Map(); for (let n = 0; n < e.length;) { if (processExiting) return; const r = e[n]; if (!r) return; let i = t.get(r.file); if (!i) { i = { bytes: await getCurrentLogFileBytes(r.file) }; if (processExiting) return; t.set(r.file, i); } const a = prepareWrite(r, i, false, e, n); activeIndex = a.nextIndex; try { await appendRegularFile({ filePath: r.file, content: a.payload }); i.bytes += a.payloadBytes; clearAppendFailure(r); } catch { warnAboutAppendFailure(r, false); } finally { for (const t of e.slice(n, a.nextIndex)) t.payload = ""; n = a.nextIndex; } } } function writeEntriesSync(e) { const t = /* @__PURE__ */ new Map(); for (let n = 0; n < e.length;) { const r = e[n]; if (!r) return; let i = t.get(r.file); if (!i) { i = { bytes: getCurrentLogFileBytesSync(r.file) }; t.set(r.file, i); } const a = prepareWrite(r, i, true, e, n); try { appendRegularFileSync({ filePath: r.file, content: a.payload }); i.bytes += a.payloadBytes; clearAppendFailure(r); } catch { warnAboutAppendFailure(r, true); } r.payload = ""; n = a.nextIndex; } } async function runFlushLoop() { for (;;) { if (processExiting) return; const e = claimQueuedEntries(); if (e.length === 0) return; activeBatch = e; activeIndex = 0; await writeEntries(e); activeBatch = null; activeIndex = 0; } } function startFlush() { if (flushPromise || processExiting) return; const e = runFlushLoop().catch(() => void 0); flushPromise = e; e.then(() => { flushPromise = null; if (queue.length > 0 || droppedCount > 0) scheduleFlush(); }); } function scheduleFlush() { if (scheduledFlush || flushPromise || processExiting) return; scheduledFlush = setImmediate(() => { scheduledFlush = null; startFlush(); }); } function handleProcessBeforeExit() { flushFileLogQueue(); } function handleProcessExit() { processExiting = true; drainFileLogQueueSync(); } function installProcessHooks() { if (processHooksInstalled) return; processHooksInstalled = true; process.on("beforeExit", handleProcessBeforeExit); process.on("exit", handleProcessExit); } /** Enqueues one serialized record without waiting for filesystem I/O. */ function enqueueFileLog(e) { if (processExiting) { writeEntriesSync([e]); return; } installProcessHooks(); if (queue.length >= DEFAULT_MAX_QUEUED_RECORDS) { const t = queue[queueStart]; if (t) { t.payload = ""; droppedTarget ??= t; droppedCount += 1; } queue[queueStart] = e; queueStart = (queueStart + 1) % queue.length; } else queue.push(e); scheduleFlush(); } /** Waits until every record currently queued for the async transport has settled. */ async function flushFileLogQueue() { for (;;) { if (scheduledFlush) { clearImmediate(scheduledFlush); scheduledFlush = null; } if (!flushPromise && (queue.length > 0 || droppedCount > 0)) startFlush(); const e = flushPromise; if (!e) return; await e; } } /** Synchronously rescues pending records for process.exit() and crash-adjacent paths. */ function drainFileLogQueueSync() { if (scheduledFlush) { clearImmediate(scheduledFlush); scheduledFlush = null; } const e = activeBatch ? activeBatch.slice(activeIndex) : []; activeBatch = null; activeIndex = 0; e.push(...claimQueuedEntries()); writeEntriesSync(e); } const fileLogTransport = resolveGlobalSingleton(Symbol.for("openclaw.fileLogTransport"), () => { if (process.env.VITEST !== "true") installProcessHooks(); return { drainSync: drainFileLogQueueSync, enqueue: enqueueFileLog, flush: flushFileLogQueue }; }); //#endregion //#region src/logging/logger.ts const DEFAULT_LOG_FILE = `${DEFAULT_POSIX_TMP_ROOT}/openclaw.log`; const MAX_LOG_AGE_MS = 864e5; const DEFAULT_MAX_LOG_FILE_BYTES = 104857600; let cachedHostname = null; const MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS = 8192; const MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS = 4096; function invalidateLoggerSettings() { loggingState.cachedLogger = null; loggingState.cachedSettings = null; loggingState.cachedConsoleSettings = null; } /** Publishes authoritative config-derived logging state for the active runtime. */ function applyLoggingConfig(e) { loggingState.appliedConfig = e; invalidateLoggingConfigCache(); invalidateLoggerSettings(); } const MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT = 32; const MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS = 2048; const MAX_DIAGNOSTIC_LOG_NAME_CHARS = 120; const MAX_FILE_LOG_CONTEXT_VALUE_CHARS = 512; const DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE = /^[A-Za-z0-9_.:-]{1,64}$/u; function clampLogText(e, t) { return e.length > t ? `${truncateUtf16Safe(e, t)}...(truncated)` : e; } function sanitizeDiagnosticLogText(e, t) { return clampLogText(redactSensitiveText(clampLogText(e, t)), t); } function normalizeDiagnosticLogName(e) { if (!e || e.trim().startsWith("{")) return; const t = sanitizeDiagnosticLogText(e.trim(), MAX_DIAGNOSTIC_LOG_NAME_CHARS); return DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE.test(t) ? t : void 0; } function assignDiagnosticLogAttribute(e, t, n, r) { if (t.count >= MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT) return; const i = n.trim(); if (isBlockedObjectKey(i)) return; if (redactSensitiveText(i) !== i) return; if (!DIAGNOSTIC_LOG_ATTRIBUTE_KEY_RE.test(i)) return; let a; if (typeof r === "string") a = sanitizeDiagnosticLogText(r, MAX_DIAGNOSTIC_LOG_ATTRIBUTE_VALUE_CHARS); else if (typeof r === "boolean" || typeof r === "number" && Number.isFinite(r)) a = r; else return; e[i] = a; t.count += 1; } function addDiagnosticLogAttributesFrom(e, t, n) { if (!n) return; for (const r in n) { if (t.count >= MAX_DIAGNOSTIC_LOG_ATTRIBUTE_COUNT) break; if (!Object.hasOwn(n, r) || r === "trace") continue; assignDiagnosticLogAttribute(e, t, r, n[r]); } } function isPlainLogRecordObject(e) { if (!isRecord(e)) return false; const t = Object.getPrototypeOf(e); return t === Object.prototype || t === null; } function normalizeTraceContext(e) { const t = asOptionalRecord(e); if (!t || !isValidDiagnosticTraceId(t.traceId)) return; if (t.spanId !== void 0 && !isValidDiagnosticSpanId(t.spanId)) return; if (t.parentSpanId !== void 0 && !isValidDiagnosticSpanId(t.parentSpanId)) return; if (t.traceFlags !== void 0 && !isValidDiagnosticTraceFlags(t.traceFlags)) return; return { traceId: t.traceId, ...t.spanId ? { spanId: t.spanId } : {}, ...t.parentSpanId ? { parentSpanId: t.parentSpanId } : {}, ...t.traceFlags ? { traceFlags: t.traceFlags } : {} }; } function extractTraceContext(e) { return normalizeTraceContext(e) ?? normalizeTraceContext(asOptionalRecord(e)?.trace); } function getSortedNumericLogEntries(e) { return Object.entries(e).filter(([e]) => /^\d+$/.test(e)).toSorted((e, t) => Number(e[0]) - Number(t[0])); } function normalizeFileLogContextValue(e) { if (typeof e === "string") { const t = e.trim(); return t ? clampLogText(t, MAX_FILE_LOG_CONTEXT_VALUE_CHARS) : void 0; } if (typeof e === "boolean" || typeof e === "number" && Number.isFinite(e)) return String(e); } function readFirstContextString(e, t) { for (const n of e) { const e = n ? readParsedField(n, t, normalizeFileLogContextValue) : void 0; if (e) return e; } } function resolveLogHostname() { if (cachedHostname) return cachedHostname; const e = os.hostname().trim(); if (!e) return "unknown"; cachedHostname = e; return e; } function withResolvedLogMetaHostname(e, t) { return isRecord(e) ? { ...e, hostname: t } : e; } function extractLogBindingPrefix(e) { if (typeof e[0] === "string" && e[0].length <= MAX_DIAGNOSTIC_LOG_BINDINGS_JSON_CHARS && e[0].trim().startsWith("{")) try { const t = JSON.parse(e[0]); if (isRecord(t)) return { bindings: t, args: e.slice(1) }; } catch {} return { args: e }; } function resolveLogTraceContext(e, t) { for (const n of [e, ...t]) { const e = extractTraceContext(n); if (e) return { trace: e, trustedTraceContext: false }; } const n = getActiveDiagnosticTraceContext(); return n ? { trace: n, trustedTraceContext: true } : { trustedTraceContext: false }; } function prepareFileLogRecord(e) { const t = getSortedNumericLogEntries(e); const { bindings: n, args: r } = extractLogBindingPrefix(t.map(([, e]) => e)); const { trace: i } = resolveLogTraceContext(n, r); const a = isPlainLogRecordObject(r[0]) ? r[0] : void 0; const o = [ a, n, e ]; const s = a && typeof a.message !== "string" ? 1 : 0; const c = t.slice(t.length - r.length + s).map(([e, t]) => { const n = { key: e, json: t != null && ![ "string", "number", "boolean", "bigint" ].includes(typeof t) && !(t instanceof Error) && !(isPlainLogRecordObject(t) && typeof t.message === "string") }; if (typeof t === "number" && !Number.isFinite(t)) n.primitiveText = String(t); return n; }); const l = readFirstContextString(o, ["agent_id", "agentId"]); const u = readFirstContextString(o, [ "session_id", "sessionId", "sessionKey" ]); const d = readFirstContextString(o, ["channel", "messageProvider"]); return { fields: { hostname: resolveLogHostname(), ...l ? { agent_id: l } : {}, ...u ? { session_id: u } : {}, ...d ? { channel: d } : {}, ...i }, messageParts: c }; } function buildDiagnosticLogRecord(e) { const t = e["_meta"]; const { bindings: n, args: r } = extractLogBindingPrefix(getSortedNumericLogEntries(e).map(([, e]) => e)); const { trace: i, trustedTraceContext: a } = resolveLogTraceContext(n, r); const o = r[0]; const s = isPlainLogRecordObject(o) ? o : void 0; if (s) r.shift(); let c = ""; if (r.length > 0 && typeof r[r.length - 1] === "string") c = sanitizeDiagnosticLogText(String(r.pop()), MAX_DIAGNOSTIC_LOG_MESSAGE_CHARS); else if (r.length === 1 && (typeof r[0] === "number" || typeof r[0] === "boolean")) { c = String(r[0]); r.length = 0; } if (!c) c = "log"; const l = Object.create(null); const u = { count: 0 }; addDiagnosticLogAttributesFrom(l, u, n); addDiagnosticLogAttributesFrom(l, u, s); const d = {}; if (t?.path?.fileLine) { const e = Number(t.path.fileLine); if (Number.isFinite(e)) d.line = e; } if (t?.path?.method) d.functionName = sanitizeDiagnosticLogText(t.path.method, MAX_DIAGNOSTIC_LOG_NAME_CHARS); const f = normalizeDiagnosticLogName(t?.name); const p = t?.parentNames?.map(normalizeDiagnosticLogName).filter((e) => Boolean(e)); return { event: { type: "log.record", level: t?.logLevelName ?? "INFO", message: c, ...f ? { loggerName: f } : {}, ...p?.length ? { loggerParents: p } : {}, ...Object.keys(l).length > 0 ? { attributes: l } : {}, ...Object.keys(d).length > 0 ? { code: d } : {}, ...i ? { trace: i } : {} }, trustedTraceContext: a }; } function attachDiagnosticEventTransport(e) { e.attachTransport({ format: () => "", write: (e) => { if (!areDiagnosticsEnabledForProcess() || !hasInternalDiagnosticEventInterest("log.record")) return; try { const t = buildDiagnosticLogRecord(redactSecrets(e)); (t.trustedTraceContext ? emitDiagnosticEventWithTrustedTraceContext : emitDiagnosticEvent)(t.event); } catch {} } }); } function canUseSilentVitestFileLogFastPath(e) { return process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG !== "1" && !e && !loggingState.overrideSettings; } function resolveDefaultActiveLogFile(e = false) { if (process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG === "1") return path.join(process.cwd(), ".artifacts", "test-logs", `${LOG_PREFIX}-vitest-${process.pid}-${formatLocalDate(/* @__PURE__ */ new Date())}${LOG_SUFFIX}`); return resolveDefaultRollingLogFile(e ? void 0 : { prepare: false }); } function resolveSettings(e = false) { if (!canUseNodeFs()) return { level: "silent", file: DEFAULT_LOG_FILE, maxFileBytes: DEFAULT_MAX_LOG_FILE_BYTES, rolling: false, defaultFile: false }; const t = resolveEnvLogLevelOverride(); if (canUseSilentVitestFileLogFastPath(t)) return { level: "silent", file: resolveDefaultRollingLogFile(e ? void 0 : { prepare: false }), maxFileBytes: DEFAULT_MAX_LOG_FILE_BYTES, rolling: true, defaultFile: true }; const n = loggingState.overrideSettings ?? readLoggingConfig(); const r = process.env.VITEST === "true" && process.env.OPENCLAW_TEST_FILE_LOG !== "1" ? "silent" : "info"; const i = normalizeLogLevel(n?.level, r); const a = t ?? i; const o = n?.file ? isLegacyRollingLogFilePath(n.file) : true; return { level: a, file: resolveActiveLogFileWithMode(n?.file ?? resolveDefaultActiveLogFile(e), o), maxFileBytes: resolveMaxLogFileBytes(n?.maxFileBytes), rolling: o, defaultFile: !n?.file }; } function getResolvedLoggerFileTarget() { const { file: e, rolling: t } = resolveSettings(true); return { file: e, rolling: t }; } function getRuntimeSettings() { const e = loggingState.cachedSettings ?? resolveSettings(); loggingState.cachedSettings = e; return e; } function isFileLogLevelEnabled(e) { return isLogLevelEnabled(e, getRuntimeSettings().level); } function inheritLogLevel(e, t) { let resolveLevel = t; Object.defineProperty(e.settings, "minLevel", { configurable: true, enumerable: true, get: () => resolveLevel(), set: (e) => { resolveLevel = () => e; } }); } var RuntimeLogger = class extends Logger { getSubLogger(e, t) { const n = e?.minLevel ?? this.settings.minLevel; const r = super.getSubLogger({ ...e, minLevel: n === Infinity ? levelToMinLevel("fatal") : n }, t); if (e?.minLevel == null) inheritLogLevel(r, () => this.settings.minLevel); else if (n === Infinity) r.settings.minLevel = n; return r; } }; function buildLogger() { const e = new RuntimeLogger({ name: "openclaw", mask: { keys: [] }, meta: { property: "_meta" }, minLevel: levelToMinLevel("fatal"), type: "hidden" }); inheritLogLevel(e, () => levelToMinLevel(getRuntimeSettings().level)); let t; let n; e.attachTransport({ format: () => "", write: (e) => { try { const r = getRuntimeSettings(); if (r.level === "silent") return; if (n?.settings !== r) n = { settings: r, file: r.defaultFile ? resolveDefaultActiveLogFile(true) : r.file }; const i = resolveActiveLogFileWithMode(n.file, r.rolling); if (i !== t) { t = i; try { ensureLogDirectorySync(path.dirname(t)); if (r.rolling) pruneOldRollingLogs(path.dirname(t)); } catch {} } const a = formatTimestamp(e.date ?? /* @__PURE__ */ new Date(), { style: "long" }); const { fields: o, messageParts: s } = prepareFileLogRecord(e); const c = serializeFileLogRecord({ ...e, _meta: withResolvedLogMetaHostname(e["_meta"], o.hostname), time: a, ...o }, s); fileLogTransport.enqueue({ file: t, hostname: o.hostname, maxFileBytes: r.maxFileBytes, payload: `${c}\n` }); } catch {} } }); attachDiagnosticEventTransport(e); return e; } function resolveMaxLogFileBytes(e) { if (typeof e === "number" && Number.isFinite(e) && e > 0) return Math.floor(e); return DEFAULT_MAX_LOG_FILE_BYTES; } function getLogger() { const e = loggingState.cachedLogger; if (e) return e; getRuntimeSettings(); const t = buildLogger(); loggingState.cachedLogger = t; return t; } function getChildLogger(e, t) { const n = getLogger(); const r = e ? JSON.stringify(e) : void 0; return n.getSubLogger({ name: r, prefix: e ? [r ?? ""] : [], ...t?.level ? { minLevel: levelToMinLevel(t.level) } : {} }); } function toPinoLikeLogger(e, t) { return { level: t, child: (n) => { const r = e.settings.minLevel; const i = e.getSubLogger({ name: n ? JSON.stringify(n) : void 0, minLevel: r === Infinity ? levelToMinLevel("fatal") : r }); inheritLogLevel(i, () => e.settings.minLevel); return toPinoLikeLogger(i, t); }, trace: (...t) => e.log(levelToMinLevel("trace"), "TRACE", ...t), debug: (...t) => e.log(levelToMinLevel("debug"), "DEBUG", ...t), info: (...t) => e.log(levelToMinLevel("info"), "INFO", ...t), warn: (...t) => e.log(levelToMinLevel("warn"), "WARN", ...t), error: (...t) => e.log(levelToMinLevel("error"), "ERROR", ...t), fatal: (...t) => e.log(levelToMinLevel("fatal"), "FATAL", ...t) }; } function getResolvedLoggerSettings() { const { rolling: e, defaultFile: t, ...n } = resolveSettings(); return n; } /** Flushes queued file logs before a graceful owner exits the process. */ async function flushLogger() { await fileLogTransport.flush(); } function setLoggerOverride(e) { loggingState.overrideSettings = e; invalidateLoggerSettings(); } function resetLogger() { loggingState.appliedConfig = APPLIED_LOGGING_CONFIG_UNOWNED; loggingState.overrideSettings = null; invalidateLoggingConfigCache(); cachedHostname = null; invalidateLoggerSettings(); } function resolveActiveLogFileWithMode(e, t) { const n = expandHomePrefix(e); return t ? resolveRollingLogFilePathForDate(n, /* @__PURE__ */ new Date()) : n; } function pruneOldRollingLogs(e) { try { const t = fs.readdirSync(e, { withFileTypes: true }); const n = Date.now() - MAX_LOG_AGE_MS; for (const r of t) { if (!r.isFile()) continue; if (!r.name.startsWith(`${"openclaw"}-`) || !r.name.endsWith(".log")) continue; const t = path.join(e, r.name); try { if (fs.statSync(t).mtimeMs < n) fs.rmSync(t, { force: true }); } catch {} } } catch {} } //#endregion export { getResolvedLoggerFileTarget as a, resetLogger as c, isSameRollingLogFileFamily as d, resolveConfiguredLogFilePath as f, getLogger as i, setLoggerOverride as l, flushLogger as n, getResolvedLoggerSettings as o, resolveEnvLogLevelOverride as p, getChildLogger as r, isFileLogLevelEnabled as s, applyLoggingConfig as t, toPinoLikeLogger as u };