openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
639 lines (638 loc) • 17.7 kB
JavaScript
import { c as normalizeOptionalLowercaseString, h as readNonEmptyStringPreservingWhitespace } from "./string-coerce-CCIiB4H7.mjs";
import { o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { l as OPENCLAW_SQLITE_BUSY_TIMEOUT_MS } from "./openclaw-state-db-contract-DfPjvL0M.mjs";
import "./sqlite-worker-contract--dxXkOty.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import "./openclaw-state-db-ARhwdPJg.mjs";
import { i as classifyAgentRunTerminalOutcome } from "./agent-run-terminal-outcome-CurjWZiA.mjs";
import { n as isExecutionIdentityCollectionEnabled, r as resolveAuditMessageMode, t as isAuditLedgerEnabled } from "./audit-config-DjeE3VAP.mjs";
import { c as mergeAgentRunTerminalOutcome, i as buildAgentRunTerminalOutcomeFromLifecycleEvent, t as AGENT_RUN_TERMINAL_RETRY_GRACE_MS } from "./agent-run-terminal-outcome-wduf2occ.mjs";
import { n as parseExecutionDecisionWork } from "./execution-decision-work-CSwdYVxn.mjs";
import { n as isAllowedToolCallName } from "./tool-call-shared-BYW0Lmcs.mjs";
import { n as formatAuditWriterRequestError, t as formatAuditWriterError } from "./audit-event-writer.errors-BTCVuKf2.mjs";
import { createHash, randomUUID } from "node:crypto";
//#region src/audit/agent-event-audit.ts
/** Redaction-safe projection from live agent events into durable audit metadata. */
const MAX_TRACKED_RUN_INSTANCES = 1024;
function auditToolName(e) {
const t = readNonEmptyStringPreservingWhitespace(e)?.trim();
if (!t) return;
return isAllowedToolCallName(t, null) ? t : "unknown";
}
function auditToolCallId(e) {
const t = readNonEmptyStringPreservingWhitespace(e);
if (!t) return;
return `sha256:${createHash("sha256").update(t).digest("hex")}`;
}
function legacyAuditSourceId(e) {
return `${e.runId}:${e.sourceSequence}:${e.occurredAt}:${e.action}`;
}
function projectExplicitAttribution(e) {
const t = readNonEmptyStringPreservingWhitespace(e.agentId);
return {
actorType: t ? "agent" : "system",
agentId: t ?? "unknown",
sessionKey: readNonEmptyStringPreservingWhitespace(e.sessionKey),
sessionId: readNonEmptyStringPreservingWhitespace(e.sessionId)
};
}
const AUDIT_TERMINAL_BY_CLASSIFICATION = {
success: { status: "succeeded" },
timeout: {
status: "timed_out",
errorCode: "run_timed_out"
},
cancellation: {
status: "cancelled",
errorCode: "run_cancelled"
},
failure: {
status: "failed",
errorCode: "run_failed"
}
};
function classifyRunTerminal(e, t) {
const n = buildAgentRunTerminalOutcomeFromLifecycleEvent({
phase: t,
data: e
});
if (n.reason === "blocked") return {
outcome: n,
status: "blocked",
errorCode: "run_blocked"
};
return {
outcome: n,
...AUDIT_TERMINAL_BY_CLASSIFICATION[classifyAgentRunTerminalOutcome(n)]
};
}
function projectAgentEvent(e) {
const t = readNonEmptyStringPreservingWhitespace(e.runId);
const n = readNonEmptyStringPreservingWhitespace(e.data.phase);
if (!t || !n) return;
const r = projectExplicitAttribution(e);
if (e.stream === "lifecycle" && n === "start") {
const n = asDateTimestampMs(e.data.startedAt) ?? e.ts;
const i = "agent.run.started";
return { input: {
sourceId: legacyAuditSourceId({
runId: t,
sourceSequence: e.seq,
occurredAt: n,
action: i
}),
sourceSequence: e.seq,
occurredAt: n,
kind: "agent_run",
action: i,
status: "started",
actorType: r.actorType,
actorId: r.agentId,
agentId: r.agentId,
...r.sessionKey ? { sessionKey: r.sessionKey } : {},
...r.sessionId ? { sessionId: r.sessionId } : {},
runId: t
} };
}
if (e.stream === "lifecycle" && (n === "end" || n === "error")) {
const { outcome: i, ...a } = classifyRunTerminal(e.data, n);
const o = asDateTimestampMs(e.data.endedAt) ?? e.ts;
const s = "agent.run.finished";
return {
input: {
sourceId: legacyAuditSourceId({
runId: t,
sourceSequence: e.seq,
occurredAt: o,
action: s
}),
sourceSequence: e.seq,
occurredAt: o,
kind: "agent_run",
action: s,
...a,
actorType: r.actorType,
actorId: r.agentId,
agentId: r.agentId,
...r.sessionKey ? { sessionKey: r.sessionKey } : {},
...r.sessionId ? { sessionId: r.sessionId } : {},
runId: t
},
terminal: {
outcome: i,
phase: n
}
};
}
}
/** Project the complete trusted tool-execution lifecycle without private diagnostic content. */
function projectToolExecutionEventToAudit(e) {
if (e.type === "tool.execution.blocked" && e.deniedReason === "unsupported_tool_schema" && !readNonEmptyStringPreservingWhitespace(e.toolCallId)) return;
const t = readNonEmptyStringPreservingWhitespace(e.runId);
const n = auditToolName(e.toolName);
if (!t || !n) return;
const r = auditToolCallId(e.toolCallId);
const i = projectExplicitAttribution(e);
const a = asDateTimestampMs(e.sourceTimestampMs) ?? e.ts;
const o = {
sourceSequence: e.seq,
occurredAt: a,
kind: "tool_action",
actorType: i.actorType,
actorId: i.agentId,
agentId: i.agentId,
...i.sessionKey ? { sessionKey: i.sessionKey } : {},
...i.sessionId ? { sessionId: i.sessionId } : {},
runId: t,
...r ? { toolCallId: r } : {},
toolName: n
};
if (e.type === "tool.execution.started") {
const n = "tool.action.started";
return {
sourceId: legacyAuditSourceId({
runId: t,
sourceSequence: e.seq,
occurredAt: a,
action: n
}),
...o,
action: n,
status: "started"
};
}
const s = e.type === "tool.execution.error" ? normalizeOptionalLowercaseString(e.errorCategory) : void 0;
const c = e.type === "tool.execution.error" ? e.terminalReason : void 0;
const l = e.type === "tool.execution.error" ? normalizeOptionalLowercaseString(e.errorCode) : void 0;
const u = c === "cancelled" || c === void 0 && (s === "aborted" || s === "aborterror" || s === "cancelled" || s === "canceled");
const d = c === "timed_out";
const f = e.type === "tool.execution.completed" ? { status: "succeeded" } : e.type === "tool.execution.blocked" ? {
status: "blocked",
errorCode: "tool_blocked"
} : l === "tool_outcome_unknown" ? {
status: "unknown",
errorCode: "tool_outcome_unknown"
} : u ? {
status: "cancelled",
errorCode: "tool_cancelled"
} : d ? {
status: "timed_out",
errorCode: "tool_timed_out"
} : {
status: "failed",
errorCode: "tool_failed"
};
const p = "tool.action.finished";
return {
sourceId: legacyAuditSourceId({
runId: t,
sourceSequence: e.seq,
occurredAt: a,
action: p
}),
...o,
action: p,
...f
};
}
/** Create the Gateway-owned non-blocking audit projection and persistence handle. */
function createAgentEventAuditRecorder(e) {
const { writer: t } = e;
const n = Math.max(0, Math.floor(e.terminalSettleMs ?? 15e3));
const r = /* @__PURE__ */ new Map();
const i = /* @__PURE__ */ new Map();
const a = /* @__PURE__ */ new Set();
const o = /* @__PURE__ */ new Set();
const rememberSettled = (e) => {
o.delete(e);
o.add(e);
if (o.size > MAX_TRACKED_RUN_INSTANCES) {
const e = o.values().next().value;
if (e !== void 0) o.delete(e);
}
};
const clearPending = (e) => {
const t = r.get(e);
if (!t) return;
clearTimeout(t.timer);
r.delete(e);
};
const flushBufferedStarts = (e = 0) => {
for (const [n, r] of i) {
if (i.size <= e) break;
i.delete(n);
t.record(r);
}
};
const settleTerminal = (e, n) => {
const r = i.get(e);
clearPending(e);
a.delete(e);
if (r ? t.recordRun(r, n) : t.record(n)) {
i.delete(e);
rememberSettled(e);
}
};
const flushPending = (e) => {
const t = r.get(e);
if (t) settleTerminal(e, t.input);
};
const scheduleTerminal = (e, t) => {
const i = r.get(e);
let a = t;
if (i) {
if (i.phase === "error" && t.phase === "end" && t.outcome.reason === "completed") a = i;
else a = mergeAgentRunTerminalOutcome(i.outcome, t.outcome) === i.outcome ? i : t;
clearTimeout(i.timer);
}
const o = setTimeout(() => flushPending(e), n);
o.unref?.();
r.delete(e);
r.set(e, {
...a,
timer: o
});
if (r.size > MAX_TRACKED_RUN_INSTANCES) {
const e = r.keys().next().value;
if (e !== void 0) flushPending(e);
}
};
return {
record: (t) => {
const n = `${t.lifecycleGeneration ?? "unknown"}\0${t.runId}`;
if (!isAuditLedgerEnabled(e.getConfig())) {
flushBufferedStarts();
a.delete(n);
return;
}
const s = projectAgentEvent(t);
if (!s) return;
if (!s.terminal) {
const e = a.has(n);
clearPending(n);
o.delete(n);
if (e) return;
a.add(n);
i.set(n, s.input);
flushBufferedStarts(MAX_TRACKED_RUN_INSTANCES);
return;
}
if (o.has(n)) return;
if (s.terminal.outcome.reason === "completed" && !r.has(n)) {
settleTerminal(n, s.input);
return;
}
scheduleTerminal(n, {
input: s.input,
...s.terminal
});
},
recordTool: (n) => {
if (!isAuditLedgerEnabled(e.getConfig())) {
flushBufferedStarts();
return;
}
const r = projectToolExecutionEventToAudit(n);
if (r) t.record(r);
},
stop: async () => {
for (const e of r.keys()) flushPending(e);
flushBufferedStarts();
await t.stop();
}
};
}
//#endregion
//#region src/audit/audit-event-writer.ts
/** Non-blocking process-owned queue for audit metadata persistence. */
const MAX_PENDING_AUDIT_EVENTS = 4096;
const MAX_AUDIT_BATCH_SIZE = 32;
const AUDIT_BATCH_DELAY_MS = 5;
const MAX_CONSECUTIVE_UNKNOWN_OUTCOMES = 3;
const AUDIT_MAINTENANCE_INTERVAL_MS = 36e5;
const AUDIT_RETRY_DELAY_MS = 25;
const AUDIT_RETRY_MAX_DELAY_MS = 1e3;
const AUDIT_RETRY_REPORT_MS = 1e3;
const AUDIT_WRITER_SHUTDOWN_TIMEOUT_MS = OPENCLAW_SQLITE_BUSY_TIMEOUT_MS + 5e3;
/** Start one bounded queue; retain the owner environment or claimed state rejects its writes. */
function createAuditEventWriter(e) {
const { scheduler: t } = e;
const n = { env: {
...process.env,
OPENCLAW_STATE_DIR: e.stateDir ?? resolveStateDir(process.env)
} };
const r = Math.max(1, Math.floor(e.maxPending ?? MAX_PENDING_AUDIT_EVENTS));
const i = [];
let a = 0;
let o = false;
let s = false;
let c = false;
let l = true;
let u;
let d;
let f;
let p = 0;
let m = 0;
let h = false;
let g;
let _;
const v = new Promise((e) => {
_ = e;
});
let y;
let b;
let x;
const fail = (t) => {
e.onError?.(formatAuditWriterError(t));
};
const reportContention = (t) => {
e.onContention?.(formatAuditWriterError(t));
};
const execute = async (e) => {
const t = captureOpenClawStateWorkerContext(n);
const { runOpenClawStateWorkerOperation: r } = await import("./openclaw-state-worker-store-BURqchns.mjs");
if (c) return;
const i = await r(t, (t) => c ? Promise.resolve(void 0) : t.execute(e), { existingOnly: true });
if (i !== void 0 || c) return i;
return r(t, (t) => c ? Promise.resolve(void 0) : t.execute(e));
};
const resetRetry = () => {
p = 0;
m = 0;
h = false;
};
const reportMaintenance = async () => {
let e = false;
try {
const t = await execute({
type: "audit.writer.prune",
input: void 0
});
for (const n of t ?? []) {
if (n.status === "retry") {
p += 1;
return "retry";
}
if (n.error !== void 0) fail(n.error);
e = (n.deleted ?? 0) > 0 || e;
}
} catch (e) {
fail(e);
}
return e ? "more" : "settled";
};
const processRequests = async (e) => {
try {
const t = await execute({
type: "audit.writer.process",
input: e
});
g = void 0;
return t ?? e.map(() => ({ status: "settled" }));
} catch (t) {
if (hasSqliteWorkerOutcomeUnknown(t)) {
g ??= {
size: e.length,
attempts: 0
};
g.attempts += 1;
fail(t);
if (g.attempts < MAX_CONSECUTIVE_UNKNOWN_OUTCOMES) return [{ status: "retry" }];
g = void 0;
return e.map(() => ({ status: "settled" }));
}
g = void 0;
return e.map((e) => ({
status: "settled",
error: formatAuditWriterRequestError(e, t)
}));
}
};
const finishStop = () => {
if (x) {
clearTimeout(x);
x = void 0;
}
const e = b;
b = void 0;
e?.();
};
const schedule = (e = 0) => {
if (s || c) return;
if (f) {
if (o) f.ref?.();
return;
}
if (u) {
if (o) u.ref?.();
return;
}
if (d) {
if (e > 0) return;
clearTimeout(d);
d = void 0;
}
if (e > 0) {
d = setTimeout(() => {
d = void 0;
drainOne();
}, e);
d.unref?.();
} else {
u = setImmediate(() => {
drainOne();
});
if (!o) u.unref?.();
}
};
const scheduleRetry = () => {
const e = Math.min(AUDIT_RETRY_MAX_DELAY_MS, AUDIT_RETRY_DELAY_MS * 2 ** Math.min(6, p - 1));
m += e;
if (!h && m >= AUDIT_RETRY_REPORT_MS) {
h = true;
reportContention("audit event persistence delayed by worker retries");
}
f = setTimeout(() => {
f = void 0;
drainOne();
}, e);
if (!o) f.unref?.();
};
async function drainOne() {
u = void 0;
if (s || c) return;
s = true;
let e = false;
try {
if (l) {
l = false;
const t = await reportMaintenance();
_();
l ||= t !== "settled";
if (t === "retry") {
e = true;
return;
}
resetRetry();
}
if (c) return;
const t = i.slice(0, g?.size ?? MAX_AUDIT_BATCH_SIZE);
if (t.length > 0) {
const n = await processRequests(t);
e = n.at(-1)?.status === "retry";
const r = n.length - (e ? 1 : 0);
for (const e of i.splice(0, r)) a -= e.type === "record-run" ? 2 : 1;
if (r > 0) resetRetry();
if (e) p += 1;
for (const e of n) if (e.status === "settled" && e.error !== void 0) fail(e.error);
}
} finally {
s = false;
if (c) finishStop();
else if (e) scheduleRetry();
else if (i.length > 0 || l) {
const e = !o && !l && i.length > 1 && i.length < MAX_AUDIT_BATCH_SIZE;
schedule(e ? AUDIT_BATCH_DELAY_MS : 0);
} else if (o) finishStop();
}
}
const S = t.schedule({
id: "audit:maintenance",
atMs: t.now() + AUDIT_MAINTENANCE_INTERVAL_MS,
everyMs: AUDIT_MAINTENANCE_INTERVAL_MS,
run: () => {
l = true;
schedule();
}
});
schedule();
const enqueue = (e) => {
const t = e.type === "record-run" ? 2 : 1;
if (o || a + t > r) {
if (!o) fail(`audit event queue is full (${r}); dropping metadata`);
return false;
}
try {
const n = e.type === "record-execution-decision-work" ? {
...e,
work: parseExecutionDecisionWork(e.work)
} : e;
i.push(structuredClone(n));
a += t;
if (!d || i.length >= MAX_AUDIT_BATCH_SIZE) schedule();
return true;
} catch (t) {
if (e.type !== "record-event" && e.type !== "record-run") fail(e.type === "record-execution-identity" ? "audit execution identity envelope could not be queued" : "audit execution decision receipt could not be queued");
else fail(t);
return false;
}
};
return {
ready: v,
record: (e) => enqueue({
type: "record-event",
eventId: randomUUID(),
input: e
}),
recordRun: (e, t) => enqueue({
type: "record-run",
start: e,
finish: t,
eventIds: [randomUUID(), randomUUID()]
}),
recordExecutionIdentity: (e) => enqueue({
type: "record-execution-identity",
work: e
}),
recordExecutionDecision: (e) => enqueue({
type: "record-execution-decision",
receipt: e
}),
recordExecutionDecisionWork: (e) => enqueue({
type: "record-execution-decision-work",
work: e
}),
stop: () => {
if (y) return y;
o = true;
S.cancel();
l = true;
y = new Promise((e) => {
b = e;
x = setTimeout(() => {
c = true;
l = false;
i.length = 0;
a = 0;
if (u) {
clearImmediate(u);
u = void 0;
}
if (d) {
clearTimeout(d);
d = void 0;
}
if (f) {
clearTimeout(f);
f = void 0;
}
fail("audit event writer shutdown timed out; pending metadata may be lost");
if (!s) {
_();
finishStop();
}
}, AUDIT_WRITER_SHUTDOWN_TIMEOUT_MS);
x.unref?.();
schedule();
});
return y;
}
};
}
//#endregion
//#region src/audit/audit-recorder.ts
/** Gateway-owned recorder joining trusted run, tool, and message lifecycle streams. */
const log = createSubsystemLogger("audit/events");
let persistenceFailureWarned = false;
function createAuditEventRecorder(e) {
let t = 0;
const n = e.writer ?? createAuditEventWriter({
scheduler: e.scheduler,
...e.stateDir ? { stateDir: e.stateDir } : {},
onContention: (e) => log.warn(e),
onError: (e) => {
if (!persistenceFailureWarned) {
persistenceFailureWarned = true;
log.warn(`audit event persistence failed: ${e}`);
}
}
});
return {
...createAgentEventAuditRecorder({
writer: n,
getConfig: e.getConfig,
terminalSettleMs: e.terminalSettleMs
}),
recordExecutionIdentity: (t) => isExecutionIdentityCollectionEnabled(e.getConfig()) && n.recordExecutionIdentity(t),
recordExecutionDecision: (t) => isExecutionIdentityCollectionEnabled(e.getConfig()) && n.recordExecutionDecision(t),
recordExecutionDecisionWork: (t) => isExecutionIdentityCollectionEnabled(e.getConfig()) && n.recordExecutionDecisionWork(t),
recordMessage: (r) => {
const i = e.getConfig();
const a = resolveAuditMessageMode(i);
if (!isAuditLedgerEnabled(i) || a === "off") return;
if (a === "direct" && r.conversationKind !== "direct") return;
t += 1;
n.record({
...r,
sourceId: r.sourceId?.trim() || `message:${randomUUID()}`,
sourceSequence: t
});
}
};
}
//#endregion
export { createAuditEventRecorder as t };