openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
2,482 lines • 81 kB
JavaScript
import { h as extractErrorCode, v as formatErrorStackWithMessage } from "./paths-0xDagtub.mjs";
import { d as asOptionalRecord, o as stripAnsi, p as isRecord } from "./utils-BclMknzT.mjs";
import { B as normalizeOptionalString, L as normalizeLowercaseStringOrEmpty, U as resolveGlobalSet, W as resolveGlobalSingleton, a as resolveStateDir, l as expandHomePrefix, y as asFiniteNumber } from "./path-guards-quCEQx1i.mjs";
import { K as getSealedRuntimeSecureTempRoot, X as truncateUtf16Safe, Z as expectDefined, d as loggingState, i as redactToolPayloadText, n as redactSecrets, q as isBlockedObjectKey, r as redactSensitiveText, t as redactLogRecordForTransport, u as readLoggingConfig } from "./redact-BRF0hr6G.mjs";
import { u as normalizeUniqueStringEntriesLower } from "./string-normalization-BMFMScZY.mjs";
import "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { n as pluginRuntimeProcessManifest, t as createRuntimeProcessEntrypoints } from "./runtime-process-manifest-BxvHhnYN.mjs";
import { n as isTruthyEnvValue } from "./env-C62NiKTo.mjs";
import { n as runtimeProcessSealedManifest } from "./runtime-process-sealed-manifest-BIIhNxD4.mjs";
import { AsyncLocalStorage } from "node:async_hooks";
import util, { stripVTControlCharacters } from "node:util";
import fsSync, { mkdirSync } from "node:fs";
import path, { basename, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { createHash, randomBytes, randomUUID } from "node:crypto";
import { appendRegularFile, appendRegularFileSync } from "@openclaw/fs-safe/advanced";
import fsPromises from "node:fs/promises";
import os from "node:os";
import { performance } from "node:perf_hooks";
import { Chalk } from "chalk";
import { Logger } from "tslog";
//#region src/logging/logger-file-message.ts
const MAX_FILE_LOG_MESSAGE_CHARS = 4096;
function clampMessage(e) {
return e.length > MAX_FILE_LOG_MESSAGE_CHARS ? `${truncateUtf16Safe(e, MAX_FILE_LOG_MESSAGE_CHARS)}...(truncated)` : e;
}
function stringifyFileLogMessagePart(e, t) {
if (t) return JSON.stringify(e);
if (typeof e === "string") return e;
if (typeof e === "number" || typeof e === "boolean" || typeof e === "bigint") return String(e);
if (isRecord(e) && typeof e.message === "string") return e.message;
}
function serializeFileLogRecord(e, t = []) {
const n = [];
const r = JSON.parse(JSON.stringify(e, function(e, t) {
while (n.length > 0 && n.at(-1) !== this) n.pop();
if (typeof t === "bigint") return String(t);
if (t !== null && typeof t === "object") {
if (n.includes(t)) return "[Circular]";
n.push(t);
}
return t;
}));
if (!isRecord(r)) throw new TypeError("File log records must serialize to objects");
const i = [];
for (const { key: e, json: n, primitiveText: a } of t) {
const t = a ?? stringifyFileLogMessagePart(r[e], n);
if (t?.trim()) i.push(t);
}
if (i.length > 0) {
const e = clampMessage(i.join(" "));
if (Object.hasOwn(r, "message")) r.message = e;
else {
const t = Object.entries(r);
t.splice(t.findIndex(([e]) => e === "hostname") + 1, 0, ["message", e]);
return JSON.stringify(Object.fromEntries(t));
}
}
return JSON.stringify(r);
}
//#endregion
//#region packages/terminal-core/src/progress-line.ts
let activeStream = null;
/** Clear the active progress line when it is attached to a TTY stream. */
function clearActiveProgressLine() {
if (!activeStream?.isTTY) return;
activeStream.write("\r\x1B[2K");
}
//#endregion
//#region src/global-state.ts
let globalVerbose = false;
function isVerbose() {
return globalVerbose;
}
//#endregion
//#region src/infra/diagnostic-event-listener-presence.ts
/** Process-wide listener counts used to avoid telemetry work without consumers. */
const listenerPresence = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticEventListenerPresence.v1"), () => ({
untrustedInterest: {
broadInterestCount: 0,
eventInterestDeltas: /* @__PURE__ */ new Map()
},
trustedInterest: {
broadInterestCount: 0,
eventInterestDeltas: /* @__PURE__ */ new Map()
},
interestListeners: /* @__PURE__ */ new Map(),
internalCount: 0,
trustedCount: 0,
promptStatsCount: 0
}));
function isInternalDiagnosticEventInterested(e, t, n) {
return (!e?.include || e.include.includes(t)) && !e?.exclude?.includes(t) && (!n || !e?.includeTrusted || e.includeTrusted.includes(t));
}
function hasInternalDiagnosticEventInterest(e, t = false) {
const n = t ? listenerPresence.trustedInterest : listenerPresence.untrustedInterest;
return n.broadInterestCount + (n.eventInterestDeltas.get(e) ?? 0) > 0;
}
//#endregion
//#region src/infra/diagnostic-event-queue-policy.ts
const ASYNC_EVENT = {
priority: false,
publicExcluded: false
};
const DIAGNOSTIC_EVENT_POLICIES = [
{
...ASYNC_EVENT,
name: "worker.request"
},
{
...ASYNC_EVENT,
name: "diagnostic.gc",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.event_loop.sample",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.main_thread.stall",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.http.cancelled",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.rpc",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "sessions.list.baseline.retired"
},
{
...ASYNC_EVENT,
name: "sessions.list.retention",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "sessions.event.retention",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "sessions.event.rows.reset",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.ws.event",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "gateway.ws.connections",
publicExcluded: true
},
{
...ASYNC_EVENT,
name: "tool.execution.started"
},
{
...ASYNC_EVENT,
name: "tool.execution.completed",
priority: true
},
{
...ASYNC_EVENT,
name: "tool.execution.error",
priority: true
},
{
...ASYNC_EVENT,
name: "tool.execution.blocked",
priority: true
},
{
...ASYNC_EVENT,
name: "skill.used"
},
{
...ASYNC_EVENT,
name: "exec.process.completed"
},
{
...ASYNC_EVENT,
name: "exec.approval.followup_suppressed"
},
{
...ASYNC_EVENT,
name: "message.delivery.started"
},
{
...ASYNC_EVENT,
name: "message.delivery.completed"
},
{
...ASYNC_EVENT,
name: "message.delivery.error"
},
{
...ASYNC_EVENT,
name: "talk.event"
},
{
...ASYNC_EVENT,
name: "model.call.started"
},
{
...ASYNC_EVENT,
name: "model.call.completed",
priority: true
},
{
...ASYNC_EVENT,
name: "model.call.error",
priority: true
},
{
...ASYNC_EVENT,
name: "model.response.observed"
},
{
...ASYNC_EVENT,
name: "run.progress"
},
{
...ASYNC_EVENT,
name: "run.execution_phase"
},
{
...ASYNC_EVENT,
name: "agent.commentary"
},
{
...ASYNC_EVENT,
name: "harness.run.completed",
priority: true
},
{
...ASYNC_EVENT,
name: "harness.run.error",
priority: true
},
{
...ASYNC_EVENT,
name: "context.assembled"
},
{
...ASYNC_EVENT,
name: "log.record",
publicExcluded: true
}
];
const ASYNC_DIAGNOSTIC_EVENT_NAMES = DIAGNOSTIC_EVENT_POLICIES.map((e) => e.name);
const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_NAMES = DIAGNOSTIC_EVENT_POLICIES.filter((e) => e.priority).map((e) => e.name);
const PUBLIC_EXCLUDED_DIAGNOSTIC_EVENT_NAMES = DIAGNOSTIC_EVENT_POLICIES.filter((e) => e.publicExcluded).map((e) => e.name);
//#endregion
//#region src/shared/async-context.ts
const context = resolveGlobalSingleton(Symbol.for("openclaw.asyncContext"), () => new AsyncLocalStorage());
/** A field in the immutable async frame, retaining its owner's value by reference. */
var AsyncContext = class {
constructor(e) {
this.key = e;
}
getStore() {
return context.getStore()?.[this.key];
}
run(e, t) {
const n = context.getStore();
const r = n?.[this.key];
if (Object.is(r, e)) return t();
const i = {
...n,
[this.key]: e
};
context.enterWith(i);
try {
return t();
} finally {
const e = context.getStore();
context.enterWith(e === i ? n : {
...e,
[this.key]: r
});
}
}
exit(e) {
return this.run(void 0, e);
}
/** Used by the single-copy runner, which owns restoration of the entire frame. */
enterWith(e) {
context.enterWith({
...context.getStore(),
[this.key]: e
});
}
};
//#endregion
//#region src/infra/diagnostic-trace-context.ts
const TRACE_ID_RE = /^[0-9a-f]{32}$/;
const SPAN_ID_RE = /^[0-9a-f]{16}$/;
const TRACE_FLAGS_RE = /^[0-9a-f]{2}$/;
const DIAGNOSTIC_TRACE_SCOPE_STATE_KEY = Symbol.for("openclaw.diagnosticTraceScope.state.v1");
function isNonZeroHex(e) {
return !/^0+$/.test(e);
}
const traceContext = new AsyncContext(DIAGNOSTIC_TRACE_SCOPE_STATE_KEY);
/** Returns whether a value is a non-zero W3C trace id. */
function isValidDiagnosticTraceId(e) {
return typeof e === "string" && TRACE_ID_RE.test(e) && isNonZeroHex(e);
}
/** Returns whether a value is a non-zero W3C span id. */
function isValidDiagnosticSpanId(e) {
return typeof e === "string" && SPAN_ID_RE.test(e) && isNonZeroHex(e);
}
/** Returns whether a value is a valid W3C trace-flags byte. */
function isValidDiagnosticTraceFlags(e) {
return typeof e === "string" && TRACE_FLAGS_RE.test(e);
}
/** Returns the trace context bound to the current async scope. */
function getActiveDiagnosticTraceContext() {
return traceContext.getStore();
}
//#endregion
//#region src/infra/diagnostic-event-snapshot.ts
const immutableSnapshots = /* @__PURE__ */ new WeakSet();
/** Owned envelopes contain data properties; their nested values still belong to producers. */
function cloneDiagnosticValueForListener(e, t = false) {
if (immutableSnapshots.has(e)) return e;
if (t && Object.getOwnPropertySymbols(e).length === 0 && Object.values(e).every((e) => isImmutableDiagnosticValue(e))) {
immutableSnapshots.add(e);
return Object.freeze(e);
}
const n = structuredClone(e);
if (freezeDiagnosticValue(n, /* @__PURE__ */ new WeakSet())) immutableSnapshots.add(n);
return n;
}
/** Capture lazily so filtered listeners never read the producer's payload. */
function createDiagnosticValueForListeners(e, t = false) {
let n;
return () => {
if (n) return n;
const r = cloneDiagnosticValueForListener(e, t);
if (immutableSnapshots.has(r)) n = r;
return r;
};
}
function isImmutableDiagnosticValue(e, t) {
if (!e || typeof e !== "object") return typeof e !== "function" && typeof e !== "symbol";
if (immutableSnapshots.has(e) || t?.has(e)) return true;
const n = Object.getPrototypeOf(e);
if (!Object.isFrozen(e) || n !== Object.prototype && n !== Array.prototype && n !== null) return false;
let r = t;
return Reflect.ownKeys(e).every((t) => {
const n = Object.getOwnPropertyDescriptor(e, t);
if (typeof t === "symbol" || !("value" in n)) return false;
if (n.value && typeof n.value === "object") (r ??= /* @__PURE__ */ new WeakSet()).add(e);
return isImmutableDiagnosticValue(n.value, r);
});
}
function freezeDiagnosticValue(e, t) {
if (!e || typeof e !== "object" || t.has(e)) return true;
if (ArrayBuffer.isView(e)) return false;
t.add(e);
const n = Object.getPrototypeOf(e);
let r = n === Object.prototype || n === Array.prototype || n === null;
for (const n of Object.values(e)) if (!freezeDiagnosticValue(n, t)) r = false;
Object.freeze(e);
return r;
}
function enrichDiagnosticEvent(e, t, n = true) {
const r = {};
for (const [e, n] of Object.entries(t)) {
if (isBlockedObjectKey(e)) continue;
r[e] = n;
}
if (n) r.trace ??= getActiveDiagnosticTraceContext();
e.seq += 1;
r.seq = e.seq;
r.ts = Date.now();
return r;
}
function captureQueuedDiagnosticEvent(e, t) {
try {
let n = false;
let r = false;
if (e.privateData || e.trustedListenersOnly) {
for (const i of t) if (isInternalDiagnosticEventInterested(i, e.event.type, e.metadata.trusted)) {
n = true;
if (i?.includePrivateData !== false) {
r = true;
break;
}
}
}
if (e.trustedListenersOnly && !n) return false;
e.event = cloneDiagnosticValueForListener(e.event, true);
if (e.privateData) try {
e.privateData = r ? cloneDiagnosticValueForListener(e.privateData) : void 0;
} catch (t) {
e.privateData = void 0;
console.error(`[diagnostic-events] private snapshot error type=${e.event.type}: ${String(t)}`);
}
return true;
} catch (t) {
console.error(`[diagnostic-events] queue snapshot error type=${e.event.type}: ${String(t)}`);
return false;
}
}
//#endregion
//#region src/infra/diagnostic-model-request-provenance.ts
const CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY = "coreModelRequestLifecycle";
//#endregion
//#region src/infra/diagnostic-otel-listener-provenance.ts
const trustedOtelDiagnosticListeners = /* @__PURE__ */ new WeakSet();
function isTrustedOtelDiagnosticListener(e) {
return trustedOtelDiagnosticListeners.has(e);
}
//#endregion
//#region src/infra/diagnostic-plugin-usage-provenance.ts
const hostPluginUsageIds = /* @__PURE__ */ new WeakMap();
function consumeHostPluginUsageDiagnosticEvent(e) {
const t = hostPluginUsageIds.get(e);
hostPluginUsageIds.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-semantic-run-progress-provenance.ts
const CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY = "coreSemanticRunProgress";
const coreSemanticRunProgressEvents = /* @__PURE__ */ new WeakMap();
function consumeCoreSemanticRunProgressDiagnosticEvent(e) {
const t = coreSemanticRunProgressEvents.get(e);
coreSemanticRunProgressEvents.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-tool-execution-liveness.ts
const TOOL_EXECUTION_LIVENESS_METADATA_KEY = "toolExecutionLiveness";
const state = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticToolExecutionLiveness"), () => ({
context: new AsyncContext(Symbol("toolExecutionDeadline")),
events: /* @__PURE__ */ new WeakMap()
}));
function consumeToolExecutionLivenessDiagnosticEvent(e) {
const t = state.events.get(e);
state.events.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-trace-propagation.ts
const DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY = Symbol.for("openclaw.diagnosticTracePropagation.state.v1");
const tracePropagationState = resolveGlobalSingleton(DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY, () => ({
marker: DIAGNOSTIC_TRACE_PROPAGATION_STATE_KEY,
bridges: /* @__PURE__ */ new Set(),
activeBridge: void 0
}));
/** Whether an exporter needs events prepared before their queued delivery. */
function hasDiagnosticTracePropagationConsumer() {
return tracePropagationState.activeBridge?.prepareEvent !== void 0;
}
function shouldPrepareDiagnosticTracePropagation(e) {
const t = tracePropagationState.activeBridge;
if (!t?.prepareEvent) return false;
if (!t.shouldPrepareEvent) return true;
try {
return t.shouldPrepareEvent(e);
} catch (e) {
console.error(`[diagnostic-trace-propagation] prepare filter error: ${String(e)}`);
return false;
}
}
function prepareDiagnosticTracePropagation(e, t) {
const n = tracePropagationState.activeBridge;
if (!n?.prepareEvent) return;
try {
n.prepareEvent(e, t);
} catch (t) {
console.error(`[diagnostic-trace-propagation] prepare error type=${e.type} seq=${e.seq}: ${String(t)}`);
}
}
//#endregion
//#region src/agents/usage.ts
const USAGE_COST_COMPONENTS = [
"input",
"output",
"cacheRead",
"cacheWrite"
];
function hasNonzeroUsage(e) {
if (!e || e.usageReport?.state === "unavailable") return false;
return [
e.input,
e.output,
e.cacheRead,
e.cacheWrite,
e.contextUsage?.state === "available" ? e.contextUsage.promptTokens : void 0,
e.contextUsage?.state === "available" ? e.contextUsage.totalTokens : void 0,
e.reasoningTokens,
e.total
].some((e) => typeof e === "number" && Number.isFinite(e) && e > 0) || e.contextUsage?.state === "unavailable";
}
/** Adapter-default zeros are not price evidence; billed totals and cost components are. */
function hasRecordedUsageCost(e) {
const t = asOptionalRecord(e);
const n = asFiniteNumber(t?.total);
return n !== void 0 && n >= 0 && (n > 0 || t?.totalOrigin === "provider-billed" || USAGE_COST_COMPONENTS.some((e) => (asFiniteNumber(t?.[e]) ?? 0) !== 0));
}
/** Empty transport snapshots synthesize $0; recorded cost evidence can establish an observation. */
function hasObservedModelUsage(e) {
return e?.usageReport !== void 0 || hasRecordedUsageCost(e?.cost) || hasNonzeroUsage(e);
}
//#endregion
//#region src/infra/diagnostic-flags-env.ts
function parseDiagnosticEnvFlags(e) {
const t = e?.trim() ?? "";
const n = t.toLowerCase();
if (!n) return {
flags: [],
disablesAll: false
};
if ([
"0",
"false",
"off",
"none"
].includes(n)) return {
flags: [],
disablesAll: true
};
if ([
"1",
"true",
"all",
"*"
].includes(n)) return {
flags: ["*"],
disablesAll: false
};
return {
flags: t.split(/[,\s]+/),
disablesAll: false
};
}
//#endregion
//#region src/infra/diagnostic-flags.ts
const DIAGNOSTICS_ENV = "OPENCLAW_DIAGNOSTICS";
/** Returns whether a diagnostic flag is enabled after config/env resolution. */
function isDiagnosticFlagEnabled(e, t, n = process.env) {
const r = t?.diagnostics?.flags ?? [];
const i = parseDiagnosticEnvFlags(n[DIAGNOSTICS_ENV]);
const a = i.disablesAll ? [] : normalizeUniqueStringEntriesLower([...r, ...i.flags]);
const o = normalizeLowercaseStringOrEmpty(e);
if (!o) return false;
for (const e of a) {
if (e === "*" || e === "all" || e === o) return true;
if (e.endsWith(".*") && o === e.slice(0, -2)) return true;
if (e.endsWith("*") && o.startsWith(e.slice(0, -1))) return true;
}
return false;
}
//#endregion
//#region src/infra/main-thread-stall.ts
const taskState = resolveGlobalSingleton(Symbol.for("openclaw.mainThreadTask"), () => ({ context: new AsyncLocalStorage() }));
/**
* Name code-owned work only; request text, paths, and identifiers do not belong in labels.
* Phases label synchronous segments; only task boundaries establish an inherited async name.
*/
function runWithMainThreadTask(e, t, n) {
const r = taskState.observer;
return r ? r.run(e, t, n) : t();
}
//#endregion
//#region src/infra/diagnostics-timeline.ts
const OPENCLAW_DIAGNOSTICS_TIMELINE_SCHEMA_VERSION = "openclaw.diagnostics.v1";
const MAX_PENDING_TIMELINE_BYTES = 65536;
/** Usage is a terminal observation, not proof of all requests hidden inside a logical call. */
function modelUsageTimelineAttributes(e) {
const t = { usageState: e?.usageReport?.state ?? (hasObservedModelUsage(e) ? "available" : "unreported") };
for (const n of [
"input",
"output",
"cacheRead",
"cacheWrite",
"cacheWrite1h",
"cacheWrite5m",
"reasoningTokens",
"promptTokens",
"total"
]) {
const r = e?.[n];
if (r !== void 0) t[n] = r;
}
return t;
}
function recordDiagnosticModelUsageTimeline(e) {
if (!isDiagnosticsTimelineEnabled()) return;
const t = e.trace ?? getActiveDiagnosticTraceContext();
emitDiagnosticsTimelineEvent({
type: "mark",
name: "model.usage",
provider: e.provider,
attributes: {
...modelUsageTimelineAttributes({
...e.usage,
usageReport: e.usageReport
}),
...e.model ? { model: e.model } : {},
...e.sessionId ? { sessionId: e.sessionId } : {},
...t ? { traceId: t.traceId } : {},
...e.purpose ? { purpose: e.purpose } : {},
...e.runtimeKind ? { runtimeKind: e.runtimeKind } : {},
...e.completionId ? { completionId: e.completionId } : {},
...e.attemptId ? { attemptId: e.attemptId } : {},
...e.costUsd !== void 0 ? { costUsd: e.costUsd } : {}
}
});
}
const activeDiagnosticsTimelineSpan = new AsyncLocalStorage();
const spanObserver = new AsyncLocalStorage();
const timelineWriter = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticsTimelineWriter"), () => {
let e;
let t;
let n;
let r = false;
let i = false;
const a = /* @__PURE__ */ new Set();
function append(e, t) {
try {
const n = dirname(e.path);
if (!a.has(n)) {
mkdirSync(n, { recursive: true });
a.add(n);
}
appendRegularFileSync({
filePath: e.path,
content: t
});
} catch (t) {
e.failedWrites++;
if (!i) {
i = true;
console.warn(`[diagnostics] failed to write timeline event: ${String(t)}`);
}
}
}
function flush() {
if (n) {
clearImmediate(n);
n = void 0;
}
const e = t;
t = void 0;
if (e) append(e.capture, e.content);
}
process.once("exit", () => {
r = true;
flush();
});
return {
flush,
write(i, a, o) {
if (e?.path !== i) {
flush();
e = {
path: i,
id: randomUUID(),
sequence: 0,
failedWrites: 0
};
}
const s = serializeTimelineEvent({
...a,
attributes: {
...a.attributes,
captureId: e.id,
sequence: ++e.sequence,
failedWrites: e.failedWrites
}
}, o);
const c = Buffer.byteLength(s, "utf8");
if (t && t.bytes + c > MAX_PENDING_TIMELINE_BYTES) flush();
if (r || c > MAX_PENDING_TIMELINE_BYTES) {
append(e, s);
return;
}
if (t) {
t.content += s;
t.bytes += c;
} else t = {
capture: e,
content: s,
bytes: c
};
n ??= setImmediate(flush).unref();
}
};
});
/** Returns true when diagnostics flags and a JSONL output path both allow timeline writes. */
function isDiagnosticsTimelineEnabled(e = {}) {
const { config: t, env: n = process.env } = e;
const r = n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH;
if (typeof r !== "string" || r.trim().length === 0) return false;
return isDiagnosticFlagEnabled("timeline", t, n) || isDiagnosticFlagEnabled("diagnostics.timeline", t, n) || isTruthyEnvValue(n.OPENCLAW_DIAGNOSTICS);
}
function normalizeNumber(e) {
if (typeof e !== "number" || !Number.isFinite(e)) return;
return Math.max(0, Math.round(e * 1e3) / 1e3);
}
function normalizeAttributes(e) {
if (!e) return;
const t = {};
for (const [n, r] of Object.entries(e)) {
if (typeof r === "number") {
if (Number.isFinite(r)) t[n] = r;
continue;
}
if (typeof r === "string" || typeof r === "boolean" || r === null) t[n] = r;
}
return Object.keys(t).length > 0 ? t : void 0;
}
function serializeTimelineEvent(e, t) {
const n = normalizeAttributes(e.attributes);
const r = {
schemaVersion: OPENCLAW_DIAGNOSTICS_TIMELINE_SCHEMA_VERSION,
type: e.type,
timestamp: e.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
name: e.name,
...t.OPENCLAW_DIAGNOSTICS_RUN_ID ? { runId: t.OPENCLAW_DIAGNOSTICS_RUN_ID } : {},
...t.OPENCLAW_DIAGNOSTICS_ENV ? { envName: t.OPENCLAW_DIAGNOSTICS_ENV } : {},
pid: process.pid,
...e.runId ? { runId: e.runId } : {},
...e.envName ? { envName: e.envName } : {},
...typeof e.pid === "number" ? { pid: e.pid } : {},
phase: e.phase || void 0,
spanId: e.spanId || void 0,
parentSpanId: e.parentSpanId || void 0,
durationMs: normalizeNumber(e.durationMs),
errorName: e.errorName || void 0,
errorMessage: e.errorMessage || void 0,
p50Ms: normalizeNumber(e.p50Ms),
p95Ms: normalizeNumber(e.p95Ms),
p99Ms: normalizeNumber(e.p99Ms),
maxMs: normalizeNumber(e.maxMs),
activeSpanName: e.activeSpanName || void 0,
provider: e.provider || void 0,
operation: e.operation || void 0,
ok: typeof e.ok === "boolean" ? e.ok : void 0,
status: normalizeNumber(e.status),
command: e.command || void 0,
exitCode: e.exitCode,
signal: e.signal,
attributes: n
};
return `${JSON.stringify(r)}\n`;
}
/** Queues one normalized event; bounded batches append on the next event-loop turn. */
function emitDiagnosticsTimelineEvent(e, t = {}) {
const n = t.env ?? process.env;
if (!isDiagnosticsTimelineEnabled(t)) return;
const r = n.OPENCLAW_DIAGNOSTICS_TIMELINE_PATH?.trim();
if (!r) return;
timelineWriter.write(r, e, n);
}
//#endregion
//#region src/infra/worker-diagnostic-script.ts
const scriptBasename = (e) => basename(e).replace(/\.[cm]?[jt]s$/u, ".js");
const entries = createRuntimeProcessEntrypoints(import.meta.url);
const workerScripts = /* @__PURE__ */ new Map();
for (const e of Object.values(entries)) {
const t = scriptBasename(e.distWorkerPath);
workerScripts.set(t, t);
workerScripts.set(scriptBasename(e.sourceModulePath), t);
}
for (const e of Object.values(pluginRuntimeProcessManifest)) {
const t = scriptBasename(e.distWorkerPath);
workerScripts.set(t, t);
workerScripts.set(scriptBasename(e.package.distWorkerPath), t);
workerScripts.set(scriptBasename(`${e.sourceWorkerName}.js`), t);
}
for (const e of Object.values(runtimeProcessSealedManifest)) for (const [t, n] of e.entries) {
const e = scriptBasename(`${n}.mjs`);
if (!workerScripts.has(e)) workerScripts.set(e, scriptBasename(entries[t].distWorkerPath));
}
const workerScriptNames = new Set(workerScripts.values());
/** Imported diagnostics may contain arbitrary paths or names. Preserve only known scripts. */
function normalizeDiagnosticWorkerScript(e) {
return typeof e === "string" && workerScriptNames.has(e) ? e : "other";
}
function workerScriptName(e, t = false) {
if (t || e instanceof URL && e.protocol !== "file:") return "other";
return workerScripts.get(scriptBasename(e instanceof URL ? fileURLToPath(e) : e)) ?? "other";
}
//#endregion
//#region src/infra/diagnostic-events.ts
const EMPTY_DIAGNOSTIC_PRIVATE_DATA = Object.freeze({});
const MAX_ASYNC_DIAGNOSTIC_EVENTS = 1e4;
const MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN = 100;
const DIAGNOSTIC_EVENTS_STATE_KEY = Symbol.for("openclaw.diagnosticEvents.state.v1");
const ASYNC_DIAGNOSTIC_EVENT_TYPES = new Set(ASYNC_DIAGNOSTIC_EVENT_NAMES);
const PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES = new Set(PRIORITY_ASYNC_DIAGNOSTIC_EVENT_NAMES);
const diagnosticEventsState = resolveGlobalSingleton(DIAGNOSTIC_EVENTS_STATE_KEY, () => ({
marker: DIAGNOSTIC_EVENTS_STATE_KEY,
enabled: true,
seq: 0,
listeners: /* @__PURE__ */ new Map(),
trustedListeners: /* @__PURE__ */ new Map(),
toolExecutionListeners: /* @__PURE__ */ new Set(),
toolExecutionSeq: 0,
dispatchDepth: 0,
asyncQueue: [],
asyncDrainScheduled: false,
asyncDroppedEvents: 0,
asyncDroppedTrustedEvents: 0,
asyncDroppedUntrustedEvents: 0,
asyncDroppedPriorityEvents: 0
}));
/** Returns the current process-wide diagnostic dispatcher enable flag. */
function areDiagnosticsEnabledForProcess() {
return diagnosticEventsState.enabled;
}
function dispatchDiagnosticEvent(e, t, n, r, i = {}) {
if (e.dispatchDepth > 100) {
console.error(`[diagnostic-events] recursion guard tripped at depth=${e.dispatchDepth}, dropping type=${t.type}`);
return;
}
e.dispatchDepth += 1;
try {
const a = createDiagnosticValueForListeners(t, true);
const o = r && createDiagnosticValueForListeners(r);
if (!i.trustedListenersOnly) for (const [r, i] of e.listeners) {
if (!isInternalDiagnosticEventInterested(i, t.type, n.trusted)) continue;
try {
r(a(), n);
} catch (e) {
const n = e instanceof Error ? formatErrorStackWithMessage(e) : String(e);
console.error(`[diagnostic-events] listener error type=${t.type} seq=${t.seq}: ${n}`);
}
}
for (const [r, s] of e.trustedListeners) {
if (!isInternalDiagnosticEventInterested(s, t.type, n.trusted)) continue;
try {
const e = a();
const t = isTrustedOtelDiagnosticListener(r);
let c = EMPTY_DIAGNOSTIC_PRIVATE_DATA;
if (s?.includePrivateData !== false) {
c = o?.() ?? EMPTY_DIAGNOSTIC_PRIVATE_DATA;
if (t && (i.hostPluginId || Object.hasOwn(c, "hostPluginId"))) {
const e = {
...c,
hostPluginId: i.hostPluginId
};
if (!i.hostPluginId) Reflect.deleteProperty(e, "hostPluginId");
c = Object.freeze(e);
}
}
r(e, n, c);
} catch (e) {
const n = e instanceof Error ? formatErrorStackWithMessage(e) : String(e);
console.error(`[diagnostic-events] trusted listener error type=${t.type} seq=${t.seq}: ${n}`);
}
}
} finally {
e.dispatchDepth -= 1;
}
}
function isPriorityAsyncDiagnosticEvent(e) {
return e.metadata.trusted && PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(e.event.type);
}
function noteAsyncDiagnosticDrop(e, t) {
e.asyncDroppedEvents += 1;
if (t.metadata.trusted) e.asyncDroppedTrustedEvents += 1;
else e.asyncDroppedUntrustedEvents += 1;
if (isPriorityAsyncDiagnosticEvent(t)) e.asyncDroppedPriorityEvents += 1;
}
function makeRoomForPriorityAsyncDiagnosticEvent(e) {
const t = e.asyncQueue.findIndex((e) => !isPriorityAsyncDiagnosticEvent(e));
if (t >= 0) return e.asyncQueue.splice(t, 1)[0];
return e.asyncQueue.shift();
}
function scheduleAsyncDiagnosticDrain(e) {
if (e.asyncDrainScheduled) return;
e.asyncDrainScheduled = true;
setImmediate(() => {
e.asyncDrainScheduled = false;
const t = e.asyncQueue.splice(0, MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN);
for (const n of t) dispatchDiagnosticEvent(e, n.event, n.metadata, n.privateData, n);
if (e.asyncQueue.length > 0) {
scheduleAsyncDiagnosticDrain(e);
return;
}
dispatchAsyncDiagnosticDropSummary(e);
});
}
function dispatchAsyncDiagnosticDropSummary(e) {
if (e.asyncDroppedEvents <= 0) return;
const t = e.asyncDroppedEvents;
const n = e.asyncDroppedTrustedEvents;
const r = e.asyncDroppedUntrustedEvents;
const i = e.asyncDroppedPriorityEvents;
e.asyncDroppedEvents = 0;
e.asyncDroppedTrustedEvents = 0;
e.asyncDroppedUntrustedEvents = 0;
e.asyncDroppedPriorityEvents = 0;
dispatchDiagnosticEvent(e, enrichDiagnosticEvent(e, {
type: "diagnostic.async_queue.dropped",
droppedEvents: t,
...n > 0 ? { droppedTrustedEvents: n } : {},
...r > 0 ? { droppedUntrustedEvents: r } : {},
...i > 0 ? { droppedPriorityEvents: i } : {},
queueLength: e.asyncQueue.length,
maxQueueLength: MAX_ASYNC_DIAGNOSTIC_EVENTS,
drainBatchSize: MAX_ASYNC_DIAGNOSTIC_EVENTS_PER_TURN
}), Object.freeze({
internal: true,
trusted: false
}));
}
function emitDiagnosticEventWithTrust(e, t, n = {}) {
const r = diagnosticEventsState;
const i = t && isToolExecutionEventInput(e) ? dispatchTrustedToolExecutionEvent(r, e) : void 0;
if (!r.enabled) return;
if (e.type === "security.event" && n.allowSecurityEvent !== true) return;
const a = hasInternalDiagnosticEventInterest(e.type, t);
if (!a && !(t && !n.queuedPhase && hasDiagnosticTracePropagationConsumer())) {
r.seq += 1;
return;
}
let o = enrichDiagnosticEvent(r, i ?? e, !n.queuedPhase);
if (t && o.type === "diagnostic.gc") {
switch (o.kind) {
case "scavenge":
case "mark_sweep_compact":
case "incremental":
case "weak_processing": break;
default: o.kind = void 0;
}
switch (o.reason) {
case "none":
case "forced":
case "synchronous_phantom_processing":
case "all_available_garbage":
case "all_external_memory":
case "schedule_idle":
case "construct_retained":
case "other": break;
default: o.reason = "other";
}
o.thread = o.thread === void 0 || o.thread === "main" ? "main" : normalizeDiagnosticWorkerScript(o.thread);
if (o.thread !== "code-mode-node.worker.js" || typeof o.workerSlot !== "number" || !Number.isInteger(o.workerSlot) || o.workerSlot < 1 || o.workerSlot > 64) o.workerSlot = void 0;
}
const { hostPluginId: s, internal: c = false, privateData: l } = n;
const u = n.trustedTraceContext === true;
const d = Object.freeze({
...c ? { internal: true } : {},
trusted: t,
...n.toolExecutionLiveness ? { [TOOL_EXECUTION_LIVENESS_METADATA_KEY]: n.toolExecutionLiveness } : {},
...n.coreModelRequestLifecycle ? { [CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY]: n.coreModelRequestLifecycle } : {},
...n.coreSemanticRunProgress ? { [CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY]: n.coreSemanticRunProgress } : {},
...u ? { trustedTraceContext: u } : {}
});
const f = t && !n.queuedPhase && shouldPrepareDiagnosticTracePropagation(o);
const p = a && (n.queuedPhase || ASYNC_DIAGNOSTIC_EVENT_TYPES.has(o.type));
if (p) {
if (r.asyncQueue.length >= MAX_ASYNC_DIAGNOSTIC_EVENTS) {
if (!t || !PRIORITY_ASYNC_DIAGNOSTIC_EVENT_TYPES.has(o.type)) {
noteAsyncDiagnosticDrop(r, {
event: o,
metadata: d,
privateData: l,
hostPluginId: s
});
return;
}
const e = makeRoomForPriorityAsyncDiagnosticEvent(r);
if (e) noteAsyncDiagnosticDrop(r, e);
}
const e = {
event: o,
metadata: d,
privateData: l,
hostPluginId: s
};
if (!captureQueuedDiagnosticEvent(e, r.trustedListeners.values())) return;
o = e.event;
r.asyncQueue.push(e);
}
if (f) {
if (!p) o = cloneDiagnosticValueForListener(o, true);
prepareDiagnosticTracePropagation(cloneDiagnosticValueForListener(o), d);
}
if (p) scheduleAsyncDiagnosticDrain(r);
else if (a) dispatchDiagnosticEvent(r, o, d, l, { hostPluginId: s });
}
function isToolExecutionEventInput(e) {
return e.type === "tool.execution.started" || e.type === "tool.execution.completed" || e.type === "tool.execution.error" || e.type === "tool.execution.blocked";
}
function dispatchTrustedToolExecutionEvent(e, t) {
e.toolExecutionSeq += 1;
if (e.toolExecutionListeners.size === 0) return;
let n;
try {
n = cloneDiagnosticValueForListener({
...t,
seq: e.toolExecutionSeq,
ts: Date.now()
}, true);
} catch (e) {
console.error(`[diagnostic-events] tool execution clone error type=${t.type}: ${String(e)}`);
return;
}
const r = createDiagnosticValueForListeners(n);
for (const t of e.toolExecutionListeners) try {
t(r());
} catch (e) {
console.error(`[diagnostic-events] tool execution listener error type=${n.type} seq=${n.seq}: ${String(e)}`);
}
return n;
}
/** Emits an untrusted diagnostic event from external/plugin-facing code. */
function emitDiagnosticEvent(e) {
emitDiagnosticEventWithTrust(e, false);
}
/** Emits an untrusted event whose trace context came from OpenClaw-owned scope. */
function emitDiagnosticEventWithTrustedTraceContext(e) {
emitDiagnosticEventWithTrust(e, false, { trustedTraceContext: true });
}
/** Emits a trusted diagnostic event from core/runtime-owned instrumentation. */
function emitTrustedDiagnosticEvent(e) {
if (e.type === "model.usage") recordDiagnosticModelUsageTimeline(e);
const t = consumeToolExecutionLivenessDiagnosticEvent(e);
const n = consumeHostPluginUsageDiagnosticEvent(e);
const r = consumeCoreSemanticRunProgressDiagnosticEvent(e);
emitDiagnosticEventWithTrust(e, true, {
...t ? { toolExecutionLiveness: t } : {},
...n ? {
hostPluginId: n,
internal: true
} : {},
...r ? { coreSemanticRunProgress: r } : {}
});
}
//#endregion
//#region packages/terminal-core/src/restore.ts
const RESET_SEQUENCE = "\x1B[0m\x1B[?25h\x1B[?1000l\x1B[?1002l\x1B[?1003l\x1B[?1006l\x1B[?2004l\x1B[<u\x1B[>4;0m";
function restoreTerminalState(e, t = {}) {
const n = t.resumeStdinIfPaused ?? t.resumeStdin ?? false;
const r = t.resetStream ?? process.stdout;
const restore = (t, n) => {
try {
n();
} catch (n) {
const r = e ? ` (${e})` : "";
const i = `[terminal] restore ${t} failed${r}: ${String(n)}`;
try {
process.stderr.write(`${i}\n`);
} catch (e) {
console.error(`[terminal] restore reporting failed${r}: ${String(e)}`);
}
}
};
restore("progress line", clearActiveProgressLine);
const i = process.stdin;
if (i.isTTY && typeof i.setRawMode === "function") {
restore("raw mode", () => i.setRawMode(false));
if (n && typeof i.isPaused === "function" && i.isPaused()) restore("stdin resume", () => i.resume());
}
if (r.isTTY) restore("terminal reset", () => r.write(RESET_SEQUENCE));
}
//#endregion
//#region src/runtime.ts
function shouldEmitRuntimeLog(e = process.env) {
if (e.VITEST !== "true") return true;
if (e.OPENCLAW_TEST_RUNTIME_LOG === "1") return true;
return typeof console.log.mock === "object";
}
function shouldEmitRuntimeStdout(e = process.env) {
if (e.VITEST !== "true") return true;
if (e.OPENCLAW_TEST_RUNTIME_LOG === "1") return true;
return typeof process.stdout.write.mock === "object";
}
function isPipeClosedError(e) {
const t = e?.code;
return t === "EPIPE" || t === "EIO";
}
function writeStdout(e) {
if (!shouldEmitRuntimeStdout()) return;
clearActiveProgressLine();
const t = e.endsWith("\n") ? e : `${e}\n`;
try {
process.stdout.write(t);
} catch (e) {
if (isPipeClosedError(e)) return;
throw e;
}
}
function createRuntimeIo() {
return {
log: (...e) => {
if (!shouldEmitRuntimeLog()) return;
clearActiveProgressLine();
console.log(...e);
},
error: (...e) => {
clearActiveProgressLine();
console.error(...e);
},
writeStdout,
writeJson: (e, t = 2) => {
writeStdout(JSON.stringify(e, void 0, t > 0 ? t : void 0));
}
};
}
/** Keep terminal reset bytes off stdout when the invocation owns machine-readable output. */
function restoreRuntimeTerminalState(e, t = {}) {
const n = t.resetStream ?? (loggingState.forceConsoleToStderr ? process.stderr : void 0);
restoreTerminalState(e, {
...t,
...n ? { resetStream: n } : {}
});
}
const defaultRuntime = {
...createRuntimeIo(),
exit: (e, t) => {
restoreRuntimeTerminalState("runtime exit", {
resumeStdinIfPaused: false,
...t?.resetStream ? { resetStream: t.resetStream } : {}
});
throw new ExitError(e);
}
};
/** Signals a deferred or non-exiting runtime exit so callers can unwind owned resources. */
var ExitError = class extends Error {
constructor(e, t) {
super(t ?? `exit ${e}`);
this.code = e;
this.name = "ExitError";
}
};
//#endregion
//#region src/cli/signal-exit-barrier.ts
const processExitOwner = resolveGlobalSingleton(Symbol.for("openclaw.signalExitOwner"), () => ({}));
const activeBarriers = resolveGlobalSet(Symbol.for("openclaw.signalExitBarriers"), "close-and-restart");
const activeGates = resolveGlobalSet(Symbol.for("openclaw.signalExitGates"), "close-and-restart");
const activeFinalizers = resolveGlobalSet(Symbol.for("openclaw.signalExitFinalizers"), "close-and-restart");
const signalObservers = resolveGlobalSet(Symbol.for("openclaw.signalExitObservers"), "close-and-restart");
function registerSignalExitBarrier(e) {
activeBarriers.add(e);
return () => activeBarriers.delete(e);
}
/** Temporary artifacts remain available until other shutdown owners have drained. */
function registerSignalExitFinalizer(e) {
activeFinalizers.add(e);
return () => activeFinalizers.delete(e);
}
const gatewayStartupSignals = resolveGlobalSingleton(Symbol.for("openclaw.gatewayStartupSignals"), () => ({}));
//#endregion
//#region src/logging/timestamps.ts
const validTimeZoneCache = /* @__PURE__ */ new Map();
const timestampFormatterCache = /* @__PURE__ */ new Map();
let hostTimeZone;
let lastTimestampParts;
function isValidTimeZone(e) {
const t = validTimeZoneCache.get(e);
if (t !== void 0) return t;
let n;
try {
new Intl.DateTimeFormat("en", { timeZone: e }).format();
n = true;
} catch {
n = false;
}
validTimeZoneCache.set(e, n);
return n;
}
function resolveEffectiveTimeZone(e) {
const t = e ?? process.env.TZ;
return t && isValidTimeZone(t) ? t : hostTimeZone ??= Intl.DateTimeFormat().resolvedOptions().timeZone;
}
function getTimestampParts(e, t) {
const n = resolveEffectiveTimeZone(t);
const r = Math.floor(e.getTime() / 1e3);
if (lastTimestampParts?.second === r && lastTimestampParts.timeZone === n) return lastTimestampParts.parts;
let i = timestampFormatterCache.get(n);
if (!i) {
i = new Intl.DateTimeFormat("en", {
timeZone: n,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
fractionalSecondDigits: 3,
timeZoneName: "longOffset"
});
timestampFormatterCache.set(n, i);
}
const a = {};
for (const t of i.formatToParts(e)) a[t.type] = t.value;
lastTimestampParts = {
second: r,
timeZone: n,
parts: a
};
return a;
}
function formatTimestamp(e, t) {
const n = t?.style ?? "medium";
const r = getTimestampParts(e, t?.timeZone);
const i = r.timeZoneName ?? "GMT";
const a = i === "GMT" ? "+00:00" : i.slice(3);
const o = String(e.getUTCMilliseconds()).padStart(3, "0");
switch (n) {
case "short": return `${r.hour}:${r.minute}:${r.second}${a}`;
case "medium": return `${r.hour}:${r.minute}:${r.second}.${o}${a}`;
case "long": return `${r.year}-${r.month}-${r.day}T${r.hour}:${r.minute}:${r.second}.${o}${a}`;
}
throw new Error("Unsupported timestamp style");
}
//#endregion
//#region src/logging/json-console-line.ts
function formatJsonConsoleLine(e) {
const t = {
...e.meta,
time: formatTimestamp(/* @__PURE__ */ new Date(), { style: "long" }),
level: e.level,
...e.subsystem ? { subsystem: e.subsystem } : {},
message: e.message
};
return JSON.stringify(redactLogRecordForTransport(t));
}
/** Formats diagnostics that must bypass console capture without bypassing JSON console style. */
function formatConsoleDiagnosticLine(e) {
return (loggingState.overrideSettings?.consoleStyle ?? readLoggingConfig()?.consoleStyle) === "json" ? formatJsonConsoleLine(e) : e.message;
}
//#endregion
//#region src/logging/levels.ts
const ALLOWED_LOG_LEVELS = [
"silent",
"fatal",
"error",
"warn",
"info",
"debug",
"trace"
];
const MIN_LEVEL_BY_LOG_LEVEL = {
trace: 1,
debug: 2,
info: 3,
warn: 4,
error: 5,
fatal: 6,
silent: Number.POSITIVE_INFINITY
};
function tryParseLogLevel(e) {
if (typeof e !== "string") return;
const t = e.trim();
return ALLOWED_LOG_LEVELS.includes(t) ? t : void 0;
}
function normalizeLogLevel(e, t = "info") {
return tryParseLogLevel(e) ?? t;
}
function levelToMinLevel(e) {
return MIN_LEVEL_BY_LOG_LEVEL[e];
}
function isLogLevelEnabled(e, t) {
return e !== "silent" && t !== "silent" && levelToMinLevel(e) >= levelToMinLevel(t);
}
//#endregion
//#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/infra/tmp-openclaw-dir.ts
/** Preferred shared OpenClaw temp root on POSIX systems when ownership and permissions are safe. */
const DEFAULT_POSIX_TMP_ROOT = "/tmp/openclaw";
let resolveSecureTempRootRuntime;
function loadResolveSecureTempRoot() {
if (resolveSecureTempRootRuntime) return resolveSecureTempRootRuntime;
const e = getSealedRuntimeSecureTempRoot();
if (e) {
resolveSecureTempRootRuntime = e;
return e;
}
if (typeof SEALED_RUNTIME_BUILD === "boolean" && SEALED_RUNTIME_BUILD) throw new Error("sealed temp-root runtime was not registered before use");
if (typeof process.getBuiltinModule !== "function") throw new Error("Node module loading is unavailable for secure temp-root resolution");
resolveSecureTempRootRuntime = process.getBuiltinModule("module").createRequire(import.meta.url)("@openclaw/fs-safe/secure-temp-root").resolveSecureTempRoot;
return resolveSecureTempRootRuntime;
}
function assertSafeTempAncestors(e, t) {
const n = t.platform ?? process.platform;
if (n === "win32" || n === "android") return;
const r = process.getBuiltinModule("fs");
const i = t.lstatSync ?? r.lstatSync;
const a = t.lstatSync ? path.resolve(e) : r.realpathSync.native(e);
for (let e = path.dirname(a);; e = path.dirname(e)) {
const t = i(e);
if (t.mode !== void 0 && (t.mode & 18) !== 0 && (t.mode & 512) === 0) {
const t = `'${e.replaceAll("'", "'\\''")}'`;
throw new Error(`Temp workspace ancestor ${JSON.stringify(e)} is group/world writable without sticky protection; have its owner run chmod +t ${t} for a shared temp directory or chmod go-w ${t} for a private ancestor.`);
}
if (path.dirname(e) === e) return;
}
}
/** Select a private root with trusted ancestors before consumers create disposable workspaces. */
function resolvePreferredOpenClawTmpDir(e = {}) {
const t = loadResolveSecureTempRoot();
const n = {
...e,
preferredDir: e.preferredDir ?? "/tmp/openclaw",
fallbackPrefix: "openclaw",
warningPrefix: "[openclaw]",
unsafeFallbackLabel: "OpenClaw temp dir",
skipPreferredOnWindows: true
};
const r = t(n);
if (e.purpose === "coordination") return r;
let i;
try {
assertSafeTempAncestors(r, e);
return r;
} catch (e) {
i = e;
}
const a = resolveStateDir();
try {
const r = t({
...n,
preferredDir: void 0,
tmpdir: () => path.join(a, "tmp")
});
assertSafeTempAncestors(r, e);
(e.warn ?? console.warn)(`[openclaw] ${String(i)} Using private state temp dir: ${r}`);
return r;
} catch (e) {
throw new Error(`No safe OpenClaw temp root is available. Default root: ${String(i)} State fallback ${JSON.stringify(a)}: ${String(e)}`, { cause: e });
}
}
//#endregion
//#region src/utils/string-readers.ts
/** Reads the first parsed field, preserving order and defined falsy values. */
function readParsedField(e, t, n) {
for (const r of typeof t === "string" ? [t] : t) {
const t = n(e[r]);
if (t !== void 0) return t;
}
}
//#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 {
fsSync.mkdirSync(e, { mode: n });
} catch (r) {
const i = extractErrorCode(r);
if (i === "EEXIST" && fsSync.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}`);
}
/** 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}`);
}
//#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));
fsSync.rmSync(rotatedLogPath(e, MAX_ROTATED_LOG_FILES), { force: true });
for (let t = 4; t >= 1; t -= 1) {
const n = rotatedLogPath(e, t);
if (fsSync.existsSync(n)) fsSync.renameSync(n, rotatedLogPath(e, t + 1));
}
if (fsSync.existsSync(e)) fsSync.renameSync(e, rotatedLogPath(e, 1));
return true;
} catch {
return false;
}
}
async function getCurrentLogFileBytes(e) {
try {
return (await fsPromises.stat(e)).size;
} catch {
return 0;
}
}
function getCurrentLogFileBytesSync(e) {
try {
return fsSync.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) fsSync.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;
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 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 resolveActiveLogFileWithMode(e, t) {
const n = expandHomePrefix(e);
return t ? resolveRollingLogFilePathForDate(n, /* @__PURE__ */ new Date()) : n;
}
function pruneOldRollingLogs(e) {
try {
const t = fsSync.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 (fsSync.statSync(t).mtimeMs < n) fsSync.rmSync(t, { force: true });
} catch {}
}
} catch {}
}
//#endregion
//#region src/logging/console.ts
function normalizeConsoleLevel(e) {
if (isVerbose()) return "debug";
if (!e && process.env.VITEST === "true" && process.env.OPENCLAW_TEST_CONSOLE !== "1") return "silent";
return normalizeLogLevel(e, "info");
}
function normalizeConsoleStyle(e) {
if (e === "compact" || e === "json" || e === "pretty") return e;
if (!process.stdout.isTTY) return "compact";
return "pretty";
}
function resolveConsoleSettings() {
const e = resolveEnvLogLevelOverride();
if (process.env.VITEST === "true" && process.env.OPENCLAW_TEST_CONSOLE !== "1" && !isVerbose() && !e && !loggingState.overrideSettings) return {
level: "silent",
style: normalizeConsoleStyle(void 0)
};
const t = loggingState.overrideSettings ?? readLoggingConfig();
return {
level: e ?? normalizeConsoleLevel(t?.consoleLevel),
style: normalizeConsoleStyle(t?.consoleStyle)
};
}
function getConsoleSettings() {
const e = loggingState.cachedConsoleSettings;
if (e) return e;
const t = resolveConsoleSettings();
loggingState.cachedConsoleSettings = t;
return t;
}
function shouldLogSubsystemToConsole(e) {
const t = loggingState.consoleSubsystemFilter;
if (!t || t.length === 0) return true;
const n = normalizeOptionalString(e);
if (!n) return false;
return t.some((e) => n === e || n.startsWith(`${e}/`));
}
const SUPPRESSED_CONSOLE_PREFIXES = [
"Closing session:",
"Opening session:",
"Removing old closed session:",
"Session already closed",
"Session already open"
];
const NODE_PROCESS_WARNING_PREFIX = `(${process.release.name}:${process.pid}) `;
function shouldSuppressConsoleMessage(e) {
return SUPPRESSED_CONSOLE_PREFIXES.some((t) => e.startsWith(t));
}
function brokenOutputReason(e) {
const t = e?.code;
return t === "EPIPE" ? "output pipe closed (EPIPE)" : t === "EIO" ? "output I/O failed (EIO)" : void 0;
}
function formatConsoleTimestamp(e) {
const t = /* @__PURE__ */ new Date();
if (e === "pretty") return formatTimestamp(t, { style: "short" }).replace(/[+-]\d{2}:\d{2}$/, "");
return formatTimestamp(t, { style: "long" });
}
function captureConsoleTraceStack(e, t) {
const n = new Error(e);
n.name = "Trace";
Error.captureStackTrace(n, t);
return n.stack === void 0 ? `Trace: ${e}` : typeof n.stack === "string" ? n.stack : util.format(n.stack);
}
function hasTimestampPrefix(e) {
return /^(?:\d{2}:\d{2}:\d{2}|\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)/.test(e);
}
function writeFormattedConsoleOutput(e) {
const t = getConsoleSettings().style;
const n = t !== "json" && loggingState.consoleTimestampPrefix ? stripAnsi(e.formatted).trimStart() : "";
const r = n && !hasTimestampPrefix(n) ? formatConsoleTimestamp(t) : "";
const i = e.level === "trace" && e.caller ? captureConsoleTraceStack(e.formatted, e.caller) : void 0;
try {
const n = t === "json" ? formatJsonConsoleLine({
level: e.level,
message: stripAnsi(e.formatted),
meta: i === void 0 ? void 0 : { stack: stripAnsi(i) }
}) : redactSensitiveText(i ?? e.formatted);
const a = r ? `${r} ${n}` : n;
clearActiveProgressLine();
if (loggingState.forceConsoleToStderr) process.stderr.write(`${a}\n`);
else if (t !== "json" && !r && e.args.length === 0 && i === void 0) e.write.apply(console, e.args);
else e.write.call(console, a);
} catch (e) {
if (brokenOutputReason(e)) return;
throw e;
}
}
/** Writes a root logger line to the pre-capture console sink without re-entering file capture. */
function writeRootConsoleLine(e, t) {
const n = loggingState.rawConsole;
if (!n) return false;
if (shouldSuppressConsoleMessage(t)) return true;
writeFormattedConsoleOutput({
level: e === "log" ? "info" : e,
args: [t],
formatted: t,
write: n[e]
});
return true;
}
//#endregion
//#region src/logging/subsystem.ts
function isRichConsoleEnv() {
const e = normalizeLowercaseStringOrEmpty(process.env.TERM);
if (process.env.COLORTERM || process.env.TERM_PROGRAM) return true;
return e.length > 0 && e !== "dumb";
}
const consoleColors = [];
const SUBSYSTEM_COLORS = [
"cyan",
"green",
"yellow",
"blue",
"magenta",
"red"
];
const SUBSYSTEM_COLOR_OVERRIDES = /* @__PURE__ */ new Map([["gmail-watcher", "blue"]]);
const SUBSYSTEM_PREFIXES_TO_DROP = /* @__PURE__ */ new Set([
"gateway",
"channels",
"providers"
]);
const CHANNEL_SUBSYSTEM_PREFIXES = /* @__PURE__ */ new Set([
"clickclack",
"discord",
"feishu",
"googlechat",
"imessage",
"irc",
"line",
"matrix",
"mattermost",
"msteams",
"nextcloud-talk",
"nostr",
"openclaw-weixin",
"qqbot",
"signal",
"slack",
"synology-chat",
"telegram",
"tlon",
"twitch",
"webchat",
"wecom",
"whatsapp",
"yuanbao",
"zalo",
"zalouser"
]);
function pickSubsystemColor(e) {
const t = SUBSYSTEM_COLOR_OVERRIDES.get(e);
if (t) return t;
let n = 0;
for (let t = 0; t < e.length; t += 1) n = n * 31 + e.charCodeAt(t) | 0;
const r = Math.abs(n) % SUBSYSTEM_COLORS.length;
return expectDefined(SUBSYSTEM_COLORS[r], "subsystem colors entry at idx");
}
function formatSubsystemForConsole(e) {
const t = e.split("/").filter(Boolean);
const n = t.join("/") || e;
while (t[0] !== void 0 && SUBSYSTEM_PREFIXES_TO_DROP.has(t[0])) t.shift();
const r = t.at(0);
if (r === void 0) return n;
if (CHANNEL_SUBSYSTEM_PREFIXES.has(normalizeLowercaseStringOrEmpty(r))) return r;
return t.slice(-2).join("/");
}
function stripRedundantSubsystemPrefixForConsole(e, t) {
if (!t) return e;
if (e.startsWith("[")) {
const n = e.indexOf("]");
if (n > 1) {
const r = e.slice(1, n);
if (normalizeLowercaseStringOrEmpty(r) === normalizeLowercaseStringOrEmpty(t)) return e.slice(n + 1).replace(/^ */, "");
}
}
const n = e.slice(0, t.length);
if (normalizeLowercaseStringOrEmpty(n) !== normalizeLowercaseStringOrEmpty(t)) return e;
const r = e.slice(t.length, t.length + 1);
if (r !== ":" && r !== " ") return e;
return e.slice(t.length).replace(/^ *:? */, "");
}
function createConsoleLineFormatter(e) {
const t = formatSubsystemForConsole(e);
const n = `[${t}]`;
const r = pickSubsystemColor(t);
return (e, i, a) => {
const o = typeof process.env.FORCE_COLOR === "string" && process.env.FORCE_COLOR.trim().length > 0 && process.env.FORCE_COLOR.trim() !== "0" || !process.env.NO_COLOR && (process.stdout.isTTY || process.stderr.isTTY || isRichConsoleEnv()) ? 1 : 0;
const s = consoleColors[o] ??= new Chalk({ level: o });
const c = e === "error" || e === "fatal" ? s.red : e === "warn" ? s.yellow : e === "debug" || e === "trace" ? s.gray : s.cyan;
const l = stripRedundantSubsystemPrefixForConsole(redactSensitiveText(i), t);
const u = a === "pretty" || loggingState.consoleTimestampPrefix ? s.gray(formatConsoleTimestamp(a)) : "";
const d = s[r](n);
return `${u ? `${u} ${d}` : d} ${c(l)}`;
};
}
function writeConsoleLine(e, t, n = {}) {
clearActiveProgressLine();
const r = process.platform === "win32" && process.env.GITHUB_ACTIONS === "true" ? t.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "?").replace(/[\uD800-\uDFFF]/g, "?") : t;
const i = n.redacted ? r : redactSensitiveText(r);
const a = loggingState.rawConsole ?? console;
if (loggingState.forceConsoleToStderr || e === "error" || e === "fatal") (a.error ?? console.error)(i);
else if (e === "warn") (a.warn ?? console.warn)(i);
else (a.log ?? console.log)(i);
}
function shouldSuppressProbeConsoleLine(e) {
if (isVerbose()) return false;
if (e.level === "error" || e.level === "fatal") return false;
const t = typeof e.message === "string" ? e.message : "";
if (!e.suppressProbeMessages) return false;
if ((typeof e.meta?.runId === "string" ? e.meta.runId : typeof e.meta?.sessionId === "string" ? e.meta.sessionId : void 0)?.startsWith("probe-")) return true;
return /(sessionId|runId)=probe-/.test(t);
}
const CONSOLE_META_LEVELS = /* @__PURE__ */ new Set([
"warn",
"error",
"fatal"
]);
const CONSOLE_META_MAX_CHARS = 2048;
function formatConsoleMetaValue(e) {
if (e === void 0) return;
if (typeof e === "string") return /\s|=/.test(e) || e.length === 0 ? JSON.stringify(e) : e;
if (e === null || typeof e === "number" || typeof e === "boolean") return String(e);
return JSON.stringify(e);
}
/** Preserve native error diagnostics before any sink reduces non-enumerable fields to `{}`. */
function prepareLogMetaRecord(e, t = false) {
let n;
for (const [r, i] of Object.entries(e)) if (i instanceof Error) {
n ??= { ...e };
n[r] = {
name: i.name,
message: i.message,
errorCode: extractErrorCode(i),
stack: t ? i.stack?.split("\n").slice(0, 6).join("\n") : i.stack
};
}
return n ?? e;
}
/**
* Renders structured fields as one compact `key=value` tail so warn/error/fatal
* records keep their diagnostics in plain-text sinks such as journald, which only
* see the console line. The JSON console style and the file sink carry the same
* fields natively, so only plain styles call this.
*
* Fields pass through the shared console transport redactor before flattening, so
* key-aware protection such as `apiToken` survives the loss of structure and the
* length cap can only clip text that is already masked. That redactor also owns
* circular references, bigints, and values with no JSON form, and returns parsed
* data, so rendering a value here cannot re-enter a stateful `toJSON`.
*/
function formatConsoleMeta(e) {
let t;
try {
t = redactLogRecordForTransport(e);
} catch {
return "";
}
const n = [];
for (const [e, r] of Object.entries(t)) {
const t = formatConsoleMetaValue(r);
if (t !== void 0) n.push(`${e}=${t}`);
}
const r = n.join(" ");
return r.length > CONSOLE_META_MAX_CHARS ? `${r.slice(0, CONSOLE_META_MAX_CHARS)}...(truncated)` : r;
}
function logToFile(e, t, n, r) {
if (t === "silent") return;
if (r && Object.keys(r).length > 0) e[t](r, n);
else e[t](n);
}
function createSubsystemLogger(e) {
const t = normalizeOptionalString(e) ?? "unknown";
const n = t === "agent/embedded" || t.startsWith("agent/embedded/") || t === "model-fallback" || t.startsWith("model-fallback/");
let r;
let i;
let a;
const getFileLogger = (e) => {
r ??= getChildLogger({ subsystem: t });
if (e === "error" || e === "fatal" || e !== "info" && areDiagnosticsEnabledForProcess() && hasInternalDiagnosticEventInterest("log.record")) return r;
if (!i) {
i = r.getSubLogger({ stack: { capture: "off" } });
i.settings.parentNames = r.settings.parentNames;
}
return i;
};
const emitLog = (e, r, i) => {
const o = getConsoleSettings();
const s = i?.consoleMessage !== false && isLogLevelEnabled(e, o.level) && shouldLogSubsystemToConsole(t);
const c = isFileLogLevelEnabled(e);
if (!s && !c) return;
let l;
let u = i;
let d = i;
if (i && Object.keys(i).length > 0) {
const { consoleMessage: e, ...t } = i;
if (typeof e === "string") l = e;
u = Object.keys(t).length > 0 ? prepareLogMetaRecord(t) : void 0;
d = u && s ? prepareLogMetaRecord(t, true) : void 0;
}
if (c) logToFile(getFileLogger(e), e, r, u);
if (!s) return;
const f = o.style !== "json" && l === void 0 && d && CONSOLE_META_LEVELS.has(e) ? formatConsoleMeta(d) : "";
const p = l ?? (f ? `${r} ${f}` : r);
if (shouldSuppressProbeConsoleLine({
level: e,
suppressProbeMessages: n,
message: p,
meta: d
})) return;
writeConsoleLine(e, o.style === "json" ? formatJsonConsoleLine({
level: e,
subsystem: t,
message: r,
meta: d
}) : (a ??= createConsoleLineFormatter(t))(e, p, o.style), { redacted: true });
};
return {
subsystem: t,
isEnabled(e, n = "any") {
const r = isLogLevelEnabled(e, getConsoleSettings().level) && shouldLogSubsystemToConsole(t);
const i = isFileLogLevelEnabled(e);
if (n === "console") return r;
if (n === "file") return i;
return r || i;
},
trace(e, t) {
emitLog("trace", e, t);
},
debug(e, t) {
emitLog("debug", e, t);
},
info(e, t) {
emitLog("info", e, t);
},
warn(e, t) {
emitLog("warn", e, t);
},
error(e, t) {
emitLog("error", e, t);
},
fatal(e, t) {
emitLog("fatal", e, t);
},
raw(e) {
if (isFileLogLevelEnabled("info")) logToFile(getFileLogger("info"), "info", e, { raw: true });
const r = getConsoleSettings();
if (isLogLevelEnabled("info", r.level) && shouldLogSubsystemToConsole(t)) {
if (shouldSuppressProbeConsoleLine({
level: "info",
suppressProbeMessages: n,
message: e
})) return;
writeConsoleLine("info", r.style === "json" ? formatJsonConsoleLine({
level: "info",
subsystem: t,
message: e
}) : e, { redacted: r.style === "json" });
}
},
child(e) {
return createSubsystemLogger(`${t}/${e}`);
}
};
}
//#endregion
export { isVerbose as _, resolvePreferredOpenClawTmpDir as a, defaultRuntime as c, workerScriptName as d, runWithMainThreadTask as f, hasInternalDiagnosticEventInterest as g, AsyncContext as h, getLogger as i, areDiagnosticsEnabledForProcess as l, parseDiagnosticEnvFlags as m, writeRootConsoleLine as n, registerSignalExitBarrier as o, isDiagnosticFlagEnabled as p, getChildLogger as r, registerSignalExitFinalizer as s, createSubsystemLogger as t, emitTrustedDiagnosticEvent as u };