openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
485 lines (484 loc) • 16.8 kB
JavaScript
import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs";
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as runWithAsyncStore } from "./async-store-C6naia_Y.mjs";
import { r as runWithMainThreadTask } from "./main-thread-stall-BhUfYJnA.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { t as AsyncContext } from "./async-context-BYDAvG9A.mjs";
import { s as hasObservedModelUsage } from "./usage-CHLnzpJG.mjs";
import { t as isDiagnosticFlagEnabled } from "./diagnostic-flags-D41PMN4c.mjs";
import { t as _usingCtx } from "./usingCtx-rhpPzaNq.mjs";
import { mkdirSync } from "node:fs";
import { dirname } from "node:path";
import { randomBytes, randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
import { performance } from "node:perf_hooks";
import { appendRegularFileSync } from "@openclaw/fs-safe/advanced";
//#region src/infra/diagnostic-trace-context.ts
const TRACEPARENT_VERSION = "00";
const DEFAULT_TRACE_FLAGS = "01";
const MAX_TRACEPARENT_LENGTH = 128;
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 TRACEPARENT_VERSION_RE = /^[0-9a-f]{2}$/;
const DIAGNOSTIC_TRACE_SCOPE_STATE_KEY = Symbol.for("openclaw.diagnosticTraceScope.state.v1");
function isNonZeroHex(e) {
return !/^0+$/.test(e);
}
function randomNonZeroHex(e) {
let t = randomBytes(e).toString("hex");
while (!isNonZeroHex(t)) t = randomBytes(e).toString("hex");
return t;
}
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);
}
function normalizeTraceField(e, t) {
if (typeof e !== "string") return;
const n = e.toLowerCase();
return t(n) ? n : void 0;
}
/** Parses a W3C `traceparent` header into a normalized diagnostic trace context. */
function parseDiagnosticTraceparent(e) {
if (typeof e !== "string" || e.length > MAX_TRACEPARENT_LENGTH) return;
const t = e.trim().toLowerCase().split("-");
if (t.length < 4) return;
const [n, r, i, a] = t;
if (!TRACEPARENT_VERSION_RE.test(expectDefined(n, "diagnostic trace context version")) || n === "ff" || n === TRACEPARENT_VERSION && t.length !== 4) return;
if (!isValidDiagnosticTraceId(r) || !isValidDiagnosticSpanId(i) || !isValidDiagnosticTraceFlags(a)) return;
return {
traceId: r,
spanId: i,
traceFlags: a
};
}
/** Formats a diagnostic trace context as a W3C `traceparent` header. */
function formatDiagnosticTraceparent(e) {
if (!e?.spanId) return;
const t = normalizeTraceField(e.traceId, isValidDiagnosticTraceId);
const n = normalizeTraceField(e.spanId, isValidDiagnosticSpanId);
const r = normalizeTraceField(e.traceFlags, isValidDiagnosticTraceFlags) ?? DEFAULT_TRACE_FLAGS;
if (!t || !n) return;
return `${TRACEPARENT_VERSION}-${t}-${n}-${r}`;
}
/** Creates a normalized trace context from explicit fields, traceparent, or generated ids. */
function createDiagnosticTraceContext(e = {}) {
const t = parseDiagnosticTraceparent(e.traceparent);
const n = normalizeTraceField(e.traceId, isValidDiagnosticTraceId) ?? t?.traceId ?? randomNonZeroHex(16);
const r = normalizeTraceField(e.spanId, isValidDiagnosticSpanId) ?? t?.spanId ?? randomNonZeroHex(8);
const i = normalizeTraceField(e.parentSpanId, isValidDiagnosticSpanId);
return {
traceId: n,
spanId: r,
...i && i !== r ? { parentSpanId: i } : {},
traceFlags: normalizeTraceField(e.traceFlags, isValidDiagnosticTraceFlags) ?? t?.traceFlags ?? DEFAULT_TRACE_FLAGS
};
}
/** Creates a child context that preserves the parent trace id and records the parent span id. */
function createChildDiagnosticTraceContext(e, t = {}) {
const n = normalizeTraceField(t.parentSpanId, isValidDiagnosticSpanId) ?? normalizeTraceField(e.spanId, isValidDiagnosticSpanId);
return createDiagnosticTraceContext({
traceId: e.traceId,
spanId: t.spanId,
parentSpanId: n,
traceFlags: t.traceFlags ?? e.traceFlags
});
}
/** Creates a child of the active trace scope, or a new root context when no scope is active. */
function createDiagnosticTraceContextFromActiveScope(e = {}) {
const t = getActiveDiagnosticTraceContext();
if (!t) return createDiagnosticTraceContext(e);
return createChildDiagnosticTraceContext(t, e);
}
/** Returns an immutable defensive copy of a trace context. */
function freezeDiagnosticTraceContext(e) {
return Object.freeze({
traceId: e.traceId,
...e.spanId ? { spanId: e.spanId } : {},
...e.parentSpanId ? { parentSpanId: e.parentSpanId } : {},
...e.traceFlags ? { traceFlags: e.traceFlags } : {}
});
}
/** Returns the trace context bound to the current async scope. */
function getActiveDiagnosticTraceContext() {
return traceContext.getStore();
}
/** Runs a callback with a frozen trace context, or explicitly without a trace. */
function runWithDiagnosticTraceContext(e, t) {
return runWithAsyncStore(traceContext, e === void 0 ? void 0 : freezeDiagnosticTraceContext(e), 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();
/** Observe existing spans within one request, independently of timeline file logging. */
function withDiagnosticsTimelineObserver(e, t) {
return spanObserver.run(e, t);
}
/** Forward an owner's measured duration without timing the same operation again. */
function recordDiagnosticsTimelineDuration(e, t) {
try {
spanObserver.getStore()?.(e, void 0, t)?.();
} catch {}
}
function observeSpan(e, t) {
let n;
try {
n = spanObserver.getStore()?.(e, t.attributes);
} catch {}
if (!n) return;
return { [Symbol.dispose]() {
try {
n?.();
} catch {}
} };
}
/** Consecutive owner phases cover waits and synchronous work without gaps or extra async hops. */
function observeDiagnosticsTimelinePhases(e) {
let t = observeSpan(e, {});
return {
mark(e) {
t?.[Symbol.dispose]();
t = observeSpan(e, {});
},
[Symbol.dispose]() {
t?.[Symbol.dispose]();
t = void 0;
}
};
}
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();
}
};
});
/** Makes all previously emitted timeline events visible before reading or closing their files. */
function flushDiagnosticsTimeline() {
timelineWriter.flush();
}
/** 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);
}
/** Starts the accounting window before the caller admits any model producers. */
function startDiagnosticsTimeline(e) {
emitDiagnosticsTimelineEvent({
type: "mark",
name: "timeline.capture.started",
attributes: { exclusiveProcess: e }
});
}
/** The caller owns producer settlement; flushing alone cannot certify a complete capture. */
function finishDiagnosticsTimeline(e, t = {}) {
flushDiagnosticsTimeline();
emitDiagnosticsTimelineEvent({
type: "mark",
name: "timeline.capture.completed",
attributes: { complete: e }
}, t);
flushDiagnosticsTimeline();
}
/** Replays a completed span after its activation config becomes available. */
function emitCompletedDiagnosticsTimelineSpan(e, t, n = {}) {
if (!isDiagnosticsTimelineEnabled(n)) return;
const r = {
name: e,
phase: n.phase,
spanId: randomUUID(),
parentSpanId: n.parentSpanId,
attributes: n.attributes
};
emitDiagnosticsTimelineEvent({
type: "span.start",
...r
}, n);
emitDiagnosticsTimelineEvent({
type: "span.end",
...r,
durationMs: t
}, n);
}
/** Returns the currently active span so callers can preserve parentage across memoized work. */
function getActiveDiagnosticsTimelineSpan() {
return activeDiagnosticsTimelineSpan.getStore();
}
function startDiagnosticsTimelineSpan(e, t) {
const n = t.env ?? process.env;
if (!isDiagnosticsTimelineEnabled({
config: t.config,
env: n
})) return;
const r = getActiveDiagnosticsTimelineSpan();
const i = t.phase ?? r?.phase;
const a = t.parentSpanId ?? r?.spanId;
const o = {
name: e,
env: n,
...t.config ? { config: t.config } : {},
spanId: randomUUID(),
startedAt: performance.now(),
...i ? { phase: i } : {},
...a ? { parentSpanId: a } : {},
...t.attributes ? { attributes: t.attributes } : {},
...t.omitErrorMessage ? { omitErrorMessage: true } : {}
};
emitDiagnosticsTimelineEvent({
type: "span.start",
...o
}, o);
return o;
}
function runInDiagnosticsTimelineSpan(e, t) {
return activeDiagnosticsTimelineSpan.run({
name: e.name,
...e.phase ? { phase: e.phase } : {},
spanId: e.spanId,
...e.parentSpanId ? { parentSpanId: e.parentSpanId } : {},
...e.attributes ? { attributes: e.attributes } : {}
}, t);
}
function emitFinishedDiagnosticsTimelineSpan(e, t) {
emitDiagnosticsTimelineEvent({
type: t ? "span.error" : "span.end",
...e,
durationMs: performance.now() - e.startedAt,
...t ? {
errorName: t.error instanceof Error ? t.error.name : typeof t.error,
...e.omitErrorMessage ? {} : { errorMessage: t.error instanceof Error ? t.error.message : String(t.error) }
} : {}
}, e);
}
/** Measures async work as a start/end timeline span, emitting an error span before rethrowing. */
async function measureDiagnosticsTimelineSpan(e, t, n = {}) {
try {
var r = _usingCtx();
r.u(observeSpan(e, n));
const i = startDiagnosticsTimelineSpan(e, n);
if (!i) return await runWithMainThreadTask(e, t);
try {
const n = await runInDiagnosticsTimelineSpan(i, () => runWithMainThreadTask(e, t));
emitFinishedDiagnosticsTimelineSpan(i);
return n;
} catch (e) {
emitFinishedDiagnosticsTimelineSpan(i, { error: e });
throw e;
}
} catch (e) {
r.e = e;
} finally {
r.d();
}
}
/** Measures sync work as a start/end timeline span, emitting an error span before rethrowing. */
function measureDiagnosticsTimelineSpanSync(e, t, n = {}) {
try {
var r = _usingCtx();
r.u(observeSpan(e, n));
const i = startDiagnosticsTimelineSpan(e, n);
if (!i) return runWithMainThreadTask(e, t);
try {
const n = runInDiagnosticsTimelineSpan(i, () => runWithMainThreadTask(e, t));
emitFinishedDiagnosticsTimelineSpan(i);
return n;
} catch (e) {
emitFinishedDiagnosticsTimelineSpan(i, { error: e });
throw e;
}
} catch (e) {
r.e = e;
} finally {
r.d();
}
}
//#endregion
export { isValidDiagnosticTraceId as C, isValidDiagnosticTraceFlags as S, runWithDiagnosticTraceContext as T, createDiagnosticTraceContextFromActiveScope as _, getActiveDiagnosticsTimelineSpan as a, getActiveDiagnosticTraceContext as b, measureDiagnosticsTimelineSpanSync as c, recordDiagnosticModelUsageTimeline as d, recordDiagnosticsTimelineDuration as f, createDiagnosticTraceContext as g, createChildDiagnosticTraceContext as h, flushDiagnosticsTimeline as i, modelUsageTimelineAttributes as l, withDiagnosticsTimelineObserver as m, emitDiagnosticsTimelineEvent as n, isDiagnosticsTimelineEnabled as o, startDiagnosticsTimeline as p, finishDiagnosticsTimeline as r, measureDiagnosticsTimelineSpan as s, emitCompletedDiagnosticsTimelineSpan as t, observeDiagnosticsTimelinePhases as u, formatDiagnosticTraceparent as v, parseDiagnosticTraceparent as w, isValidDiagnosticSpanId as x, freezeDiagnosticTraceContext as y };