UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

2,079 lines • 66.9 kB
import { m as collectNestedErrorCandidates } from "./paths-0xDagtub.mjs";
import { H as resolveGlobalMap, L as normalizeLowercaseStringOrEmpty, R as normalizeNullableString, W as resolveGlobalSingleton, a as resolveStateDir } from "./path-guards-quCEQx1i.mjs";
import { a as migrateSqliteSchemaToStrict, n as runOpenClawStateWriteTransaction, t as openOpenClawStateDatabase } from "./openclaw-state-db-kPhNg45U.mjs";
import { t as SqliteWorkerError } from "./sqlite-worker-error-Q7g0aE9t.mjs";
import { a as hasRegisteredSecretValuesForRedaction, o as redactRegisteredSecretValues, s as registerSecretValueForRedaction } from "./redact-BRF0hr6G.mjs";
import { l as normalizeUniqueStringEntries } from "./string-normalization-BMFMScZY.mjs";
import { o as registerSignalExitBarrier } from "./subsystem-CeOCPr4l.mjs";
import { t as collectSynchronousErrors } from "./error-graph-internal-G5_kmB_7.mjs";
import { n as getPluginExecutionFrame } from "./plugin-instance-invocation-DLc0_aJ8.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { a as registerListener, n as isPostgresSqlConnection } from "./sql-connection-VmV9pnJI.mjs";
import { i as executeWithCachedStatement } from "./kysely-sync-cache-state-D75yJYFp.mjs";
import { o as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-5PCLNGIM.mjs";
import { S as getNodeSqliteKysely, b as executeSqliteQuerySync, v as compileSqliteQueryBindings, x as executeSqliteQueryTakeFirstSync } from "./openclaw-state-db-schema-helpers-Bn-sHIhd.mjs";
import { _ as publishSqliteDatabaseAdmission, o as getSqliteDatabaseAdmission } from "./sqlite-database-admission-DMm34jqt.mjs";
import { t as openNodeSqliteDatabase } from "./node-sqlite-DrCtoYsd.mjs";
import { t as sha256Hex } from "./node-crypto-CWAQhBWK.mjs";
import "./gateway-process-argv-DB5Y-Mad.mjs";
import { Et as resolveSqliteDatabaseFilePaths, dt as registerSqliteCacheExitClose, g as registerOpenClawStateDatabaseLifecycleListener, h as registerOpenClawStateDatabaseAsyncResource, lt as configureSqliteConnectionPragmas, y as retainOpenClawStateDatabaseForIdle } from "./openclaw-state-db-cache-D7C7Hg5y.mjs";
import { s as getOpenClawDatabaseMaintenanceScope } from "./openclaw-state-db-async-lifecycle-DLH47xBr.mjs";
import { a as runSqliteImmediateTransactionSync } from "./sqlite-transaction-DYxlAnZ2.mjs";
import { d as object, i as boolean, m as string, n as _undefined, o as discriminatedUnion, s as literal, t as _enum, u as number } from "./schemas-DA6xYxQu.mjs";
import { g as applyPrivateModeSync } from "./gateway-state-owner-CW5kvbov.mjs";
import "./sqlite-worker-operation-admission-DjndFB3C.mjs";
import { r as reserveSqliteWorkerInputPreparation, t as createOpenClawStateWorkerLease } from "./openclaw-state-worker-store-CpJWs6Nu.mjs";
import { n as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-GPo8ZZmA.mjs";
import { t as getPluginRegistryState } from "./runtime-state-wvrNT8EC.mjs";
import { t as isHeadersLike } from "./fetch-headers-r34WWC5V.mjs";
import { n as withResponseBodyTimeout } from "./http-response-body-timeout-D-i9t_LZ.mjs";
import process$1 from "node:process";
import { request } from "node:http";
import { AsyncLocalStorage } from "node:async_hooks";
import fsSync, { writeSync } from "node:fs";
import path from "node:path";
import { URL as URL$1 } from "node:url";
import { randomUUID } from "node:crypto";
import { isUtf8 } from "node:buffer";
import { expressionBuilder, sql } from "kysely";
import { serialize } from "node:v8";
import { StringDecoder } from "node:string_decoder";
import "@openclaw/proxyline";
import { gunzipSync, gzipSync } from "node:zlib";
//#region src/plugins/sdk-deprecation-usage.ts
const usage = resolveGlobalMap(Symbol.for("openclaw.pluginSdkDeprecationUsage"));
function recordPluginSdkDeprecationUsage(e, t, n, r, i) {
	let a = usage.get(e);
	if (!a) {
		a = /* @__PURE__ */ new Map();
		usage.set(e, a);
	}
	if (!a.has(t)) a.set(t, {
		id: t,
		displayName: n,
		replacement: r,
		...i ? { removeAfter: i } : {}
	});
}
//#endregion
//#region src/plugins/sdk-deprecation.ts
const warned = resolveGlobalSingleton(Symbol.for("openclaw.pluginSdkDeprecations"), () => /* @__PURE__ */ new Set());
const sqliteRemovalFamilies = /* @__PURE__ */ new Set([
	"acp-session",
	"agent-end-side-effects",
	"agent-harness-host",
	"agent-harness-session-runtime-ownership",
	"agent-harness-tool-surface",
	"approval-event-publication",
	"approval-session-routing",
	"auth-profile-sync-operations",
	"auth-profiles",
	"channel-conversation-bindings",
	"channel-inbound-envelope",
	"channel-pairing-sync-allowlist",
	"codex-session-context",
	"command-authorization-sync",
	"conversation-bindings",
	"cron-store-path",
	"exec-approvals-sync-read",
	"github-publication",
	"memory-session",
	"memory-session-sync-inventory",
	"memory-status",
	"model-account-connect",
	"model-registry-native-read",
	"native-command-menu",
	"native-session-binding",
	"native-session-deletion",
	"node-host-sync-workspace",
	"openrouter-model-capabilities",
	"plugin-state-keyed-store",
	"provider-auth",
	"provider-selection",
	"provider-sync-configuration",
	"proxy-capture-reader",
	"proxy-capture-runtime",
	"proxy-capture-store",
	"reply-run-start",
	"reply-tool-authority-sync-preparation",
	"reply-visibility",
	"runtime-config",
	"session-catalog-identity",
	"session-catalog-title",
	"session-conversation",
	"session-deletion-transaction-callback",
	"session-entry-freshness",
	"session-input-completion",
	"session-model-override",
	"session-observer",
	"session-persistence",
	"session-store",
	"session-transcript",
	"session-transcript-key",
	"session-transcript-store",
	"session-upstream-links",
	"skill-command-discovery",
	"sqlite-runtime-native-access",
	"tool-surface",
	"tts",
	"watched-sessions-prompt",
	"watched-sessions-sync-harness-context",
	"web-search-providers"
]);
/** Call only at a legacy operation, with static capability and migration descriptions. */
function warnPluginSdkDeprecation(e) {
	const t = getPluginExecutionFrame();
	const n = e.pluginId ?? t?.invocation?.instance.pluginId ?? getPluginRegistryState()?.registrationContext?.pluginId ?? t?.runtimePluginId;
	const r = n && n.length <= 128 && /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/iu.test(n) ? n : void 0;
	const i = sqliteRemovalFamilies.has(e.family) ? "2026-12-31" : void 0;
	const a = JSON.stringify([
		r ?? null,
		e.family,
		...i ? [e.method] : []
	]);
	if (r) recordPluginSdkDeprecationUsage(r, `${e.family}:${e.method}`, e.method, e.replacement, i);
	if (warned.has(a)) return;
	warned.add(a);
	const o = i ? "Final compatibility day: 2026-12-31. Removal ships in the first January 2027 stable release; no SDK major is required." : "Removal requires an announced ordinary stable release window.";
	process.emitWarning(`${r ? `Plugin ${r}` : "Plugin SDK"}: ${e.method} is deprecated; use ${e.replacement} instead. ${e.compatibility ?? "The legacy contract remains supported during its deprecation period."} ${o}`, {
		code: e.code ?? "DEP_PLUGIN_SDK",
		type: "DeprecationWarning"
	});
}
//#endregion
//#region src/proxy-capture/env.ts
function resolveDebugProxyRootDir(e = process$1.env) {
	return path.join(resolveStateDir(e), "debug-proxy");
}
function resolveDebugProxyCertDir(e = process$1.env) {
	return path.join(resolveDebugProxyRootDir(e), "certs");
}
const OPENCLAW_DEBUG_PROXY_ENABLED = "OPENCLAW_DEBUG_PROXY_ENABLED";
const OPENCLAW_DEBUG_PROXY_URL = "OPENCLAW_DEBUG_PROXY_URL";
const OPENCLAW_DEBUG_PROXY_CERT_DIR = "OPENCLAW_DEBUG_PROXY_CERT_DIR";
const OPENCLAW_DEBUG_PROXY_SESSION_ID = "OPENCLAW_DEBUG_PROXY_SESSION_ID";
const OPENCLAW_DEBUG_PROXY_REQUIRE = "OPENCLAW_DEBUG_PROXY_REQUIRE";
const DEBUG_PROXY_CHILD_CAPTURE_USERNAME = "openclaw-capture";
function readDebugProxyChildEndpoint(e = process$1.env) {
	const t = URL.parse(e[OPENCLAW_DEBUG_PROXY_URL]?.trim() ?? "");
	return t?.username === "openclaw-capture" ? t : void 0;
}
let cachedImplicitSessionId;
function isTruthy(e) {
	return e === "1" || e === "true" || e === "yes" || e === "on";
}
function resolveDebugProxySettings(e = process$1.env) {
	const t = isTruthy(e[OPENCLAW_DEBUG_PROXY_ENABLED]);
	const n = e[OPENCLAW_DEBUG_PROXY_SESSION_ID]?.trim() || void 0;
	const r = readDebugProxyChildEndpoint(e);
	const i = n ?? (cachedImplicitSessionId ??= randomUUID());
	return {
		enabled: t,
		required: isTruthy(e[OPENCLAW_DEBUG_PROXY_REQUIRE]),
		proxyUrl: r?.origin ?? (e[OPENCLAW_DEBUG_PROXY_URL]?.trim() || void 0),
		dbPath: path.join(resolveDebugProxyRootDir(e), "capture.sqlite"),
		blobDir: path.join(resolveDebugProxyRootDir(e), "blobs"),
		certDir: e[OPENCLAW_DEBUG_PROXY_CERT_DIR]?.trim() || resolveDebugProxyCertDir(e),
		sessionId: i,
		sourceProcess: "openclaw"
	};
}
function resolveEnabledDebugProxySettings(e) {
	if (!(e?.enabled ?? isTruthy(process$1.env[OPENCLAW_DEBUG_PROXY_ENABLED]))) return;
	return e ?? resolveDebugProxySettings();
}
//#endregion
//#region src/secrets/model-provider-header-policy.ts
/** Classifies model-provider request headers that should be treated as credential material. */
const SENSITIVE_MODEL_PROVIDER_HEADER_NAME_FRAGMENTS = [
	"api-key",
	"apikey",
	"token",
	"secret",
	"password",
	"credential"
];
/**
* Returns whether a model-provider header name should be treated as secret-bearing.
* This is intentionally conservative: false positives are audit noise, false negatives leak keys.
*/
function isLikelySensitiveModelProviderHeaderName(e) {
	const t = normalizeLowercaseStringOrEmpty(e);
	return t === "authorization" || t === "proxy-authorization" || SENSITIVE_MODEL_PROVIDER_HEADER_NAME_FRAGMENTS.some((e) => t.includes(e));
}
//#endregion
//#region src/proxy-capture/header-redaction.ts
const REDACTED_CAPTURE_HEADER_VALUE = "[REDACTED]";
function isSensitiveCaptureHeaderName(e) {
	const t = e.trim().toLowerCase();
	return isLikelySensitiveModelProviderHeaderName(t) || t === "cookie" || t === "set-cookie" || t.includes("session");
}
function redactedCaptureHeaders(e, t) {
	if (!e) return;
	const n = new Set([...t ?? []].map((e) => e.trim().toLowerCase()));
	const r = isHeadersLike(e) ? Array.from(e.entries()) : Object.entries(e);
	const i = {};
	for (const [e, t] of r) {
		if (n.has(e.trim().toLowerCase()) || isSensitiveCaptureHeaderName(e)) {
			i[e] = REDACTED_CAPTURE_HEADER_VALUE;
			continue;
		}
		const r = Array.isArray(t) ? t.join(", ") : t ?? "";
		i[e] = redactRegisteredSecretValues(r, () => REDACTED_CAPTURE_HEADER_VALUE);
	}
	return i;
}
//#endregion
//#region src/proxy-capture/runtime-deferral.ts
const captureDeferral = new AsyncLocalStorage();
function isDebugProxyCaptureDeferred() {
	const e = captureDeferral.getStore();
	return e !== void 0 && e.phase !== "released";
}
//#endregion
//#region src/proxy-capture/cli-contract.ts
const text = string();
const event = object({
	sessionId: text.min(1),
	ts: number().finite(),
	sourceScope: literal("openclaw"),
	sourceProcess: text,
	protocol: _enum([
		"http",
		"https",
		"sse",
		"ws",
		"wss",
		"connect"
	]),
	direction: _enum([
		"outbound",
		"inbound",
		"local"
	]),
	kind: _enum([
		"connect",
		"tls-handshake",
		"request",
		"response",
		"ws-open",
		"ws-frame",
		"ws-close",
		"error",
		"retry-link"
	]),
	flowId: text,
	method: text.optional(),
	host: text.optional(),
	path: text.optional(),
	status: number().optional(),
	closeCode: number().optional(),
	contentType: text.optional(),
	headersJson: text.optional(),
	dataText: text.optional(),
	dataBlobId: text.optional(),
	dataSha256: text.optional(),
	errorText: text.optional(),
	metaJson: text.optional()
}).strict();
const debugProxyCaptureWriteCommandSchema = discriminatedUnion("type", [
	object({
		type: literal("capture.upsertSession"),
		input: object({
			id: text.min(1),
			startedAt: number().finite(),
			endedAt: number().finite().optional(),
			mode: text,
			sourceScope: literal("openclaw"),
			sourceProcess: text,
			proxyUrl: text.optional()
		}).strict()
	}).strict(),
	object({
		type: literal("capture.endSession"),
		input: object({
			sessionId: text.min(1),
			endedAt: number().finite()
		}).strict()
	}).strict(),
	object({
		type: literal("capture.recordEvent"),
		input: event
	}).strict(),
	object({
		type: literal("capture.recordEventWithPayload"),
		input: object({
			event,
			payload: object({
				data: text.nullable().optional(),
				base64: boolean().optional(),
				contentType: text.optional(),
				previewLimit: number().int().nonnegative().optional()
			}).strict().transform(({ data: e, base64: t, ...n }) => ({
				...n,
				data: t && e != null ? Buffer.from(e, "base64") : e
			}))
		}).strict()
	}).strict()
]);
const captureQueryPresetSchema = _enum([
	"double-sends",
	"retry-storms",
	"cache-busting",
	"ws-duplicate-frames",
	"missing-ack",
	"error-bursts"
]);
const debugProxyCliCommandSchema = discriminatedUnion("type", [
	...debugProxyCaptureWriteCommandSchema.options,
	object({
		type: literal("capture.listSessions"),
		input: object({ limit: number().int().positive().optional() }).strict()
	}).strict(),
	object({
		type: literal("capture.readBlob"),
		input: object({ blobId: text.min(1) }).strict()
	}).strict(),
	object({
		type: literal("capture.queryPreset"),
		input: object({
			preset: captureQueryPresetSchema,
			sessionId: text.optional()
		}).strict()
	}).strict(),
	object({
		type: literal("capture.purgeAll"),
		input: _undefined().optional()
	}).strict()
]);
function encodeDebugProxyPayload(e) {
	return {
		...e,
		...Buffer.isBuffer(e.data) ? {
			data: e.data.toString("base64"),
			base64: true
		} : {}
	};
}
//#endregion
//#region src/proxy-capture/store-lifecycle.ts
const finalizers$1 = /* @__PURE__ */ new WeakMap();
const closed = /* @__PURE__ */ new WeakSet();
function registerCaptureStoreFinalizer(e, t) {
	if (closed.has(e)) throw new Error("Capture store is already finalized.");
	let n = finalizers$1.get(e);
	if (!n) {
		n = /* @__PURE__ */ new Set();
		finalizers$1.set(e, n);
	}
	return registerListener(n, t);
}
function finalizeCaptureStore(e) {
	if (closed.has(e)) return;
	closed.add(e);
	const t = finalizers$1.get(e);
	finalizers$1.delete(e);
	const n = collectSynchronousErrors(t ?? [], (e) => e());
	if (n.length) throw new AggregateError(n, "Capture store finalization failed.");
}
const asyncFinalizers = /* @__PURE__ */ new WeakMap();
const asyncFinalizations = /* @__PURE__ */ new WeakMap();
function registerAsyncCaptureStoreFinalizer(e, t) {
	if (closed.has(e)) throw new Error("Capture store is already finalized.");
	let n = asyncFinalizers.get(e);
	if (!n) {
		n = /* @__PURE__ */ new Set();
		asyncFinalizers.set(e, n);
	}
	n.add(t);
	return () => n.delete(t);
}
function finalizeCaptureStoreAsync(e, t) {
	const n = asyncFinalizations.get(e);
	if (n) return n;
	if (closed.has(e)) return Promise.resolve();
	const r = createDeferredCore();
	asyncFinalizations.set(e, r.promise);
	closed.add(e);
	const i = [...finalizers$1.get(e) ?? [], ...asyncFinalizers.get(e) ?? []];
	finalizers$1.delete(e);
	asyncFinalizers.delete(e);
	const a = [];
	const o = collectSynchronousErrors(i, (e) => {
		a.push(Promise.resolve(e(t)));
	});
	Promise.allSettled(a).then((e) => {
		for (const t of e) if (t.status === "rejected") o.push(t.reason);
		if (o.length) r.reject(new AggregateError(o, "Capture store finalization failed."));
		else r.resolve();
	});
	r.promise.catch(() => void 0);
	return r.promise;
}
//#endregion
//#region src/proxy-capture/child-transport.ts
const DEBUG_PROXY_CHILD_CAPTURE_PATH = "/.openclaw/debug-proxy-capture";
/** A child forwards only its capture writes to the parent's already-selected state owner. */
function createDebugProxyChildCaptureStore(e) {
	const t = readDebugProxyChildEndpoint();
	if (!t) return;
	const n = decodeURIComponent(t.password);
	if (!n) throw new Error("Parent debug proxy capture credentials are missing or invalid; no local fallback was attempted");
	if (!e.proxyUrl) throw new Error("Debug proxy child capture requires its parent proxy URL");
	const r = new URL(DEBUG_PROXY_CHILD_CAPTURE_PATH, e.proxyUrl);
	if (r.protocol !== "http:") throw new Error("Debug proxy child capture requires an HTTP parent listener");
	registerSecretValueForRedaction(n);
	let i = false;
	let a = false;
	let o;
	let s = Promise.resolve();
	const send = (e) => {
		const t = JSON.stringify(e);
		const i = s.then(() => new Promise((e, i) => {
			const a = request(r, {
				method: "POST",
				agent: false,
				headers: {
					authorization: `Bearer ${n}`,
					"content-type": "application/json",
					"content-length": Buffer.byteLength(t)
				}
			}, (t) => {
				t.resume();
				t.once("error", i);
				t.once("end", () => t.statusCode === 204 ? e() : i(/* @__PURE__ */ new Error(`Parent debug proxy refused capture (HTTP ${t.statusCode})`)));
			});
			a.once("error", i);
			a.setTimeout(6e5, () => a.destroy(/* @__PURE__ */ new Error("Parent debug proxy capture outcome is unknown; no retry was attempted")));
			a.end(t);
		}));
		s = i.catch(() => void 0);
		return i;
	};
	const writer = (e) => {
		const execute = (t) => {
			e();
			return send(t);
		};
		return {
			get isClosed() {
				return i;
			},
			upsertSession: (e) => execute({
				type: "capture.upsertSession",
				input: e
			}),
			endSession: (e, t = Date.now()) => execute({
				type: "capture.endSession",
				input: {
					sessionId: e,
					endedAt: t
				}
			}),
			recordEvent: (e) => execute({
				type: "capture.recordEvent",
				input: e
			}),
			recordEventWithPayload: (e, t) => execute({
				type: "capture.recordEventWithPayload",
				input: {
					event: e,
					payload: encodeDebugProxyPayload(t)
				}
			}),
			close: () => {
				a = true;
				o ??= (async () => {
					try {
						await finalizeCaptureStoreAsync(c, writer(() => {
							if (i) throw new Error("Debug proxy child capture is closed");
						}));
					} finally {
						await s;
						i = true;
					}
				})();
				return o;
			}
		};
	};
	const assertOpen = () => {
		if (i || a) throw new Error("Debug proxy child capture is closed");
	};
	const c = writer(assertOpen);
	return {
		store: c,
		ready: Promise.resolve(),
		release: () => c.close(),
		async runOperation(e) {
			assertOpen();
			let t = true;
			try {
				return await e(writer(() => {
					if (!t || i) throw new Error("Debug proxy child capture operation has settled");
				}));
			} finally {
				t = false;
			}
		}
	};
}
//#endregion
//#region src/proxy-capture/runtime-cleanup.ts
const finalizers = /* @__PURE__ */ new Set();
function registerActiveDebugProxyCapture(e) {
	finalizers.add(e);
	const t = registerSignalExitBarrier(e);
	return () => {
		finalizers.delete(e);
		t();
	};
}
//#endregion
//#region src/proxy-capture/store.async.ts
function createDebugProxyCaptureStoreForContext(e) {
	let t = false;
	let n = false;
	let r;
	let i;
	const retire = async () => {
		t = true;
		try {
			await i.retire();
		} finally {
			a();
			o();
		}
	};
	const a = registerOpenClawStateDatabaseAsyncResource({
		admission: e.admission,
		close: retire
	});
	const o = registerOpenClawStateDatabaseLifecycleListener((t) => {
		if (t.kind !== "opened" && t.identity?.key === e.admission.identity.key) retire().catch(() => void 0);
	});
	const executePublic = (e) => {
		const r = t || n ? Promise.reject(new SqliteWorkerError("Capture store is closed", "closed")) : i.execute(e);
		r.catch(() => void 0);
		return r;
	};
	const createStore = (a) => ({
		dbPath: e.admission.databasePath,
		get isClosed() {
			if (t) return true;
			try {
				e.admission.assertCurrent();
				return false;
			} catch {
				return true;
			}
		},
		upsertSession: (e) => a({
			type: "capture.upsertSession",
			input: { ...e }
		}),
		endSession: (e, t = Date.now()) => a({
			type: "capture.endSession",
			input: {
				sessionId: e,
				endedAt: t
			}
		}),
		persistPayload: (e, t) => a({
			type: "capture.persistPayload",
			input: {
				data: Buffer.from(e),
				contentType: t
			}
		}),
		recordEvent: (e) => a({
			type: "capture.recordEvent",
			input: { ...e }
		}),
		recordEventWithPayload: (e, t) => a({
			type: "capture.recordEventWithPayload",
			input: {
				event: { ...e },
				payload: {
					...t,
					data: Buffer.isBuffer(t.data) ? Buffer.from(t.data) : t.data
				}
			}
		}),
		listSessions: (e) => a({
			type: "capture.listSessions",
			input: { limit: e }
		}),
		getSessionEvents: (e, t) => a({
			type: "capture.getSessionEvents",
			input: {
				sessionId: e,
				limit: t
			}
		}),
		summarizeSessionCoverage: (e) => a({
			type: "capture.summarizeSessionCoverage",
			input: { sessionId: e }
		}),
		readBlob: (e) => a({
			type: "capture.readBlob",
			input: { blobId: e }
		}),
		queryPreset: (e, t) => a({
			type: "capture.queryPreset",
			input: {
				preset: e,
				sessionId: t
			}
		}),
		deleteSessions: (e) => a({
			type: "capture.deleteSessions",
			input: { sessionIds: [...e] }
		}),
		purgeAll: () => a({
			type: "capture.purgeAll",
			input: void 0
		}),
		close: () => {
			n = true;
			return r ??= i.release();
		}
	});
	const s = createStore(executePublic);
	try {
		i = createOpenClawStateWorkerLease(e, async (e) => {
			n = true;
			try {
				await finalizeCaptureStoreAsync(s, createStore(e.execute));
			} finally {
				t = true;
				a();
				o();
			}
		});
	} catch (e) {
		a();
		o();
		throw e;
	}
	const c = i.ready.then(() => {
		e.admission.assertCurrent();
		if (t) throw new SqliteWorkerError("Capture store is closed", "closed");
	});
	c.catch(() => {
		a();
		o();
	});
	return {
		store: s,
		ready: c,
		runOperation: (e) => i.runOperation((t) => e(createStore(t.execute))),
		release: () => s.close()
	};
}
//#endregion
//#region src/infra/database-engine/scalar.ts
/**
* Scalar minimum for non-NULL numeric operands. SQLite min propagates any NULL;
* PostgreSQL least ignores NULLs. Coalesce nullable operands explicitly.
* Include a SQL-typed numeric operand so PostgreSQL can infer bound values' type.
*/
function engineLeast(e, t) {
	return expressionBuilder().fn(isPostgresSqlConnection(e) ? "least" : "min", t);
}
//#endregion
//#region src/proxy-capture/store-readonly.ts
function listDebugProxyCaptureSessions(e, t = 50) {
	const n = getNodeSqliteKysely(e);
	const r = n.selectFrom("capture_sessions").select([
		"id",
		"started_at",
		"ended_at",
		"mode",
		"source_process",
		"proxy_url"
	]).groupBy("id").orderBy("started_at", "desc").limit(t).as("s");
	const i = n.selectFrom(r).select([
		"s.id",
		"s.started_at as startedAt",
		"s.ended_at as endedAt",
		"s.mode",
		"s.source_process as sourceProcess",
		"s.proxy_url as proxyUrl"
	]).select((e) => e.selectFrom("capture_events as e").select((e) => e.fn.count("e.id").as("count")).whereRef("e.session_id", "=", "s.id").as("eventCount")).orderBy("s.started_at", "desc");
	const { compiled: a, bind: o } = compileSqliteQueryBindings(() => i);
	return e.prepare(a.sql).all(...o(void 0));
}
function findDebugProxyCaptureBlobReference(e, t) {
	const n = getNodeSqliteKysely(e).selectFrom("capture_events").select("data_blob_id as blobId").where("data_blob_id", "=", t).limit(1);
	const { compiled: r, bind: i } = compileSqliteQueryBindings(() => n);
	return e.prepare(r.sql).get(...i(void 0))?.blobId || null;
}
function queryDebugProxyCapturePreset(e, t, n) {
	const r = getNodeSqliteKysely(e);
	let i = r.selectFrom("capture_events");
	if (n) i = i.where("session_id", "=", n);
	const a = i.select(["host", "path"]);
	const o = r.fn.countAll();
	let s;
	switch (t) {
		case "double-sends":
			s = a.select(["method", o.as("duplicateCount")]).where("kind", "=", "request").groupBy([
				"host",
				"path",
				"method",
				"data_sha256"
			]).having(o, ">", 1).orderBy("duplicateCount", "desc").orderBy("host", (e) => e.asc().nullsFirst());
			break;
		case "retry-storms":
			s = a.select(o.as("errorCount")).where("kind", "=", "response").where("status", ">=", 429).groupBy(["host", "path"]).having(o, ">", 1).orderBy("errorCount", "desc").orderBy("host", (e) => e.asc().nullsFirst());
			break;
		case "cache-busting":
			s = a.select(o.as("variantCount")).where("kind", "=", "request").where((e) => e.or([
				e("path", "like", "%?%"),
				e("headers_json", "like", "%cache-control%"),
				e("headers_json", "like", "%pragma%")
			])).groupBy(["host", "path"]).orderBy("variantCount", "desc").orderBy("host", (e) => e.asc().nullsFirst());
			break;
		case "ws-duplicate-frames":
			s = a.select(o.as("duplicateFrames")).where("kind", "=", "ws-frame").where("direction", "=", "outbound").groupBy([
				"host",
				"path",
				"data_sha256"
			]).having(o, ">", 1).orderBy("duplicateFrames", "desc").orderBy("host", (e) => e.asc().nullsFirst());
			break;
		case "missing-ack":
			s = i.select([
				"flow_id as flowId",
				"host",
				"path",
				o.as("outboundFrames")
			]).where("kind", "=", "ws-frame").where("direction", "=", "outbound").where("flow_id", "not in", i.select("flow_id").where("kind", "=", "ws-frame").where("direction", "=", "inbound")).groupBy([
				"flow_id",
				"host",
				"path"
			]).orderBy("outboundFrames", "desc");
			break;
		case "error-bursts":
			s = a.select(o.as("errorCount")).where("kind", "=", "error").groupBy(["host", "path"]).orderBy("errorCount", "desc").orderBy("host", (e) => e.asc().nullsFirst());
			break;
		default: return [];
	}
	const { compiled: c, bind: l } = compileSqliteQueryBindings(() => s);
	return e.prepare(c.sql).all(...l(void 0));
}
function readDebugProxyCaptureSessionEvents(e, t, n = 500) {
	return executeSqliteQuerySync(e, getNodeSqliteKysely(e).selectFrom("capture_events").select([
		"id",
		"session_id as sessionId",
		"ts",
		"source_scope as sourceScope",
		"source_process as sourceProcess",
		"protocol",
		"direction",
		"kind",
		"flow_id as flowId",
		"method",
		"host",
		"path",
		"status",
		"close_code as closeCode",
		"content_type as contentType",
		"headers_json as headersJson",
		"data_text as dataText",
		"data_blob_id as dataBlobId",
		"data_sha256 as dataSha256",
		"error_text as errorText",
		"meta_json as metaJson"
	]).where("session_id", "=", t).orderBy("ts", "desc").orderBy("id", "desc").limit(n)).rows;
}
function parseMetaJson(e) {
	if (typeof e !== "string" || e.trim().length === 0) return null;
	try {
		const t = JSON.parse(e);
		return t && typeof t === "object" ? t : null;
	} catch {
		return null;
	}
}
function sortObservedCounts(e) {
	return [...e.entries()].map(([e, t]) => ({
		value: e,
		count: t
	})).toSorted((e, t) => t.count - e.count || e.value.localeCompare(t.value));
}
function summarizeDebugProxyCaptureSessionCoverage(e, t) {
	const { compiled: n, bind: r } = compileSqliteQueryBindings((t) => getNodeSqliteKysely(e).selectFrom("capture_events").select(["host", "meta_json as metaJson"]).where("session_id", "=", t((e) => e)));
	const i = e.prepare(n.sql).iterate(...r(t));
	const a = /* @__PURE__ */ new Map();
	const o = /* @__PURE__ */ new Map();
	const s = /* @__PURE__ */ new Map();
	const c = /* @__PURE__ */ new Map();
	const l = /* @__PURE__ */ new Map();
	let u = 0;
	let d = 0;
	try {
		for (const e of i) {
			u += 1;
			const t = parseMetaJson(e.metaJson);
			const n = normalizeNullableString(t?.provider);
			const r = normalizeNullableString(t?.api);
			const i = normalizeNullableString(t?.model);
			const f = normalizeNullableString(e.host);
			if (!n && !r && !i) d += 1;
			if (n) a.set(n, (a.get(n) ?? 0) + 1);
			if (r) o.set(r, (o.get(r) ?? 0) + 1);
			if (i) s.set(i, (s.get(i) ?? 0) + 1);
			if (f) {
				c.set(f, (c.get(f) ?? 0) + 1);
				if (f.startsWith("127.0.0.1:") || f.startsWith("localhost:")) l.set(f, (l.get(f) ?? 0) + 1);
			}
		}
	} catch (e) {
		try {
			i.return?.();
		} catch {}
		throw e;
	}
	return {
		sessionId: t,
		totalEvents: u,
		unlabeledEventCount: d,
		providers: sortObservedCounts(a),
		apis: sortObservedCounts(o),
		models: sortObservedCounts(s),
		hosts: sortObservedCounts(c),
		localPeers: sortObservedCounts(l)
	};
}
function readDebugProxyCaptureBlob(e, t) {
	const n = executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("capture_blobs").select(["encoding", "data"]).where("blob_id", "=", t));
	if (!n?.data) return null;
	const r = Buffer.from(n.data);
	return (n.encoding === "gzip" ? gunzipSync(r) : r).toString("utf8");
}
//#endregion
//#region src/proxy-capture/store.kernel.ts
const DEBUG_PROXY_CAPTURE_DIR_MODE = 448;
const DEBUG_PROXY_CAPTURE_FILE_MODE = 384;
var DebugProxyCaptureKernel = class {
	constructor(e) {
		this.db = e.db;
		this.dbPath = e.dbPath;
		this.blobDir = e.blobDir;
		this.capturePathBased = e.pathBased;
		this.runWrite = e.runWrite;
	}
	upsertSession(e) {
		const t = this.capturePathBased;
		const { compiled: n, bind: r } = compileSqliteQueryBindings((e) => {
			const n = {
				id: e((e) => e.id),
				started_at: e((e) => e.startedAt),
				ended_at: e((e) => e.endedAt ?? null),
				mode: e((e) => e.mode),
				source_scope: e((e) => e.sourceScope),
				source_process: e((e) => e.sourceProcess),
				proxy_url: e((e) => e.proxyUrl ?? null)
			};
			if (t) return getNodeSqliteKysely(this.db).insertInto("capture_sessions").values({
				...n,
				db_path: e((e) => e.dbPath ?? this.dbPath),
				blob_dir: e((e) => e.blobDir ?? t.blobDir)
			}).onConflict((e) => e.column("id").doUpdateSet((e) => ({
				ended_at: e.ref("excluded.ended_at"),
				proxy_url: e.ref("excluded.proxy_url"),
				source_process: e.ref("excluded.source_process")
			})));
			return getNodeSqliteKysely(this.db).insertInto("capture_sessions").values(n).onConflict((e) => e.column("id").doUpdateSet((e) => ({
				started_at: engineLeast(this.db, [e.ref("capture_sessions.started_at"), e.ref("excluded.started_at")]),
				ended_at: e.ref("excluded.ended_at"),
				mode: e.case().when("capture_sessions.mode", "=", "implicit").then(e.ref("excluded.mode")).else(e.ref("capture_sessions.mode")).end(),
				proxy_url: e.ref("excluded.proxy_url"),
				source_process: e.ref("excluded.source_process")
			})));
		});
		const upsert = () => {
			const t = r(e);
			return executeWithCachedStatement(this.db, n.sql, t, (e) => e.run(...t));
		};
		if (t) {
			upsert();
			return;
		}
		this.runWrite(upsert);
	}
	endSession(e, t = Date.now()) {
		const { compiled: n, bind: r } = compileSqliteQueryBindings(() => getNodeSqliteKysely(this.db).updateTable("capture_sessions").set({ ended_at: t }).where("id", "=", e));
		const update = () => {
			const e = r();
			return executeWithCachedStatement(this.db, n.sql, e, (t) => t.run(...e));
		};
		if (this.capturePathBased) {
			update();
			return;
		}
		this.runWrite(update);
	}
	persistPayload(e, t) {
		const n = sha256Hex(e);
		const r = n.slice(0, 24);
		if (this.capturePathBased) {
			fsSync.mkdirSync(this.capturePathBased.blobDir, {
				recursive: true,
				mode: 448
			});
			const i = path.join(this.capturePathBased.blobDir, `${r}.bin.gz`);
			if (!fsSync.existsSync(i)) fsSync.writeFileSync(i, gzipSync(e), { mode: 384 });
			applyPrivateModeSync(i, 384);
			return {
				blobId: r,
				path: i,
				encoding: "gzip",
				sizeBytes: e.byteLength,
				sha256: n,
				...t ? { contentType: t } : {}
			};
		}
		const { compiled: i, bind: a } = compileSqliteQueryBindings((e) => getNodeSqliteKysely(this.db).insertInto("capture_blobs").values({
			blob_id: r,
			content_type: t ?? null,
			encoding: "gzip",
			size_bytes: e((e) => e.byteLength),
			sha256: n,
			data: e((e) => gzipSync(e)),
			created_at: e(() => Date.now())
		}).onConflict((e) => e.column("blob_id").doNothing()));
		this.runWrite(() => executeWithCachedStatement(this.db, i.sql, [
			e,
			t ?? null,
			r,
			n
		], (t) => t.run(...a(e))));
		return {
			blobId: r,
			encoding: "gzip",
			sizeBytes: e.byteLength,
			sha256: n,
			...t ? { contentType: t } : {}
		};
	}
	recordEvent(e) {
		if (this.capturePathBased) {
			this.insertEvent(e, e.dataBlobId ?? null);
			return;
		}
		this.runWrite(() => {
			const t = compileSqliteQueryBindings((e) => getNodeSqliteKysely(this.db).insertInto("capture_sessions").values({
				id: e((e) => e.sessionId),
				started_at: e((e) => e.ts),
				mode: "implicit",
				source_scope: e((e) => e.sourceScope),
				source_process: e((e) => e.sourceProcess)
			}).onConflict((e) => e.column("id").doNothing()));
			const n = t.bind(e);
			executeWithCachedStatement(this.db, t.compiled.sql, n, (e) => e.run(...n));
			let r = null;
			if (e.dataBlobId) {
				const t = compileSqliteQueryBindings((e) => getNodeSqliteKysely(this.db).selectFrom("capture_blobs").select((e) => e.lit(1).as("present")).where("blob_id", "=", e((e) => e)));
				const n = t.bind(e.dataBlobId);
				r = executeWithCachedStatement(this.db, t.compiled.sql, n, (e) => e.get(...n)) ? e.dataBlobId : null;
			}
			this.insertEvent(e, r);
		});
	}
	insertEvent(e, t) {
		const { compiled: n, bind: r } = compileSqliteQueryBindings((e) => getNodeSqliteKysely(this.db).insertInto("capture_events").values({
			session_id: e((e) => e.sessionId),
			ts: e((e) => e.ts),
			source_scope: e((e) => e.sourceScope),
			source_process: e((e) => e.sourceProcess),
			protocol: e((e) => e.protocol),
			direction: e((e) => e.direction),
			kind: e((e) => e.kind),
			flow_id: e((e) => e.flowId),
			method: e((e) => e.method ?? null),
			host: e((e) => e.host ?? null),
			path: e((e) => e.path ?? null),
			status: e((e) => e.status ?? null),
			close_code: e((e) => e.closeCode ?? null),
			content_type: e((e) => e.contentType ?? null),
			headers_json: e((e) => e.headersJson ?? null),
			data_text: e((e) => e.dataText ?? null),
			data_blob_id: t,
			data_sha256: e((e) => e.dataSha256 ?? null),
			error_text: e((e) => e.errorText ?? null),
			meta_json: e((e) => e.metaJson ?? null)
		}));
		const i = r(e);
		executeWithCachedStatement(this.db, n.sql, i, (e) => e.run(...i));
	}
	listSessions(e = 50) {
		return listDebugProxyCaptureSessions(this.db, e);
	}
	getSessionEvents(e, t = 500) {
		return readDebugProxyCaptureSessionEvents(this.db, e, t);
	}
	summarizeSessionCoverage(e) {
		return summarizeDebugProxyCaptureSessionCoverage(this.db, e);
	}
	readBlob(e) {
		if (this.capturePathBased) {
			const t = findDebugProxyCaptureBlobReference(this.db, e);
			if (!t) return null;
			const n = path.join(this.capturePathBased.blobDir, `${t}.bin.gz`);
			return fsSync.existsSync(n) ? gunzipSync(fsSync.readFileSync(n)).toString("utf8") : null;
		}
		return readDebugProxyCaptureBlob(this.db, e);
	}
	queryPreset(e, t) {
		return queryDebugProxyCapturePreset(this.db, e, t);
	}
	purgeAll() {
		const e = getNodeSqliteKysely(this.db);
		const t = [e.deleteFrom("capture_events").compile().sql, e.deleteFrom("capture_sessions").compile().sql];
		if (this.capturePathBased) {
			const e = this.countCaptureRows("capture_sessions");
			const n = this.countCaptureRows("capture_events");
			runSqliteImmediateTransactionSync(this.db, () => {
				for (const e of t) executeWithCachedStatement(this.db, e, [], (e) => e.run());
			});
			let r = 0;
			if (fsSync.existsSync(this.capturePathBased.blobDir)) for (const e of fsSync.readdirSync(this.capturePathBased.blobDir)) {
				fsSync.rmSync(path.join(this.capturePathBased.blobDir, e), { force: true });
				r += 1;
			}
			return {
				sessions: e,
				events: n,
				blobs: r
			};
		}
		return this.runWrite(() => {
			const n = this.countCaptureRows("capture_sessions");
			const r = this.countCaptureRows("capture_events");
			const i = this.countCaptureRows("capture_blobs");
			for (const n of [...t, e.deleteFrom("capture_blobs").compile().sql]) executeWithCachedStatement(this.db, n, [], (e) => e.run());
			return {
				sessions: n,
				events: r,
				blobs: i
			};
		});
	}
	deleteSessions(e) {
		const t = normalizeUniqueStringEntries(e);
		if (t.length === 0) return {
			sessions: 0,
			events: 0,
			blobs: 0
		};
		if (this.capturePathBased) return this.deletePathBasedSessions(t);
		return this.runWrite(() => {
			const e = this.readSessionDeletionBlobRows(t);
			const { events: n, sessions: r } = this.deleteSessionMetadata(t);
			const i = e.map((e) => e.blobId?.trim()).filter((e) => Boolean(e));
			const a = this.findRemainingBlobReferences(i);
			const { compiled: o, bind: s } = compileSqliteQueryBindings((e) => getNodeSqliteKysely(this.db).deleteFrom("capture_blobs").where("blob_id", "=", e((e) => e)));
			return {
				sessions: r,
				events: n,
				blobs: executeWithCachedStatement(this.db, o.sql, i, (e) => {
					let t = 0;
					for (const n of i) {
						if (a.has(n)) continue;
						const r = e.run(...s(n));
						if (Number(r.changes) > 0) t += 1;
					}
					return t;
				})
			};
		});
	}
	deletePathBasedSessions(e) {
		const t = this.capturePathBased;
		if (!t) throw new Error("path-based debug proxy capture store is unavailable");
		const n = this.readSessionDeletionBlobRows(e);
		const { events: r, sessions: i } = runSqliteImmediateTransactionSync(this.db, () => this.deleteSessionMetadata(e));
		const a = n.map((e) => e.blobId?.trim()).filter((e) => Boolean(e));
		const o = this.findRemainingBlobReferences(a);
		let s = 0;
		for (const e of a) {
			if (o.has(e)) continue;
			const n = path.join(t.blobDir, `${e}.bin.gz`);
			if (fsSync.existsSync(n)) {
				fsSync.rmSync(n, { force: true });
				s += 1;
			}
		}
		return {
			sessions: i,
			events: r,
			blobs: s
		};
	}
	countCaptureRows(e) {
		const t = getNodeSqliteKysely(this.db).selectFrom(e).select((e) => e.fn.countAll().as("count"));
		return executeWithCachedStatement(this.db, t.compile().sql, [], (e) => e.get()).count ?? 0;
	}
	readSessionDeletionBlobRows(e) {
		const t = getNodeSqliteKysely(this.db).selectFrom("capture_events").where("session_id", "in", e);
		const n = compileSqliteQueryBindings(() => t.select("data_blob_id as blobId").distinct().where("data_blob_id", "is not", null));
		const r = n.bind(void 0);
		return executeWithCachedStatement(this.db, n.compiled.sql, r, (e) => e.all(...r));
	}
	deleteSessionMetadata(e) {
		const t = getNodeSqliteKysely(this.db);
		const n = compileSqliteQueryBindings(() => t.deleteFrom("capture_events").where("session_id", "in", e));
		const r = n.bind(void 0);
		const i = executeWithCachedStatement(this.db, n.compiled.sql, r, (e) => e.run(...r));
		const a = compileSqliteQueryBindings(() => t.deleteFrom("capture_sessions").where("id", "in", e));
		const o = a.bind(void 0);
		const s = executeWithCachedStatement(this.db, a.compiled.sql, o, (e) => e.run(...o));
		return {
			events: Number(i.changes),
			sessions: Number(s.changes)
		};
	}
	findRemainingBlobReferences(e) {
		if (e.length === 0) return /* @__PURE__ */ new Set();
		const { compiled: t, bind: n } = compileSqliteQueryBindings(() => getNodeSqliteKysely(this.db).selectFrom("capture_events").select("data_blob_id as blobId").distinct().where("data_blob_id", "in", e).where("data_blob_id", "is not", null));
		const r = n(void 0);
		const i = executeWithCachedStatement(this.db, t.sql, r, (e) => e.all(...r));
		return new Set(i.map((e) => e.blobId?.trim()).filter((e) => Boolean(e)));
	}
};
function persistEventPayload(e, t) {
	if (t.data == null) return {};
	const n = Buffer.isBuffer(t.data) ? t.data : Buffer.from(t.data);
	const r = t.previewLimit ?? 8192;
	const i = e.persistPayload(n, t.contentType);
	return {
		dataText: new StringDecoder("utf8").write(n.subarray(0, r)),
		dataBlobId: i.blobId,
		dataSha256: i.sha256
	};
}
//#endregion
//#region src/proxy-capture/store.sqlite.ts
const DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_VERSION = 1;
const legacySchemaAdmission = {
	name: "openclaw.proxyCapture.legacySchema",
	schemaDependent: true,
	read: (e) => e === true ? true : void 0
};
const DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_SQL = `
  CREATE TABLE IF NOT EXISTS capture_sessions (
    id TEXT PRIMARY KEY,
    started_at INTEGER NOT NULL,
    ended_at INTEGER,
    mode TEXT NOT NULL,
    source_scope TEXT NOT NULL,
    source_process TEXT NOT NULL,
    proxy_url TEXT,
    db_path TEXT NOT NULL,
    blob_dir TEXT NOT NULL
  ) STRICT;
  CREATE TABLE IF NOT EXISTS capture_events (
    id INTEGER PRIMARY KEY,
    session_id TEXT NOT NULL,
    ts INTEGER NOT NULL,
    source_scope TEXT NOT NULL,
    source_process TEXT NOT NULL,
    protocol TEXT NOT NULL,
    direction TEXT NOT NULL,
    kind TEXT NOT NULL,
    flow_id TEXT NOT NULL,
    method TEXT,
    host TEXT,
    path TEXT,
    status INTEGER,
    close_code INTEGER,
    content_type TEXT,
    headers_json TEXT,
    data_text TEXT,
    data_blob_id TEXT,
    data_sha256 TEXT,
    error_text TEXT,
    meta_json TEXT
  ) STRICT;
  CREATE INDEX IF NOT EXISTS capture_events_session_ts_idx ON capture_events(session_id, ts);
  CREATE INDEX IF NOT EXISTS capture_events_flow_idx ON capture_events(flow_id, ts);
`;
function isInMemoryDatabasePath(e) {
	if (e === ":memory:") return true;
	if (!e.startsWith("file:")) return false;
	const t = e.indexOf("#");
	const n = t === -1 ? e : e.slice(0, t);
	const r = n.indexOf("?");
	const i = r === -1 ? n : n.slice(0, r);
	try {
		if (decodeURIComponent(i.slice(5)) === ":memory:") return true;
	} catch {}
	return r !== -1 && new URLSearchParams(n.slice(r + 1)).get("mode") === "memory";
}
function hardenLegacyDatabaseFiles(e) {
	for (const t of resolveSqliteDatabaseFilePaths(e)) if (fsSync.existsSync(t)) applyPrivateModeSync(t, 384);
}
function openPathBasedDebugProxyCaptureStore(e, t) {
	const n = isInMemoryDatabasePath(e) ? void 0 : e;
	if (n) {
		fsSync.mkdirSync(path.dirname(n), {
			recursive: true,
			mode: 448
		});
		if (!fsSync.existsSync(n)) fsSync.closeSync(fsSync.openSync(n, "a", 384));
	}
	const r = openNodeSqliteDatabase(e);
	let i;
	try {
		if (n) applyPrivateModeSync(n, 384);
		i = configureSqliteConnectionPragmas(r, {
			busyTimeoutMs: 5e3,
			databaseLabel: "debug-proxy-capture-sdk",
			...n ? { databasePath: n } : {},
			foreignKeys: true
		});
		if (!getSqliteDatabaseAdmission(r, legacySchemaAdmission)) {
			const t = r.prepare("PRAGMA user_version").get();
			const i = Number(t?.user_version ?? 0);
			if (i > DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_VERSION) throw new Error(`Legacy debug proxy capture database uses newer schema version ${i}; this build supports ${DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_VERSION}`);
			r.exec(DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_SQL);
			if (i < DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_VERSION) {
				migrateSqliteSchemaToStrict(r, DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_SQL, { databaseLabel: n ?? e });
				r.exec(`PRAGMA user_version = ${DEBUG_PROXY_CAPTURE_LEGACY_SCHEMA_VERSION};`);
			}
			publishSqliteDatabaseAdmission(r, legacySchemaAdmission, true);
		}
		if (n) hardenLegacyDatabaseFiles(n);
		return {
			db: r,
			pathBased: {
				blobDir: t,
				walMaintenance: i
			}
		};
	} catch (e) {
		i?.close();
		r.close();
		throw e;
	}
}
var DebugProxyCaptureStoreImpl = class extends DebugProxyCaptureKernel {
	constructor(e = {}, t) {
		warnPluginSdkDeprecation({
			family: "proxy-capture-store",
			method: "DebugProxyCaptureStore",
			replacement: "await acquireDebugProxyCaptureStoreAsync()"
		});
		if (typeof e === "string") {
			if (!t) throw new TypeError("legacy debug proxy capture store requires a blob directory");
			const n = openPathBasedDebugProxyCaptureStore(e, t);
			super({
				db: n.db,
				dbPath: e,
				blobDir: t,
				pathBased: n.pathBased,
				runWrite: () => {
					throw new Error("shared debug proxy capture state is unavailable");
				}
			});
			this.pathBased = n.pathBased;
			this.closed = false;
			this.closing = false;
			return;
		}
		const n = e.env;
		const r = openOpenClawStateDatabase({ env: n });
		super({
			db: r.db,
			dbPath: r.path,
			blobDir: r.path,
			runWrite: (e) => runOpenClawStateWriteTransaction(e, {
				database: r,
				env: n ?? process.env
			})
		});
		this.closed = false;
		this.closing = false;
		this.releaseIdleReference = retainOpenClawStateDatabaseForIdle(r);
	}
	close() {
		if (this.closed || this.closing) return;
		this.closing = true;
		const e = collectSynchronousErrors([
			() => finalizeCaptureStore(this),
			() => this.releaseIdleReference?.(),
			() => this.pathBased?.walMaintenance.close(),
			() => {
				if (this.pathBased && this.db.isOpen) this.db.close();
			}
		], (e) => e());
		this.closed = true;
		this.closing = false;
		if (e.length) throw new AggregateError(e, "Capture store close failed.");
	}
	get isClosed() {
		return this.closed || !this.db.isOpen;
	}
};
const cachedStores = /* @__PURE__ */ new Map();
let unregisterExitClose = null;
function resolveDebugProxyCaptureStoreKey(e, t) {
	return typeof e === "string" ? `legacy:${e}:${t ?? ""}` : `shared:${resolveOpenClawStateSqlitePath(e.env ?? process.env)}`;
}
function getDebugProxyCaptureStoreImpl(e = {}, t) {
	const n = resolveDebugProxyCaptureStoreKey(e, t);
	const r = cachedStores.get(n);
	if (r && !r.store.isClosed) return r.store;
	const i = new DebugProxyCaptureStoreImpl(e, t);
	cachedStores.set(n, {
		store: i,
		leases: 0
	});
	unregisterExitClose ??= registerSqliteCacheExitClose(closeDebugProxyCaptureStore);
	return i;
}
function getDebugProxyCaptureStore(e = {}, t) {
	warnPluginSdkDeprecation({
		family: "proxy-capture-store",
		method: "getDebugProxyCaptureStore",
		replacement: "await acquireDebugProxyCaptureStoreAsync() and await lease.release() in finally"
	});
	return getDebugProxyCaptureStoreImpl(e, t);
}
/** @deprecated Await each async capture lease's release instead. Final compatibility day: 2026-12-31. Removal in the first January 2027 stable release. */
function closeDebugProxyCaptureStore() {
	warnPluginSdkDeprecation({
		family: "proxy-capture-store",
		method: "closeDebugProxyCaptureStore",
		replacement: "await each async capture lease.release() in finally"
	});
	unregisterExitClose?.();
	unregisterExitClose = null;
	const e = [...cachedStores.values()];
	cachedStores.clear();
	const t = collectSynchronousErrors(e, (e) => e.store.close());
	if (t.length) throw new AggregateError(t, "Capture stores failed to close.");
}
function safeJsonString(e) {
	return e == null ? void 0 : JSON.stringify(e);
}
//#endregion
//#region src/proxy-capture/runtime-owner.ts
const DEBUG_PROXY_FETCH_PATCH_KEY = Symbol.for("openclaw.debugProxy.fetchPatch");
function captureStateContext() {
	try {
		return { context: captureOpenClawStateWorkerContext() };
	} catch (e) {
		return { error: e };
	}
}
function currentStateContext(e) {
	if ("error" in e.state) throw e.state.error;
	e.state.context.admission.assertCurrent();
	return e.state.context;
}
function resolveRuntimeDeps(e = {}) {
	return {
		getStore: e.getStore ?? getDebugProxyCaptureStore,
		closeStore: e.closeStore,
		persistEventPayload: e.persistEventPayload ?? ((e, t) => persistEventPayload(e, t)),
		safeJsonString: e.safeJsonString ?? safeJsonString,
		fetchTarget: e.fetchTarget ?? globalThis
	};
}
const captureOwners = /* @__PURE__ */ new WeakMap();
const globalFetchPatches = /* @__PURE__ */ new WeakMap();
/** Guarded requests own capture admission, including when given a saved patch. */
function resolveDebugProxyFetchTransport(e) {
	return globalFetchPatches.get(e)?.originalFetch ?? e;
}
function uninstallDebugProxyGlobalFetchPatch(e = {}, t) {
	const n = resolveRuntimeDeps(e).fetchTarget;
	const r = n[DEBUG_PROXY_FETCH_PATCH_KEY];
	if (!r || t && r.admission !== t) return;
	n.fetch = r.originalFetch;
	delete n[DEBUG_PROXY_FETCH_PATCH_KEY];
}
function captureOwnerKey(e) {
	return JSON.stringify([e.dbPath, e.sessionId]);
}
function reportCapturePersistenceFailure(e, t) {
	e.errors.push(t);
	reportCaptureError(t);
}
function reportCaptureError(e) {
	try {
		const t = redactRegisteredSecretValues(e instanceof Error ? e.message : String(e), () => REDACTED_CAPTURE_HEADER_VALUE);
		writeSync(2, `[proxy-capture] Capture persistence failed: ${t}\n`);
	} catch {}
}
function finishCaptureOwner(e) {
	if (!e.active) return;
	sealCaptureOwner(e);
	const t = releaseCaptureClaim(e);
	try {
		if (t && !e.store.isClosed) e.store.endSession(e.settings.sessionId);
	} catch (t) {
		reportCapturePersistenceFailure(e, t);
	}
	forgetCaptureOwner(e);
	if (e.errors.length) throw new AggregateError(e.errors.splice(0), "Capture session finalization failed.");
}
function resolveCaptureOwner(e, t, n = {}) {
	if (isDebugProxyCaptureDeferred()) return;
	let r = captureOwners.get(t.getStore);
	const i = captureOwnerKey(e);
	let a = r?.owners.get(i);
	if (!a) {
		const t = n.explicit ? r?.resolved.get(e) : r?.ambient?.sessionId === e.sessionId && r.ambient.dbPath === e.dbPath ? r.ambient.admission : void 0;
		if (!n.initialize && t) {
			a = t.current;
			if (!a) return;
		}
	}
	if (a?.closing) return;
	const o = getOpenClawDatabaseMaintenanceScope();
	o?.assertAdmission();
	if (!r) {
		r = {
			owners: /* @__PURE__ */ new Map(),
			resolved: /* @__PURE__ */ new WeakMap()
		};
		captureOwners.set(t.getStore, r);
	}
	if (!a) {
		a = {
			settings: { ...e },
			runtime: t,
			state: captureStateContext(),
			errors: [],
			claims: /* @__PURE__ */ new Set(),
			admission: {},
			closing: false,
			syncClosed: false,
			usedAsync: false,
			writes: Promise.resolve()
		};
		a.admission.current = a;
	}
	const s = n.asynchronous === true;
	if (!s) {
		if (n.initialize) a.syncClosed = false;
		else if (a.syncClosed) return;
	}
	let c = [...a.claims].find((e) => e.maintenanceScope === o && e.asynchronous === s);
	if (!c) {
		const e = [];
		const t = "context" in a.state ? { context: {
			...a.state.context,
			maintenanceScope: o
		} } : a.state;
		const getStore = () => {
			if (a.runtime.getStore !== getDebugProxyCaptureStore) return a.runtime.getStore();
			if ("error" in t) throw t.error;
			t.context.admission.assertCurrent();
			return getDebugProxyCaptureStore({ env: t.context.environment });
		};
		const l = n.asynchronous ? void 0 : getStore();
		if (l?.isClosed) return;
		c = {
			session: a,
			maintenanceScope: o,
			settings: a.settings,
			runtime: a.runtime,
			syncStore: l,
			get store() {
				if (!this.syncStore) {
					if (this.asyncStore?.isClosed) throw new Error("Capture store is closed.");
					this.syncStore = getStore();
					e.push(registerCaptureStoreFinalizer(this.syncStore, () => finishCaptureOwner(this)));
				}
				return this.syncStore;
			},
			state: t,
			asynchronous: s,
			writes: /* @__PURE__ */ new Set(),
			active: true,
			pending: /* @__PURE__ */ new Set(),
			errors: [],
			unregister: () => {
				for (const t of e.splice(0)) t();
			},
			admission: {}
		};
		c.admission.current = c;
		const u = c;
		if (l) e.push(registerCaptureStoreFinalizer(l, () => finishCaptureOwner(u)));
		e.push(registerActiveDebugProxyCapture(() => closeCaptureOwnerAsync(u)));
		a.claims.add(c);
		r.owners.set(i, a);
		o?.own(u, "shared-resources", () => closeCaptureOwnerAsync(u));
	}
	if (!c.active) return;
	if (n.asynchronous) a.usedAsync = true;
	if (n.explicit) r.resolved.set(e, a.admission);
	else r.ambient = {
		sessionId: e.sessionId,
		dbPath: e.dbPath,
		admission: a.admission
	};
	return c;
}
function resolveCaptureOwnerForTransport(e, t = {}, n = {}) {
	let r;
	let i;
	try {
		r = resolveEnabledDebugProxySettings(e);
		if (!r) return;
		i = resolveRuntimeDeps(t);
		return resolveCaptureOwner(r, i, {
			explicit: e !== void 0,
			...n
		});
	} catch (e) {
		const t = r && i ? captureOwners.get(i.getStore)?.owners.get(captureOwnerKey(r)) : void 0;
		if (t) reportCapturePersistenceFailure(t, e);
		else reportCaptureError(e);
		return;
	}
}
function sealCaptureOwner(e) {
	revokeCaptureOwner(e);
	for (const t of e.pending) t();
}
function revokeCaptureOwner(e) {
	e.active = false;
	e.admission.current = void 0;
}
function forgetCaptureOwner(e) {
	const t = captureOwners.get(e.runtime.getStore);
	if (e.session.claims.size === 0 && t?.owners.get(captureOwnerKey(e.settings)) === e.session) t.owners.delete(captureOwnerKey(e.settings));
	e.unregister();
}
function releaseCaptureClaim(e) {
	const t = e.session;
	if (!t.claims.delete(e)) return false;
	if (t.claims.size > 0) return false;
	t.closing = true;
	t.admission.current = void 0;
	e.errors.push(...t.errors.splice(0));
	uninstallDebugProxyGlobalFetchPatch(t.runtime, t.admission);
	return true;
}
/** Observe callback-owned work without converting its rejection into success. */
function observeCaptureWrite(e, t) {
	e.writes.add(t);
	t.then(() => e.writes.delete(t), (n) => {
		e.writes.delete(t);
		reportCapturePersistenceFailure(e, n);
	});
	return t;
}
function ensureAsyncCaptureLease(e) {
	const t = currentStateContext(e);
	if (!e.asyncLease) {
		const n = createDebugProxyChildCaptureStore(e.settings) ?? createDebugProxyCaptureStoreForContext(t);
		e.asyncLease = n;
		e.asyncStore = n.store;
		const r = registerAsyncCaptureStoreFinalizer(n.store, (t) => {
			e.asyncStore = t;
			const r = finishCaptureOwnerAsync(e);
			const forgetAfterStoreClose = () => {
				if (!e.closing) forgetCaptureOwner(e);
			};
			n.store.close().then(forgetAfterStoreClose, forgetAfterStoreClose);
			return r;
		});
		const i = e.unregister;
		e.unregister = () => {
			r();
			i();
		};
	}
	return e.asyncLease;
}
async function getAsyncCaptureStore(e) {
	const t = ensureAsyncCaptureLease(e);
	await t.ready;
	return t.store;
}
function runCaptureOperation(e, t) {
	return ensureAsyncCaptureLease(e).runOperation(t);
}
/** Reserve retained input before copying facts or waiting for FIFO admission. */
async function recordCaptureEventAsync(e, t, n, r) {
	const i = n?.data;
	const a = serialize(n === void 0 ? {
		type: "capture.recordEvent",
		input: t
	} : {
		type: "capture.recordEventWithPayload",
		input: {
			event: t,
			payload: {
				...n,
				data: Buffer.isBuffer(i) ? Buffer.alloc(0) : i
			}
		}
	}).byteLength + (Buffer.isBuffer(i) ? i.byteLength : 0);
	const o = reserveSqliteWorkerInputPreparation(a);
	try {
		const a = { ...t };
		const s = n === void 0 ? void 0 : {
			...n,
			data: Buffer.isBuffer(i) ? Buffer.from(i) : i
		};
		const c = ensureAsyncCaptureLease(e).ready;
		return await sequenceCaptureWrite(e, r, async (e) => {
			await c;
			return o.handoff(() => s === void 0 ? e.recordEvent(a) : e.recordEventWithPayload(a, s));
		});
	} finally {
		o.release();
	}
}
function sequenceCaptureWrite(e, t, n) {
	const r = e.session.writes.then(() => n(t));
	e.session.writes = r.then(() => void 0, () => void 0);
	return e.maintenanceScope ? e.maintenanceScope.track(r) : r;
}
function finishCaptureOwnerAsync(e) {
	if (e.finishing) return e.finishing;
	const t = createDeferredCore();
	e.finishing = t.promise;
	sealCaptureOwner(e);
	const finish = async () => {
		while (e.writes.size) await Promise.allSettled(e.writes);
		try {
			const t = releaseCaptureClaim(e);
			if (t && e.asyncLease) {
				const t = e.asyncLease;
				await t.ready;
				const n = e.asyncStore ?? t.store;
				if (n.isClosed) throw new SqliteWorkerError("Capture store is closed", "closed");
				await n.endSession(e.settings.sessionId);
			} else if (t && e.syncStore && !e.syncStore.isClosed) e.syncStore.endSession(e.settings.sessionId);
		} catch (t) {
			reportCapturePersistenceFailure(e, t);
		}
		if (e.errors.length) throw new AggregateError(e.errors.splice(0), "Capture session finalization failed.");
	};
	finish().then(t.resolve, t.reject);
	t.promise.catch(() => void 0);
	return t.promise;
}
function closeCaptureOwnerAsync(e) {
	if (e.closing) return e.closing;
	const t = createDeferredCore();
	e.closing = t.promise;
	revokeCaptureOwner(e);
	const close = async () => {
		const t = [];
		try {
			if (e.asyncLease) await e.asyncLease.release();
		} catch (e) {
			t.push(e);
		}
		try {
			await finishCaptureOwnerAsync(e);
		} catch (e) {
			if (!t.some((t) => collectNestedErrorCandidates(t).includes(e))) t.push(e);
		}
		try {
			const t = e.syncStore;
			if (t && ![...e.session.claims].some((e) => e.syncStore === t)) {
				if (e.runtime.closeStore) e.runtime.closeStore();
				else t.close?.();
			}
		} catch (e) {
			t.push(e);
		}
		forgetCaptureOwner(e);
		if (t.length) throw new AggregateError(t, "Capture finalization failed.");
	};
	close().then(t.resolve, t.reject);
	t.promise.catch(() => void 0);
	return t.promise;
}
//#endregion
//#region src/proxy-capture/runtime-response-body.ts
const MAX_CAPTURED_RESPONSE_BODY_BYTES = 16777216;
const CAPTURED_RESPONSE_BODY_IDLE_TIMEOUT_MS = 1e4;
/** Distinguishes the capture deadline from a genuine response-stream failure. */
var CaptureReadIdleTimeoutError = class extends Error {};
function readCapturedResponseBodyBounded(e, t, n, r, i = false) {
	const recordMetadata = (e) => {
		try {
			n({ status: e });
		} catch (e) {
			reportCapturePersistenceFailure(t, e);
		}
	};
	if (typeof e.clone !== "function") {
		recordMetadata("unavailable");
		return;
	}
	const a = parseDeclaredCaptureContentLength(typeof e.headers?.get === "function" ? e.headers.get("content-length") : void 0);
	if (a !== void 0 && a > BigInt(MAX_CAPTURED_RESPONSE_BODY_BYTES)) {
		recordMetadata("too-large");
		return;
	}
	let o;
	let s = [];
	let c = 0;
	let l = false;
	let u = false;
	let detachAbort = () => {};
	const cancel = (e) => {
		if (!o || u) return;
		u = true;
		try {
			o.cancel(e).catch(() => void 0);
		} catch (e) {
			t.errors.push(e);
		}
	};
	const release = () => {
		try {
			o?.releaseLock();
		} catch {}
	};
	const finish = (e) => {
		if (l) return;
		l = true;
		detachAbort();
		t.pending.delete(finalize);
		try {
			if (!i && t.store.isClosed) throw new Error("Capture store closed before its response could be finalized.");
			n(e);
		} catch (e) {
			reportCapturePersistenceFailure(t, e);
		} finally {
			s = [];
			cancel();
			release();
		}
	};
	const finalize = () => finish({
		status: "finalized",
		buffer: Buffer.concat(s, c)
	});
	t.pending.add(finalize);
	if (r) {
		const onAbort = () => {
			setTimeout(() => {
				if (l) return;
				finish({
					status: "failed",
					buffer: Buffer.concat(s, c),
					error: r.reason instanceof Error ? r.reason : new Error("Response capture aborted", { cause: r.reason })
				});
			}, 0);
		};
		if (r.aborted) onAbort();
		else {
			r.addEventListener("abort", onAbort, { once: true });
			detachAbort = () => r.removeEventListener("abort", onAbort);
		}
	}
	(async () => {
		try {
			const n = e.clone();
			const r = n.body;
			if (!r || typeof r.getReader !== "function") {
				finish(n instanceof Response && n.body === null ? {
					status: "captured",
					buffer: Buffer.alloc(0)
				} : { status: "unavailable" });
				return;
			}
			o = r.getReader();
			for (;;) {
				if (l || !t.active) return;
				const { done: e, value: n } = await withResponseBodyTimeout({
					timeoutMs: CAPTURED_RESPONSE_BODY_IDLE_TIMEOUT_MS,
					onTimeout: ({ timeoutMs: e }) => new CaptureReadIdleTimeoutError(`capture read stalled: no data for ${e}ms`),
					cancel: async (e) => cancel(e),
					read: () => o.read()
				});
				if (l || !t.active) return;
				if (e) {
					finish({
						status: "captured",
						buffer: Buffer.concat(s, c)
					});
					return;
				}
				if (!n?.length) continue;
				if (c + n.length > MAX_CAPTURED_RESPONSE_BODY_BYTES) {
					finish({ status: "too-large" });
					return;
				}
				s.push(Buffer.from(n));
				c += n.length;
			}
		} catch (e) {
			if (!l && t.active) finish(e instanceof CaptureReadIdleTimeoutError ? {
				status: "stalled",
				buffer: Buffer.concat(s, c)
			} : {
				status: "failed",
				buffer: Buffer.concat(s, c),
				error: e
			});
		} finally {
			release();
		}
	})();
}
function parseDeclaredCaptureContentLength(e) {
	if (e === null || e === void 0) return;
	const t = e.trim();
	if (!/^\d+$/.test(t)) return;
	return BigInt(t);
}
//#endregion
//#region src/proxy-capture/runtime.ts
const REDACTED_CAPTURE_BINARY_PAYLOAD = Buffer.from("[REDACTED BINARY PAYLOAD]", "utf8");
function protocolFromUrl(e) {
	switch (e.protocol) {
		case "https:": return "https";
		case "wss:": return "wss";
		case "ws:": return "ws";
		default: return "http";
	}
}
function redactCaptureUrl(e) {
	let t;
	try {
		t = new URL$1(e);
	} catch {
		return "https://redacted.invalid/%5BREDACTED%5D";
	}
	const decodeComponent = (e) => {
		try {
			return decodeURIComponent(e);
		} catch {
			return e;
		}
	};
	if (redactCaptureText(t.hostname) !== t.hostname) t.hostname = "redacted.invalid";
	for (const e of ["username", "password"]) {
		const n = decodeComponent(t[e]);
		const r = redactCaptureText(n);
		if (r !== n) t[e] = r;
	}
	t.pathname = t.pathname.split("/").map((e) => {
		try {
			const t = decodeURIComponent(e);
			const n = redactCaptureText(t);
			return n === t ? e : encodeURIComponent(n);
		} catch {
			return e;
		}
	}).join("/");
	const n = new URLSearchParams();
	let r = false;
	for (const [e, i] of t.searchParams.entries()) {
		const t = redactCaptureText(e);
		const a = redactCaptureText(i);
		n.append(t, a);
		if (t !== e || a !== i) r = true;
	}
	if (r) t.search = n.toString();
	const i = decodeComponent(t.hash.slice(1));
	const a = redactCaptureText(i);
	if (a !== i) t.hash = a;
	const o = t.toString();
	return redactCaptureText(o) === o ? o : `${t.protocol}//redacted.invalid/%5BREDACTED%5D`;
}
function redactCaptureText(e) {
	return redactRegisteredSecretValues(e, () => REDACTED_CAPTURE_HEADER_VALUE);
}
function redactCapturePayload(e) {
	if (typeof e === "string") return redactCaptureText(e);
	if (!Buffer.isBuffer(e)) return e ?? null;
	if (!isUtf8(e)) return hasRegisteredSecretValuesForRedaction() ? REDACTED_CAPTURE_BINARY_PAYLOAD : e;
	const t = e.toString("utf8");
	const n = redactCaptureText(t);
	return n === t ? e : Buffer.from(n, "utf8");
}
function redactedCaptureJson(e, t = safeJsonString) {
	const n = t(e);
	return n === void 0 ? void 0 : redactCaptureText(n);
}
function createHttpCaptureEventBase(e) {
	return {
		sessionId: e.settings.sessionId,
		ts: Date.now(),
		sourceScope: "openclaw",
		sourceProcess: e.settings.sourceProcess,
		protocol: e.transport ?? protocolFromUrl(e.url),
		direction: e.direction,
		kind: e.kind,
		flowId: e.flowId,
		method: e.method,
		host: e.url.host,
		path: `${e.url.pathname}${e.url.search}`
	};
}
function captureInstalledFetch(e, t) {
	return runOwnedCapture(e, e.asynchronous, (n) => "response" in t ? captureOwnedHttpExchange(t, e, n) : captureOwnedHttpError(t, e, n));
}
function runOwnedCapture(e, t, n) {
	if (isDebugProxyCaptureDeferred()) return;
	if (!t) {
		try {
			e.maintenanceScope?.assertAdmission();
		} catch (t) {
			reportCapturePersistenceFailure(e, t);
			return;
		}
		return n({ asynchronous: false });
	}
	try {
		e.maintenanceScope?.assertAdmission();
		return observeCaptureWrite(e, runCaptureOperation(e, async (e) => {
			await n({
				asynchronous: true,
				store: e
			});
		}));
	} catch (t) {
		const n = createDeferredCore();
		n.reject(t);
		return observeCaptureWrite(e, n.promise);
	}
}
function writeCaptureEvent(e, t, n, r) {
	if (r.asynchronous) return recordCaptureEventAsync(e, t, n, r.store);
	const i = e.store;
	const a = n === void 0 ? {} : e.runtime.persistEventPayload(i, n);
	i.recordEvent({
		...t,
		...a
	});
}
function captureOwnedHttpError(e, t, n = { asynchronous: false }) {
	const r = n.asynchronous;
	try {
		const r = redactCaptureUrl(e.url);
		return writeCaptureEvent(t, {
			...createHttpCaptureEventBase({
				settings: t.settings,
				url: new URL$1(r),
				transport: e.transport,
				direction: "local",
				kind: "error",
				flowId: e.flowId ?? randomUUID(),
				method: e.method
			}),
			errorText: redactCaptureText(e.error instanceof Error ? e.error.message : String(e.error)),
			metaJson: redactedCaptureJson(e.meta, t.runtime.safeJsonString)
		}, void 0, n);
	} catch (e) {
		if (r) throw e;
		reportCapturePersistenceFailure(t, e);
	}
}
function captureOwnedHttpExchange(e, t, n = { asynchronous: false }) {
	const r = n.asynchronous;
	const { settings: i, runtime: a } = t;
	const o = e.flowId ?? randomUUID();
	const s = redactCaptureUrl(e.url);
	const c = new URL$1(s);
	const l = e.method;
	const u = e.transport;
	const d = e.response.status;
	const f = typeof e.requestBody === "string" || Buffer.isBuffer(e.requestBody) ? e.requestBody : null;
	const p = e.requestHeaders ? isHeadersLike(e.requestHeaders) ? e.requestHeaders.get("content-type") ?? void 0 : e.requestHeaders["content-type"] : void 0;
	const m = p === void 0 ? void 0 : redactCaptureText(p);
	const h = typeof e.response.headers?.get === "function" ? e.response.headers.get("content-type") ?? void 0 : void 0;
	const g = h === void 0 ? void 0 : redactCaptureText(h);
	let _;
	let v;
	let y;
	let b;
	try {
		_ = e.response.headers && typeof e.response.headers.entries === "function" ? a.safeJsonString(redactedCaptureHeaders(e.response.headers)) : void 0;
		v = redactedCaptureJson(e.meta, a.safeJsonString);
		y = v === void 0 ? void 0 : JSON.parse(v);
		b = writeCaptureEvent(t, {
			...createHttpCaptureEventBase({
				settings: i,
				url: c,
				transport: u,
				direction: "outbound",
				kind: "request",
				flowId: o,
				method: l
			}),
			contentType: m,
			headersJson: a.safeJsonString(redactedCaptureHeaders(e.requestHeaders, Array.isArray(e.meta?.sensitiveRequestHeaderNames) ? e.meta.sensitiveRequestHeaderNames.filter((e) => typeof e === "string") : void 0)),
			metaJson: v
		}, {
			data: redactCapturePayload(f),
			contentType: m
		}, n);
	} catch (e) {
		if (r) throw e;
		reportCapturePersistenceFailure(t, e);
		return;
	}
	const x = r ? createDeferredCore() : void 0;
	const S = r ? Promise.resolve(b) : void 0;
	if (x && S) S.catch(x.reject);
	const recordTerminal = (e) => {
		try {
			const r = e.status === "failed";
			const s = {
				...createHttpCaptureEventBase({
					settings: i,
					url: c,
					transport: u,
					direction: r ? "local" : "inbound",
					kind: r ? "error" : "response",
					flowId: o,
					method: l
				}),
				status: d,
				contentType: g,
				headersJson: _,
				errorText: r ? redactCaptureText(e.error instanceof Error ? e.error.message : String(e.error)) : void 0,
				metaJson: e.status === "captured" ? v : redactedCaptureJson(Object.assign({}, y, {
					bodyCapture: e.status,
					...r ? { stage: "response-body" } : {}
				}), a.safeJsonString)
			};
			const f = "buffer" in e ? {
				data: redactCapturePayload(e.buffer),
				contentType: g
			} : void 0;
			if (x && S) S.then(() => writeCaptureEvent(t, s, f, n)).then(x.resolve, x.reject);
			else writeCaptureEvent(t, s, f, n);
		} catch (e) {
			if (x) x.reject(e);
			else throw e;
		}
	};
	readCapturedResponseBodyBounded(e.response, t, recordTerminal, e.signal, r);
	return x?.promise;
}
function prepareHttpCaptureForTransport() {
	const e = resolveCaptureOwnerForTransport(void 0, {}, { asynchronous: true });
	if (!e) return;
	const t = e.admission;
	const n = observeCaptureWrite(e, getAsyncCaptureStore(e).then(() => void 0));
	const r = e.asyncLease !== void 0;
	return (e) => {
		const i = t.current;
		if (!i) return Promise.resolve();
		if (!r) return n;
		return Promise.resolve(captureInstalledFetch(i, e));
	};
}
//#endregion
export { prepareHttpCaptureForTransport, resolveDebugProxyFetchTransport };