UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,322 lines • 52.4 kB
import { n as isPostgresSqlConnection } from "./sql-connection-Beiyg5Dt.mjs";
import { s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs";
import { _ as sql, a as executeSqliteQueryTakeFirstSync, d as prepareSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, n as createSqliteQueryCache, s as getNodeSqliteKysely, u as prepareSqliteQuerySync } from "./kysely-sync-YJo2lmGV.mjs";
import { a as tableExists, n as ensureColumn } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs";
import "./sqlite-transaction-BHHu6P5-.mjs";
import { n as normalizeSqliteNumber } from "./sqlite-number-D8n3srri.mjs";
import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs";
import { r as ensureStatePostgresFragment } from "./openclaw-state-db-engine-sM0tpxNy.mjs";
import "./approval-resolution-ref-CfeQNT84.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { l as runOpenClawStateWriteTransaction, r as openOpenClawStateDatabase } from "./openclaw-state-db-ARhwdPJg.mjs";
import { t as createSqliteSchemaEnsurer } from "./sqlite-schema-ensure-B6yDrFvM.mjs";
import { t as getOpenClawStateFeatureSchemaSql } from "./openclaw-state-feature-schema-CEI_WUTe.mjs";
import { a as parseExecutionIdentityAdmissionToken, c as sortUniqueExecutionIdentityEntries, o as parseExecutionIdentityAdmissionWork, s as executionIdentitySpawnAdmission } from "./execution-identity-admission-EuMO_R29.mjs";
import { t as createOpenClawStateSchemaEnsurer } from "./openclaw-state-feature-schema-ensure-DcloJsFG.mjs";
import { n as validateExecutionIdentityContextV1 } from "./audit-run-validators-DQArxEAR.mjs";
import { r as AUDIT_ACTIVITY_MESSAGE_KIND } from "./audit-activity-D5l1XT6-.mjs";
import { a as pseudonymizeAuditIdentity, i as loadOrCreateAuditIdentityKey, o as pseudonymizeExecutionIdentityRef, r as clearAuditIdentityKeyCacheForDatabase } from "./execution-decision-facts-CD9zMcWU.mjs";
import "./execution-owner-lifecycle-binding-store-BhoPNL3Q.mjs";
import "./operator-approval-store.rows-DGzIpZI3.mjs";
import { t as parsePositiveAuditCursor } from "./audit-cursor-f-Y7DpmR.mjs";
import { createHash, randomUUID } from "node:crypto";
//#region src/audit/audit-event-types.ts
const AUDIT_INBOUND_MESSAGE_COMPLETED_REASONS = [
	"fast_abort",
	"plugin_bound_handled",
	"plugin_bound_unavailable",
	"plugin_bound_declined",
	"before_dispatch_handled",
	"acp_dispatch_completed",
	"acp_dispatch_empty",
	"active_run_injected"
];
const AUDIT_INBOUND_MESSAGE_SKIPPED_REASONS = [
	"duplicate",
	"reply_operation_active",
	"reply_operation_aborted",
	"acp_dispatch_aborted"
];
const AUDIT_OUTBOUND_MESSAGE_SUPPRESSED_REASONS = [
	"cancelled_by_message_sending_hook",
	"cancelled_by_reply_payload_sending_hook",
	"empty_after_message_sending_hook",
	"empty_after_reply_payload_sending_hook",
	"no_visible_payload"
];
function isOutboundMessageProgressInput(e) {
	return e.kind === "message" && e.direction === "outbound" && (e.action === "message.outbound.queued" || e.action === "message.outbound.platform-started");
}
//#endregion
//#region src/audit/audit-event-row.ts
const RUN_ACTIONS = ["agent.run.started", "agent.run.finished"];
const TOOL_ACTIONS = ["tool.action.started", "tool.action.finished"];
const CONVERSATION_KINDS = [
	"direct",
	"group",
	"channel",
	"unknown"
];
const DELIVERY_KINDS = [
	"text",
	"media",
	"other"
];
const FAILURE_STAGES = [
	"platform_send",
	"queue",
	"unknown"
];
const AUDIT_HMAC_REF_RE$1 = /^hmac-sha256:v1:[a-f0-9]{32}:[a-f0-9]{64}$/u;
const MESSAGE_COLUMNS = [
	"direction",
	"channel",
	"conversation_kind",
	"message_outcome",
	"reason_code",
	"delivery_kind",
	"failure_stage",
	"duration_ms",
	"result_count",
	"account_ref",
	"conversation_ref",
	"message_ref",
	"target_ref"
];
function corruptAuditRow(e, t) {
	const n = normalizeSqliteNumber(e.sequence);
	const r = n === void 0 ? "" : ` ${n}`;
	throw new Error(`corrupt audit event row${r}: ${t}`);
}
function requiredInteger(e, t, n, r) {
	const i = normalizeSqliteNumber(t);
	if (i === void 0 || !Number.isSafeInteger(i) || i < r) corruptAuditRow(e, `invalid ${n}`);
	return i;
}
function optionalInteger(e, t, n, r) {
	return t === null ? void 0 : requiredInteger(e, t, n, r);
}
function requiredText$1(e, t, n) {
	if (typeof t !== "string" || t.length === 0) corruptAuditRow(e, `invalid ${n}`);
	return t;
}
function optionalText$1(e, t, n) {
	return t === null || t === void 0 ? void 0 : requiredText$1(e, t, n);
}
function requiredEnum(e, t, n, r) {
	for (const e of r) if (t === e) return e;
	return corruptAuditRow(e, `invalid ${n}`);
}
function optionalEnum(e, t, n, r) {
	if (t === null || t === void 0) return;
	return requiredEnum(e, t, n, r);
}
function requiredHmacRef(e, t, n) {
	const r = requiredText$1(e, t, n);
	if (!AUDIT_HMAC_REF_RE$1.test(r)) corruptAuditRow(e, `invalid ${n}`);
	return r;
}
function optionalHmacRef$1(e, t, n) {
	if (t === null || t === void 0) return;
	return requiredHmacRef(e, t, n);
}
function requireNull(e, t) {
	if (e[t] !== null) corruptAuditRow(e, `unexpected ${t}`);
}
function requireNullColumns(e, t) {
	for (const n of t) requireNull(e, n);
}
function parseAuditRecordBase(e) {
	const t = requiredInteger(e, e.schema_version, "schemaVersion", 1);
	if (t !== 1) corruptAuditRow(e, `unsupported schemaVersion ${t}`);
	return {
		schemaVersion: t,
		sequence: requiredInteger(e, e.sequence, "sequence", 1),
		eventId: requiredText$1(e, e.event_id, "eventId"),
		sourceSequence: requiredInteger(e, e.source_sequence, "sourceSequence", 1),
		occurredAt: requiredInteger(e, e.occurred_at, "occurredAt", 0),
		redaction: "metadata_only"
	};
}
function parseAgentRecordFields(e) {
	requireNullColumns(e, MESSAGE_COLUMNS);
	return {
		...parseAuditRecordBase(e),
		actorType: requiredEnum(e, e.actor_type, "actorType", ["agent", "system"]),
		actorId: requiredText$1(e, e.actor_id, "actorId"),
		agentId: requiredText$1(e, e.agent_id, "agentId"),
		...optionalText$1(e, e.session_key, "sessionKey") !== void 0 ? { sessionKey: requiredText$1(e, e.session_key, "sessionKey") } : {},
		...optionalText$1(e, e.session_id, "sessionId") !== void 0 ? { sessionId: requiredText$1(e, e.session_id, "sessionId") } : {},
		runId: requiredText$1(e, e.run_id, "runId")
	};
}
function parseAgentRunRow(e) {
	requireNull(e, "tool_call_id");
	requireNull(e, "tool_name");
	const t = {
		...parseAgentRecordFields(e),
		kind: "agent_run"
	};
	const n = requiredEnum(e, e.action, "action", RUN_ACTIONS);
	if (n === "agent.run.started") {
		requiredEnum(e, e.status, "status", ["started"]);
		requireNull(e, "error_code");
		return {
			...t,
			action: n,
			status: "started"
		};
	}
	if (e.status === "succeeded") {
		requireNull(e, "error_code");
		return {
			...t,
			action: n,
			status: "succeeded"
		};
	}
	const r = e.status === "failed" ? {
		status: "failed",
		errorCode: "run_failed"
	} : e.status === "cancelled" ? {
		status: "cancelled",
		errorCode: "run_cancelled"
	} : e.status === "timed_out" ? {
		status: "timed_out",
		errorCode: "run_timed_out"
	} : e.status === "blocked" ? {
		status: "blocked",
		errorCode: "run_blocked"
	} : corruptAuditRow(e, "invalid run terminal status");
	requiredEnum(e, e.error_code, "errorCode", [r.errorCode]);
	return {
		...t,
		action: n,
		...r
	};
}
function parseToolActionRow(e) {
	const t = optionalText$1(e, e.tool_call_id, "toolCallId");
	const n = optionalText$1(e, e.tool_name, "toolName");
	const r = {
		...parseAgentRecordFields(e),
		kind: "tool_action",
		...t ? { toolCallId: t } : {},
		...n ? { toolName: n } : {}
	};
	const i = requiredEnum(e, e.action, "action", TOOL_ACTIONS);
	if (i === "tool.action.started") {
		requiredEnum(e, e.status, "status", ["started"]);
		requireNull(e, "error_code");
		return {
			...r,
			action: i,
			status: "started"
		};
	}
	if (e.status === "succeeded") {
		requireNull(e, "error_code");
		return {
			...r,
			action: i,
			status: "succeeded"
		};
	}
	const a = e.status === "failed" ? {
		status: "failed",
		errorCode: "tool_failed"
	} : e.status === "cancelled" ? {
		status: "cancelled",
		errorCode: "tool_cancelled"
	} : e.status === "timed_out" ? {
		status: "timed_out",
		errorCode: "tool_timed_out"
	} : e.status === "blocked" ? {
		status: "blocked",
		errorCode: "tool_blocked"
	} : e.status === "unknown" ? {
		status: "unknown",
		errorCode: "tool_outcome_unknown"
	} : corruptAuditRow(e, "invalid tool terminal status");
	requiredEnum(e, e.error_code, "errorCode", [a.errorCode]);
	return {
		...r,
		action: i,
		...a
	};
}
function parseMessageRecordFields(e) {
	requireNullColumns(e, [
		"session_key",
		"session_id",
		"tool_call_id",
		"tool_name"
	]);
	const t = optionalText$1(e, e.agent_id, "agentId");
	const n = optionalText$1(e, e.run_id, "runId");
	const r = optionalInteger(e, e.duration_ms, "durationMs", 0);
	const i = optionalInteger(e, e.result_count, "resultCount", 0);
	const a = optionalHmacRef$1(e, e.account_ref, "accountRef");
	const o = optionalHmacRef$1(e, e.conversation_ref, "conversationRef");
	const s = optionalHmacRef$1(e, e.message_ref, "messageRef");
	const c = optionalHmacRef$1(e, e.target_ref, "targetRef");
	return {
		...parseAuditRecordBase(e),
		kind: "message",
		channel: requiredText$1(e, e.channel, "channel"),
		conversationKind: requiredEnum(e, e.conversation_kind, "conversationKind", CONVERSATION_KINDS),
		...t ? { agentId: t } : {},
		...n ? { runId: n } : {},
		...r !== void 0 ? { durationMs: r } : {},
		...i !== void 0 ? { resultCount: i } : {},
		...a ? { accountRef: a } : {},
		...o ? { conversationRef: o } : {},
		...s ? { messageRef: s } : {},
		...c ? { targetRef: c } : {}
	};
}
function parseInboundMessageRow(e) {
	requiredEnum(e, e.action, "action", ["message.inbound.processed"]);
	requiredEnum(e, e.direction, "direction", ["inbound"]);
	requireNull(e, "delivery_kind");
	requireNull(e, "failure_stage");
	const t = requiredEnum(e, e.actor_type, "actorType", ["channel_sender", "system"]);
	const n = t === "channel_sender" ? requiredHmacRef(e, e.actor_id, "actorId") : requiredText$1(e, e.actor_id, "actorId");
	const r = {
		...parseMessageRecordFields(e),
		action: "message.inbound.processed",
		direction: "inbound",
		actorType: t,
		actorId: n
	};
	if (e.status === "succeeded") {
		requiredEnum(e, e.message_outcome, "outcome", ["completed"]);
		requireNull(e, "error_code");
		const t = optionalEnum(e, e.reason_code, "reasonCode", AUDIT_INBOUND_MESSAGE_COMPLETED_REASONS);
		return {
			...r,
			status: "succeeded",
			outcome: "completed",
			...t ? { reasonCode: t } : {}
		};
	}
	if (e.status === "blocked") {
		requiredEnum(e, e.message_outcome, "outcome", ["skipped"]);
		requireNull(e, "error_code");
		const t = optionalEnum(e, e.reason_code, "reasonCode", AUDIT_INBOUND_MESSAGE_SKIPPED_REASONS);
		return {
			...r,
			status: "blocked",
			outcome: "skipped",
			...t ? { reasonCode: t } : {}
		};
	}
	if (e.status === "failed") {
		requiredEnum(e, e.message_outcome, "outcome", ["failed"]);
		requiredEnum(e, e.error_code, "errorCode", ["message_processing_failed"]);
		const t = optionalEnum(e, e.reason_code, "reasonCode", ["acp_dispatch_failed", "plugin_bound_error"]);
		return {
			...r,
			status: "failed",
			outcome: "failed",
			errorCode: "message_processing_failed",
			...t ? { reasonCode: t } : {}
		};
	}
	return corruptAuditRow(e, "invalid inbound status");
}
function parseOutboundMessageRow(e) {
	const t = requiredEnum(e, e.action, "action", [
		"message.outbound.queued",
		"message.outbound.platform-started",
		"message.outbound.finished"
	]);
	requiredEnum(e, e.direction, "direction", ["outbound"]);
	const n = requiredEnum(e, e.actor_type, "actorType", ["agent", "system"]);
	const r = requiredText$1(e, e.actor_id, "actorId");
	const i = {
		...parseMessageRecordFields(e),
		action: t,
		direction: "outbound",
		actorType: n,
		actorId: r
	};
	if (e.status === "started") {
		requireNull(e, "delivery_kind");
		requireNullColumns(e, [
			"error_code",
			"reason_code",
			"failure_stage"
		]);
		if (t === "message.outbound.queued") {
			requiredEnum(e, e.message_outcome, "outcome", ["queued"]);
			return {
				...i,
				action: t,
				status: "started",
				outcome: "queued"
			};
		}
		if (t === "message.outbound.platform-started") {
			requiredEnum(e, e.message_outcome, "outcome", ["platform_started"]);
			return {
				...i,
				action: t,
				status: "started",
				outcome: "platform_started"
			};
		}
		return corruptAuditRow(e, "invalid outbound lifecycle action");
	}
	requiredEnum(e, t, "action", ["message.outbound.finished"]);
	const a = {
		...i,
		action: "message.outbound.finished"
	};
	if (e.status === "succeeded") {
		const t = optionalEnum(e, e.delivery_kind, "deliveryKind", DELIVERY_KINDS);
		requiredEnum(e, e.message_outcome, "outcome", ["sent"]);
		requireNullColumns(e, [
			"error_code",
			"reason_code",
			"failure_stage"
		]);
		return {
			...a,
			status: "succeeded",
			outcome: "sent",
			...t ? { deliveryKind: t } : {}
		};
	}
	if (e.status === "blocked") {
		requireNull(e, "delivery_kind");
		requiredEnum(e, e.message_outcome, "outcome", ["suppressed"]);
		requireNullColumns(e, ["error_code", "failure_stage"]);
		const t = requiredEnum(e, e.reason_code, "reasonCode", AUDIT_OUTBOUND_MESSAGE_SUPPRESSED_REASONS);
		return {
			...a,
			status: "blocked",
			outcome: "suppressed",
			reasonCode: t
		};
	}
	if (e.status === "failed") {
		const t = optionalEnum(e, e.delivery_kind, "deliveryKind", DELIVERY_KINDS);
		requiredEnum(e, e.message_outcome, "outcome", ["failed"]);
		requireNull(e, "reason_code");
		const n = requiredEnum(e, e.error_code, "errorCode", ["message_delivery_failed", "message_delivery_partial_failure"]);
		const r = requiredEnum(e, e.failure_stage, "failureStage", FAILURE_STAGES);
		return {
			...a,
			status: "failed",
			outcome: "failed",
			errorCode: n,
			failureStage: r,
			...t ? { deliveryKind: t } : {}
		};
	}
	if (e.status === "unknown") {
		requireNull(e, "delivery_kind");
		requiredEnum(e, e.message_outcome, "outcome", ["unknown"]);
		requireNullColumns(e, ["error_code", "reason_code"]);
		const t = requiredEnum(e, e.failure_stage, "failureStage", FAILURE_STAGES);
		return {
			...a,
			status: "unknown",
			outcome: "unknown",
			failureStage: t
		};
	}
	return corruptAuditRow(e, "invalid outbound status");
}
function rowToAuditEvent(e) {
	if (e.kind === "agent_run") return parseAgentRunRow(e);
	if (e.kind === "tool_action") return parseToolActionRow(e);
	if (e.kind !== "message") corruptAuditRow(e, "invalid kind");
	if (e.direction === "inbound") return parseInboundMessageRow(e);
	if (e.direction === "outbound") return parseOutboundMessageRow(e);
	return corruptAuditRow(e, "invalid message direction");
}
//#endregion
//#region src/audit/audit-event-queries.ts
function bindAuditEventColumns(e) {
	return {
		event_id: e((e) => e.event_id),
		source_id: e((e) => e.source_id),
		source_sequence: e((e) => e.source_sequence),
		schema_version: e((e) => e.schema_version),
		occurred_at: e((e) => e.occurred_at),
		kind: e((e) => e.kind),
		action: e((e) => e.action),
		status: e((e) => e.status),
		error_code: e((e) => e.error_code),
		actor_type: e((e) => e.actor_type),
		actor_id: e((e) => e.actor_id),
		agent_id: e((e) => e.agent_id),
		session_key: e((e) => e.session_key),
		session_id: e((e) => e.session_id),
		run_id: e((e) => e.run_id),
		tool_call_id: e((e) => e.tool_call_id),
		tool_name: e((e) => e.tool_name),
		direction: e((e) => e.direction),
		channel: e((e) => e.channel),
		conversation_kind: e((e) => e.conversation_kind),
		message_outcome: e((e) => e.message_outcome),
		reason_code: e((e) => e.reason_code),
		delivery_kind: e((e) => e.delivery_kind),
		failure_stage: e((e) => e.failure_stage),
		duration_ms: e((e) => e.duration_ms),
		result_count: e((e) => e.result_count),
		account_ref: e((e) => e.account_ref),
		conversation_ref: e((e) => e.conversation_ref),
		message_ref: e((e) => e.message_ref),
		target_ref: e((e) => e.target_ref)
	};
}
function createAuditEventQueries(e) {
	const t = getNodeSqliteKysely(e);
	return {
		insert: prepareSqliteQueryTakeFirstSync(e, (e) => t.insertInto("audit_events").values(bindAuditEventColumns(e)).onConflict((e) => e.doNothing()).returning((e) => e.cast("sequence", "text").as("sequence"))),
		insertRun: prepareSqliteQuerySync(e, (e) => t.insertInto("audit_events").values([bindAuditEventColumns((t) => e((e) => t(e[0]))), bindAuditEventColumns((t) => e((e) => t(e[1])))]).onConflict((e) => e.doNothing()).returning("event_id").returning((e) => e.cast("sequence", "text").as("sequence"))),
		read: prepareSqliteQueryTakeFirstSync(e, (e) => t.selectFrom("audit_events").selectAll().where("sequence", "=", e((e) => e)))
	};
}
const getAuditEventQueries = createSqliteQueryCache(createAuditEventQueries);
//#endregion
//#region src/audit/message-execution-binding.ts
/** Exact execution binding for owner-native outbound message lifecycle facts. */
const ensuredTerminalBindingDatabases = /* @__PURE__ */ new WeakSet();
function terminalBindingSchemaSql() {
	return getOpenClawStateFeatureSchemaSql("outbound_message_execution_bindings", {
		endMarker: "  ON outbound_message_execution_bindings (context_id, execution_id, run_id, event_id);",
		errorMessage: "canonical outbound message execution binding schema is missing"
	});
}
const ensureTerminalBindingSchema = createSqliteSchemaEnsurer(terminalBindingSchemaSql, {
	tables: ["outbound_message_execution_bindings"],
	indexes: ["outbound_message_execution_bindings_execution_event_idx"]
});
/** Install the terminal binding companion only when an exact producer first uses it. */
function ensureTerminalMessageExecutionBindingSchema(e) {
	const t = openOpenClawStateDatabase(e);
	if (ensuredTerminalBindingDatabases.has(t.db)) return;
	runOpenClawStateWriteTransaction(({ db: e }) => {
		if (isPostgresSqlConnection(e)) ensureStatePostgresFragment(e, "outbound_message_execution_bindings");
		else ensureTerminalBindingSchema(e);
	}, {
		...e,
		database: t
	}, { operationLabel: "audit.outbound-message.execution-binding.schema.ensure" });
	ensuredTerminalBindingDatabases.add(t.db);
	stageSqliteTransactionState(t.db, {
		commit: () => {},
		rollback: () => ensuredTerminalBindingDatabases.delete(t.db),
		invalidate: () => ensuredTerminalBindingDatabases.delete(t.db)
	});
}
/** Validate queue-loaded token bytes before entering a synchronous write transaction. */
function planMessageExecutionBinding(e, t) {
	if (!e) return;
	const n = parseExecutionIdentityAdmissionToken(e);
	if (!t || n.runId !== t) throw new Error("outbound message execution binding disagrees with the admitted run");
	return n;
}
/** Confirm the exact retained admission row; run correlation alone never binds a receipt. */
function confirmMessageExecutionBinding(e, t) {
	if (!t || !tableExists(e, "execution_identity_contexts")) return;
	return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("execution_identity_contexts").select("context_id").where("context_id", "=", t.contextId).where("execution_id", "=", t.executionId).where("run_id", "=", t.runId).where("created_at", "=", t.createdAt)) ? {
		contextId: t.contextId,
		executionId: t.executionId
	} : void 0;
}
function recordTerminalMessageExecutionBinding(e, t) {
	executeSqliteQuerySync(e, getNodeSqliteKysely(e).insertInto("outbound_message_execution_bindings").values({
		event_id: t.eventId,
		context_id: t.contextId,
		execution_id: t.executionId,
		run_id: t.runId
	}));
}
function recordConfirmedTerminalMessageExecutionBinding(e, t) {
	if (!t.eventId) return;
	const n = confirmMessageExecutionBinding(e, t.token);
	if (n && t.token) recordTerminalMessageExecutionBinding(e, {
		eventId: t.eventId,
		runId: t.token.runId,
		...n
	});
}
//#endregion
//#region src/audit/audit-event-store.ts
/** SQLite persistence and stable cursor queries for metadata-only audit events. */
const AUDIT_EVENT_RETENTION_MS = 2592e6;
const AUDIT_EVENT_MAX_ROWS = 1e5;
const AUDIT_EVENT_PRUNE_BATCH_ROWS = 1024;
const auditEventRetention = /* @__PURE__ */ new WeakMap();
function projectMessageIdentities(e, t) {
	const n = loadOrCreateAuditIdentityKey(e);
	const r = t.conversationId ?? (t.direction === "outbound" ? t.targetId : void 0);
	const ref = (e, i) => pseudonymizeAuditIdentity({
		identity: n,
		kind: e,
		channel: t.channel,
		...e !== "account" && t.accountId !== void 0 ? { accountId: t.accountId } : {},
		...e === "message" && r !== void 0 ? { conversationId: r } : {},
		value: i
	});
	return {
		actorId: t.actorType === "channel_sender" ? ref("actor", t.actorId) : t.actorId,
		accountRef: ref("account", t.accountId),
		conversationRef: ref("conversation", r),
		messageRef: ref("message", t.messageId),
		targetRef: ref("target", t.targetId)
	};
}
function bindAuditEvent(e, t, n) {
	const r = t.kind === "message" ? projectMessageIdentities(e, t) : void 0;
	return {
		event_id: n,
		source_id: t.sourceId,
		source_sequence: t.sourceSequence,
		schema_version: 1,
		occurred_at: t.occurredAt,
		kind: t.kind,
		action: t.action,
		status: t.status,
		error_code: t.errorCode ?? null,
		actor_type: t.actorType,
		actor_id: r?.actorId ?? t.actorId,
		agent_id: t.agentId ?? null,
		session_key: t.kind === "message" ? null : t.sessionKey ?? null,
		session_id: t.kind === "message" ? null : t.sessionId ?? null,
		run_id: t.runId ?? null,
		tool_call_id: t.kind === "tool_action" ? t.toolCallId ?? null : null,
		tool_name: t.kind === "tool_action" ? t.toolName : null,
		direction: t.kind === "message" ? t.direction : null,
		channel: t.kind === "message" ? t.channel : null,
		conversation_kind: t.kind === "message" ? t.conversationKind : null,
		message_outcome: t.kind === "message" ? t.outcome : null,
		reason_code: t.kind === "message" ? t.reasonCode ?? null : null,
		delivery_kind: t.kind === "message" ? t.deliveryKind ?? null : null,
		failure_stage: t.kind === "message" ? t.failureStage ?? null : null,
		duration_ms: t.kind === "message" ? t.durationMs ?? null : null,
		result_count: t.kind === "message" ? t.resultCount ?? null : null,
		account_ref: r?.accountRef ?? null,
		conversation_ref: r?.conversationRef ?? null,
		message_ref: r?.messageRef ?? null,
		target_ref: r?.targetRef ?? null
	};
}
function readAuditEventRetention(e) {
	const t = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("audit_events").select((e) => [e.fn.countAll().as("count"), e.fn.min("occurred_at").as("oldest")]));
	return {
		rowCount: normalizeSqliteNumber(t?.count ?? null) ?? 0,
		nextExpiryAt: (normalizeSqliteNumber(t?.oldest ?? null) ?? Number.POSITIVE_INFINITY) + AUDIT_EVENT_RETENTION_MS
	};
}
function deleteExpiredAuditEvents(e, t) {
	const n = getNodeSqliteKysely(e);
	const r = n.selectFrom("audit_events").select("sequence").where("occurred_at", "<", t - AUDIT_EVENT_RETENTION_MS).orderBy("occurred_at", "asc").orderBy("sequence", "asc").limit(AUDIT_EVENT_PRUNE_BATCH_ROWS);
	return executeSqliteQuerySync(e, n.deleteFrom("audit_events").where("sequence", "in", r));
}
function pruneAfterInsert(e, t, n, r, i) {
	const a = getNodeSqliteKysely(e);
	const o = auditEventRetention.get(e);
	let s = o ? {
		rowCount: o.rowCount + r,
		nextExpiryAt: Math.min(o.nextExpiryAt, n + AUDIT_EVENT_RETENTION_MS)
	} : readAuditEventRetention(e);
	let c = false;
	if (s.nextExpiryAt < t) {
		const n = deleteExpiredAuditEvents(e, t);
		s.rowCount = Math.max(0, s.rowCount - Number(n.numAffectedRows ?? 0n));
		c = true;
	}
	if (s.rowCount > AUDIT_EVENT_MAX_ROWS) {
		const t = a.selectFrom("audit_events").select("sequence").orderBy("sequence", "desc").offset(98976).limit(1);
		const n = executeSqliteQuerySync(e, a.deleteFrom("audit_events").where("sequence", "<=", t));
		const r = Number(n.numAffectedRows ?? 0n);
		if (r > 0) {
			s.rowCount = Math.max(0, s.rowCount - r);
			c = true;
		} else {
			s = readAuditEventRetention(e);
			c = false;
		}
	}
	if (c) {
		const t = executeSqliteQueryTakeFirstSync(e, a.selectFrom("audit_events").select((e) => e.fn.min("occurred_at").as("oldest")));
		s.nextExpiryAt = (normalizeSqliteNumber(t?.oldest ?? null) ?? Number.POSITIVE_INFINITY) + AUDIT_EVENT_RETENTION_MS;
	}
	stageSqliteTransactionState(e, {
		commit: () => {},
		rollback: () => auditEventRetention.delete(e),
		invalidate: () => auditEventRetention.delete(e)
	});
	auditEventRetention.set(e, {
		...s,
		nextSequence: i
	});
}
function getAuditAutocommitRetention(e, t, n, r) {
	const i = auditEventRetention.get(e);
	return !e.isTransaction && !isPostgresSqlConnection(e) && i && i.rowCount + r <= AUDIT_EVENT_MAX_ROWS && i.nextExpiryAt >= t && n + 2592e6 >= t && Number.isSafeInteger(i.nextSequence + (r - 1)) ? i : void 0;
}
function parseInsertedAuditSequence(e) {
	const t = Number(e);
	if (!Number.isSafeInteger(t) || t < 1) throw new Error("audit event sequence is outside the supported integer range");
	return t;
}
/** Persist one projected event idempotently and prune fixed retention bounds. */
function recordAuditEventInDatabase(e, t, n = randomUUID()) {
	const r = e.kind === "message" && e.direction === "outbound" ? planMessageExecutionBinding(e.executionIdentityToken, e.runId) : void 0;
	if (r) ensureTerminalMessageExecutionBindingSchema(t);
	const { db: i } = t.database;
	try {
		const a = e.kind !== "message" ? getAuditAutocommitRetention(i, Date.now(), e.occurredAt, 1) : void 0;
		if (a) {
			const r = bindAuditEvent(i, e, n);
			const o = rowToAuditEvent({
				...r,
				sequence: a.nextSequence
			});
			const s = getAuditEventQueries(i);
			const c = runOpenClawStateWriteTransaction(() => s.insert(r), t, { singleStatement: true });
			a.nextSequence += 1;
			if (c) {
				a.rowCount += 1;
				a.nextExpiryAt = Math.min(a.nextExpiryAt, e.occurredAt + AUDIT_EVENT_RETENTION_MS);
			}
			return c ? o : void 0;
		}
		return runOpenClawStateWriteTransaction(() => {
			const t = bindAuditEvent(i, e, n);
			const a = getAuditEventQueries(i);
			const o = a.insert(t);
			if (o === void 0) {
				auditEventRetention.delete(i);
				return;
			}
			const s = parseInsertedAuditSequence(o.sequence);
			const c = Date.now();
			pruneAfterInsert(i, c, t.occurred_at, 1, s + 1);
			const l = t.occurred_at < c - 2592e6 ? a.read(s) : {
				...t,
				sequence: s
			};
			recordConfirmedTerminalMessageExecutionBinding(i, {
				eventId: l?.event_id,
				token: r
			});
			return l ? rowToAuditEvent(l) : void 0;
		}, t);
	} catch (e) {
		auditEventRetention.delete(i);
		clearAuditIdentityKeyCacheForDatabase(i);
		throw e;
	}
}
/** Persist a completed run as one replay-safe insert and one retention pass. */
function recordAuditRunInDatabase(e, t, n, r) {
	const { db: i } = n.database;
	const a = [bindAuditEvent(i, e, r[0]), bindAuditEvent(i, t, r[1])];
	for (const e of a) parseAgentRunRow({
		...e,
		sequence: 1
	});
	const o = getAuditEventQueries(i);
	try {
		const s = getAuditAutocommitRetention(i, Date.now(), Math.min(e.occurredAt, t.occurredAt), 2);
		if (s) {
			const { rows: e } = runOpenClawStateWriteTransaction(() => o.insertRun(a), n, { singleStatement: true });
			s.nextSequence += 2;
			s.rowCount += e.length;
			s.nextExpiryAt = Math.min(s.nextExpiryAt, ...e.map((e) => a[e.event_id === r[0] ? 0 : 1].occurred_at + AUDIT_EVENT_RETENTION_MS));
			return;
		}
		return runOpenClawStateWriteTransaction(() => {
			const { rows: e } = o.insertRun(a);
			if (e.length === 0) {
				auditEventRetention.delete(i);
				return;
			}
			const t = e.map((e) => ({
				values: e.event_id === r[0] ? a[0] : a[1],
				sequence: parseInsertedAuditSequence(e.sequence)
			}));
			pruneAfterInsert(i, Date.now(), Math.min(...t.map((e) => e.values.occurred_at)), t.length, Math.max(...t.map((e) => e.sequence + (e.values === a[0] ? 2 : 1))));
		}, n);
	} catch (e) {
		auditEventRetention.delete(i);
		throw e;
	}
}
/** List newest-first records using the shared state worker and a stable sequence cursor. */
async function listAuditEvents(e) {
	const t = {
		limit: e.limit,
		now: e.now ?? Date.now(),
		...e.cursor !== void 0 ? { cursor: e.cursor } : {},
		...e.filters ? { filters: { ...e.filters } } : {}
	};
	const n = captureOpenClawStateWorkerContext(e.database);
	const { executeOpenClawStateWorker: r } = await import("./openclaw-state-worker-store-BURqchns.mjs");
	return r(n, {
		type: "audit.events.list",
		input: t
	});
}
/** Delete one bounded batch during Gateway startup and periodic audit maintenance. */
function pruneExpiredAuditEventsInDatabase(e) {
	return runOpenClawStateWriteTransaction(({ db: t }) => {
		const n = deleteExpiredAuditEvents(t, e.now ?? Date.now());
		auditEventRetention.delete(t);
		return Number(n.numAffectedRows ?? 0n);
	}, e.database, { singleStatement: true });
}
//#endregion
//#region src/gateway/operator-approval-store.receipts.ts
const OPERATOR_APPROVAL_PAYLOAD_COLUMNS = {
	presentation_json: sql`operator_approvals.presentation_json`,
	reviewer_device_ids_json: sql`operator_approvals.reviewer_device_ids_json`,
	audience_session_keys_json: sql`operator_approvals.audience_session_keys_json`
};
//#endregion
//#region src/audit/message-delivery-progress-store.ts
/** Lazy owner-native persistence for nonterminal outbound message progress. */
const OUTBOUND_MESSAGE_PROGRESS_RETENTION_MS = 2592e6;
const OUTBOUND_MESSAGE_PROGRESS_MAX_ROWS = 2e5;
const OUTBOUND_MESSAGE_PROGRESS_PRUNE_BATCH_ROWS = 1024;
const AUDIT_HMAC_REF_RE = /^hmac-sha256:v1:[a-f0-9]{32}:[a-f0-9]{64}$/u;
const ensuredDatabases = /* @__PURE__ */ new WeakSet();
const progressRowCounts = /* @__PURE__ */ new WeakMap();
function progressSchemaSql() {
	return getOpenClawStateFeatureSchemaSql("outbound_message_progress", {
		endMarker: "  ON outbound_message_progress (run_id, occurred_at, sequence);",
		errorMessage: "canonical outbound message progress schema is missing"
	});
}
function progressDb(e) {
	return getNodeSqliteKysely(e);
}
const ensureProgressSchemaInDatabase = createSqliteSchemaEnsurer(progressSchemaSql, {
	tables: ["outbound_message_progress"],
	indexes: ["outbound_message_progress_occurred_idx", "outbound_message_progress_run_occurred_idx"]
});
function ensureProgressSchema(e) {
	const t = openOpenClawStateDatabase(e);
	if (ensuredDatabases.has(t.db)) return;
	runOpenClawStateWriteTransaction(({ db: e }) => {
		if (isPostgresSqlConnection(e)) ensureStatePostgresFragment(e, "outbound_message_progress");
		else {
			ensureProgressSchemaInDatabase(e);
			ensureColumn(e, "outbound_message_progress", "context_id TEXT");
			ensureColumn(e, "outbound_message_progress", "execution_id TEXT");
		}
	}, e, { operationLabel: "audit.outbound-message-progress.schema.ensure" });
	ensuredDatabases.add(t.db);
	stageSqliteTransactionState(t.db, {
		commit: () => {},
		rollback: () => ensuredDatabases.delete(t.db),
		invalidate: () => ensuredDatabases.delete(t.db)
	});
}
function projectProgressIdentities(e, t) {
	const n = loadOrCreateAuditIdentityKey(e);
	const r = t.conversationId ?? t.targetId;
	const ref = (e, r) => pseudonymizeAuditIdentity({
		identity: n,
		kind: e,
		channel: t.channel,
		...e !== "account" && t.accountId !== void 0 ? { accountId: t.accountId } : {},
		value: r
	});
	return {
		accountRef: ref("account", t.accountId),
		conversationRef: ref("conversation", r),
		targetRef: ref("target", t.targetId)
	};
}
function bindProgressRow(e, t, n) {
	const r = projectProgressIdentities(e, t);
	return {
		progress_id: randomUUID(),
		source_id: t.sourceId,
		source_sequence: t.sourceSequence,
		schema_version: 1,
		occurred_at: t.occurredAt,
		action: t.action,
		outcome: t.outcome,
		actor_type: t.actorType,
		actor_id: t.actorId,
		agent_id: t.agentId ?? null,
		run_id: t.runId ?? null,
		context_id: n?.contextId ?? null,
		execution_id: n?.executionId ?? null,
		channel: t.channel,
		conversation_kind: t.conversationKind,
		duration_ms: t.durationMs ?? null,
		account_ref: r.accountRef ?? null,
		conversation_ref: r.conversationRef ?? null,
		target_ref: r.targetRef ?? null
	};
}
function requiredText(e, t) {
	if (typeof e !== "string" || e.length === 0) throw new Error(`corrupt outbound message progress row: invalid ${t}`);
	return e;
}
function optionalText(e, t) {
	if (e === null || e === void 0) return;
	return requiredText(e, t);
}
function optionalHmacRef(e, t) {
	const n = optionalText(e, t);
	if (n !== void 0 && !AUDIT_HMAC_REF_RE.test(n)) throw new Error(`corrupt outbound message progress row: invalid ${t}`);
	return n;
}
function rowToProgressEvent(e) {
	const t = normalizeSqliteNumber(e.sequence);
	const n = normalizeSqliteNumber(e.source_sequence);
	const r = normalizeSqliteNumber(e.occurred_at);
	const i = normalizeSqliteNumber(e.duration_ms);
	if (t === void 0 || t < 1 || n === void 0 || n < 1 || r === void 0 || r < 0 || e.schema_version !== 1 || i !== void 0 && i < 0) throw new Error("corrupt outbound message progress row: invalid numeric field");
	if (e.action === "message.outbound.queued" && e.outcome !== "queued" || e.action === "message.outbound.platform-started" && e.outcome !== "platform_started" || e.action !== "message.outbound.queued" && e.action !== "message.outbound.platform-started") throw new Error("corrupt outbound message progress row: invalid lifecycle field");
	const a = e.actor_type === "agent" ? "agent" : e.actor_type === "system" ? "system" : void 0;
	if (!a) throw new Error("corrupt outbound message progress row: invalid actor type");
	const o = e.conversation_kind === "direct" ? "direct" : e.conversation_kind === "group" ? "group" : e.conversation_kind === "channel" ? "channel" : e.conversation_kind === "unknown" ? "unknown" : void 0;
	if (!o) throw new Error("corrupt outbound message progress row: invalid conversation kind");
	const s = {
		schemaVersion: 1,
		sequence: t,
		eventId: requiredText(e.progress_id, "progressId"),
		sourceSequence: n,
		occurredAt: r,
		redaction: "metadata_only",
		kind: "message",
		actorType: a,
		actorId: requiredText(e.actor_id, "actorId"),
		...optionalText(e.agent_id, "agentId") !== void 0 ? { agentId: e.agent_id } : {},
		...optionalText(e.run_id, "runId") !== void 0 ? { runId: e.run_id } : {},
		direction: "outbound",
		channel: requiredText(e.channel, "channel"),
		conversationKind: o,
		...i !== void 0 ? { durationMs: i } : {},
		resultCount: 0,
		...optionalHmacRef(e.account_ref, "accountRef") !== void 0 ? { accountRef: e.account_ref } : {},
		...optionalHmacRef(e.conversation_ref, "conversationRef") !== void 0 ? { conversationRef: e.conversation_ref } : {},
		...optionalHmacRef(e.target_ref, "targetRef") !== void 0 ? { targetRef: e.target_ref } : {}
	};
	return e.action === "message.outbound.queued" ? {
		...s,
		action: e.action,
		status: "started",
		outcome: "queued"
	} : {
		...s,
		action: e.action,
		status: "started",
		outcome: "platform_started"
	};
}
function countProgressRows(e) {
	const t = executeSqliteQueryTakeFirstSync(e, progressDb(e).selectFrom("outbound_message_progress").select((e) => e.fn.countAll().as("count")));
	return normalizeSqliteNumber(t?.count ?? null) ?? 0;
}
function deleteExpiredProgressRows(e, t, n) {
	const r = progressDb(e);
	const i = r.selectFrom("outbound_message_progress").select("sequence").where("occurred_at", "<", t - OUTBOUND_MESSAGE_PROGRESS_RETENTION_MS).orderBy("occurred_at", "asc").orderBy("sequence", "asc").limit(n);
	return executeSqliteQuerySync(e, r.deleteFrom("outbound_message_progress").where("sequence", "in", i));
}
function pruneProgressAfterInsert(e, t) {
	stageSqliteTransactionState(e, {
		commit: () => {},
		rollback: () => progressRowCounts.delete(e),
		invalidate: () => progressRowCounts.delete(e)
	});
	const n = progressDb(e);
	const r = deleteExpiredProgressRows(e, t, OUTBOUND_MESSAGE_PROGRESS_PRUNE_BATCH_ROWS);
	const i = progressRowCounts.get(e);
	let a = i === void 0 ? countProgressRows(e) : Math.max(0, i + 1 - Number(r.numAffectedRows ?? 0n));
	if (a <= OUTBOUND_MESSAGE_PROGRESS_MAX_ROWS) {
		progressRowCounts.set(e, a);
		return;
	}
	const o = Math.max(0, 198976);
	const s = n.selectFrom("outbound_message_progress").select("sequence").orderBy("sequence", "desc").offset(o).limit(1);
	const c = executeSqliteQuerySync(e, n.deleteFrom("outbound_message_progress").where("sequence", "<=", s));
	a = Math.max(0, a - Number(c.numAffectedRows ?? 0n));
	progressRowCounts.set(e, a);
}
/** Persist one progress fact idempotently; first use installs only this owner table. */
function recordOutboundMessageProgressInDatabase(e, t) {
	const n = planMessageExecutionBinding(e.executionIdentityToken, e.runId);
	ensureProgressSchema(t);
	let r;
	try {
		return runOpenClawStateWriteTransaction(({ db: t }) => {
			r = t;
			const i = confirmMessageExecutionBinding(t, n);
			const a = executeSqliteQueryTakeFirstSync(t, progressDb(t).insertInto("outbound_message_progress").values(bindProgressRow(t, e, i)).onConflict((e) => e.column("source_id").doNothing()).returning("sequence"));
			if (!a) return;
			const o = a.sequence;
			if (!Number.isSafeInteger(o) || o < 1) throw new Error("outbound message progress sequence is outside the supported range");
			pruneProgressAfterInsert(t, Date.now());
			const s = executeSqliteQueryTakeFirstSync(t, progressDb(t).selectFrom("outbound_message_progress").selectAll().where("sequence", "=", o));
			return s ? rowToProgressEvent(s) : void 0;
		}, t);
	} catch (e) {
		if (r) {
			progressRowCounts.delete(r);
			clearAuditIdentityKeyCacheForDatabase(r);
		}
		throw e;
	}
}
/** Prune existing progress without creating its lazy table. */
function pruneExpiredOutboundMessageProgressInDatabase(e) {
	const t = openOpenClawStateDatabase(e.database);
	if (!tableExists(t.db, "outbound_message_progress")) return 0;
	return runOpenClawStateWriteTransaction(({ db: t }) => {
		const n = deleteExpiredProgressRows(t, e.now ?? Date.now(), OUTBOUND_MESSAGE_PROGRESS_PRUNE_BATCH_ROWS);
		progressRowCounts.delete(t);
		return Number(n.numAffectedRows ?? 0n);
	}, e.database);
}
//#endregion
//#region src/audit/execution-decision-receipts.ts
var ExecutionDecisionCursorError = class extends Error {
	constructor(e = "invalid execution decision cursor") {
		super(e);
		this.name = "ExecutionDecisionCursorError";
	}
};
function parseDecisionCursor(e) {
	if (e === void 0) return;
	const t = parsePositiveAuditCursor(e);
	if (t !== null && t !== void 0) return { offset: t };
	const n = /^([amgctf]):(0|[1-9]\d*):(0|[1-9]\d*)$/.exec(e);
	if (!n) return null;
	const r = Number(n[2]);
	const i = Number(n[3]);
	if (!Number.isSafeInteger(r) || !Number.isSafeInteger(i)) return null;
	if (n[1] === "t" || n[1] === "f") return { retired: true };
	return {
		stage: n[1] === "a" ? "approval" : n[1] === "m" ? "message" : n[1] === "g" ? "generic" : "cron",
		...r === 0 && i === 0 ? {} : { after: {
			occurredAt: r,
			rowId: i
		} }
	};
}
function isExecutionDecisionCursor(e) {
	return parseDecisionCursor(e) !== null;
}
//#endregion
//#region src/audit/execution-identity-context-build.ts
/** Worker-only canonical context construction and bounded value helpers. */
function ensureBoundedExecutionIdentityRef(e, t, n = 256) {
	if (!e || e.length > n) throw new Error(`${t} must be between 1 and ${String(n)} characters`);
	return e;
}
function ensureRawRef(e, t) {
	return ensureBoundedExecutionIdentityRef(e, t, 4096);
}
function freezeExecutionIdentityContext(e, t = /* @__PURE__ */ new WeakSet()) {
	if (!e || typeof e !== "object" || t.has(e)) return e;
	t.add(e);
	for (const n of Object.values(e)) freezeExecutionIdentityContext(n, t);
	return Object.freeze(e);
}
function hmacRef(e, t, n, r) {
	return pseudonymizeExecutionIdentityRef({
		db: e,
		kind: t,
		scope: ensureBoundedExecutionIdentityRef(n, "HMAC scope"),
		value: ensureRawRef(r, "HMAC value")
	});
}
function buildExecutionIdentityContext(e, t, n) {
	const r = ensureBoundedExecutionIdentityRef(t.runId, "run id");
	const i = ensureBoundedExecutionIdentityRef(t.executionId, "execution id");
	const a = ensureBoundedExecutionIdentityRef(t.agentId, "agent id");
	const o = ensureBoundedExecutionIdentityRef(n.contextId, "context id");
	const s = hmacRef(e, "domain", "gateway-cell", "gateway-cell");
	const c = hmacRef(e, "runtime", s, ensureRawRef(t.runtimeInstanceId, "runtime instance id"));
	const l = t.invoker?.state === "present" ? {
		state: "present",
		principal: {
			kind: t.invoker.kind,
			domainRef: s,
			principalRef: hmacRef(e, "principal", `${s}:${t.invoker.kind}`, t.invoker.rawPrincipalRef),
			...t.invoker.displayLabel !== void 0 ? { displayLabel: t.invoker.displayLabel } : {}
		}
	} : t.invoker?.state === "unknown" ? { state: "unknown" } : { state: "absent" };
	const u = sortUniqueExecutionIdentityEntries(t.assurance.map((t) => ({
		kind: t.kind,
		evidenceRef: hmacRef(e, "evidence", `${s}:${t.kind}`, t.rawEvidenceRef),
		strength: t.strength
	})), (e) => `${e.kind}\0${e.evidenceRef}\0${e.strength}`);
	const d = sortUniqueExecutionIdentityEntries(t.applicableGrants.map((t) => ({
		grantRef: hmacRef(e, "grant", s, t.rawGrantRef),
		state: t.state
	})), (e) => `${e.grantRef}\0${e.state}`);
	const f = executionIdentitySpawnAdmission({
		operation: "read",
		value: t
	});
	const [p, m] = f ? executionIdentitySpawnAdmission({
		operation: "parse",
		value: f
	}) : [void 0, []];
	const h = p ? {
		...typeof p.parentContextId === "string" ? { parentContextId: p.parentContextId } : {},
		...typeof p.parentExecutionId === "string" ? { parentExecutionId: p.parentExecutionId } : {},
		...typeof p.parentRunId === "string" ? { parentRunId: p.parentRunId } : {},
		parentAgentPrincipal: {
			kind: "agent",
			domainRef: s,
			principalRef: p.parentAgentId
		},
		delegationRef: hmacRef(e, "grant", `${s}:delegation`, JSON.stringify([
			p.relation,
			p.rawRequesterRef,
			p.rawControllerRef,
			p.localPolicyRefs,
			p.targetPolicyRefs
		])),
		depth: p.depth
	} : void 0;
	const g = sortUniqueExecutionIdentityEntries([...t.invoker?.state === "present" ? [] : ["invoker.principal"], ...m], (e) => e);
	const _ = {
		schemaVersion: 1,
		contextId: o,
		executionId: i,
		runId: r,
		createdAt: n.createdAt,
		trustDomain: {
			kind: "gateway-cell",
			domainRef: s,
			state: "present"
		},
		invoker: l,
		...t.representedSubject ? { representedSubject: {
			state: "present",
			principal: {
				kind: "person",
				domainRef: s,
				principalRef: hmacRef(e, "principal", `${s}:person`, t.representedSubject.rawPrincipalRef)
			}
		} } : {},
		ingress: {
			kind: t.ingress.kind,
			boundary: ensureBoundedExecutionIdentityRef(t.ingress.boundary, "ingress boundary"),
			state: t.ingress.state,
			...t.ingress.rawSourceRef ? { sourceRef: hmacRef(e, "principal", `${s}:ingress:${t.ingress.kind}`, t.ingress.rawSourceRef) } : {}
		},
		agentPrincipal: {
			kind: "agent",
			domainRef: s,
			principalRef: a
		},
		agentDefinition: {
			definitionRef: a,
			state: "present"
		},
		runtimeInstance: {
			runtimeRef: c,
			kind: t.runtime.kind,
			state: "present"
		},
		applicableGrants: d,
		assurance: u,
		...h ? { lineage: h } : {},
		coverageState: h ? "attribution-only" : t.invoker?.state === "present" ? "attribution-only" : t.invoker?.state === "unknown" ? "unknown" : "unattributed",
		missingEvidence: g
	};
	if (!validateExecutionIdentityContextV1(_)) throw new Error("prepared execution identity context violates the V1 contract");
	return freezeExecutionIdentityContext(_);
}
//#endregion
//#region src/audit/execution-identity-context.ts
const EXECUTION_IDENTITY_CONTEXT_MAX_BYTES = 16384;
const EXECUTION_IDENTITY_CONTEXT_RETENTION_MS = 2592e6;
const EXECUTION_IDENTITY_CONTEXT_MAX_ROWS = 1e5;
const EXECUTION_IDENTITY_CONTEXT_PRUNE_BATCH_ROWS = 1024;
const EXECUTION_IDENTITY_HMAC_REF_RE = /^hmac-sha256:v1:[a-f0-9]{32}:[a-f0-9]{64}$/u;
const ensureExecutionIdentityContextSchema = createOpenClawStateSchemaEnsurer({
	table: "execution_identity_contexts",
	indexes: ["execution_identity_contexts_run_created_idx"],
	endMarker: "  ON execution_identity_contexts (run_id, created_at, execution_id);\n",
	operationLabel: "audit.execution-identity.schema.ensure"
});
function executionIdentityDb(e) {
	return getNodeSqliteKysely(e);
}
function parseExecutionIdentityRow(e) {
	if (typeof e.context_json !== "string" || Buffer.byteLength(e.context_json, "utf8") !== normalizeSqliteNumber(e.context_bytes) || Buffer.byteLength(e.context_json, "utf8") > EXECUTION_IDENTITY_CONTEXT_MAX_BYTES) throw new Error("invalid context payload bounds");
	const t = JSON.parse(e.context_json);
	if (!validateExecutionIdentityContextV1(t)) throw new Error("invalid context payload schema");
	if (t.contextId !== e.context_id || t.executionId !== e.execution_id || t.runId !== e.run_id || t.createdAt !== normalizeSqliteNumber(e.created_at) || t.coverageState !== e.coverage_state || JSON.stringify(t) !== e.context_json || !EXECUTION_IDENTITY_HMAC_REF_RE.test(t.trustDomain.domainRef) || !EXECUTION_IDENTITY_HMAC_REF_RE.test(t.runtimeInstance.runtimeRef)) throw new Error("context payload disagrees with indexed columns");
	return freezeExecutionIdentityContext(t);
}
function readRowByExecutionId(e, t) {
	return executeSqliteQueryTakeFirstSync(e, executionIdentityDb(e).selectFrom("execution_identity_contexts").selectAll().where("execution_id", "=", t));
}
function deleteExpiredExecutionIdentityContexts(e, t, n) {
	const r = executionIdentityDb(e);
	const i = r.selectFrom("execution_identity_contexts").select("context_id").where("created_at", "<", t - EXECUTION_IDENTITY_CONTEXT_RETENTION_MS).orderBy("created_at", "asc").orderBy("context_id", "asc").limit(n);
	return executeSqliteQuerySync(e, r.deleteFrom("execution_identity_contexts").where("context_id", "in", i));
}
function pruneExecutionIdentityContextsAfterInsert(e, t, n) {
	const r = executionIdentityDb(e);
	const i = deleteExpiredExecutionIdentityContexts(e, t, n.pruneBatchRows);
	const a = Number(i.numAffectedRows ?? 0n);
	const o = Math.max(0, n.pruneBatchRows - a);
	if (o > 0) {
		const t = r.selectFrom("execution_identity_contexts").select(["created_at", "context_id"]).orderBy("created_at", "desc").orderBy("context_id", "desc").offset(n.maxRows).limit(1).$asTuple("created_at", "context_id");
		const i = r.selectFrom("execution_identity_contexts").select("context_id").where((e) => e(e.refTuple("created_at", "context_id"), "<=", t)).orderBy("created_at", "asc").orderBy("context_id", "asc").limit(o);
		executeSqliteQuerySync(e, r.deleteFrom("execution_identity_contexts").where("context_id", "in", i));
	}
}
/** Delete one bounded batch during the existing audit startup/hourly maintenance tick. */
function pruneExpiredExecutionIdentityContextsInDatabase(e) {
	const t = e.database;
	const n = openOpenClawStateDatabase(t);
	if (!tableExists(n.db, "execution_identity_contexts")) return 0;
	return runOpenClawStateWriteTransaction(({ db: t }) => {
		const n = deleteExpiredExecutionIdentityContexts(t, e.now ?? Date.now(), EXECUTION_IDENTITY_CONTEXT_PRUNE_BATCH_ROWS);
		return Number(n.numAffectedRows ?? 0n);
	}, {
		...t,
		database: n
	}, { operationLabel: "audit.execution-identity.context.maintenance" });
}
/** Worker-owned canonicalization and persistence for one accepted admission envelope. */
function persistExecutionIdentityAdmissionEnvelope(e, t = {}) {
	ensureExecutionIdentityContextSchema(t);
	const n = e.executionId;
	const r = openOpenClawStateDatabase(t);
	const i = buildExecutionIdentityContext(r.db, e, {
		contextId: e.contextId,
		createdAt: e.createdAt
	});
	const a = JSON.stringify(i);
	const o = Buffer.byteLength(a, "utf8");
	if (o > EXECUTION_IDENTITY_CONTEXT_MAX_BYTES) throw new Error("prepared execution identity context exceeds 16 KiB");
	let s;
	try {
		return runOpenClawStateWriteTransaction(({ db: e }) => {
			s = e;
			const r = readRowByExecutionId(e, n);
			if (r) {
				const e = parseExecutionIdentityRow(r);
				if (a !== r.context_json) throw new Error("execution identity context conflict for execution");
				return e;
			}
			executeSqliteQuerySync(e, executionIdentityDb(e).insertInto("execution_identity_contexts").values({
				context_id: i.contextId,
				execution_id: i.executionId,
				run_id: i.runId,
				created_at: i.createdAt,
				coverage_state: i.coverageState,
				context_bytes: o,
				context_json: a
			}));
			pruneExecutionIdentityContextsAfterInsert(e, t.now ?? Date.now(), t.limits ?? {
				maxRows: EXECUTION_IDENTITY_CONTEXT_MAX_ROWS,
				pruneBatchRows: EXECUTION_IDENTITY_CONTEXT_PRUNE_BATCH_ROWS
			});
			return i;
		}, t, { operationLabel: "audit.execution-identity.context.record" });
	} catch (e) {
		if (s) clearAuditIdentityKeyCacheForDatabase(s);
		throw e;
	}
}
/** A durable recovery retry may only confirm the originally captured execution. */
function verifyExecutionIdentityAdmissionRetry(e, t = {}) {
	const { db: n } = openOpenClawStateDatabase(t);
	if (!tableExists(n, "execution_identity_contexts")) throw new Error("execution identity recovery evidence unavailable");
	const r = readRowByExecutionId(n, e.executionId);
	if (!r) throw new Error("execution identity recovery evidence unavailable");
	const i = parseExecutionIdentityRow(r);
	if (i.contextId !== e.contextId || i.executionId !== e.executionId || i.runId !== e.runId || i.createdAt !== e.createdAt) throw new Error("execution identity context conflict for execution");
	return i;
}
/** Worker-owned persistence/verification for one accepted bounded queue item. */
function processExecutionIdentityAdmissionWorkInDatabase(e, t) {
	const n = parseExecutionIdentityAdmissionWork(e);
	return n.kind === "capture" ? persistExecutionIdentityAdmissionEnvelope(n.envelope, t) : verifyExecutionIdentityAdmissionRetry(n.token, t);
}
function unavailableResult(e) {
	return {
		schemaVersion: 1,
		run: "executionId" in e.selector ? {
			executionId: e.selector.executionId,
			...e.resolvedRunId ? { runId: e.resolvedRunId } : {},
			status: e.runStatus
		} : {
			runId: e.resolvedRunId ?? e.selector.runId,
			status: e.runStatus
		},
		identity: {
			state: e.state,
			reasonCode: e.reasonCode,
			missingEvidence: e.missingEvidence,
			remediation: e.remediation
		},
		decisions: [],
		decisionDisplays: [],
		coverage: {
			state: e.state,
			missingEvidence: e.missingEvidence
		}
	};
}
function missingInspectionResult(e) {
	if ("executionId" in e) return unavailableResult({
		selector: e,
		runStatus: "unknown",
		state: "unknown",
		reasonCode: "execution_not_found",
		missingEvidence: ["identity.context"],
		remediation: [{
			code: "verify_execution_id",
			text: "Verify the exact execution id; absence of best-effort identity evidence is not proof that no run occurred."
		}]
	});
	const t = e.runId;
	return unavailableResult({
		selector: { runId: t },
		runStatus: "unknown",
		state: "unknown",
		reasonCode: "run_not_found",
		missingEvidence: ["run.record", "identity.context"],
		remediation: [{
			code: "verify_run_id",
			text: "Verify the run id; absence of best-effort audit activity is not proof of no run."
		}]
	});
}
/** Inspect one exact execution or discover bounded executions without host SQLite. */
async function inspectExecutionIdentityRun(e, t = {}) {
	const n = {
		...e,
		now: t.now ?? Date.now()
	};
	if ("executionId" in n) ensureBoundedExecutionIdentityRef(n.executionId, "execution id");
	else ensureBoundedExecutionIdentityRef(n.runId, "run id");
	const r = await executeExistingOpenClawStateRead(t, {
		type: "audit.run.inspect",
		input: n
	});
	if (!r) return missingInspectionResult(n);
	if (!r.ok || r.type !== "audit.run.inspect") throw new Error("Unexpected audit run inspection result");
	if (r.result.status === "invalid-cursor") throw new ExecutionDecisionCursorError(r.result.message);
	const i = r.result.inspection;
	if (i.identity.state === "present") freezeExecutionIdentityContext(i.identity.context);
	return i;
}
//#endregion
export { isExecutionDecisionCursor as a, AUDIT_EVENT_RETENTION_MS as c, recordAuditEventInDatabase as d, recordAuditRunInDatabase as f, ExecutionDecisionCursorError as i, listAuditEvents as l, isOutboundMessageProgressInput as m, processExecutionIdentityAdmissionWorkInDatabase as n, pruneExpiredOutboundMessageProgressInDatabase as o, rowToAuditEvent as p, pruneExpiredExecutionIdentityContextsInDatabase as r, recordOutboundMessageProgressInDatabase as s, inspectExecutionIdentityRun as t, pruneExpiredAuditEventsInDatabase as u };