openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
635 lines (634 loc) • 23 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as normalizeDiagnosticWorkerScript } from "./worker-diagnostic-script-BuAZtI7E.mjs";
import { r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { s as redactSensitiveText } from "./redact-Mj7pppxC.mjs";
import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as formatDiagnosticFilenameTimestamp } from "./timestamps-CX4IhE2n.mjs";
import { c as resolveRuntimeServiceCommit, o as resolveRuntimeServiceBuildId, t as VERSION } from "./version-GlxUMdxI.mjs";
import { c as DIAGNOSTIC_MEMORY_PRESSURE_METRICS, l as DIAGNOSTIC_WORKER_RETAINED_STRUCTURES, o as MAX_DIAGNOSTIC_STABILITY_LIMIT, t as getDiagnosticStabilitySnapshot, u as isMemoryPressureReason } from "./diagnostic-stability-Cu_EL85T.mjs";
import { n as setFatalErrorHook } from "./fatal-error-hooks-Bhtt3ct0.mjs";
import fs from "node:fs";
import process from "node:process";
import path from "node:path";
import { replaceFileAtomicSync } from "@openclaw/fs-safe/atomic";
//#region src/logging/diagnostic-stability-readers.ts
function readObject(e, t) {
if (!isRecord(e)) throw new Error(`Invalid stability bundle: ${t} must be an object`);
return e;
}
function readRequiredNumber(e, t) {
if (typeof e !== "number" || !Number.isFinite(e)) throw new Error(`Invalid stability bundle: ${t} must be a finite number`);
return e;
}
function readOptionalNumber(e, t) {
if (e === void 0) return;
return readRequiredNumber(e, t);
}
function readOptionalPositiveInteger(e, t) {
if (e === void 0) return;
const n = readRequiredNumber(e, t);
return n >= 0 ? Math.floor(n) : void 0;
}
function assignOptionalFields(e, t, n, r, i) {
for (const a of r) {
const r = i(t[a], `${n}.${a}`);
if (r !== void 0) e[a] = r;
}
}
//#endregion
//#region src/logging/diagnostic-memory-bundle.ts
function readMemoryUsage(e, t) {
const n = readObject(e, t);
const r = {
rssBytes: readRequiredNumber(n.rssBytes, `${t}.rssBytes`),
heapTotalBytes: readRequiredNumber(n.heapTotalBytes, `${t}.heapTotalBytes`),
heapUsedBytes: readRequiredNumber(n.heapUsedBytes, `${t}.heapUsedBytes`),
externalBytes: readRequiredNumber(n.externalBytes, `${t}.externalBytes`),
arrayBuffersBytes: readRequiredNumber(n.arrayBuffersBytes, `${t}.arrayBuffersBytes`)
};
assignOptionalFields(r, n, t, [
"anonymousRssBytes",
"anonymousSwapBytes",
"heapSizeLimitBytes",
"oldGenerationAfterGcBytes",
"workerCount",
"postgresBridgeCount",
"postgresPoolSelfRootCount",
"workerHeapSampledCount",
"workerHeapTotalBytes",
"workerHeapUsedBytes",
"workerExternalBytes",
"workerArrayBuffersBytes",
"workerArrayBuffersSampledCount"
], readOptionalPositiveInteger);
if (n.workerMemoryScope === "direct") r.workerMemoryScope = n.workerMemoryScope;
if (n.workerMemoryCoverage === "complete" || n.workerMemoryCoverage === "partial" || n.workerMemoryCoverage === "unavailable") r.workerMemoryCoverage = n.workerMemoryCoverage;
if (Array.isArray(n.workerHeaps)) r.workerHeaps = n.workerHeaps.map((e, n) => {
const r = `${t}.workerHeaps[${n}]`;
const i = readObject(e, r);
const a = {
script: normalizeDiagnosticWorkerScript(i.script),
heapUsed: readRequiredNumber(i.heapUsed, `${r}.heapUsed`),
heapTotal: readRequiredNumber(i.heapTotal, `${r}.heapTotal`)
};
assignOptionalFields(a, i, r, [
"threadId",
"external",
"arrayBuffers",
"sampleAgeMs",
"heapSizeLimitBytes",
"oldGenerationAfterGcBytes"
], readOptionalPositiveInteger);
if (Array.isArray(i.retainedData)) a.retainedData = i.retainedData.flatMap((e, t) => {
const n = `${r}.retainedData[${t}]`;
const i = readObject(e, n);
const a = DIAGNOSTIC_WORKER_RETAINED_STRUCTURES.find((e) => e === i.structure);
if (!a) return [];
const o = {
structure: a,
entries: readRequiredNumber(i.entries, `${n}.entries`),
approximateBytes: readRequiredNumber(i.approximateBytes, `${n}.approximateBytes`)
};
assignOptionalFields(o, i, n, [
"stringBytes",
"objects",
"generations",
"providers",
"accounts"
], readOptionalPositiveInteger);
if (typeof i.truncated === "boolean") o.truncated = i.truncated;
return [o];
});
return a;
});
if (Array.isArray(n.workerMemoryMissing)) r.workerMemoryMissing = n.workerMemoryMissing.flatMap((e, n) => {
const r = `${t}.workerMemoryMissing[${n}]`;
const i = readObject(e, r);
if (i.reason !== "pending" && i.reason !== "stale" && i.reason !== "unavailable") return [];
return [{
script: normalizeDiagnosticWorkerScript(i.script),
threadId: readRequiredNumber(i.threadId, `${r}.threadId`),
reason: i.reason
}];
});
return r;
}
//#endregion
//#region src/logging/diagnostic-stability-bundle.ts
const DIAGNOSTIC_STABILITY_BUNDLE_VERSION = 1;
const MAX_DIAGNOSTIC_STABILITY_BUNDLE_BYTES = 5242880;
const SAFE_REASON_CODE = /^[A-Za-z0-9_.:-]{1,120}$/u;
const BUNDLE_PREFIX = "openclaw-stability-";
const BUNDLE_SUFFIX = ".json";
const REDACTED_HOSTNAME = "<redacted-hostname>";
const MAX_SAFE_ERROR_MESSAGE_LENGTH = 500;
const MAX_SHUTDOWN_ERRORS = 32;
const MAX_SAFE_ERROR_STACK_LENGTH = 8e3;
let fatalHookInstalled = false;
function normalizeReason(e) {
return SAFE_REASON_CODE.test(e) ? e : "unknown";
}
function readErrorMessage(e) {
if (typeof e !== "string") return;
const t = redactSensitiveText(e, { mode: "tools" }).replace(/\s+/gu, " ").trim();
if (!t) return;
return t.length > MAX_SAFE_ERROR_MESSAGE_LENGTH ? `${truncateUtf16Safe(t, MAX_SAFE_ERROR_MESSAGE_LENGTH)}...` : t;
}
function readSafeErrorMetadata(e) {
if (!e || typeof e !== "object") return;
const t = "name" in e ? e.name : void 0;
const n = typeof t === "string" && SAFE_REASON_CODE.test(t) ? t : void 0;
const r = "code" in e ? e.code : void 0;
const i = typeof r === "string" && SAFE_REASON_CODE.test(r) ? r : typeof r === "number" && Number.isFinite(r) ? String(r) : void 0;
const a = readErrorMessage("message" in e ? e.message : void 0);
const o = "stack" in e && typeof e.stack === "string" ? truncateUtf16Safe(redactSensitiveText(e.stack, { mode: "tools" }), MAX_SAFE_ERROR_STACK_LENGTH) : void 0;
if (!n && !i && !a && !o) return;
return {
...n ? { name: n } : {},
...i ? { code: i } : {},
...a ? { message: a } : {},
...o ? { stack: o } : {}
};
}
function readShutdownError(e) {
return readSafeErrorMetadata(e && typeof e === "object" ? e : { message: formatErrorMessage(e) }) ?? {};
}
function collectShutdownErrors(e) {
let t = 31;
const n = collectErrorGraphCandidates(e, (e) => {
const n = [e.cause, ...Array.isArray(e.errors) ? e.errors.slice(0, t) : []].filter((e) => e !== void 0).slice(0, t);
t -= n.length;
return n;
});
return (n.length ? n : [e]).map(readShutdownError);
}
function resolveDiagnosticStabilityBundleDir(e = {}) {
return path.join(e.stateDir ?? resolveStateDir(e.env ?? process.env), "logs", "stability");
}
function isBundleFile(e) {
return e.startsWith(BUNDLE_PREFIX) && e.endsWith(BUNDLE_SUFFIX);
}
function readTimestampMs(e, t) {
const n = readRequiredNumber(e, t);
if (Number.isNaN(new Date(n).getTime())) throw new Error(`Invalid stability bundle: ${t} must be a valid timestamp`);
return n;
}
function readRequiredString(e, t) {
if (typeof e !== "string") throw new Error(`Invalid stability bundle: ${t} must be a string`);
return e;
}
function readTimestampString(e, t) {
const n = readRequiredString(e, t);
if (Number.isNaN(new Date(n).getTime())) throw new Error(`Invalid stability bundle: ${t} must be a valid timestamp`);
return n;
}
function readCodeString(e, t) {
const n = readRequiredString(e, t);
if (!SAFE_REASON_CODE.test(n)) throw new Error(`Invalid stability bundle: ${t} must be a safe diagnostic code`);
return n;
}
function readOptionalCodeString(e, t) {
if (e === void 0) return;
const n = readRequiredString(e, t);
return SAFE_REASON_CODE.test(n) ? n : void 0;
}
function readProcessBuildIdentity(e) {
const t = {};
for (const [n, r] of [
["openclawVersion", /^[A-Za-z0-9.+_-]{1,256}$/u],
["buildId", /^[A-Za-z0-9._-]{1,96}$/u],
["commit", /^[0-9a-f]{7,40}$/iu]
]) {
const i = e[n];
if (typeof i === "string" && r.test(i)) t[n] = i;
}
return t;
}
function readHeapStatistics(e) {
if (e === void 0) return;
const t = readObject(e, "evidence.memoryPressure.heapStatistics");
const n = {};
assignOptionalFields(n, t, "evidence.memoryPressure.heapStatistics", [
"totalHeapSizeBytes",
"totalHeapSizeExecutableBytes",
"totalPhysicalSizeBytes",
"totalAvailableSizeBytes",
"usedHeapSizeBytes",
"heapSizeLimitBytes",
"mallocedMemoryBytes",
"externalMemoryBytes"
], readOptionalPositiveInteger);
return Object.keys(n).length > 0 ? n : void 0;
}
function readEvidenceArray(e, t, n) {
if (e === void 0) return;
if (!Array.isArray(e)) throw new Error(`Invalid stability bundle: ${t} must be an array`);
const r = [];
for (const [i, a] of e.entries()) {
const e = `${t}[${i}]`;
const o = n(readObject(a, e), e);
if (o !== void 0) r.push(o);
}
return r.length > 0 ? r : void 0;
}
function readHeapSpaces(e) {
return readEvidenceArray(e, "evidence.memoryPressure.heapSpaces", (e, t) => {
const n = readOptionalCodeString(e.spaceName, `${t}.spaceName`);
if (!n) return;
return {
spaceName: n,
spaceSizeBytes: readOptionalPositiveInteger(e.spaceSizeBytes, `${t}.spaceSizeBytes`) ?? 0,
spaceUsedBytes: readOptionalPositiveInteger(e.spaceUsedBytes, `${t}.spaceUsedBytes`) ?? 0,
spaceAvailableBytes: readOptionalPositiveInteger(e.spaceAvailableBytes, `${t}.spaceAvailableBytes`) ?? 0,
physicalSpaceSizeBytes: readOptionalPositiveInteger(e.physicalSpaceSizeBytes, `${t}.physicalSpaceSizeBytes`) ?? 0
};
});
}
function readCgroupMemorySummary(e) {
if (e === void 0) return;
const t = readObject(e, "evidence.memoryPressure.cgroup");
const n = readCodeString(t.version, "evidence.memoryPressure.cgroup.version");
if (n !== "v2") return;
const r = readObject(t.values, "evidence.memoryPressure.cgroup.values");
const i = {};
for (const [e, t] of Object.entries(r)) {
if (!SAFE_REASON_CODE.test(e)) continue;
if (t === "max") i[e] = "max";
else i[e] = readOptionalPositiveInteger(t, `evidence.memoryPressure.cgroup.values.${e}`) ?? 0;
}
return {
version: n,
values: i,
events: readNumberMap(t.events, "evidence.memoryPressure.cgroup.events")
};
}
function readActiveResources(e) {
if (e === void 0) return;
const t = readObject(e, "evidence.memoryPressure.activeResources");
return {
total: readOptionalPositiveInteger(t.total, "evidence.memoryPressure.activeResources.total") ?? 0,
byType: readNumberMap(t.byType, "evidence.memoryPressure.activeResources.byType")
};
}
function readSessionFiles(e) {
return readEvidenceArray(e, "evidence.memoryPressure.topSessionFiles", (e, t) => {
const n = readRequiredString(e.relativePath, `${t}.relativePath`);
if (path.isAbsolute(n) || n.includes("..") || n.length > 300 || /[\r\n]/u.test(n)) return;
return {
relativePath: sanitizeSessionEvidencePath(n),
sizeBytes: readOptionalPositiveInteger(e.sizeBytes, `${t}.sizeBytes`) ?? 0,
mtimeMs: readOptionalPositiveInteger(e.mtimeMs, `${t}.mtimeMs`) ?? 0
};
});
}
function readMemoryPressureEvidence(e) {
if (e === void 0) return;
const t = readObject(e, "evidence.memoryPressure");
const n = readCodeString(t.level, "evidence.memoryPressure.level");
const r = readCodeString(t.reason, "evidence.memoryPressure.reason");
if (n !== "warning" && n !== "critical" || !isMemoryPressureReason(r)) return;
const i = readHeapStatistics(t.heapStatistics);
const a = readHeapSpaces(t.heapSpaces);
const o = readCgroupMemorySummary(t.cgroup);
const s = readActiveResources(t.activeResources);
const c = readSessionFiles(t.topSessionFiles);
const l = {
level: n,
reason: r,
memory: readMemoryUsage(t.memory, "evidence.memoryPressure.memory")
};
assignOptionalFields(l, t, "evidence.memoryPressure", DIAGNOSTIC_MEMORY_PRESSURE_METRICS, readOptionalNumber);
return {
...l,
...i ? { heapStatistics: i } : {},
...a ? { heapSpaces: a } : {},
...o ? { cgroup: o } : {},
...s ? { activeResources: s } : {},
...c ? { topSessionFiles: c } : {}
};
}
function readBundleEvidence(e) {
if (e === void 0) return;
const t = readObject(e, "evidence");
const n = readMemoryPressureEvidence(t.memoryPressure);
let r;
if (t.shutdown !== void 0) {
const e = readObject(t.shutdown, "evidence.shutdown");
if (!Array.isArray(e.errors)) throw new Error("Invalid stability bundle: evidence.shutdown.errors must be an array");
r = {
step: readCodeString(e.step, "evidence.shutdown.step"),
errors: e.errors.slice(0, MAX_SHUTDOWN_ERRORS).map(readShutdownError)
};
}
return n || r ? {
...n ? { memoryPressure: n } : {},
...r ? { shutdown: r } : {}
} : void 0;
}
function readNumberMap(e, t) {
const n = readObject(e, t);
const r = {};
for (const [e, i] of Object.entries(n)) {
if (!SAFE_REASON_CODE.test(e)) continue;
r[e] = readRequiredNumber(i, `${t}.${e}`);
}
return r;
}
function readMemorySummary(e) {
const t = readObject(e, "snapshot.summary.memory");
const n = t.latest === void 0 ? void 0 : readMemoryUsage(t.latest, "snapshot.summary.memory.latest");
const r = n ? { latest: n } : {};
assignOptionalFields(r, t, "snapshot.summary.memory", ["maxRssBytes", "maxHeapUsedBytes"], readOptionalNumber);
return {
...r,
pressureCount: readRequiredNumber(t.pressureCount, "snapshot.summary.memory.pressureCount")
};
}
function readPayloadLargeSummary(e) {
const t = readObject(e, "snapshot.summary.payloadLarge");
return {
count: readRequiredNumber(t.count, "snapshot.summary.payloadLarge.count"),
rejected: readRequiredNumber(t.rejected, "snapshot.summary.payloadLarge.rejected"),
truncated: readRequiredNumber(t.truncated, "snapshot.summary.payloadLarge.truncated"),
chunked: readRequiredNumber(t.chunked, "snapshot.summary.payloadLarge.chunked"),
bySurface: readNumberMap(t.bySurface, "snapshot.summary.payloadLarge.bySurface")
};
}
function readStabilityEventRecord(e, t) {
const n = readObject(e, t);
const r = {
seq: readRequiredNumber(n.seq, `${t}.seq`),
ts: readTimestampMs(n.ts, `${t}.ts`),
type: readCodeString(n.type, `${t}.type`)
};
assignOptionalFields(r, n, t, [
"channel",
"pluginId",
"source",
"surface",
"action",
"reason",
"outcome",
"level",
"phase",
"approvalId",
"detector",
"toolName",
"activeWorkKind",
"pairedToolName",
"provider",
"model",
"failureKind"
], readOptionalCodeString);
assignOptionalFields(r, n, t, [
"durationMs",
"providerProcessingMs",
"providerWaitEstimateMs",
"requestBytes",
"responseBytes",
"timeToFirstByteMs",
"costUsd",
"count",
"bytes",
...DIAGNOSTIC_MEMORY_PRESSURE_METRICS,
"ageMs",
"queueDepth",
"queueSize",
"queueLength",
"waitMs",
"active",
"waiting",
"queued",
"droppedEvents",
"droppedTrustedEvents",
"droppedUntrustedEvents",
"droppedPriorityEvents",
"maxQueueLength",
"drainBatchSize"
], readOptionalNumber);
if (n.webhooks !== void 0) {
const e = readObject(n.webhooks, `${t}.webhooks`);
r.webhooks = {
received: readRequiredNumber(e.received, `${t}.webhooks.received`),
processed: readRequiredNumber(e.processed, `${t}.webhooks.processed`),
errors: readRequiredNumber(e.errors, `${t}.webhooks.errors`)
};
}
if (n.memory !== void 0) r.memory = readMemoryUsage(n.memory, `${t}.memory`);
if (n.usage !== void 0) {
const e = readObject(n.usage, `${t}.usage`);
r.usage = {};
assignOptionalFields(r.usage, e, `${t}.usage`, [
"input",
"output",
"cacheRead",
"cacheWrite",
"promptTokens",
"total"
], readOptionalNumber);
}
if (n.context !== void 0) {
const e = readObject(n.context, `${t}.context`);
r.context = {};
assignOptionalFields(r.context, e, `${t}.context`, ["limit", "used"], readOptionalNumber);
}
return r;
}
function readStabilitySnapshot(e) {
const t = readObject(e, "snapshot");
const n = readTimestampString(t.generatedAt, "snapshot.generatedAt");
const r = readRequiredNumber(t.capacity, "snapshot.capacity");
const i = readRequiredNumber(t.count, "snapshot.count");
const a = readRequiredNumber(t.dropped, "snapshot.dropped");
const o = readOptionalNumber(t.firstSeq, "snapshot.firstSeq");
const s = readOptionalNumber(t.lastSeq, "snapshot.lastSeq");
if (!Array.isArray(t.events)) throw new Error("Invalid stability bundle: snapshot.events must be an array");
const c = t.events.map((e, t) => readStabilityEventRecord(e, `snapshot.events[${t}]`));
const l = readObject(t.summary, "snapshot.summary");
return {
generatedAt: n,
capacity: r,
count: i,
dropped: a,
...o !== void 0 ? { firstSeq: o } : {},
...s !== void 0 ? { lastSeq: s } : {},
events: c,
summary: {
byType: readNumberMap(l.byType, "snapshot.summary.byType"),
...l.memory !== void 0 ? { memory: readMemorySummary(l.memory) } : {},
...l.payloadLarge !== void 0 ? { payloadLarge: readPayloadLargeSummary(l.payloadLarge) } : {}
}
};
}
function parseDiagnosticStabilityBundle(e) {
const t = readObject(e, "bundle");
if (t.version !== DIAGNOSTIC_STABILITY_BUNDLE_VERSION) throw new Error(`Unsupported stability bundle version: ${String(t.version)}`);
const n = readObject(t.process, "process");
readObject(t.host, "host");
const r = t.error === void 0 ? void 0 : readSafeErrorMetadata(t.error);
const i = readBundleEvidence(t.evidence);
return {
version: DIAGNOSTIC_STABILITY_BUNDLE_VERSION,
generatedAt: readTimestampString(t.generatedAt, "generatedAt"),
reason: normalizeReason(readRequiredString(t.reason, "reason")),
process: {
pid: readRequiredNumber(n.pid, "process.pid"),
platform: readCodeString(n.platform, "process.platform"),
arch: readCodeString(n.arch, "process.arch"),
node: readCodeString(n.node, "process.node"),
uptimeMs: readRequiredNumber(n.uptimeMs, "process.uptimeMs"),
...readProcessBuildIdentity(n)
},
host: { hostname: REDACTED_HOSTNAME },
...r ? { error: r } : {},
...i ? { evidence: i } : {},
snapshot: readStabilitySnapshot(t.snapshot)
};
}
function sanitizeSessionEvidencePath(e) {
const t = e.split("/");
if (t.length === 4 && t[0] === "agents" && t[2] === "sessions") return `agents/<agent>/sessions/${sanitizeSessionEvidenceFileName(expectDefined(t[3], "parts entry at 3"))}`;
if (t.length === 2 && t[0] === "sessions") return `sessions/${sanitizeSessionEvidenceFileName(expectDefined(t[1], "parts entry at 1"))}`;
return redactSensitiveText(e, { mode: "tools" });
}
function sanitizeSessionEvidenceFileName(e) {
if (e === "sessions.json") return "sessions.json";
if (e.endsWith(".jsonl")) return "<session>.jsonl";
if (e.endsWith(".json")) return "<session>.json";
return "<session>";
}
function listDiagnosticStabilityBundleFilesSync(e, t) {
try {
return fs.readdirSync(e, { withFileTypes: true }).filter((e) => e.isFile() && isBundleFile(e.name)).map((n) => {
const r = path.join(e, n.name);
let i = 0;
try {
i = fs.statSync(r).mtimeMs;
} catch (e) {
if (t === "throw") throw e;
}
return {
path: r,
mtimeMs: i
};
}).toSorted((e, t) => t.mtimeMs - e.mtimeMs || t.path.localeCompare(e.path));
} catch (e) {
if (isMissingPathError(e)) return [];
throw e;
}
}
function readDiagnosticStabilityBundleFileSync(e) {
try {
const t = fs.statSync(e);
if (t.size > 5242880) throw new Error(`Stability bundle is too large: ${t.size} bytes exceeds ${MAX_DIAGNOSTIC_STABILITY_BUNDLE_BYTES}`);
const n = fs.readFileSync(e, "utf8");
const r = parseDiagnosticStabilityBundle(JSON.parse(n));
return {
status: "found",
path: e,
mtimeMs: t.mtimeMs,
bundle: r
};
} catch (t) {
return {
status: "failed",
path: e,
error: t
};
}
}
function readLatestDiagnosticStabilityBundleSync(e = {}) {
try {
const t = listDiagnosticStabilityBundleFilesSync(resolveDiagnosticStabilityBundleDir(e), "throw")[0];
if (!t) return {
status: "missing",
dir: resolveDiagnosticStabilityBundleDir(e)
};
return readDiagnosticStabilityBundleFileSync(t.path);
} catch (e) {
return {
status: "failed",
error: e
};
}
}
function pruneOldBundles(e, t) {
try {
const n = listDiagnosticStabilityBundleFilesSync(e, "use-zero").filter((e) => e.path !== t);
for (const e of n.slice(19)) try {
fs.unlinkSync(e.path);
} catch {}
} catch {}
}
function writeDiagnosticStabilityBundleForFailureSync(e, t, n = {}) {
try {
const r = n.now ?? /* @__PURE__ */ new Date();
const i = getDiagnosticStabilitySnapshot({ limit: MAX_DIAGNOSTIC_STABILITY_LIMIT });
const a = normalizeReason(e);
const o = t ? readSafeErrorMetadata(t) : void 0;
const s = n.shutdownStep ? { shutdown: {
step: readCodeString(n.shutdownStep, "shutdownStep"),
errors: collectShutdownErrors(t)
} } : void 0;
const c = {
version: DIAGNOSTIC_STABILITY_BUNDLE_VERSION,
generatedAt: r.toISOString(),
reason: a,
process: {
pid: process.pid,
platform: process.platform,
arch: process.arch,
node: process.versions.node,
uptimeMs: Math.round(process.uptime() * 1e3),
...readProcessBuildIdentity({
openclawVersion: VERSION,
buildId: resolveRuntimeServiceBuildId(),
commit: resolveRuntimeServiceCommit()
})
},
host: { hostname: REDACTED_HOSTNAME },
...o ? { error: o } : {},
...s ? { evidence: s } : {},
snapshot: i
};
const l = resolveDiagnosticStabilityBundleDir(n);
const u = path.join(l, `${BUNDLE_PREFIX}${formatDiagnosticFilenameTimestamp(r)}-${process.pid}-${a}${BUNDLE_SUFFIX}`);
replaceFileAtomicSync({
filePath: u,
content: `${JSON.stringify(c, null, 2)}\n`,
dirMode: 448,
mode: 384,
tempPrefix: ".openclaw-stability"
});
pruneOldBundles(l, u);
return {
status: "written",
path: u,
message: `wrote stability bundle: ${u}`
};
} catch (e) {
return {
status: "failed",
message: `failed to write stability bundle: ${String(e)}`
};
}
}
function installDiagnosticStabilityFatalHook(e = {}) {
if (fatalHookInstalled) return;
fatalHookInstalled = true;
setFatalErrorHook(({ reason: t, error: n }) => {
return writeDiagnosticStabilityBundleForFailureSync(t, n, e).message;
});
}
function uninstallDiagnosticStabilityFatalHook() {
setFatalErrorHook(void 0);
fatalHookInstalled = false;
}
//#endregion
export { uninstallDiagnosticStabilityFatalHook as a, readLatestDiagnosticStabilityBundleSync as i, installDiagnosticStabilityFatalHook as n, writeDiagnosticStabilityBundleForFailureSync as o, readDiagnosticStabilityBundleFileSync as r, MAX_DIAGNOSTIC_STABILITY_BUNDLE_BYTES as t };