UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

287 lines (286 loc) • 8.62 kB
import { c as normalizeOptionalLowercaseString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs"; import { f as resolveLogTailRedactOptions, o as redactSensitiveLines } from "./redact-Mj7pppxC.mjs"; import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs"; import { n as clamp } from "./utils-C8YECn2Q.mjs"; import { a as getResolvedLoggerFileTarget, d as isSameRollingLogFileFamily } from "./logger-1QDNfT7Y.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { readFileWindowFully } from "@openclaw/fs-safe/advanced"; import { StringDecoder } from "node:string_decoder"; //#region src/logging/parse-log-line.ts function extractMessage(e) { const t = []; for (const n of Object.keys(e)) { if (!/^\d+$/.test(n)) continue; const r = e[n]; if (typeof r === "string") t.push(r); else if (r != null) t.push(JSON.stringify(r)); } return t.join(" "); } function parseMetaName(e) { const t = typeof e === "string" ? safeParseJsonRecord(e) : void 0; if (!t) return {}; return { subsystem: typeof t.subsystem === "string" ? t.subsystem : void 0, module: typeof t.module === "string" ? t.module : void 0, plugin: typeof t.plugin === "string" ? t.plugin : void 0 }; } /** Parses a raw log line into compact metadata and message text, or null for non-JSON lines. */ function parseLogLine(e) { try { const t = JSON.parse(e); if (!isRecord(t)) return null; const n = isRecord(t["_meta"]) ? t["_meta"] : void 0; let r = parseMetaName(n?.name); if (n?.name !== t["0"]) { const e = parseMetaName(t["0"]); r = { subsystem: r.subsystem ?? e.subsystem, module: r.module ?? e.module, plugin: r.plugin ?? e.plugin }; } const i = typeof n?.logLevelName === "string" ? n.logLevelName : t.level; return { time: typeof t.time === "string" ? t.time : typeof n?.date === "string" ? n.date : void 0, level: normalizeOptionalLowercaseString(i), subsystem: r.subsystem ?? (typeof t.subsystem === "string" ? t.subsystem : void 0), module: r.module, plugin: r.plugin, message: typeof t.message === "string" ? t.message : extractMessage(t), raw: e }; } catch { return null; } } //#endregion //#region src/logging/log-tail.ts const DEFAULT_LIMIT = 500; const DEFAULT_MAX_BYTES = 25e4; const MAX_LIMIT = 5e3; const MAX_BYTES = 1e6; let redactionAnchor; function invalidateRedactionAnchor(e, t) { if (redactionAnchor?.file === e && (!t || t.dev !== redactionAnchor.dev || t.ino !== redactionAnchor.ino || t.size < redactionAnchor.offset)) redactionAnchor = void 0; } function missingPathToNull(e) { if (!isMissingPathError(e)) throw e; return null; } /** Resolves a rolling daily log path to the newest existing rolling log when needed. */ async function resolveLogFile(e, t) { const n = await fs.stat(e).catch(missingPathToNull); const r = { file: e, stat: n }; if (n || !t) return r; const i = path.dirname(e); const a = await fs.readdir(i, { withFileTypes: true }).catch(missingPathToNull); if (!a) return r; return (await Promise.all(a.filter((t) => t.isFile() && isSameRollingLogFileFamily(e, t.name)).map(async (e) => { const t = path.join(i, e.name); const n = await fs.stat(t).catch(missingPathToNull); return n ? { file: t, stat: n } : null; }))).filter((e) => Boolean(e)).toSorted((e, t) => t.stat.mtimeMs - e.stat.mtimeMs)[0] ?? r; } async function readConfiguredLogTail(e, t) { const n = getResolvedLoggerFileTarget(); const { file: r, stat: i } = await resolveLogFile(n.file, n.rolling); invalidateRedactionAnchor(r, i); const a = e?.cursor; const o = e?.limit ?? DEFAULT_LIMIT; const s = e?.maxBytes ?? DEFAULT_MAX_BYTES; const c = resolveLogTailRedactOptions(); if (i && !i.isFile()) throw new Error(`Log path is not a regular file: ${r}`); const l = i?.size ?? 0; const u = clamp(s, 1, MAX_BYTES); const d = clamp(o, 1, MAX_LIMIT); let f = typeof a === "number" && Number.isFinite(a) ? Math.max(0, Math.floor(a)) : void 0; let p = false; let m; let h = false; let g; if (f != null) { if (f > l) { p = true; g = Math.max(0, l - u); h = g > 0; } else { g = f; if (l - g > u) { p = true; h = true; const e = Math.max(0, l - u); m = e - g; g = e; } } } else { g = Math.max(0, l - u); h = g > 0; } if (l === 0 || l <= g) return { file: r, cursor: l, size: l, lines: [], truncated: h, reset: p, skippedBytes: m }; const _ = await fs.open(r, "r").catch(missingPathToNull); if (!_) return { file: r, cursor: 0, size: 0, lines: [], truncated: false, reset: f != null && f > 0 }; try { let e = ""; if (g > 0) { const t = Buffer.alloc(1); const n = await _.read(t, 0, 1, g - 1); e = t.toString("utf8", 0, n.bytesRead); } const n = Math.max(0, l - g); const i = Buffer.alloc(n); const a = await readFileWindowFully(_, i, g); let o = i.toString("utf8", 0, a).split("\n"); o.pop(); let s = 0; if (g > 0 && e !== "\n") { o.shift(); s = i.subarray(0, a).indexOf(10) + 1; } let u = o.map((e) => t?.(e) ?? true); let v = u.filter(Boolean).length; if (v > d) { h = true; for (let e = 0; v > d; e += 1) if (u[e]) { u[e] = false; v -= 1; } } const y = u.indexOf(true); if (y > 0) { for (let e = 0; e < y; e += 1) s = i.indexOf(10, s) + 1; o = o.slice(y); u = u.slice(y); } const b = c.patterns.map((e) => e instanceof RegExp ? void 0 : e.createContext?.()); let x = b.filter((e) => e !== void 0); const S = x.length > 0 ? await _.stat() : void 0; if (S) invalidateRedactionAnchor(r, S); const C = g + s; const w = redactionAnchor; const T = w?.file === r && w.offset <= C && b.every((e, t) => !e || w.states.has(c.patterns[t])) ? w : void 0; const E = T?.offset ?? 0; let D = C; const O = i.subarray(0, a).lastIndexOf(10); f = g + O + 1; const k = O >= 0 && f >= C; if (k && D > E && x.length > 0) { const e = Buffer.alloc(Math.min(D - E, DEFAULT_MAX_BYTES)); let t = Math.min(4096, e.length); let n; const readPrefix = async (t, r) => { if (t >= g && t + r <= g + a) return i.subarray(t - g, t - g + r); if (n && t >= n.offset && t + r <= n.offset + n.length) return e.subarray(t - n.offset, t - n.offset + r); const o = e.subarray(0, r); if (await readFileWindowFully(_, o, t) !== r) throw new Error("Log file changed while reading redaction context"); n = { offset: t, length: r }; return o; }; while (D > E && x.length > 0) { let n = Math.max(E, D - t); let r = await readPrefix(n, D - n); let i = r.indexOf(10); let a = n === E ? E : n + i + 1; while (n > E && (i < 0 || a === D)) { const o = n; t = Math.min(e.length, t * 2); n = Math.max(E, o - t); r = await readPrefix(n, o - n); i = r.lastIndexOf(10); a = n === E && i < 0 ? E : n + i + 1; } const o = x.map((e) => ({ context: e, block: e.prepend() })); const s = new StringDecoder("utf8"); for (let t = a; t < D;) { const n = Math.min(e.length, D - t); const r = s.write(await readPrefix(t, n)); for (const { block: e } of o) e.consume(r); t += n; } const c = s.end(); for (const { block: e } of o) e.consume(c); x = o.filter(({ block: e }) => !e.finish()).map(({ context: e }) => e); D = a; t = Math.min(e.length, t * 2); } } if (k && S) { const e = i.toString("utf8", s, f - g); const t = /* @__PURE__ */ new Map(); for (const [n, r] of b.entries()) if (r) { const i = c.patterns[n]; r.resolve(T?.states.get(i) ?? false); t.set(i, r.advance(e)); } redactionAnchor = { file: r, dev: S.dev, ino: S.ino, offset: f, states: t }; } return { file: r, cursor: f, size: l, lines: v === 0 ? [] : redactSensitiveLines(o, { ...c, patterns: c.patterns.map((e, t) => b[t]?.pattern ?? e) }, u), truncated: h, reset: p, skippedBytes: m }; } finally { await _.close(); } } /** Reads the canonical configured tail and parses its already-redacted lines. */ async function readConfiguredParsedLogTail(e) { const t = await readConfiguredLogTail(e, (t) => { const n = parseLogLine(t); return n !== null && (e?.filter?.(n) ?? true); }); return { ...t, lines: t.lines.flatMap((e) => { const t = parseLogLine(e); return t ? [t] : []; }) }; } //#endregion export { readConfiguredParsedLogTail as n, parseLogLine as r, readConfiguredLogTail as t };