UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,913 lines • 69.5 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { u as asNonNegativeInteger } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord, o as asRecord } from "./record-coerce-CVPuDqcc.mjs";
import { m as toStringifiedError } from "./error-coercion-hDrHOSGy.mjs";
import "./src-H3RMXyFL.mjs";
import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs";
import { r as filterStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs";
import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { n as sanitizeTerminalText } from "./safe-text-C80HAQ2e.mjs";
import { d as sleepWithAbort, i as createAbortError, l as resolveSleepDelayMs, s as raceWithTimeout, t as RetrySupervisor } from "./src-BPmQBLJp.mjs";
import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs";
import { t as VERSION } from "./version-GlxUMdxI.mjs";
import { l as publicKeyRawBase64UrlFromEd25519Pem, u as signEd25519Payload } from "./ed25519-signature-CUaH7IDK.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { t as isNonEmptyProtocolString } from "./protocol-value-normalization-CXHG8cRQ.mjs";
import { o as isRetryableGatewayStartupUnavailableError, s as resolveGatewayStartupRetryAfterMs } from "./startup-unavailable-DEGJREFb.mjs";
import { a as parseHostForAddressChecks, n as isGatewayClientStoppedError, r as normalizeTlsFingerprint, t as formatGatewayClientErrorForLog } from "./client-address-utils-Clpzy8Fr.mjs";
import { a as isGatewaySuspendUnavailableError, i as isGatewayRestartUnavailableError, n as GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS } from "./restart-unavailable-CqvsgSBG.mjs";
import { i as PROTOCOL_VERSION, n as MIN_NODE_PROTOCOL_VERSION, r as MIN_PROBE_PROTOCOL_VERSION, t as MIN_CLIENT_PROTOCOL_VERSION } from "./version-CwNT1gaY.mjs";
import { d as readConnectErrorRecoveryAdvice, p as readPairingConnectErrorDetails, t as ConnectErrorDetailCodes, u as readConnectErrorDetailCode } from "./connect-error-details-BdhXf496.mjs";
import { n as logError, t as logDebug } from "./logger-CIwfuhOU.mjs";
import { a as resolveGatewayWebSocketTransport, i as isGatewayLoopbackHost, n as GatewayWebSocketTransportConfigurationError } from "./websocket-transport-CF478NbJ.mjs";
import { a as resolveConnectChallengeTimeoutMs, c as resolveSafeTimeoutDelayMs, i as clearGatewayConnectTimeout, l as startGatewayConnectTimeout, o as resolveFiniteTimeoutDelayMs, s as resolvePreauthHandshakeTimeoutMs, t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS } from "./timeouts-nwfOzsiL.mjs";
import { t as normalizeDeviceAuthRole } from "./device-auth-Cu5vRDvP.mjs";
import { c as storeDeviceAuthToken, i as loadDeviceAuthTokenReadOnly, l as storeOriginDeviceToken, n as clearOriginDeviceToken, o as loadOriginDeviceToken, r as loadDeviceAuthToken, s as loadOriginDeviceTokenReadOnly, t as clearDeviceAuthToken } from "./device-auth-store-B3F61F1r.mjs";
import { i as retainGatewayResponsePayload, n as GatewayProtocolRequestTimeoutError, t as GatewayProtocolRequestError } from "./protocol-request-CsClAJsG.mjs";
import { i as markGatewayConnectAssemblyError, n as GatewayClientRequestTimeoutError, t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs";
import { n as loadDeviceIdentityIfPresentAsync, r as loadOrCreateDeviceIdentityAsync } from "./device-identity-async-B1EfjFkw.mjs";
import { t as WebSocket } from "./websocket-CGHaToS5.mjs";
import { n as buildDeviceAuthPayloadV3 } from "./device-auth-D9CpjNQV.mjs";
import { t as rawDataToString } from "./websocket-data-BMMkrJdl.mjs";
import "./device-identity-JBn8J50B.mjs";
import { r as registerManagedProxyGatewayLoopbackBypass, t as ensureInheritedManagedProxyRoutingActive } from "./proxy-lifecycle-78PDzQG7.mjs";
import { t as resolveGatewayClientPlatformIdentity } from "./gateway-client-platform-DW3cGQgF.mjs";
import { randomUUID } from "node:crypto";
//#region packages/gateway-client/src/client-device-auth.ts
/** Owns pending host storage work for one client across connection generations. */
var GatewayClientDeviceAuth = class {
	constructor(e) {
		this.storage = e;
		this.operations = /* @__PURE__ */ new Set();
	}
	load(e) {
		const load = () => {
			e.signal?.throwIfAborted();
			e.assertCurrent?.();
			return this.track(this.storage.loadDeviceAuthToken(e));
		};
		return this.operations.size > 0 ? this.settle().then(load) : load();
	}
	store(e, t, n) {
		const failed = (e) => {
			const t = toStringifiedError(e);
			let r = false;
			try {
				r = n(t);
			} catch {}
			if (!r) this.unreportedPersistenceFailure ??= t;
			throw t;
		};
		e.signal?.throwIfAborted();
		e.assertCurrent?.();
		const r = this.storage.storeDeviceAuthToken(e);
		return r instanceof Promise ? this.track(r.then(t).catch(failed)) : t();
	}
	clear(e, t, n) {
		const clear = () => {
			if (!n()) return;
			const r = [t.token, t.receiptToken].filter((e) => typeof e === "string");
			const i = [...new Set(r)];
			if (t.token === void 0 && i.length === 0) i.push(void 0);
			const clearToken = (t) => {
				e.signal?.throwIfAborted();
				e.assertCurrent?.();
				const n = this.storage.clearDeviceAuthToken({
					...e,
					...t === void 0 ? {} : { expectedToken: t }
				});
				return n instanceof Promise ? n.then(() => {}) : void 0;
			};
			let a;
			for (const e of i) a = a ? a.then(() => clearToken(e)) : clearToken(e);
			return a;
		};
		return this.track(t.persistence ? t.persistence.then(clear, clear) : clear());
	}
	async settle() {
		await Promise.allSettled(this.operations);
	}
	async drain() {
		await this.settle();
		const e = this.unreportedPersistenceFailure;
		this.unreportedPersistenceFailure = void 0;
		if (e) throw e;
	}
	track(e) {
		if (!(e instanceof Promise)) return e;
		this.operations.add(e);
		e.then(() => this.operations.delete(e), () => this.operations.delete(e));
		return e;
	}
};
//#endregion
//#region packages/gateway-client/src/client-upgrade-error.ts
const MAX_UPGRADE_ERROR_BODY_BYTES = 2048;
const UPGRADE_ERROR_BODY_TIMEOUT_MS = 1e3;
async function readUpgradeErrorBody(e) {
	return await new Promise((t) => {
		const n = [];
		let r = 0;
		let i = false;
		const finish = () => {
			if (i) return;
			i = true;
			clearTimeout(a);
			e.off("data", onData);
			e.off("end", finish);
			e.off("error", finish);
			e.off("aborted", finish);
			t(Buffer.concat(n, r).toString("utf8").replace(/\s+/gu, " ").trim());
		};
		const stop = () => {
			finish();
			e.destroy();
		};
		const onData = (e) => {
			const t = Buffer.isBuffer(e) ? e : Buffer.from(e);
			const i = MAX_UPGRADE_ERROR_BODY_BYTES - r;
			if (i > 0) {
				const e = t.subarray(0, i);
				n.push(e);
				r += e.byteLength;
			}
			if (t.byteLength >= i) stop();
		};
		const a = setTimeout(stop, UPGRADE_ERROR_BODY_TIMEOUT_MS);
		a.unref?.();
		e.on("data", onData);
		e.once("end", finish);
		e.once("error", finish);
		e.once("aborted", finish);
	});
}
//#endregion
//#region packages/gateway-client/src/connect-auth.ts
function selectGatewayConnectAuth(e) {
	const t = normalizeOptionalString(e.token);
	const n = normalizeOptionalString(e.bootstrapToken);
	const r = normalizeOptionalString(e.deviceToken);
	const i = normalizeOptionalString(e.password);
	const a = normalizeOptionalString(e.storedToken);
	const o = {
		storedToken: a,
		storedScopes: e.storedScopes
	};
	if (e.preferBootstrapToken && n) return {
		authBootstrapToken: n,
		signatureToken: n,
		...o
	};
	const s = e.pendingDeviceTokenRetry === true && !r && Boolean(t && a && e.trustedDeviceTokenRetry);
	const c = r ?? (s || !(t || i) && (!n || a) ? a : void 0);
	const l = Boolean(c && !r && a) && c === a;
	const u = t ?? c;
	const d = !t && !c && !i ? n : void 0;
	return {
		authToken: t,
		authBootstrapToken: d,
		authDeviceToken: s ? a : void 0,
		authPassword: i,
		authApprovalRuntimeToken: normalizeOptionalString(e.approvalRuntimeToken),
		authAgentRuntimeIdentityToken: normalizeOptionalString(e.agentRuntimeIdentityToken),
		signatureToken: u ?? d,
		resolvedDeviceToken: c,
		usingStoredDeviceToken: l,
		...o
	};
}
function buildGatewayConnectAuth(e) {
	const t = {
		token: e.authToken,
		bootstrapToken: e.authBootstrapToken,
		deviceToken: e.authDeviceToken ?? e.resolvedDeviceToken,
		password: e.authPassword,
		approvalRuntimeToken: e.authApprovalRuntimeToken,
		agentRuntimeIdentityToken: e.authAgentRuntimeIdentityToken
	};
	return Object.values(t).some(Boolean) ? t : void 0;
}
function resolveGatewayConnectScopes(e) {
	return e.requestedScopes ?? (e.usingStoredDeviceToken && e.storedScopes?.length ? e.storedScopes : [...e.defaultScopes]);
}
function shouldRetryGatewayWithDeviceToken(e) {
	if (e.retryBudgetUsed || e.currentDeviceToken || !e.explicitToken || !e.storedToken || !e.trustedEndpoint) return false;
	const t = readConnectErrorRecoveryAdvice(e.errorDetails);
	return e.canRetryWithDeviceTokenHint === true || t.canRetryWithDeviceToken === true || t.recommendedNextStep === "retry_with_device_token" || readConnectErrorDetailCode(e.errorDetails) === ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH;
}
//#endregion
//#region packages/gateway-client/src/model-catalog-connect.ts
const MODEL_CATALOG_SNAPSHOT = "model-catalog-snapshot";
/** A requested snapshot opts in only after the server advertises its connect field. */
function resolveModelCatalogConnect(e) {
	const t = e.serverCapabilities.includes(MODEL_CATALOG_SNAPSHOT) ? e.modelCatalog : void 0;
	const n = e.caps?.filter((e) => e !== MODEL_CATALOG_SNAPSHOT);
	if (t === void 0) return { caps: n };
	return {
		modelCatalog: t,
		caps: [...n ?? [], MODEL_CATALOG_SNAPSHOT]
	};
}
//#endregion
//#region packages/gateway-client/src/node-protocol.ts
/** Match the shipped v3 node envelope before signing its metadata. */
function resolveNodeProtocolClientMetadata(e, t, n) {
	const r = e.platform ?? t;
	if (!n) return {
		platform: r,
		deviceFamily: e.deviceFamily,
		modelIdentifier: e.modelIdentifier
	};
	return { platform: r === "macos" ? "darwin" : r === "windows" ? "win32" : r };
}
function shouldNegotiateLegacyNodeProtocol(e) {
	if (e.role !== "node" || e.mode !== GATEWAY_CLIENT_MODES.NODE || e.clientName !== GATEWAY_CLIENT_NAMES.NODE_HOST) return false;
	return (e.minProtocol ?? 3) === 3 && (e.maxProtocol ?? 4) === 4;
}
//#endregion
//#region packages/gateway-protocol/src/frame-guards.ts
function isGatewayErrorShape(e) {
	if (!isRecord(e)) return false;
	if (!isNonEmptyProtocolString(e.code) || !isNonEmptyProtocolString(e.message)) return false;
	if (e.retryable !== void 0 && typeof e.retryable !== "boolean") return false;
	return e.retryAfterMs === void 0 || asNonNegativeInteger(e.retryAfterMs) !== void 0;
}
function isGatewayEventFrame(e) {
	if (!isRecord(e) || e.type !== "event" || !isNonEmptyProtocolString(e.event)) return false;
	return e.seq === void 0 || asNonNegativeInteger(e.seq) !== void 0;
}
function isGatewayResponseFrame(e) {
	if (!isRecord(e) || e.type !== "res" || !isNonEmptyProtocolString(e.id) || typeof e.ok !== "boolean") return false;
	return e.error === void 0 || isGatewayErrorShape(e.error);
}
//#endregion
//#region packages/gateway-client/src/event-listeners.ts
/** Subscription identity prevents old frames and disposers from reviving callbacks. */
var GatewayEventListeners = class {
	constructor() {
		this.listeners = /* @__PURE__ */ new Map();
	}
	add(e) {
		const t = this.listeners.get(e) ?? {};
		this.listeners.set(e, t);
		return () => {
			if (this.listeners.get(e) === t) this.listeners.delete(e);
		};
	}
	snapshot() {
		return [...this.listeners];
	}
	isCurrent(e, t) {
		return this.listeners.get(e) === t;
	}
};
//#endregion
//#region packages/gateway-client/src/pending-request.ts
/** Owns request deadlines, correlation, settlement, and generation-scoped IDs. */
var GatewayPendingRequests = class {
	constructor(e) {
		this.opts = e;
		this.pending = /* @__PURE__ */ new Map();
		this.requestSequence = 0;
	}
	setSuspensionPhase(e) {
		if (e === "accepting") this.resumeBootstrapRequests();
		else if (e === "preparing" || e === "draining" || e === "prepared") this.pauseBootstrapRequests(void 0, true);
	}
	pauseBootstrapRequests(e = GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS, t = false) {
		const n = this.opts.nowMs();
		const r = resolveSafeTimeoutDelayMs(Number.isFinite(e) && e > 0 ? e : GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS);
		const i = this.bootstrapPause ??= {
			retryAtMs: n,
			revision: 0,
			announced: t
		};
		i.announced ||= t;
		i.revision += 1;
		i.retryAtMs = Math.max(i.retryAtMs, n + r);
		clearTimeout(i.timer);
		i.timer = void 0;
		if (i.announced) return;
		i.timer = setTimeout(() => {
			i.timer = void 0;
			this.drainBootstrapRequests();
		}, resolveSafeTimeoutDelayMs(i.retryAtMs - n));
		i.timer.unref?.();
	}
	resumeBootstrapRequests() {
		clearTimeout(this.bootstrapPause?.timer);
		this.bootstrapPause = void 0;
		this.drainBootstrapRequests();
	}
	drainBootstrapRequests() {
		for (const e of this.pending.values()) if (e.waitingForResume) e.resend?.();
	}
	get hasPending() {
		return this.pending.size > 0;
	}
	get hasUnboundedPending() {
		for (const e of this.pending.values()) if (e.unbounded) return true;
		return false;
	}
	releaseHeldRequests(e) {
		for (const t of this.pending.values()) {
			if (!e()) return;
			const n = t.afterHello;
			t.afterHello = void 0;
			n?.();
		}
	}
	request(e, t, n, r, i = false) {
		let a;
		try {
			this.requestSequence += 1;
			a = `${this.requestSequence}:${this.opts.createRequestId()}`;
		} catch (e) {
			return Promise.reject(toStringifiedError(e));
		}
		const o = r?.timeoutMs === null ? void 0 : r?.timeoutMs ?? this.opts.requestTimeoutMs;
		const s = typeof o === "number" && Number.isFinite(o) ? resolveSafeTimeoutDelayMs(o, { minMs: 0 }) : void 0;
		return new Promise((o, c) => {
			let l;
			let u;
			let d = false;
			let f = false;
			const p = {
				resolve: (e) => o(e),
				reject: c,
				expectFinal: r?.expectFinal === true,
				acceptedNotified: false,
				onAccepted: r?.onAccepted,
				unbounded: s === void 0,
				method: t,
				startedAtMs: this.opts.nowMs(),
				prepareRetry: () => {
					f = false;
					d = false;
					if (r?.signal?.aborted) {
						onAbort();
						return false;
					}
					return true;
				}
			};
			const cleanup = () => {
				clearTimeout(u);
				if (l !== void 0) clearTimeout(l);
				r?.signal?.removeEventListener("abort", onAbort);
				if (this.bootstrapPause?.probe?.pending === p) {
					this.bootstrapPause.probe = void 0;
					this.drainBootstrapRequests();
				}
			};
			const retire = (e) => {
				if (this.pending.get(a) !== p) return false;
				this.pending.delete(a);
				cleanup();
				this.finishTiming(a, p, false, e);
				return true;
			};
			const onAbort = () => {
				if (r?.retainSentResultOnAbort && f) return;
				if (!retire("CLIENT_ABORTED")) return;
				c(this.opts.createRequestAbortError?.(t) ?? /* @__PURE__ */ new Error(`gateway request aborted for ${t}`));
			};
			if (r?.signal?.aborted) {
				c(this.opts.createRequestAbortError?.(t) ?? /* @__PURE__ */ new Error(`gateway request aborted for ${t}`));
				return;
			}
			p.cleanup = cleanup;
			if (s !== void 0) {
				l = setTimeout(() => {
					if (!retire("CLIENT_TIMEOUT")) return;
					c(this.opts.createRequestTimeoutError?.(t, s, d) ?? new GatewayProtocolRequestTimeoutError({
						method: t,
						timeoutMs: s,
						requestSent: d
					}));
				}, s);
				l.unref?.();
			}
			r?.signal?.addEventListener("abort", onAbort, { once: true });
			this.pending.set(a, p);
			try {
				const o = JSON.stringify({
					type: "req",
					id: a,
					method: t,
					params: n
				});
				const send = () => {
					if (this.pending.get(a) !== p || r?.signal?.aborted || s !== void 0 && this.opts.nowMs() - p.startedAtMs >= s) return;
					const t = p.resend ? this.bootstrapPause : void 0;
					if (t && !t.announced && !t.timer && !t.probe) t.probe = {
						pending: p,
						revision: t.revision
					};
					p.waitingForResume = Boolean(t && (t.announced || t.probe?.pending !== p));
					if (p.waitingForResume) return;
					try {
						f = true;
						e.send(o);
						if (this.pending.get(a) !== p) return;
						d = f;
						this.invoke("sent", () => r?.onSent?.(a));
					} catch (e) {
						if (retire("CLIENT_SEND_ERROR")) c(toStringifiedError(e));
					}
				};
				p.retryStartup = (e) => {
					p.resend = send;
					clearTimeout(u);
					u = setTimeout(send, resolveFiniteTimeoutDelayMs(e, GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS));
					u.unref?.();
				};
				if (t === "agent.identity.get" || t === "sessions.subscribe" || t === "sessions.groups.list" || t === "question.list" || t === "sessions.list") p.resend = send;
				if (i) p.afterHello = send;
				else send();
			} catch (e) {
				if (retire("CLIENT_SEND_ERROR")) c(toStringifiedError(e));
			}
		});
	}
	handleResponse(e) {
		const t = this.pending.get(e.id);
		if (!t) return;
		const n = e.payload?.status;
		if (e.ok && t.expectFinal && n === "accepted") {
			if (!t.acceptedNotified) {
				t.acceptedNotified = true;
				this.invoke("accepted", () => t.onAccepted?.(e.payload));
			}
			return;
		}
		const r = e.error?.details;
		if (!e.ok && isRetryableGatewayStartupUnavailableError(e.error) && r !== null && typeof r === "object" && "method" in r && r.method === t.method && !t.acceptedNotified) {
			if (t.prepareRetry()) {
				t.retryStartup?.(e.error?.retryAfterMs);
				if (this.bootstrapPause?.probe?.pending === t && this.bootstrapPause.probe.revision === this.bootstrapPause.revision) this.resumeBootstrapRequests();
			}
			return;
		}
		if (!e.ok && t.resend && !t.acceptedNotified && e.error?.code === "UNAVAILABLE" && e.error.retryable === true && (isGatewaySuspendUnavailableError(e.error) || isGatewayRestartUnavailableError(e.error))) {
			if (!t.prepareRetry()) return;
			if (this.bootstrapPause?.probe?.pending === t) this.bootstrapPause.probe = void 0;
			this.pauseBootstrapRequests(isGatewayRestartUnavailableError(e.error) ? Math.ceil(Math.max(GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS, e.error.retryAfterMs ?? 0) * (1 + Math.random() * .2)) : e.error.retryAfterMs);
			t.waitingForResume = true;
			return;
		}
		this.pending.delete(e.id);
		if (e.ok && this.bootstrapPause?.probe?.pending === t && this.bootstrapPause.probe.revision === this.bootstrapPause.revision) this.resumeBootstrapRequests();
		t.cleanup?.();
		if (e.ok) {
			this.finishTiming(e.id, t, true);
			t.resolve(e.payload);
			return;
		}
		this.finishTiming(e.id, t, false, e.error?.code);
		const i = this.opts.createRequestError?.(e.error ?? {}) ?? new GatewayProtocolRequestError(e.error ?? {});
		retainGatewayResponsePayload(i, e.payload);
		t.reject(i);
	}
	flush(e) {
		clearTimeout(this.bootstrapPause?.timer);
		this.bootstrapPause = void 0;
		const t = this.pending;
		this.pending = /* @__PURE__ */ new Map();
		this.requestSequence = 0;
		for (const [n, r] of t) {
			r.cleanup?.();
			this.finishTiming(n, r, false, "CLIENT_CLOSED");
			r.reject(e);
		}
	}
	finishTiming(e, t, n, r) {
		const i = this.opts.nowMs();
		this.invoke("request timing", () => this.opts.onTiming?.({
			id: e,
			method: t.method,
			ok: n,
			durationMs: Math.max(0, i - t.startedAtMs),
			startedAtMs: t.startedAtMs,
			endedAtMs: i,
			errorCode: r
		}));
	}
	invoke(e, t) {
		try {
			t();
		} catch (t) {
			this.opts.onCallbackError?.(e, t);
		}
	}
};
//#endregion
//#region packages/gateway-client/src/protocol-client.ts
const DEFAULT_CONNECT_FAILURE = Object.freeze({
	closeCode: 1008,
	closeReason: "connect failed"
});
/**
* Browser-safe gateway wire client. Environment adapters own transport and auth
* policy; this class owns the single socket/handshake/reconnect/frame state machine.
*/
var GatewayProtocolClient = class {
	constructor(e) {
		this.opts = e;
		this.socket = null;
		this.listeners = new GatewayEventListeners();
		this.stopped = true;
		this.generation = 0;
		this.connectionAbort = null;
		this.lastSeq = null;
		this.connectNonce = null;
		this.serverCapabilities = [];
		this.connectSent = false;
		this.connectRequestSent = false;
		this.handshakeTimer = null;
		this.reconnectSignal = null;
		this.socketOpened = false;
		this.helloReceived = false;
		this.readyForRequests = false;
		this.connectTiming = null;
		this.reconnectSupervisor = new RetrySupervisor({
			initialMs: e.reconnect.initialMs,
			maxMs: e.reconnect.maxMs,
			factor: e.reconnect.multiplier,
			jitter: 0
		});
		this.requests = new GatewayPendingRequests({
			createRequestId: e.createRequestId,
			createRequestError: e.createRequestError,
			createRequestTimeoutError: e.createRequestTimeoutError,
			createRequestAbortError: e.createRequestAbortError,
			requestTimeoutMs: e.requestTimeoutMs,
			nowMs: () => this.nowMs(),
			onTiming: e.onRequestTiming,
			onCallbackError: e.onCallbackError
		});
	}
	get connected() {
		return this.socket?.isOpen() ?? false;
	}
	get hasPendingRequests() {
		return this.requests.hasPending;
	}
	get connecting() {
		return this.connectSent && !this.helloReceived;
	}
	/** A transport upgrade is in flight; the socket adapter bounds how long it may stay open. */
	get opening() {
		return this.socket !== null && !this.socketOpened;
	}
	get hasUnboundedPendingRequests() {
		return this.requests.hasUnboundedPending;
	}
	start() {
		if (this.socket || this.reconnectSignal) return;
		this.stopped = false;
		this.reconnectSupervisor.cancel();
		this.connect();
	}
	stop() {
		this.stopped = true;
		this.connectionAbort?.abort();
		this.clearHandshakeTimer();
		this.reconnectSignal = null;
		this.reconnectSupervisor.reset();
		const e = this.socket;
		if (e && this.opts.notifyStoppedClose) this.stoppedSocket = {
			socket: e,
			context: this.closeContext()
		};
		this.socket = null;
		this.connectFailure = void 0;
		this.connectTiming = null;
		this.requests.flush(/* @__PURE__ */ new Error("gateway client stopped"));
		e?.close();
	}
	request(e, t, n) {
		const r = this.socket;
		if (!r || this.socketOpened && !r.isOpen()) return Promise.reject(/* @__PURE__ */ new Error("gateway not connected"));
		if (typeof e !== "string" || e.length === 0) return Promise.reject(/* @__PURE__ */ new Error("invalid request frame: method must be a non-empty string"));
		return this.requests.request(r, e, t, n, !this.readyForRequests);
	}
	addEventListener(e) {
		return this.listeners.add(e);
	}
	closeSocket(e, t) {
		this.connectionAbort?.abort();
		this.socket?.close(e, t);
	}
	resetReconnectBackoff(e) {
		this.reconnectSignal = null;
		this.reconnectSupervisor.reset(e);
	}
	recordTiming(e, t, n, r) {
		const i = this.nowMs();
		const a = this.connectTiming;
		if (!a || a.generation !== t) return;
		a.hasChallenge ||= e === "challenge";
		a.usedFallback ||= e === "fallback";
		this.invoke("connect timing", () => this.opts.onTiming?.({
			phase: e,
			generation: t,
			durationMs: Math.max(0, i - a.startedAtMs),
			phaseDurationMs: Math.max(0, i - a.lastAtMs),
			hasChallenge: a.hasChallenge,
			usedFallback: a.usedFallback,
			plan: n,
			detail: r
		}));
		a.lastAtMs = i;
		if (e === "hello" || e === "failed") this.connectTiming = null;
	}
	connect() {
		if (this.stopped) return;
		const e = this.generation + 1;
		this.lastSeq = null;
		this.connectNonce = null;
		this.connectChallengeTs = void 0;
		this.serverCapabilities = [];
		this.connectSent = this.connectRequestSent = false;
		this.socketOpened = false;
		this.helloReceived = false;
		this.readyForRequests = false;
		this.connectFailure = void 0;
		let t;
		try {
			t = this.opts.createSocket({
				open: () => {
					if (!this.isActive(t, e)) return;
					this.socketOpened = true;
					this.recordTiming("socket-open", e);
					if (this.connectNonce) {
						this.sendConnect(t, e);
						return;
					}
					this.clearHandshakeTimer();
					const n = Date.now();
					this.handshakeTimer = setTimeout(() => {
						this.handshakeTimer = null;
						if (!this.isActive(t, e) || this.connectSent || !t.isOpen()) return;
						if (this.opts.handshake.mode === "fallback") {
							this.recordTiming("fallback", e);
							this.sendConnect(t, e);
							return;
						}
						const r = Date.now() - n;
						const i = new Error(this.opts.handshake.timeoutMessage?.(r) ?? `gateway connect challenge timeout after ${r}ms`);
						this.opts.onConnectError?.(i);
						t.close(1008, "connect challenge timeout");
					}, this.opts.handshake.timeoutMs);
					this.handshakeTimer.unref?.();
				},
				message: (n) => this.handleMessage(t, e, n),
				close: (n, r) => {
					if (this.socket !== t) {
						if (this.stoppedSocket?.socket === t) {
							const e = {
								...this.stoppedSocket.context,
								code: n,
								reason: r
							};
							this.stoppedSocket = void 0;
							this.invoke("close", () => this.opts.onClose?.(e, {
								retry: false,
								notify: true
							}));
						}
						return;
					}
					this.socket = null;
					this.connectionAbort?.abort();
					this.clearHandshakeTimer();
					const i = {
						...this.closeContext(),
						code: n,
						reason: r,
						generation: e
					};
					this.connectFailure = void 0;
					const a = this.opts.resolveClose(i);
					this.requests.flush(a.pendingError ?? i.connectFailure?.error ?? /* @__PURE__ */ new Error(`gateway closed (${n}): ${r}`));
					this.invoke("close", () => this.opts.onClose?.(i, a));
					if (a.retry && !this.stopped && !this.socket && !this.reconnectSignal) {
						const e = i.connectFailure?.error;
						const t = e instanceof GatewayProtocolRequestError && e.retryable && e.retryAfterMs !== void 0 && Number.isFinite(e.retryAfterMs) && e.retryAfterMs > 0 ? e.retryAfterMs : void 0;
						this.scheduleReconnect(a.reconnectDelayMs ?? i.connectFailure?.reconnectDelayMs, t);
					}
				},
				error: (n) => {
					if (!this.isActive(t, e) || this.connectSent) return;
					this.connectFailure = { error: n };
					this.opts.onConnectError?.(n);
				}
			});
		} catch (e) {
			const t = toStringifiedError(e);
			this.opts.onSocketFactoryError?.(t);
			this.opts.onConnectError?.(t);
			if (this.opts.rethrowSocketFactoryError?.(t)) {
				if (this.generation > 0 && !this.stopped && !this.socket && !this.reconnectSignal) this.opts.onReconnectStopped?.(t);
				throw t;
			}
			if (this.opts.shouldRetrySocketFactoryError?.(t) && !this.stopped && !this.socket && !this.reconnectSignal) this.scheduleReconnect();
			else if (this.generation > 0 && !this.stopped && !this.socket && !this.reconnectSignal) this.opts.onReconnectStopped?.(t);
			return;
		}
		this.generation = e;
		this.connectionAbort = new AbortController();
		this.socket = t;
		const n = this.nowMs();
		this.connectTiming = {
			generation: e,
			startedAtMs: n,
			lastAtMs: n,
			hasChallenge: false,
			usedFallback: false
		};
	}
	sendConnect(e, t) {
		if (!this.isActive(e, t) || !e.isOpen() || this.connectSent) return;
		this.connectSent = true;
		this.clearHandshakeTimer();
		this.handshakeTimer = startGatewayConnectTimeout(() => {
			if (this.isActive(e, t) && !this.helloReceived) e.close(4e3, "connect timeout");
		});
		let n;
		try {
			n = this.opts.buildConnectPlan({
				nonce: this.connectNonce,
				challengeTs: this.connectChallengeTs,
				serverCapabilities: this.serverCapabilities,
				generation: t,
				...this.connectAuthority(e, t)
			});
		} catch (n) {
			this.handleConnectPlanError(e, t, n);
			return;
		}
		if (n instanceof Promise) {
			n.then((n) => this.sendConnectPlan(e, t, n)).catch((n) => this.handleConnectPlanError(e, t, n));
			return;
		}
		this.sendConnectPlan(e, t, n);
	}
	handleConnectPlanError(e, t, n) {
		if (!this.isConnectCurrent(e, t)) return;
		const r = toStringifiedError(n);
		const i = this.opts.onConnectPlanError?.(r) ?? DEFAULT_CONNECT_FAILURE;
		this.opts.onConnectError?.(i.error ?? r);
		if (i.stop) this.stopped = true;
		e.close(i.closeCode, i.closeReason);
	}
	sendConnectPlan(e, t, n) {
		if (!this.isConnectCurrent(e, t)) return;
		const r = {
			...this.connectAuthority(e, t),
			generation: t,
			nonce: this.connectNonce,
			challengeTs: this.connectChallengeTs,
			plan: n
		};
		this.recordTiming("connect-plan-ready", t, n);
		this.requests.request(e, "connect", this.opts.buildConnectParams(n), { onSent: () => {
			this.connectRequestSent = true;
			this.recordTiming("request-sent", t, n);
		} }).then((i) => {
			if (!this.isConnectCurrent(e, t)) return;
			this.helloReceived = true;
			this.requests.setSuspensionPhase(i.snapshot?.suspension?.phase);
			this.clearHandshakeTimer();
			this.connectFailure = void 0;
			this.reconnectSupervisor.reset();
			this.recordTiming("hello", t, n);
			const publishHello = () => {
				if (!this.isConnectCurrent(e, t)) return;
				this.invoke("hello", () => this.opts.onHello?.(i));
				if (!this.isConnectCurrent(e, t)) return;
				this.requests.releaseHeldRequests(() => this.isConnectCurrent(e, t));
				if (this.isConnectCurrent(e, t)) this.readyForRequests = true;
			};
			const a = this.opts.onConnectHello?.(i, r);
			if (a instanceof Promise) return a.then(publishHello);
			return publishHello();
		}).catch((n) => {
			if (!this.isActive(e, t)) return;
			const i = n instanceof GatewayProtocolRequestError ? n : new GatewayProtocolRequestError({ message: String(n) });
			this.connectFailure = { error: i };
			const a = this.opts.onConnectFailure?.(i, r) ?? DEFAULT_CONNECT_FAILURE;
			const applyFailure = (n) => {
				if (!this.isActive(e, t)) return;
				this.connectFailure = {
					error: i,
					reconnectDelayMs: n.reconnectDelayMs
				};
				if (n.keepOpen) {
					this.clearHandshakeTimer();
					return;
				}
				if (n.stop) this.stopped = true;
				this.connectionAbort?.abort();
				e.close(n.closeCode, n.closeReason);
			};
			if (a instanceof Promise) return a.then(applyFailure);
			return applyFailure(a);
		}).catch((n) => {
			if (!this.isConnectCurrent(e, t)) return;
			this.opts.onConnectError?.(toStringifiedError(n));
			this.closeSocket(DEFAULT_CONNECT_FAILURE.closeCode, DEFAULT_CONNECT_FAILURE.closeReason);
		});
	}
	handleMessage(e, t, n) {
		if (!this.isActive(e, t) || this.connectionAbort?.signal.aborted) return;
		let r;
		try {
			r = JSON.parse(n);
		} catch (e) {
			this.opts.onParseError?.(e);
			return;
		}
		if (isGatewayEventFrame(r)) {
			this.opts.onActivity?.();
			if (r.event === "connect.challenge") {
				const n = r.payload;
				const i = typeof n?.nonce === "string" ? n.nonce.trim() : "";
				if (!i) {
					if (this.opts.handshake.mode === "require-challenge") {
						const t = /* @__PURE__ */ new Error("gateway connect challenge missing nonce");
						this.opts.onConnectError?.(t);
						e.close(1008, "connect challenge missing nonce");
					}
					return;
				}
				this.connectNonce = i;
				this.serverCapabilities = filterStringEntries(n?.capabilities);
				const a = n?.ts;
				this.connectChallengeTs = typeof a === "number" && Number.isSafeInteger(a) && a >= 0 ? a : null;
				this.recordTiming("challenge", t);
				this.sendConnect(e, t);
				return;
			}
			const n = r.seq;
			if (n !== void 0) {
				if (this.lastSeq !== null && n > this.lastSeq + 1) {
					const i = this.lastSeq + 1;
					const a = asRecord(r.payload).state;
					if (r.event === "chat" && (a === "final" || a === "error" || a === "aborted")) this.dispatchEvent(e, t, r);
					if (!this.isActive(e, t) || this.connectionAbort?.signal.aborted) return;
					this.invoke("gap", () => this.opts.onGap?.({
						expected: i,
						received: n
					}));
					if (this.isActive(e, t) && !this.connectionAbort?.signal.aborted) this.closeSocket(4e3, "event sequence gap");
					return;
				}
				this.lastSeq = n;
			}
			this.dispatchEvent(e, t, r);
			return;
		}
		if (!isGatewayResponseFrame(r)) return;
		this.opts.onActivity?.();
		this.requests.handleResponse(r);
	}
	dispatchEvent(e, t, n) {
		const r = this.listeners.snapshot();
		if (n.event === "gateway.suspension") this.requests.setSuspensionPhase(asRecord(n.payload).phase);
		else if (n.event === "shutdown" && typeof asRecord(n.payload).restartExpectedMs === "number") this.requests.setSuspensionPhase("draining");
		this.invoke("event", () => this.opts.onEvent?.(n));
		for (const [i, a] of r) {
			if (!this.isActive(e, t) || this.connectionAbort?.signal.aborted) return;
			if (this.listeners.isCurrent(i, a)) this.invoke("event listener", () => i(n));
		}
	}
	scheduleReconnect(e, t = 0) {
		if (e !== void 0) this.reconnectSupervisor.nextDelayOverrideMs = e;
		const n = this.reconnectSupervisor.next();
		if (!n) return;
		this.reconnectSignal = n.signal;
		let r = e;
		if (r === void 0) {
			const e = Math.max(n.delayMs, t);
			const i = Math.max(this.opts.reconnect.maxMs, Math.min(Number.MAX_VALUE, t * 1.2));
			const a = Math.max(t, Math.min(e, i / 1.2));
			const o = Math.min(e * 1.2, i);
			r = Math.ceil(a + Math.random() * (o - a));
		}
		r = resolveSleepDelayMs(r);
		sleepWithAbort(r, n.signal).then(() => {
			if (this.reconnectSignal !== n.signal) return;
			this.reconnectSignal = null;
			this.invoke("reconnect", () => this.connect());
		}, () => {
			if (this.reconnectSignal === n.signal) this.reconnectSignal = null;
		});
		this.invoke("reconnect scheduled", () => this.opts.onReconnectScheduled?.(r, n.signal));
	}
	closeContext() {
		return {
			generation: this.generation,
			socketOpened: this.socketOpened,
			helloReceived: this.helloReceived,
			connectRequestSent: this.connectRequestSent,
			connectFailure: this.connectFailure
		};
	}
	isConnectCurrent(e, t) {
		return this.isActive(e, t) && e.isOpen() && !this.connectionAbort?.signal.aborted;
	}
	connectAuthority(e, t) {
		const n = this.connectionAbort?.signal;
		if (!n) throw new Error("gateway connection authority is unavailable");
		return {
			signal: n,
			assertCurrent: () => {
				n.throwIfAborted();
				if (!this.isConnectCurrent(e, t)) throw new Error("gateway connection retired");
			}
		};
	}
	isActive(e, t) {
		return !this.stopped && this.socket === e && this.generation === t;
	}
	nowMs() {
		return this.opts.nowMs?.() ?? Date.now();
	}
	clearHandshakeTimer() {
		this.handshakeTimer = clearGatewayConnectTimeout(this.handshakeTimer);
	}
	invoke(e, t) {
		try {
			t();
		} catch (t) {
			this.opts.onCallbackError?.(e, t);
		}
	}
};
//#endregion
//#region packages/gateway-client/src/reconnect-policy.ts
const NON_RECOVERABLE_AUTH_ERRORS = /* @__PURE__ */ new Set([
	ConnectErrorDetailCodes.AUTH_TOKEN_MISSING,
	ConnectErrorDetailCodes.AUTH_BOOTSTRAP_TOKEN_INVALID,
	ConnectErrorDetailCodes.AUTH_PASSWORD_MISSING,
	ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH,
	ConnectErrorDetailCodes.AUTH_RATE_LIMITED,
	ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH,
	ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH,
	ConnectErrorDetailCodes.AUTH_IDENTITY_HEADER_REQUIRED,
	ConnectErrorDetailCodes.AUTH_VERIFIED_USER_REQUIRED,
	ConnectErrorDetailCodes.CONTROL_UI_BUILD_MISMATCH,
	ConnectErrorDetailCodes.PAIRING_REQUIRED,
	ConnectErrorDetailCodes.PAIRING_REJECTED,
	ConnectErrorDetailCodes.PAIRING_EXPIRED,
	ConnectErrorDetailCodes.CONTROL_UI_DEVICE_IDENTITY_REQUIRED,
	ConnectErrorDetailCodes.DEVICE_IDENTITY_REQUIRED
]);
function shouldPauseGatewayReconnect(e) {
	const t = readConnectErrorDetailCode(e.details);
	if (!t) return false;
	const n = readPairingConnectErrorDetails(e.details);
	if (t === ConnectErrorDetailCodes.PAIRING_REQUIRED && (n?.pauseReconnect === false || n?.recommendedNextStep === "wait_then_retry")) return false;
	if (t === ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH) return e.tokenMismatchIsTerminal === true && !e.deviceTokenRetryPending;
	if (t === ConnectErrorDetailCodes.AUTH_IDENTITY_HEADER_REQUIRED) return !e.deviceTokenRetryPending;
	return NON_RECOVERABLE_AUTH_ERRORS.has(t) || e.protocolMismatchIsTerminal === true && t === ConnectErrorDetailCodes.PROTOCOL_MISMATCH || e.clientVersionMismatchIsTerminal === true && t === ConnectErrorDetailCodes.CLIENT_VERSION_MISMATCH;
}
//#endregion
//#region packages/gateway-client/src/client.ts
const DEFAULT_HOST_DEPS = {
	loadOrCreateDeviceIdentity: () => void 0,
	signDevicePayload: () => {
		throw new Error("GatewayClient device signature dependency is not configured");
	},
	publicKeyRawBase64UrlFromPem: () => {
		throw new Error("GatewayClient public key dependency is not configured");
	},
	loadDeviceAuthToken: () => null,
	storeDeviceAuthToken: () => {},
	clearDeviceAuthToken: () => {},
	beforeConnect: () => {},
	registerGatewayLoopbackBypass: () => void 0,
	logDebug: () => {},
	logError: () => {},
	redactForLog: (e) => e,
	normalizeTlsFingerprint
};
function resolveHostDeps(e) {
	return Object.fromEntries(Object.entries(DEFAULT_HOST_DEPS).map(([t, n]) => [t, e?.[t] ?? n]));
}
const DEFAULT_GATEWAY_CLIENT_URL = "ws://127.0.0.1:18789";
const DEFAULT_CLIENT_VERSION = "0.0.0";
var GatewayClientTransportPolicyError = class extends GatewayWebSocketTransportConfigurationError {};
const FORCE_STOP_TERMINATE_GRACE_MS = 250;
const STOP_AND_WAIT_TIMEOUT_MS = 1e3;
const MAX_SUPPRESSED_TRANSIENT_PRE_HELLO_CLEAN_CLOSES = 1;
var GatewayClient$1 = class {
	constructor(e) {
		this.ws = null;
		this.stopped = false;
		this.useLegacyNodeProtocolEnvelope = false;
		this.nodeProtocolTransitionPending = false;
		this.pendingDeviceTokenRetry = false;
		this.deviceTokenRetryBudgetUsed = false;
		this.approvalRuntimeTokenCompatibilityDisabled = false;
		this.approvalRuntimeTokenRetryBudgetUsed = false;
		this.lastTick = null;
		this.tickIntervalMs = 3e4;
		this.tickTimer = null;
		this.pendingStop = null;
		this.transportValidated = false;
		this.suppressedTransientPreHelloCleanCloses = 0;
		this.deps = resolveHostDeps(e.hostDeps);
		this.deviceAuth = new GatewayClientDeviceAuth(this.deps);
		this.opts = {
			...e,
			deviceIdentity: e.deviceIdentity === null ? void 0 : e.deviceIdentity ?? this.deps.loadOrCreateDeviceIdentity()
		};
		this.requestTimeoutMs = typeof e.requestTimeoutMs === "number" && Number.isFinite(e.requestTimeoutMs) ? e.requestTimeoutMs : DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS;
		const t = resolveConnectChallengeTimeoutMs(this.opts.connectChallengeTimeoutMs, {
			env: this.opts.env,
			configuredTimeoutMs: this.opts.preauthHandshakeTimeoutMs
		});
		this.protocol = new GatewayProtocolClient({
			createSocket: (e) => this.createSocket(e),
			createRequestId: randomUUID,
			createRequestError: (e) => new GatewayClientRequestError(e),
			createRequestTimeoutError: (e, t, n) => new GatewayClientRequestTimeoutError({
				method: e,
				timeoutMs: t,
				requestSent: n
			}),
			createRequestAbortError: (e) => createAbortError(`gateway request aborted for ${e}`),
			buildConnectPlan: ({ nonce: e, challengeTs: t, serverCapabilities: n, generation: r, ...i }) => {
				if (!e) throw new Error("gateway connect challenge missing nonce");
				if (this.opts.deviceIdentity && t == null) throw new Error("gateway connect challenge timestamp invalid");
				const a = this.opts.role ?? "operator";
				const assemble = (o) => {
					i.assertCurrent();
					const s = t ?? Date.now();
					const c = selectGatewayConnectAuth({
						token: this.opts.token,
						bootstrapToken: this.opts.bootstrapToken,
						preferBootstrapToken: this.opts.preferBootstrapToken,
						deviceToken: this.opts.deviceToken,
						password: this.opts.password,
						approvalRuntimeToken: this.approvalRuntimeTokenCompatibilityDisabled ? void 0 : this.opts.approvalRuntimeToken,
						agentRuntimeIdentityToken: this.opts.agentRuntimeIdentityToken,
						storedToken: o?.token,
						storedScopes: o?.scopes,
						pendingDeviceTokenRetry: this.pendingDeviceTokenRetry,
						trustedDeviceTokenRetry: this.isTrustedDeviceRetryEndpoint()
					});
					const { authDeviceToken: l, authApprovalRuntimeToken: u, authAgentRuntimeIdentityToken: d, signatureToken: f, resolvedDeviceToken: p, storedToken: m, storedScopes: h, usingStoredDeviceToken: g } = c;
					if (this.pendingDeviceTokenRetry && l) this.pendingDeviceTokenRetry = false;
					const _ = buildGatewayConnectAuth(c);
					const v = resolveGatewayConnectScopes({
						requestedScopes: this.opts.scopes,
						usingStoredDeviceToken: g,
						storedScopes: h,
						defaultScopes: ["operator.admin"]
					});
					const y = this.opts.mode ?? GATEWAY_CLIENT_MODES.BACKEND;
					const b = this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
					const x = a === "node" && y === GATEWAY_CLIENT_MODES.NODE && b === GATEWAY_CLIENT_NAMES.NODE_HOST;
					const S = shouldNegotiateLegacyNodeProtocol(this.opts);
					const C = x && (this.useLegacyNodeProtocolEnvelope || this.opts.maxProtocol === 3 && (this.opts.minProtocol ?? 3) <= 3);
					const w = C ? 3 : S ? 4 : this.opts.minProtocol ?? (y === GATEWAY_CLIENT_MODES.PROBE ? 3 : a === "node" && y === GATEWAY_CLIENT_MODES.NODE ? 3 : 4);
					const T = C ? 3 : S ? 4 : this.opts.maxProtocol ?? 4;
					const { platform: E, deviceFamily: D, modelIdentifier: O } = resolveNodeProtocolClientMetadata(this.opts, process.platform, C);
					const k = {
						minProtocol: w,
						maxProtocol: T,
						client: {
							id: b,
							displayName: this.opts.clientDisplayName,
							version: this.opts.clientVersion ?? DEFAULT_CLIENT_VERSION,
							buildId: this.opts.clientBuildId,
							platform: E,
							deviceFamily: D,
							modelIdentifier: O,
							mode: y,
							instanceId: this.opts.instanceId
						},
						...resolveModelCatalogConnect({
							caps: Array.isArray(this.opts.caps) ? this.opts.caps : [],
							modelCatalog: C ? void 0 : this.opts.modelCatalog,
							serverCapabilities: n
						}),
						commands: Array.isArray(this.opts.commands) ? this.opts.commands : void 0,
						computerUse: C ? void 0 : this.opts.computerUse,
						workerRuns: C ? void 0 : this.opts.workerRuns,
						permissions: this.opts.permissions && typeof this.opts.permissions === "object" ? this.opts.permissions : void 0,
						pathEnv: this.opts.pathEnv,
						auth: _,
						role: a,
						scopes: v,
						device: void 0
					};
					if (this.opts.deviceIdentity) {
						const t = buildDeviceAuthPayloadV3({
							deviceId: this.opts.deviceIdentity.deviceId,
							clientId: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
							clientMode: y,
							role: a,
							scopes: v,
							signedAtMs: s,
							token: f ?? null,
							nonce: e,
							platform: E,
							deviceFamily: D
						});
						const n = this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem, t);
						k.device = {
							id: this.opts.deviceIdentity.deviceId,
							publicKey: this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),
							signature: n,
							signedAt: s,
							nonce: e
						};
					}
					const A = {
						params: k,
						authApprovalRuntimeToken: u,
						authAgentRuntimeIdentityToken: d,
						resolvedDeviceToken: p,
						storedScopes: h,
						storedToken: m,
						usingStoredDeviceToken: g
					};
					this.connectionStoredToken = {
						generation: r,
						token: A.storedToken ?? null
					};
					return A;
				};
				const o = this.opts.deviceIdentity ? this.deviceAuth.load({
					deviceId: this.opts.deviceIdentity.deviceId,
					role: a,
					env: this.opts.env,
					...i
				}) : null;
				return o instanceof Promise ? o.then(assemble) : assemble(o);
			},
			buildConnectParams: (e) => e.params,
			onConnectPlanError: (e) => {
				this.stopped = true;
				const t = markGatewayConnectAssemblyError(e);
				const n = `gateway connect failed: ${formatGatewayClientErrorForLog(e)}`;
				if (this.opts.mode === GATEWAY_CLIENT_MODES.PROBE || isGatewayClientStoppedError(e)) this.logDebug(n);
				else this.logError(n);
				return {
					closeCode: 1008,
					closeReason: "connect failed",
					stop: true,
					error: t
				};
			},
			onConnectHello: (e, t) => {
				const n = t.plan;
				t.assertCurrent();
				const r = this.opts.role ?? "operator";
				const i = e.auth;
				const a = this.connectionStoredToken;
				const persisted = () => {
					if (i?.deviceToken && (i.role ?? r) === r && a) a.token = i.deviceToken;
					if (this.opts.preferBootstrapToken) {
						this.opts.token = void 0;
						this.opts.bootstrapToken = void 0;
						this.opts.password = void 0;
						this.opts.preferBootstrapToken = false;
					}
				};
				let o = void 0;
				if (i?.deviceToken && this.opts.deviceIdentity) {
					const e = i.role ?? r;
					const t = e === r && i.deviceToken === n.storedToken ? n.storedScopes ?? i.scopes ?? [] : i.scopes ?? [];
					if (e === r && a) a.receiptToken = i.deviceToken;
					o = this.deviceAuth.store({
						deviceId: this.opts.deviceIdentity.deviceId,
						role: e,
						token: i.deviceToken,
						scopes: t,
						env: this.opts.env,
						...e === r ? { expectedToken: n.storedToken ?? null } : {}
					}, persisted, (e) => {
						n.persistenceFailed = true;
						const t = this.notifyConnectError(e);
						this.logError(`gateway device token persistence failed: ${formatGatewayClientErrorForLog(e)}`);
						return t;
					});
					if (a && o instanceof Promise) a.persistence = o;
				} else persisted();
				const complete = () => {
					if (t.signal.aborted || !this.protocol.connected) return;
					t.assertCurrent();
					const n = this.useLegacyNodeProtocolEnvelope && shouldNegotiateLegacyNodeProtocol(this.opts) && e.protocol > 3;
					if (n) this.useLegacyNodeProtocolEnvelope = false;
					this.nodeProtocolTransitionPending = false;
					this.pendingDeviceTokenRetry = false;
					this.deviceTokenRetryBudgetUsed = false;
					this.suppressedTransientPreHelloCleanCloses = 0;
					this.tickIntervalMs = typeof e.policy?.tickIntervalMs === "number" ? e.policy.tickIntervalMs : 3e4;
					if (n) {
						this.protocol.resetReconnectBackoff(250);
						this.protocol.closeSocket(1012, "gateway protocol upgraded");
						return;
					}
					this.lastTick = Date.now();
					this.startTickWatch();
				};
				return o instanceof Promise ? o.then(complete) : complete();
			},
			onHello: (e) => {
				this.opts.onHelloOk?.(e);
			},
			onConnectFailure: (e, t) => {
				const n = t.plan;
				if (n.persistenceFailed) return {
					closeCode: 1008,
					closeReason: "connect failed"
				};
				const r = e instanceof GatewayClientRequestError ? readConnectErrorDetailCode(e.details) : null;
				const i = this.opts.deviceIdentity && n.usingStoredDeviceToken && r === ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH ? this.clearDeviceToken(this.opts.deviceIdentity.deviceId, { token: n.storedToken }) : void 0;
				const a = this.resolveConnectRequestFailure(e, n);
				return i instanceof Promise ? i.then(() => a) : a;
			},
			resolveClose: (e) => this.resolveClose(e),
			onClose: (e, t) => {
				clearInterval(this.tickTimer ?? void 0);
				this.tickTimer = null;
				if (t.notify) this.opts.onClose?.(e.code, e.reason, this.closeInfo(e));
			},
			notifyStoppedClose: true,
			onConnectError: (e) => this.notifyConnectError(e),
			onReconnectStopped: (e) => this.notifyReconnectPaused({
				code: 1008,
				reason: e.message,
				detailCode: null
			}),
			onParseError: (e) => this.logDebug(`gateway client parse error: ${formatGatewayClientErrorForLog(e)}`),
			onEvent: (e) => this.opts.onEvent?.(e),
			onGap: (e) => this.opts.onGap?.(e),
			onRequestTiming: (e) => this.opts.onRequestTiming?.(e),
			onActivity: () => {
				this.lastTick = Date.now();
			},
			onCallbackError: (e, t) => this.logDebug(`gateway client ${e === "hello" ? "hello-ok" : e === "gap" ? "event" : e} handler error: ${formatGatewayClientErrorForLog(t)}`),
			handshake: {
				mode: "require-challenge",
				timeoutMs: t,
				timeoutMessage: (e) => `gateway connect challenge timeout (waited ${e}ms, limit ${t}ms)`
			},
			reconnect: {
				initialMs: 1e3,
				multiplier: 2,
				maxMs: 3e4
			},
			requestTimeoutMs: this.requestTimeoutMs,
			shouldRetrySocketFactoryError: (e) => !(e instanceof GatewayWebSocketTransportConfigurationError) && !(e instanceof SyntaxError) && !(e instanceof TypeError) && !(e instanceof RangeError),
			rethrowSocketFactoryError: (e) => e instanceof GatewayClientTransportPolicyError
		});
	}
	/** Current transport state, including CLOSING before the close callback fires.
	* This is not authentication or readiness evidence on its own. */
	get connected() {
		return !this.stopped && this.protocol.connected;
	}
	getConnectionMetadata() {
		return {
			clientName: this.opts.clientName,
			hasDeviceIdentity: Boolean(this.opts.deviceIdentity),
			mode: this.opts.mode,
			preauthHandshakeTimeoutMs: this.opts.preauthHandshakeTimeoutMs
		};
	}
	updateNodeManifest(e) {
		this.opts = {
			...this.opts,
			caps: [...e.caps],
			commands: [...e.commands],
			computerUse: e.computerUse === void 0 ? void 0 : structuredClone(e.computerUse),
			workerRuns: e.workerRuns ? structuredClone(e.workerRuns) : void 0
		};
		if (!this.stopped) this.protocol.closeSocket(1012, "node manifest changed");
	}
	start() {
		if (this.stopped) return;
		this.protocol.start();
	}
	createSocket(e) {
		const t = this.opts.url ?? DEFAULT_GATEWAY_CLIENT_URL;
		const n = this.opts.edgeAuthHeaders;
		const r = n && Object.keys(n).length > 0 ? n : void 0;
		if (r && new URL(t).protocol !== "wss:") throw new GatewayWebSocketTransportConfigurationError("edge auth headers require a wss:// Gateway URL");
		const i = resolvePreauthHandshakeTimeoutMs({
			env: this.opts.env,
			configuredTimeoutMs: this.opts.preauthHandshakeTimeoutMs
		});
		const a = resolveGatewayWebSocketTransport({
			url: t,
			tlsFingerprint: this.opts.tlsFingerprint,
			tlsServerName: this.opts.tlsServerName,
			env: this.opts.env,
			normalizeTlsFingerprint: this.deps.normalizeTlsFingerprint,
			options: {
				maxPayload: 26214400,
				handshakeTimeout: i,
				...this.opts.origin ? { origin: this.opts.origin } : {},
				...r ? {
					followRedirects: false,
					headers: r
				} : {}
			}
		});
		this.deps.beforeConnect();
		let o;
		let s;
		try {
			try {
				s = this.deps.registerGatewayLoopbackBypass(t);
				this.opts.assertConnectionCurrent?.();
			} catch (e) {
				throw new GatewayClientTransportPolicyError(e instanceof Error ? e.message : String(e));
			}
			o = new WebSocket(t, a.options);
			o.binaryType = "nodebuffer";
		} finally {
			s?.();
		}
		this.ws = o;
		this.transportValidated = false;
		let c;
		o.on("open", () => {
			this.transportValidated = true;
			e.open();
		});
		o.on("message", (t) => e.message(rawDataToString(t)));
		o.on("close", (t, n) => {
			const r = n.toString();
			if (this.ws === o) this.ws = null;
			this.resolvePendingStop(o);
			e.close(t, r);
		});
		o.on("unexpected-response", (t, n) => {
			readUpgradeErrorBody(n).then((r) => {
				const i = n.statusCode;
				const a = safeParseJsonRecord(r)?.error;
				const s = isRecord(a) ? a : void 0;
				const l = n.headers.location;
				const u = l ? redactSensitiveUrlLikeString(Array.isArray(l) ? l[0] ?? "" : l) : void 0;
				const d = `gateway rejected websocket upgrade (HTTP ${i ?? "unknown"})${r ? `: ${r}` : ""}`;
				c = new GatewayClientRequestError({
					code: "UNAVAILABLE",
					message: d,
					retryable: true,
					details: {
						reason: "websocket-upgrade-rejected",
						...i === void 0 ? {} : { httpStatus: i },
						...u ? { location: u } : {},
						...typeof s?.type === "string" ? {
							gatewayErrorType: s.type,
							...typeof s.message === "string" ? { gatewayErrorMessage: s.message } : {}
						} : {}
					}
				});
				e.error(c);
				t.destroy();
				o.close();
			});
		});
		o.on("error", (t) => {
			if (c) return;
			if (t.message === "Opening handshake has timed out") Object.assign(t, { code: "ETIMEDOUT" });
			this.logDebug(`gateway client error: ${formatGatewayClientErrorForLog(t)}`);
			e.error(t instanceof Error ? t : new Error(String(t)));
		});
		return {
			isOpen: () => o.readyState === WebSocket.OPEN,
			send: (e) => {
				this.opts.assertConnectionCurrent?.();
				o.send(e);
			},
			close: (e, t) => o.close(e, t)
		};
	}
	stop() {
		this.beginStop();
	}
	async stopAndWait(e) {
		const t = this.beginStop();
		const n = e?.timeoutMs === void 0 ? STOP_AND_WAIT_TIMEOUT_MS : resolveSafeTimeoutDelayMs(e.timeoutMs);
		try {
			await raceWithTimeout(Promise.resolve(t), n, () => {
				throw new Error(`gateway client stop timed out after ${n}ms`);
			}, { ref: false });
		} finally {
			await this.deviceAuth.drain();
		}
	}
	beginStop() {
		this.stopped = true;
		this.pendingDeviceTokenRetry = false;
		this.deviceTokenRetryBudgetUsed = false;
		clearInterval(this.tickTimer ?? void 0);
		this.tickTimer = null;
		if (this.pendingStop) return this.pendingStop.promise;
		const e = this.ws;
		this.ws = null;
		if (e) {
			let resolve = () => {};
			const t = {
				ws: e,
				promise: new Promise((e) => {
					resolve = e;
				}),
				resolve
			};
			this.pendingStop = t;
			const n = setTimeout(() => {
				try {
					e.terminate();
				} finally {
					this.resolvePendingStop(e);
				}
			}, FORCE_STOP_TERMINATE_GRACE_MS);
			n.unref?.();
			t.terminateTimer = n;
			if (this.protocol.connecting) {
				const e = /* @__PURE__ */ new Error("gateway client stopped");
				this.notifyConnectError(e);
				this.logDebug(`gateway connect failed: ${formatGatewayClientErrorForLog(e)}`);
			}
			this.protocol.stop();
			return t.promise;
		}
		this.protocol.stop();
		return null;
	}
	resolvePendingStop(e) {
		if (this.pendingStop?.ws !== e) return;
		const { resolve: t, terminateTimer: n } = this.pendingStop;
		if (n) clearTimeout(n);
		this.pendingStop = null;
		t();
	}
	logDebug(e) {
		this.deps.logDebug(this.deps.redactForLog(e));
	}
	logError(e) {
		this.deps.logError(this.deps.redactForLog(e));
	}
	shouldRetryWithAlternateNodeProtocol(e) {
		if (!shouldNegotiateLegacyNodeProtocol(this.opts) || !(e instanceof GatewayClientRequestError)) return false;
		const t = readConnectErrorDetailCode(e.details);
		return e.details?.expectedProtocol === (this.useLegacyNodeProtocolEnvelope ? 4 : 3) && (t === ConnectErrorDetailCodes.PROTOCOL_MISMATCH || normalizeLowercaseStringOrEmpty(e.message).includes("protocol mismatch"));
	}
	resolveConnectRequestFailure(e, t) {
		if (this.shouldRetryWithAlternateNodeProtocol(e)) {
			const e = !this.nodeProtocolTransitionPending;
			this.useLegacyNodeProtocolEnvelope = !this.useLegacyNodeProtocolEnvelope;
			this.nodeProtocolTransitionPending = true;
			if (e) this.protocol.resetReconnectBackoff(250);
			this.logDebug(this.useLegacyNodeProtocolEnvelope ? `gateway rejected protocol v${4}; retrying node host with protocol v${3}` : `gateway rejected protocol v${3}; retrying node host with protocol v${4}`);
			return {
				closeCode: 1008,
				closeReason: "connect retry"
			};
		}
		this.nodeProtocolTransitionPending = false;
		const n = e instanceof GatewayClientRequestError ? readConnectErrorDetailCode(e.details) : null;
		if (shouldRetryGatewayWithDeviceToken({
			retryBudgetUsed: this.deviceTokenRetryBudgetUsed,
			currentDeviceToken: t.resolvedDeviceToken,
			explicitToken: this.opts.token?.trim() || void 0,
			storedToken: t.storedToken,
			trustedEndpoint: this.isTrustedDeviceRetryEndpoint(),
			errorDetails: e instanceof GatewayClientRequestError ? e.details : void 0
		})) {
			this.pendingDeviceTokenRetry = true;
			this.deviceTokenRetryBudgetUsed = true;
			this.protocol.resetReconnectBackoff(250);
		}
		const r = resolveGatewayStartupRetryAfterMs(e);
		if (r !== null) {
			this.logDebug(`gateway connect failed: ${formatGatewayClientErrorForLog(e)}`);
			return {
				closeCode: 1013,
				closeReason: "gateway starting",
				reconnectDelayMs: r
			};
		}
		if (t.authAgentRuntimeIdentityToken && this.isUnsupportedConnectAuthField(e, "agentruntimeidentitytoken")) {
			const e = /* @__PURE__ */ new Error("gateway rejected required agent runtime identity auth field; refusing to retry without it");
			this.stopped = true;
			this.notifyConnectError(e);
			this.logError(`gateway connect failed: ${e.message}`);
			return {
				closeCode: 1008,
				closeReason: "connect failed",
				stop: true
			};
		}
		if (!this.approvalRuntimeTokenRetryBudgetUsed && t.authApprovalRuntimeToken && this.isUnsupportedConnectAuthField(e, "approvalruntimetoken")) {
			this.approvalRuntimeTokenCompatibilityDisabled = true;
			this.approvalRuntimeTokenRetryBudgetUsed = true;
			this.protocol.resetReconnectBackoff(250);
			this.logDebug("gateway rejected approval runtime auth field; retrying without it");
			return {
				closeCode: 1008,
				closeReason: "connect retry"
			};
		}
		this.notifyConnectError(e);
		const i = `gateway connect failed: ${formatGatewayClientErrorForLog(e)}`;
		if (this.opts.mode === GATEWAY_CLIENT_MODES.PROBE || isGatewayClientStoppedError(e) || n === ConnectErrorDetailCodes.AUTH_RATE_LIMITED) this.logDebug(i);
		else this.logError(i);
		return {
			closeCode: 1008,
			closeReason: "connect failed"
		};
	}
	resolveClose(e) {
		const t = this.closeInfo(e);
		const n = e.connectFailure?.error instanceof GatewayClientRequestError ? readConnectErrorDetailCode(e.connectFailure.error.details) : null;
		const r = e.connectFailure?.error instanceof GatewayClientRequestError ? e.connectFailure.error.details : void 0;
		if (e.code === 1013 && e.connectFailure?.reconnectDelayMs !== void 0) return {
			retry: true,
			notify: this.opts.notifyOnStartupRetry === true,
			reconnectDelayMs: e.connectFailure.reconnectDelayMs
		};
		if (t.transientPreHelloCleanClose && this.suppressedTransientPreHelloCleanCloses < MAX_SUPPRESSED_TRANSIENT_PRE_HELLO_CLEAN_CLOSES) {
			this.suppressedTransientPreHelloCleanCloses += 1;
			return {
				retry: true,
				notify: true,
				pendingError: /* @__PURE__ */ new Error("gateway transient pre-hello clean close")
			};
		}
		if (t.transientPreHelloCleanClose || e.connectRequestSent && !e.helloReceived && !e.connectFailure) {
			const t = /* @__PURE__ */ new Error(`gateway closed (${e.code}): ${e.reason}`);
			this.notifyConnectError(t);
			this.logError(`gateway connect failed: ${formatGatewayClientErrorForLog(t)}`);
		}
		this.clearStaleDeviceTokenForClose(e);
		if (shouldPauseGatewayReconnect({
			details: r,
			deviceTokenRetryPending: this.pendingDeviceTokenRetry,
			tokenMismatchIsTerminal: true,
			protocolMismatchIsTerminal: !this.nodeProtocolTransitionPending,
			clientVersionMismatchIsTerminal: true
		})) {
			this.notifyReconnectPaused({
				code: e.code,
				reason: e.reason,
				detailCode: n
			});
			return {
				retry: false,
				notify: true
			};
		}
		return {
			retry: true,
			notify: true,
			reconnectDelayMs: e.connectFailure?.reconnectDelayMs
		};
	}
	closeInfo(e) {
		return {
			phase: e.helloReceived ? "post-hello" : "pre-hello",
			socketOpened: e.socketOpened,
			transportValidated: this.transportValidated,
			connectRequestSent: e.connectRequestSent,
			transientPreHelloCleanClose: !e.helloReceived && e.code === 1e3 && e.reason === "",
			...e.connectFailure?.error ? { connectError: e.connectFailure.error } : {}
		};
	}
	clearStaleDeviceTokenForClose(e) {
		const { code: t, reason: n, generation: r } = e;
		if (t !== 1008 || !normalizeLowercaseStringOrEmpty(n).includes("device token mismatch") || !this.opts.deviceIdentity) return;
		const i = this.connectionStoredToken?.generation === r ? this.connectionStoredToken : { token: void 0 };
		this.clearDeviceToken(this.opts.deviceIdentity.deviceId, i, () => !this.opts.token && !this.opts.password);
	}
	clearDeviceToken(e, t, n = () => true) {
		const failed = (t) => {
			this.logDebug(`failed clearing stale device-auth token for device ${e}: ${String(t)}`);
		};
		const cleared = () => this.logDebug(`cleared stale device-auth token for device ${e}`);
		try {
			const r = this.deviceAuth.clear({
				deviceId: e,
				role: this.opts.role ?? "operator",
				env: this.opts.env,
				assertCurrent: () => {
					if (this.stopped) throw new Error("gateway client stopped");
				}
			}, t, n);
			return r instanceof Promise ? r.then(cleared, failed) : cleared();
		} catch (e) {
			failed(e);
		}
	}
	notifyConnectError(e) {
		if (!this.opts.onConnectError) return false;
		try {
			this.opts.onConnectError(e);
			return true;
		} catch (e) {
			this.logDebug(`gateway client connect error handler error: ${formatGatewayClientErrorForLog(e)}`);
			return false;
		}
	}
	notifyReconnectPaused(e) {
		try {
			this.opts.onReconnectPaused?.(e);
		} catch (e) {
			this.logDebug(`gateway client reconnect paused handler error: ${formatGatewayClientErrorForLog(e)}`);
		}
	}
	isUnsupportedConnectAuthField(e, t) {
		if (!(e instanceof GatewayClientRequestError) || e.gatewayCode !== "INVALID_REQUEST") return false;
		const n = normalizeLowercaseStringOrEmpty(e.message);
		return n.includes("invalid connect params") && n.includes(t);
	}
	isTrustedDeviceRetryEndpoint() {
		const e = this.opts.url ?? "ws://127.0.0.1:18789";
		try {
			const t = new URL(e);
			const n = t.protocol === "https:" ? "wss:" : t.protocol === "http:" ? "ws:" : t.protocol;
			if (isGatewayLoopbackHost(t.hostname)) return true;
			return n === "wss:" && Boolean(this.opts.tlsFingerprint?.trim());
		} catch {
			return false;
		}
	}
	startTickWatch() {
		clearInterval(this.tickTimer ?? void 0);
		const e = this.opts.tickWatchMinIntervalMs;
		const t = typeof e === "number" && Number.isFinite(e) ? Math.max(1, Math.min(3e4, e)) : 1e3;
		const n = resolveSafeTimeoutDelayMs(Math.max(this.tickIntervalMs, t));
		this.tickTimer = setInterval(() => {
			if (this.stopped) return;
			if (!this.lastTick) return;
			if (this.protocol.hasPendingRequests && !this.protocol.hasUnboundedPendingRequests) return;
			const e = Date.now() - this.lastTick;
			const t = this.opts.tickWatchTimeoutMs;
			if (e > (typeof t === "number" && Number.isFinite(t) ? Math.max(1, t) : this.tickIntervalMs * 2)) this.protocol.closeSocket(4e3, "tick timeout");
		}, n);
	}
	async request(e, t, n) {
		const r = n?.expectFinal === true;
		const i = n?.timeoutMs === null ? null : typeof n?.timeoutMs === "number" && Number.isFinite(n.timeoutMs) ? n.timeoutMs : r ? null : this.requestTimeoutMs;
		return this.protocol.request(e, t, {
			...n,
			expectFinal: r,
			timeoutMs: i
		});
	}
};
//#endregion
//#region src/gateway/client.ts
function shouldSuppressStoredDeviceAuth(e) {
	return Boolean(e.deviceAuthScope && (e.token?.trim() || e.password?.trim())) || !e.deviceAuthScope && e.sharedStateMode === "read-only" && Boolean(e.password?.trim()) && !e.token?.trim() && !e.bootstrapToken?.trim() && !e.deviceToken?.trim() && !e.approvalRuntimeToken?.trim() && !e.agentRuntimeIdentityToken?.trim() && !e.preferBootstrapToken;
}
var GatewayClient = class {
	#e;
	#t;
	#n;
	#r;
	#i;
	#a = new AbortController();
	constructor(e) {
		if (e.sshTunnel && !e.deviceAuthScope) throw new Error("Gateway SSH route requires its own device-auth scope");
		if (e.preparedSshTunnel && !e.sshTunnel) throw new Error("Prepared Gateway SSH tunnel requires its selected route");
		this.#t = e;
		this.#n = e.preparedSshTunnel;
		if (!e.sshTunnel && !this.needsDeviceIdentity()) this.#e = this.createClient(e.url);
	}
	needsDeviceIdentity() {
		return this.#t.deviceIdentity === void 0 && (this.#t.sharedStateMode === "read-only" || !this.#t.hostDeps?.loadOrCreateDeviceIdentity);
	}
	createClient(e, t) {
		const n = this.#t;
		const { deviceAuthScope: r, preparedDeviceAuth: i, sharedStateMode: a, sshTunnel: o, preparedSshTunnel: s, ...c } = n;
		const l = resolveGatewayClientPlatformIdentity(process.platform);
		const u = shouldSuppressStoredDeviceAuth(n);
		for (const e of Object.values(c.edgeAuthHeaders ?? {})) registerSecretValueForRedaction(e);
		const d = a === "read-only";
		const f = i ? { expectedToken: i.token } : void 0;
		let p;
		const observe = (e) => {
			const t = e.deviceId;
			const n = normalizeDeviceAuthRole(e.role);
			return (e) => {
				p = {
					deviceId: t,
					role: n,
					expectedToken: e.expectedToken
				};
			};
		};
		const observedFor = (e) => p?.deviceId === e.deviceId && p.role === normalizeDeviceAuthRole(e.role) ? p : void 0;
		const writeFence = (e) => {
			if (f) return f;
			const t = observedFor(e);
			return t ? { expectedToken: t.expectedToken } : void 0;
		};
		const clearFence = (e) => {
			const t = f?.expectedToken ?? e.expectedToken;
			const n = observedFor(e)?.expectedToken;
			return {
				...f,
				...typeof n === "string" && n !== t && n.trim() === t ? { observedToken: n } : {}
			};
		};
		const m = {
			loadDeviceAuthToken: r ? async (e) => {
				if (d) return u ? null : loadOriginDeviceTokenReadOnly({
					...e,
					gatewayScope: r
				});
				const t = await loadOriginDeviceToken({
					...e,
					gatewayScope: r,
					onSnapshot: observe(e)
				});
				return u ? null : t;
			} : d ? u ? () => null : loadDeviceAuthTokenReadOnly : (e) => loadDeviceAuthToken({
				...e,
				onSnapshot: observe(e)
			}),
			storeDeviceAuthToken: d ? () => {} : (e) => {
				const t = {
					...e,
					...writeFence(e)
				};
				return r ? storeOriginDeviceToken({
					...t,
					gatewayScope: r
				}) : storeDeviceAuthToken(t);
			},
			clearDeviceAuthToken: d ? () => {} : (e) => {
				const t = {
					...e,
					...clearFence(e)
				};
				return r ? clearOriginDeviceToken({
					...t,
					gatewayScope: r
				}) : clearDeviceAuthToken(t);
			}
		};
		const h = i ? {
			...m,
			loadDeviceAuthToken: () => i
		} : m;
		const g = {
			signDevicePayload: signEd25519Payload,
			publicKeyRawBase64UrlFromPem: publicKeyRawBase64UrlFromEd25519Pem,
			...h,
			beforeConnect: ensureInheritedManagedProxyRoutingActive,
			registerGatewayLoopbackBypass: registerManagedProxyGatewayLoopbackBypass,
			logDebug,
			logError,
			redactForLog: (e) => redactToolPayloadText(sanitizeTerminalText(redactToolPayloadText(e))),
			...c.hostDeps,
			...d ? {
				loadOrCreateDeviceIdentity: () => void 0,
				...h
			} : {}
		};
		if (o) {
			const e = g.beforeConnect;
			g.beforeConnect = () => {
				e?.();
				if (this.#a.signal.aborted || !this.#n?.isActive()) throw new Error("Gateway SSH tunnel is no longer active");
			};
		}
		return new GatewayClient$1({
			...c,
			url: e,
			...t ? { tlsServerName: t } : {},
			clientVersion: c.clientVersion ?? VERSION,
			platform: c.platform ?? l.platform,
			deviceFamily: c.deviceFamily ?? (c.platform === void 0 ? l.deviceFamily : void 0),
			hostDeps: g
		});
	}
	start() {
		if (this.#r || this.#a.signal.aborted) return;
		if (this.#e) {
			this.#e.start();
			return;
		}
		this.#r = this.startPreparedClient().catch((e) => {
			if (this.#a.signal.aborted) return;
			this.stop();
			const t = e instanceof Error ? e : new Error(String(e));
			this.notifyClosed(t);
		});
	}
	async startPreparedClient() {
		if (this.needsDeviceIdentity()) {
			const e = { env: this.#t.env };
			const t = this.#t.sharedStateMode === "read-only" ? await loadDeviceIdentityIfPresentAsync(e) : await loadOrCreateDeviceIdentityAsync(e);
			this.#t = {
				...this.#t,
				deviceIdentity: t
			};
		}
		if (this.#a.signal.aborted) return;
		if (this.#t.sshTunnel) await this.startSsh();
		else {
			this.#e = this.createClient(this.#t.url);
			this.#e.start();
		}
	}
	async startSsh() {
		const e = this.#t.sshTunnel;
		if (!e) return;
		const t = new URL(this.#t.url ?? "");
		if (!this.#n) {
			const { startSshPortForward: n } = await import("./ssh-tunnel-3VCewHVk.mjs");
			this.#a.signal.throwIfAborted();
			this.#n = await n({
				...e,
				localPortPreferred: Number(t.port) || (t.protocol === "wss:" ? 443 : 80),
				timeoutMs: this.#t.preauthHandshakeTimeoutMs ?? 1e4,
				signal: this.#a.signal
			});
		}
		if (this.#a.signal.aborted) {
			await this.#n.stop();
			return;
		}
		if (!this.#n.isActive()) throw new Error("Gateway SSH tunnel closed before connection");
		this.#n.closed.then(() => {
			if (!this.#a.signal.aborted) {
				this.stop();
				this.notifyClosed();
			}
		});
		const n = t.protocol === "wss:" ? parseHostForAddressChecks(t.hostname)?.unbracketedHost : void 0;
		t.hostname = "127.0.0.1";
		t.port = String(this.#n.localPort);
		this.#e = this.createClient(t.href, n);
		this.#e.start();
	}
	notifyClosed(e) {
		if (e) try {
			this.#t.onConnectError?.(e);
		} catch {
			logError("Gateway connect-error callback failed");
		}
		try {
			this.#t.onClose?.(1006, e?.message ?? "Gateway SSH tunnel closed");
		} catch {
			logError("Gateway close callback failed");
		}
	}
	stop() {
		this.stopAndWait().catch((e) => logError(String(e)));
	}
	stopAndWait(e) {
		this.#a.abort();
		this.#e?.stop();
		return this.#i ??= (async () => {
			try {
				await this.#r;
				await this.#e?.stopAndWait(e);
			} finally {
				await this.#n?.stop();
			}
		})();
	}
	request(e, t, n) {
		return this.#e ? this.#e.request(e, t, n) : Promise.reject(/* @__PURE__ */ new Error("Gateway connection has not started"));
	}
	/** Current transport state, including CLOSING before the close callback fires.
	* This is not authentication or readiness evidence on its own. */
	get connected() {
		return this.#e?.connected ?? false;
	}
	getConnectionMetadata() {
		return this.#e?.getConnectionMetadata() ?? {
			clientName: this.#t.clientName,
			hasDeviceIdentity: Boolean(this.#t.deviceIdentity),
			mode: this.#t.mode,
			preauthHandshakeTimeoutMs: this.#t.preauthHandshakeTimeoutMs
		};
	}
	updateNodeManifest(e) {
		if (this.#e) this.#e.updateNodeManifest(e);
		else this.#t = {
			...this.#t,
			...e
		};
	}
};
//#endregion
export { GatewayClient as t };