openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
976 lines (975 loc) • 33 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { t as normalizeDiagnosticWorkerScript } from "./worker-diagnostic-script-BuAZtI7E.mjs";
import { c as formatErrorStackWithMessage } from "./error-coercion-hDrHOSGy.mjs";
import { t as isBlockedObjectKey } from "./prototype-keys-CLGi5xDj.mjs";
import { t as AsyncContext } from "./async-context-BYDAvG9A.mjs";
import { a as pluginInstanceInvocation } from "./plugin-instance-invocation-Bq_toGDw.mjs";
import { n as notifyListeners, r as registerListener } from "./listeners-Cb2-CnP8.mjs";
import { b as getActiveDiagnosticTraceContext, d as recordDiagnosticModelUsageTimeline, v as formatDiagnosticTraceparent } from "./diagnostics-timeline-CSwiG24r.mjs";
import { randomUUID } from "node:crypto";
//#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 updateEventInterestDelta(e, t, n) {
const r = (e.eventInterestDeltas.get(t) ?? 0) + n;
if (r === 0) e.eventInterestDeltas.delete(t);
else e.eventInterestDeltas.set(t, r);
}
function updateEventInterest(e, t, n, r) {
const i = r ? t?.includeTrusted ?? t?.include : t?.include;
if (!i) {
e.broadInterestCount += n;
for (const r of new Set(t?.exclude)) updateEventInterestDelta(e, r, -n);
return;
}
for (const a of new Set(i)) if (isInternalDiagnosticEventInterested(t, a, r)) updateEventInterestDelta(e, a, n);
}
function updateInternalDiagnosticEventInterest(e, t) {
const n = listenerPresence;
const r = [...n.interestListeners].filter(([e]) => !hasInternalDiagnosticEventInterest(e));
updateEventInterest(n.untrustedInterest, e, t, false);
updateEventInterest(n.trustedInterest, e, t, true);
if (e?.includePromptStats !== false && [
"model.call.started",
"model.call.completed",
"model.call.error"
].some((t) => isInternalDiagnosticEventInterested(e, t, true))) n.promptStatsCount += t;
for (const [e, t] of r) if (hasInternalDiagnosticEventInterest(e)) notifyListeners(t, void 0);
}
function onInternalDiagnosticEventInterest(e, t) {
const n = listenerPresence;
const r = n.interestListeners.get(e) ?? /* @__PURE__ */ new Set();
n.interestListeners.set(e, r);
r.add(t);
return () => {
if (r.delete(t) && r.size === 0) n.interestListeners.delete(e);
};
}
function hasInternalDiagnosticEventInterest(e, t = false) {
const n = t ? listenerPresence.trustedInterest : listenerPresence.untrustedInterest;
return n.broadInterestCount + (n.eventInterestDeltas.get(e) ?? 0) > 0;
}
function hasModelCallPromptStatsInterest() {
return listenerPresence.promptStatsCount > 0;
}
function resetInternalDiagnosticEventListenerPresence() {
const e = listenerPresence;
e.internalCount = 0;
e.trustedCount = 0;
e.promptStatsCount = 0;
e.untrustedInterest.broadInterestCount = 0;
e.untrustedInterest.eventInterestDeltas.clear();
e.trustedInterest.broadInterestCount = 0;
e.trustedInterest.eventInterestDeltas.clear();
}
function setInternalDiagnosticEventListenerCounts(e, t) {
const n = listenerPresence;
n.internalCount = e;
n.trustedCount = t;
}
function hasInternalDiagnosticEventListeners() {
const e = listenerPresence;
return e.internalCount > 0 || e.trustedCount > 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/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;
}
}
/** Returns whether listener metadata marks dispatcher-internal provenance. */
function isInternalDiagnosticEventMetadata(e) {
return e.internal === true;
}
//#endregion
//#region src/infra/diagnostic-model-request-provenance.ts
const CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY = "coreModelRequestLifecycle";
const coreModelRequestLifecycleEvents = /* @__PURE__ */ new WeakMap();
function markCoreModelRequestLifecycleDiagnosticEvent(e, t) {
coreModelRequestLifecycleEvents.set(e, t);
return e;
}
function consumeCoreModelRequestLifecycleDiagnosticEvent(e) {
const t = coreModelRequestLifecycleEvents.get(e);
coreModelRequestLifecycleEvents.delete(e);
return t;
}
//#endregion
//#region src/infra/diagnostic-otel-listener-provenance.ts
const trustedOtelDiagnosticListeners = /* @__PURE__ */ new WeakSet();
function markTrustedOtelDiagnosticListener(e) {
const registeredListener = (...t) => e(...t);
trustedOtelDiagnosticListeners.add(registeredListener);
return registeredListener;
}
function isTrustedOtelDiagnosticListener(e) {
return trustedOtelDiagnosticListeners.has(e);
}
//#endregion
//#region src/infra/diagnostic-plugin-usage-provenance.ts
const hostPluginUsageIds = /* @__PURE__ */ new WeakMap();
function markHostPluginUsageDiagnosticEvent(e, t) {
const n = t?.trim();
if (n) hostPluginUsageIds.set(e, n);
return e;
}
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 markCoreSemanticRunProgressDiagnosticEvent(e, t) {
coreSemanticRunProgressEvents.set(e, t ?? true);
return e;
}
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 noop = () => {};
function createDeadlineCarrier(e) {
let t = e;
const carrier = (e) => t?.(e);
carrier.register = (e) => t?.register?.(e) ?? noop;
return {
carrier,
close() {
t = void 0;
}
};
}
const state = resolveGlobalSingleton(Symbol.for("openclaw.diagnosticToolExecutionLiveness"), () => ({
context: new AsyncContext(Symbol("toolExecutionDeadline")),
events: /* @__PURE__ */ new WeakMap()
}));
/** The invocation owns the reference; only its execution owner supplies a deadline. */
function createDiagnosticToolExecutionLiveness(e, t) {
let n = true;
let r;
const i = /* @__PURE__ */ new Map();
const a = Object.freeze({ get deadlineAtMs() {
if (e?.aborted) return;
let t = r;
for (const e of i.values()) t = Math.max(t ?? e, e);
return t;
} });
const o = t?.attempt.beginTool({
toolCallId: t.toolCallId,
toolName: t.toolName,
get deadlineAtMs() {
return a.deadlineAtMs;
}
});
const record = (t) => {
if (n && !e?.aborted) r = t;
};
record.register = (t) => {
const r = {};
if (n && !e?.aborted && Number.isFinite(t)) i.set(r, t);
return () => {
i.delete(r);
};
};
const s = createDeadlineCarrier(record);
return {
view: a,
run(e) {
return state.context.run(s.carrier, e);
},
close(t = false) {
o?.(t && !e?.aborted);
n = false;
s.close();
i.clear();
}
};
}
function recordDiagnosticToolExecutionDeadline(e) {
state.context.getStore()?.(e);
}
/** The enforced response wait owns this allowance, independently of overlapping waits. */
function registerDiagnosticToolExecutionDeadline(e) {
return state.context.getStore()?.register?.(e);
}
/** Keep the live reference out of the cloned, plugin-facing event payload. */
function markToolExecutionLivenessDiagnosticEvent(e, t) {
state.events.set(e, t);
return e;
}
function consumeToolExecutionLivenessDiagnosticEvent(e) {
const t = state.events.get(e);
state.events.delete(e);
return t;
}
function resolveToolExecutionLivenessDiagnosticMetadata(e) {
return e.trusted ? e[TOOL_EXECUTION_LIVENESS_METADATA_KEY] : void 0;
}
//#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 registerDiagnosticTracePropagationBridge(e) {
const t = tracePropagationState;
const n = e;
if (!t.bridges.has(n)) {
t.bridges.add(n);
t.activeBridge = n;
}
return () => {
if (!t.bridges.delete(n) || t.activeBridge !== n) return;
t.activeBridge = void 0;
for (const e of t.bridges) t.activeBridge = e;
};
}
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)}`);
}
}
/** Formats the exporter-owned context when one is active, suppressing unresolved identities. */
function formatPropagatedDiagnosticTraceparent(e) {
if (!e) return;
const t = tracePropagationState.activeBridge;
if (!t) return formatDiagnosticTraceparent(e);
let n;
try {
n = t.resolveTraceContext(e);
} catch (e) {
console.error(`[diagnostic-trace-propagation] resolve error: ${String(e)}`);
return;
}
return formatDiagnosticTraceparent(n);
}
function resetDiagnosticTracePropagationForTest() {
tracePropagationState.bridges.clear();
tracePropagationState.activeBridge = void 0;
}
//#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 whether diagnostics are enabled for a loaded config; missing config defaults enabled. */
function isDiagnosticsEnabled(e) {
return e?.diagnostics?.enabled !== false;
}
/** Sets the process-wide diagnostic dispatcher enable flag. */
function setDiagnosticsEnabledForProcess(e) {
diagnosticEventsState.enabled = e;
}
/** 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
}));
}
/** Waits until async diagnostic events queued when called are no longer pending. */
async function waitForDiagnosticEventsDrained() {
const e = diagnosticEventsState;
const t = e.asyncQueue.at(-1)?.event.seq;
if (t === void 0) return;
while ((e.asyncQueue[0]?.event.seq ?? Number.POSITIVE_INFINITY) <= t) await new Promise((e) => {
setImmediate(e);
});
}
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 an untrusted internal diagnostic event; private listener-only payload data
* stays off the public event payload and reaches trusted private-data listeners only. */
function emitInternalDiagnosticEvent(e, t) {
emitDiagnosticEventWithTrust(e, false, {
internal: true,
privateData: t
});
}
/** Returns the latest diagnostic event sequence number assigned in this process. */
function getInternalDiagnosticEventSequence() {
return diagnosticEventsState.seq;
}
/** 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 } : {}
});
}
/** Queues runtime phase observations without changing synchronous startup phases. */
function createQueuedDiagnosticPhaseEmitter() {
const e = diagnosticEventsState;
const interested = () => {
if (!e.enabled) return false;
for (const t of e.trustedListeners.values()) if (isInternalDiagnosticEventInterested(t, "diagnostic.phase.completed", true)) return true;
return false;
};
if (!interested()) return;
const t = getActiveDiagnosticTraceContext();
return (e) => {
if (!interested()) return;
emitDiagnosticEventWithTrust({
...e,
type: "diagnostic.phase.completed",
trace: t,
details: e.details ? { ...e.details } : void 0
}, true, { queuedPhase: true });
};
}
/** Keeps trusted internal skill accounting alive when optional diagnostics are disabled. */
function emitTrustedSkillUsedDiagnosticEvent(e, t) {
const n = diagnosticEventsState;
if (n.enabled) {
emitDiagnosticEventWithTrust(e, true, { privateData: t });
return;
}
const r = {
event: enrichDiagnosticEvent(n, e),
metadata: Object.freeze({ trusted: true }),
privateData: t,
trustedListenersOnly: true
};
if (n.asyncQueue.length >= MAX_ASYNC_DIAGNOSTIC_EVENTS) {
noteAsyncDiagnosticDrop(n, r);
return;
}
if (!captureQueuedDiagnosticEvent(r, n.trustedListeners.values())) return;
n.asyncQueue.push(r);
scheduleAsyncDiagnosticDrain(n);
}
/** Emits a trusted diagnostic event with private listener-only payload data. */
function emitTrustedDiagnosticEventWithPrivateData(e, t) {
const n = consumeCoreModelRequestLifecycleDiagnosticEvent(e);
let r = t;
if (t && Object.hasOwn(t, "hostPluginId")) {
r = { ...t };
Reflect.deleteProperty(r, "hostPluginId");
}
emitDiagnosticEventWithTrust(e, true, {
coreModelRequestLifecycle: n,
privateData: r
});
}
/** Emits a trusted canonical security event from core-owned enforcement boundaries. */
function emitTrustedSecurityEvent(e) {
emitDiagnosticEventWithTrust({
type: "security.event",
...e,
eventId: e.eventId ?? randomUUID()
}, true, { allowSecurityEvent: true });
}
/** Emits a trusted model failover diagnostic event. */
function emitFailoverEvent(e) {
emitTrustedDiagnosticEvent({
type: "model.failover",
...e
});
}
/** SDK subscriptions belong to the registering instance, even if it drops the handle. */
function ownDiagnosticSubscription(e) {
const t = pluginInstanceInvocation.getStore()?.instance;
if (!t) return e;
let n = e;
let r;
const release = () => {
r?.();
r = void 0;
n?.();
n = void 0;
};
try {
r = t.lifecycle.onDispose(release);
} catch (e) {
release();
throw e;
}
return release;
}
function registerDiagnosticEventListener(e, t, n, r) {
if (t.has(n)) updateInternalDiagnosticEventInterest(t.get(n), -1);
t.set(n, r);
updateInternalDiagnosticEventInterest(r, 1);
setInternalDiagnosticEventListenerCounts(e.listeners.size, e.trustedListeners.size);
return ownDiagnosticSubscription(() => {
const r = t.get(n);
if (t.delete(n)) updateInternalDiagnosticEventInterest(r, -1);
setInternalDiagnosticEventListenerCounts(e.listeners.size, e.trustedListeners.size);
});
}
/** Subscribes to diagnostic events with dispatcher metadata. */
function onInternalDiagnosticEvent(e, t) {
const n = diagnosticEventsState;
return registerDiagnosticEventListener(n, n.listeners, e, t);
}
/** Subscribes to diagnostic events plus trusted private payload data. */
function onTrustedInternalDiagnosticEvent(e, t, n) {
const r = diagnosticEventsState;
return registerDiagnosticEventListener(r, r.trustedListeners, e, {
...t,
includePrivateData: n?.includePrivateData
});
}
/** Subscribes to trusted metadata-only tool execution events, even when diagnostics are disabled. */
function onTrustedToolExecutionEvent(e) {
return ownDiagnosticSubscription(registerListener(diagnosticEventsState.toolExecutionListeners, e));
}
/** Checks currently queued async diagnostic events without draining the queue. */
function hasPendingInternalDiagnosticEvent(e) {
const t = diagnosticEventsState;
for (const n of t.asyncQueue) {
let t;
try {
t = cloneDiagnosticValueForListener(n.event);
} catch {
continue;
}
if (e(t, n.metadata)) return true;
}
return false;
}
/** Subscribes to public untrusted diagnostic events only. */
function onDiagnosticEvent(e) {
return onInternalDiagnosticEvent((t) => e(t), {
includeTrusted: [],
exclude: PUBLIC_EXCLUDED_DIAGNOSTIC_EVENT_NAMES
});
}
/** Resets dispatcher state between tests. */
function resetDiagnosticEventsForTest() {
const e = diagnosticEventsState;
e.enabled = true;
e.seq = 0;
e.listeners.clear();
e.trustedListeners.clear();
resetInternalDiagnosticEventListenerPresence();
e.toolExecutionListeners.clear();
e.toolExecutionSeq = 0;
e.dispatchDepth = 0;
e.asyncQueue = [];
e.asyncDrainScheduled = false;
e.asyncDroppedEvents = 0;
e.asyncDroppedTrustedEvents = 0;
e.asyncDroppedUntrustedEvents = 0;
e.asyncDroppedPriorityEvents = 0;
resetDiagnosticTracePropagationForTest();
}
//#endregion
export { markCoreSemanticRunProgressDiagnosticEvent as A, registerDiagnosticTracePropagationBridge as C, registerDiagnosticToolExecutionDeadline as D, recordDiagnosticToolExecutionDeadline as E, isInternalDiagnosticEventMetadata as F, hasInternalDiagnosticEventInterest as I, hasInternalDiagnosticEventListeners as L, markTrustedOtelDiagnosticListener as M, CORE_MODEL_REQUEST_LIFECYCLE_METADATA_KEY as N, resolveToolExecutionLivenessDiagnosticMetadata as O, markCoreModelRequestLifecycleDiagnosticEvent as P, hasModelCallPromptStatsInterest as R, hasDiagnosticTracePropagationConsumer as S, markToolExecutionLivenessDiagnosticEvent as T, onTrustedToolExecutionEvent as _, emitFailoverEvent as a, waitForDiagnosticEventsDrained as b, emitTrustedDiagnosticEventWithPrivateData as c, getInternalDiagnosticEventSequence as d, hasPendingInternalDiagnosticEvent as f, onTrustedInternalDiagnosticEvent as g, onInternalDiagnosticEvent as h, emitDiagnosticEventWithTrustedTraceContext as i, markHostPluginUsageDiagnosticEvent as j, CORE_SEMANTIC_RUN_PROGRESS_METADATA_KEY as k, emitTrustedSecurityEvent as l, onDiagnosticEvent as m, createQueuedDiagnosticPhaseEmitter as n, emitInternalDiagnosticEvent as o, isDiagnosticsEnabled as p, emitDiagnosticEvent as r, emitTrustedDiagnosticEvent as s, areDiagnosticsEnabledForProcess as t, emitTrustedSkillUsedDiagnosticEvent as u, resetDiagnosticEventsForTest as v, createDiagnosticToolExecutionLiveness as w, formatPropagatedDiagnosticTraceparent as x, setDiagnosticsEnabledForProcess as y, onInternalDiagnosticEventInterest as z };