@openclaw/gateway-client 2026.10.10-beta.5 → 2026.11.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,18 +1,32 @@
1
- import { A as buildGatewayConnectAuth, B as normalizeDeviceMetadataForAuth, C as isGatewayProtocolResponseError, D as gatewayCredentialScope, E as resolveModelCatalogConnect, I as asRecord, L as isRecord, M as selectGatewayConnectAuth, N as shouldRetryGatewayWithDeviceToken, O as gatewayOriginScope, P as mergeChatStreamMessage, R as buildDeviceAuthPayload, S as GatewayProtocolRequestTimeoutError, T as raceWithTimeout, _ as isSessionProjectionErrorMessage, a as createSessionProjection, b as GatewayProtocolClient, c as reduceSessionProjection, d as readSessionProjectionFinalMessageIdentity, f as isLocallyOptimisticSessionMessage, g as readSessionMessageSequence, h as readSessionMessageIdentity, i as resetGatewaySessionMessageSubscriptionCoordinator, j as resolveGatewayConnectScopes, k as GatewayBrowserDeviceAuthLifecycle, l as reduceSessionProjectionRunEvent, m as readAssistantStreamSegmentIdentity, n as getGatewaySessionMessageSubscriptionCoordinator, o as projectLiveSessionMessage, p as normalizeSessionProjectionRunId, r as releaseGatewaySessionMessageSubscription, s as reconcileSessionProjectionSnapshot, t as GatewaySessionMessageSubscriptionCoordinator, u as hasSessionProjectionAcceptedFinal, v as projectSessionTerminalReplyMessage, w as createAbortError, x as GatewayProtocolRequestError, y as shouldPauseGatewayReconnect, z as buildDeviceAuthPayloadV3 } from "./session-subscriptions-DJ5H6a_1.mjs";
2
- import { _ as normalizeOptionalString, a as MIN_CONNECT_CHALLENGE_TIMEOUT_MS, c as clearGatewayConnectTimeout, d as resolveFiniteTimeoutDelayMs, f as resolvePreauthHandshakeTimeoutMs, h as normalizeLowercaseStringOrEmpty, i as MAX_SAFE_TIMEOUT_DELAY_MS, l as getConnectChallengeTimeoutMsFromEnv, m as startGatewayConnectTimeout, n as DEFAULT_PREAUTH_HANDSHAKE_TIMEOUT_MS, o as addSafeTimeoutDelayGraceMs, p as resolveSafeTimeoutDelayMs, r as MAX_CONNECT_CHALLENGE_TIMEOUT_MS, s as clampConnectChallengeTimeoutMs, t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS, u as resolveConnectChallengeTimeoutMs } from "./timeouts-F2UKsnjG.mjs";
1
+ import { A as GatewayBrowserDeviceAuthLifecycle, B as buildDeviceAuthPayload, C as isGatewayProtocolResponseError, D as resolveModelCatalogConnect, E as toStringifiedError, F as mergeChatStreamMessage, H as normalizeDeviceMetadataForAuth, L as asOptionalRecord, M as resolveGatewayConnectScopes, N as selectGatewayConnectAuth, O as gatewayCredentialScope, P as shouldRetryGatewayWithDeviceToken, R as asRecord, S as GatewayProtocolRequestTimeoutError, T as raceWithTimeout, V as buildDeviceAuthPayloadV3, _ as isSessionProjectionErrorMessage, a as createSessionProjection, b as GatewayProtocolClient, c as reduceSessionProjection, d as readSessionProjectionFinalMessageIdentity, f as isLocallyOptimisticSessionMessage, g as readSessionMessageSequence, h as readSessionMessageIdentity, i as resetGatewaySessionMessageSubscriptionCoordinator, j as buildGatewayConnectAuth, k as gatewayOriginScope, l as reduceSessionProjectionRunEvent, m as readAssistantStreamSegmentIdentity, n as getGatewaySessionMessageSubscriptionCoordinator, o as projectLiveSessionMessage, p as normalizeSessionProjectionRunId, r as releaseGatewaySessionMessageSubscription, s as reconcileSessionProjectionSnapshot, t as GatewaySessionMessageSubscriptionCoordinator, u as hasSessionProjectionAcceptedFinal, v as projectSessionTerminalReplyMessage, w as createAbortError, x as GatewayProtocolRequestError, y as shouldPauseGatewayReconnect, z as isRecord } from "./session-subscriptions-Bc7A64MY.mjs";
2
+ import { _ as normalizeOptionalString, a as MIN_CONNECT_CHALLENGE_TIMEOUT_MS, c as clearGatewayConnectTimeout, d as resolveFiniteTimeoutDelayMs, f as resolvePreauthHandshakeTimeoutMs, h as normalizeLowercaseStringOrEmpty, i as MAX_SAFE_TIMEOUT_DELAY_MS, l as getConnectChallengeTimeoutMsFromEnv, m as startGatewayConnectTimeout, n as DEFAULT_PREAUTH_HANDSHAKE_TIMEOUT_MS, o as addSafeTimeoutDelayGraceMs, p as resolveSafeTimeoutDelayMs, r as MAX_CONNECT_CHALLENGE_TIMEOUT_MS, s as clampConnectChallengeTimeoutMs, t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS, u as resolveConnectChallengeTimeoutMs } from "./timeouts-BBVOnLnf.mjs";
3
3
  import { rawDataToString } from "./websocket-data.mjs";
4
- import { n as startGatewayClientWithReadinessWait, r as waitForEventLoopReady, t as startGatewayClientWhenEventLoopReady } from "./readiness-CwRz4ZX8.mjs";
4
+ import { n as startGatewayClientWithReadinessWait, r as waitForEventLoopReady, t as startGatewayClientWhenEventLoopReady } from "./readiness-C7IsnvXj.mjs";
5
5
  import { GatewayScopeUpgrade } from "./scope-upgrade.mjs";
6
6
  import { createRequire } from "node:module";
7
7
  import { ConnectErrorDetailCodes, formatConnectErrorMessage, readConnectErrorDetailCode } from "@openclaw/gateway-protocol/connect-error-details";
8
- import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "@openclaw/gateway-protocol/client-info";
9
8
  import { resolveGatewayStartupRetryAfterMs } from "@openclaw/gateway-protocol/startup-unavailable";
9
+ import { GATEWAY_CLIENT_MODES, GATEWAY_CLIENT_NAMES } from "@openclaw/gateway-protocol/client-info";
10
10
  import { MIN_CLIENT_PROTOCOL_VERSION, MIN_NODE_PROTOCOL_VERSION, MIN_PROBE_PROTOCOL_VERSION, PROTOCOL_VERSION } from "@openclaw/gateway-protocol/version";
11
11
  import { randomUUID } from "node:crypto";
12
12
  import ipaddr from "ipaddr.js";
13
13
  import { isIP } from "node:net";
14
14
  import { TLSSocket, checkServerIdentity } from "node:tls";
15
15
  import path from "node:path";
16
+ //#region packages/normalization-core/src/json-coercion.ts
17
+ /** Parses JSON without throwing, returning undefined for invalid input. */
18
+ function safeParseJson(value) {
19
+ try {
20
+ return JSON.parse(value);
21
+ } catch {
22
+ return;
23
+ }
24
+ }
25
+ /** Parses JSON into a non-array record, returning undefined for every other result. */
26
+ function safeParseJsonRecord(value) {
27
+ return /^[\t\n\r ]*\{/.test(value) ? asOptionalRecord(safeParseJson(value)) : void 0;
28
+ }
29
+ //#endregion
16
30
  //#region packages/net-policy/src/redact-sensitive-url.ts
17
31
  const SENSITIVE_URL_QUERY_PARAM_NAMES = /* @__PURE__ */ new Set([
18
32
  "token",
@@ -329,10 +343,15 @@ function parseCanonicalIpAddress(raw) {
329
343
  }
330
344
  /** Normalizes canonical IP literals and maps IPv4-mapped IPv6 addresses to IPv4 text. */
331
345
  function normalizeIpAddress(raw) {
346
+ return parseNormalizedIpAddress(raw)?.toString();
347
+ }
348
+ /** Parses canonical literals, normalizing mapped IPv4 and lowercase IPv6 zone IDs. */
349
+ function parseNormalizedIpAddress(raw) {
332
350
  const parsed = parseCanonicalIpAddress(raw);
333
351
  if (!parsed) return;
334
352
  const normalized = normalizeIpv4MappedAddress(parsed);
335
- return normalizeLowercaseStringOrEmpty(normalized.toString());
353
+ if (isIpv6Address(normalized) && normalized.zoneId) normalized.zoneId = normalized.zoneId.toLowerCase();
354
+ return normalized;
336
355
  }
337
356
  /** True when a canonical IP literal is loopback, including IPv4-mapped IPv6. */
338
357
  function isLoopbackIpAddress(raw) {
@@ -391,7 +410,7 @@ var GatewayClientDeviceAuth = class {
391
410
  }
392
411
  store(params, onStored, onFailed) {
393
412
  const failed = (error) => {
394
- const failure = error instanceof Error ? error : new Error(String(error));
413
+ const failure = toStringifiedError(error);
395
414
  let reported = false;
396
415
  try {
397
416
  reported = onFailed(failure);
@@ -483,6 +502,22 @@ async function readUpgradeErrorBody(response) {
483
502
  });
484
503
  }
485
504
  //#endregion
505
+ //#region packages/gateway-client/src/node-protocol.ts
506
+ /** Match the shipped v3 node envelope before signing its metadata. */
507
+ function resolveNodeProtocolClientMetadata(configured, defaultPlatform, legacy) {
508
+ const platform = configured.platform ?? defaultPlatform;
509
+ if (!legacy) return {
510
+ platform,
511
+ deviceFamily: configured.deviceFamily,
512
+ modelIdentifier: configured.modelIdentifier
513
+ };
514
+ return { platform: platform === "macos" ? "darwin" : platform === "windows" ? "win32" : platform };
515
+ }
516
+ function shouldNegotiateLegacyNodeProtocol(options) {
517
+ if (options.role !== "node" || options.mode !== GATEWAY_CLIENT_MODES.NODE || options.clientName !== GATEWAY_CLIENT_NAMES.NODE_HOST) return false;
518
+ return (options.minProtocol ?? MIN_NODE_PROTOCOL_VERSION) === MIN_NODE_PROTOCOL_VERSION && (options.maxProtocol ?? PROTOCOL_VERSION) === PROTOCOL_VERSION;
519
+ }
520
+ //#endregion
486
521
  //#region packages/gateway-client/src/request-error.ts
487
522
  var GatewayClientRequestError = class extends GatewayProtocolRequestError {
488
523
  constructor(error) {
@@ -496,6 +531,12 @@ var GatewayClientRequestError = class extends GatewayProtocolRequestError {
496
531
  this.name = "GatewayClientRequestError";
497
532
  }
498
533
  };
534
+ var GatewayClientRequestTimeoutError = class extends GatewayProtocolRequestTimeoutError {
535
+ constructor(params) {
536
+ super(params, `gateway request timeout for ${params.method}`);
537
+ this.name = "GatewayClientRequestTimeoutError";
538
+ }
539
+ };
499
540
  const GATEWAY_CONNECT_ASSEMBLY_ERROR = Symbol("gateway.connectAssemblyError");
500
541
  function markGatewayConnectAssemblyError(error) {
501
542
  Object.defineProperty(error, GATEWAY_CONNECT_ASSEMBLY_ERROR, {
@@ -639,23 +680,10 @@ function resolveHostDeps(overrides) {
639
680
  }
640
681
  const DEFAULT_GATEWAY_CLIENT_URL = "ws://127.0.0.1:18789";
641
682
  const DEFAULT_CLIENT_VERSION = "0.0.0";
642
- var GatewayClientRequestTimeoutError = class extends GatewayProtocolRequestTimeoutError {
643
- constructor(params) {
644
- super(params, `gateway request timeout for ${params.method}`);
645
- this.name = "GatewayClientRequestTimeoutError";
646
- }
647
- };
648
683
  var GatewayClientTransportPolicyError = class extends GatewayWebSocketTransportConfigurationError {};
649
684
  const FORCE_STOP_TERMINATE_GRACE_MS = 250;
650
685
  const STOP_AND_WAIT_TIMEOUT_MS = 1e3;
651
686
  const MAX_SUPPRESSED_TRANSIENT_PRE_HELLO_CLEAN_CLOSES = 1;
652
- function resolveLegacyNodePlatform(platform) {
653
- switch (platform) {
654
- case "macos": return "darwin";
655
- case "windows": return "win32";
656
- default: return;
657
- }
658
- }
659
687
  var GatewayClient = class {
660
688
  constructor(opts) {
661
689
  this.ws = null;
@@ -699,13 +727,97 @@ var GatewayClient = class {
699
727
  const role = this.opts.role ?? "operator";
700
728
  const assemble = (storedAuth) => {
701
729
  authority.assertCurrent();
702
- const assembled = this.assembleConnectParams({
703
- role,
704
- nonce,
705
- signedAtMs: challengeTs ?? Date.now(),
706
- serverCapabilities,
707
- storedAuth
730
+ const signedAtMs = challengeTs ?? Date.now();
731
+ const selectedAuth = selectGatewayConnectAuth({
732
+ token: this.opts.token,
733
+ bootstrapToken: this.opts.bootstrapToken,
734
+ preferBootstrapToken: this.opts.preferBootstrapToken,
735
+ deviceToken: this.opts.deviceToken,
736
+ password: this.opts.password,
737
+ approvalRuntimeToken: this.approvalRuntimeTokenCompatibilityDisabled ? void 0 : this.opts.approvalRuntimeToken,
738
+ agentRuntimeIdentityToken: this.opts.agentRuntimeIdentityToken,
739
+ storedToken: storedAuth?.token,
740
+ storedScopes: storedAuth?.scopes,
741
+ pendingDeviceTokenRetry: this.pendingDeviceTokenRetry,
742
+ trustedDeviceTokenRetry: this.isTrustedDeviceRetryEndpoint()
708
743
  });
744
+ const { authDeviceToken, authApprovalRuntimeToken, authAgentRuntimeIdentityToken, signatureToken, resolvedDeviceToken, storedToken, storedScopes, usingStoredDeviceToken } = selectedAuth;
745
+ if (this.pendingDeviceTokenRetry && authDeviceToken) this.pendingDeviceTokenRetry = false;
746
+ const auth = buildGatewayConnectAuth(selectedAuth);
747
+ const scopes = resolveGatewayConnectScopes({
748
+ requestedScopes: this.opts.scopes,
749
+ usingStoredDeviceToken,
750
+ storedScopes,
751
+ defaultScopes: ["operator.admin"]
752
+ });
753
+ const clientMode = this.opts.mode ?? GATEWAY_CLIENT_MODES.BACKEND;
754
+ const clientId = this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
755
+ const isBuiltInNodeHost = role === "node" && clientMode === GATEWAY_CLIENT_MODES.NODE && clientId === GATEWAY_CLIENT_NAMES.NODE_HOST;
756
+ const negotiatesNodeProtocol = shouldNegotiateLegacyNodeProtocol(this.opts);
757
+ const useLegacyNodeProtocolEnvelope = isBuiltInNodeHost && (this.useLegacyNodeProtocolEnvelope || this.opts.maxProtocol === MIN_NODE_PROTOCOL_VERSION && (this.opts.minProtocol ?? MIN_NODE_PROTOCOL_VERSION) <= MIN_NODE_PROTOCOL_VERSION);
758
+ const minProtocol = useLegacyNodeProtocolEnvelope ? MIN_NODE_PROTOCOL_VERSION : negotiatesNodeProtocol ? PROTOCOL_VERSION : this.opts.minProtocol ?? (clientMode === GATEWAY_CLIENT_MODES.PROBE ? MIN_PROBE_PROTOCOL_VERSION : role === "node" && clientMode === GATEWAY_CLIENT_MODES.NODE ? MIN_NODE_PROTOCOL_VERSION : MIN_CLIENT_PROTOCOL_VERSION);
759
+ const maxProtocol = useLegacyNodeProtocolEnvelope ? MIN_NODE_PROTOCOL_VERSION : negotiatesNodeProtocol ? PROTOCOL_VERSION : this.opts.maxProtocol ?? PROTOCOL_VERSION;
760
+ const { platform, deviceFamily, modelIdentifier } = resolveNodeProtocolClientMetadata(this.opts, process.platform, useLegacyNodeProtocolEnvelope);
761
+ const connectParams = {
762
+ minProtocol,
763
+ maxProtocol,
764
+ client: {
765
+ id: clientId,
766
+ displayName: this.opts.clientDisplayName,
767
+ version: this.opts.clientVersion ?? DEFAULT_CLIENT_VERSION,
768
+ buildId: this.opts.clientBuildId,
769
+ platform,
770
+ deviceFamily,
771
+ modelIdentifier,
772
+ mode: clientMode,
773
+ instanceId: this.opts.instanceId
774
+ },
775
+ ...resolveModelCatalogConnect({
776
+ caps: Array.isArray(this.opts.caps) ? this.opts.caps : [],
777
+ modelCatalog: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.modelCatalog,
778
+ serverCapabilities
779
+ }),
780
+ commands: Array.isArray(this.opts.commands) ? this.opts.commands : void 0,
781
+ computerUse: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.computerUse,
782
+ workerRuns: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.workerRuns,
783
+ permissions: this.opts.permissions && typeof this.opts.permissions === "object" ? this.opts.permissions : void 0,
784
+ pathEnv: this.opts.pathEnv,
785
+ auth,
786
+ role,
787
+ scopes,
788
+ device: void 0
789
+ };
790
+ if (this.opts.deviceIdentity) {
791
+ const payload = buildDeviceAuthPayloadV3({
792
+ deviceId: this.opts.deviceIdentity.deviceId,
793
+ clientId: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
794
+ clientMode,
795
+ role,
796
+ scopes,
797
+ signedAtMs,
798
+ token: signatureToken ?? null,
799
+ nonce,
800
+ platform,
801
+ deviceFamily
802
+ });
803
+ const signature = this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem, payload);
804
+ connectParams.device = {
805
+ id: this.opts.deviceIdentity.deviceId,
806
+ publicKey: this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),
807
+ signature,
808
+ signedAt: signedAtMs,
809
+ nonce
810
+ };
811
+ }
812
+ const assembled = {
813
+ params: connectParams,
814
+ authApprovalRuntimeToken,
815
+ authAgentRuntimeIdentityToken,
816
+ resolvedDeviceToken,
817
+ storedScopes,
818
+ storedToken,
819
+ usingStoredDeviceToken
820
+ };
709
821
  this.connectionStoredToken = {
710
822
  generation,
711
823
  token: assembled.storedToken ?? null
@@ -734,17 +846,79 @@ var GatewayClient = class {
734
846
  error: marked
735
847
  };
736
848
  },
737
- onConnectHello: (hello, context) => this.handleConnectHello(hello, context.plan, context),
849
+ onConnectHello: (helloOk, authority) => {
850
+ const assembled = authority.plan;
851
+ authority.assertCurrent();
852
+ const role = this.opts.role ?? "operator";
853
+ const authInfo = helloOk.auth;
854
+ const observation = this.connectionStoredToken;
855
+ const persisted = () => {
856
+ if (authInfo?.deviceToken && (authInfo.role ?? role) === role && observation) observation.token = authInfo.deviceToken;
857
+ if (this.opts.preferBootstrapToken) {
858
+ this.opts.token = void 0;
859
+ this.opts.bootstrapToken = void 0;
860
+ this.opts.password = void 0;
861
+ this.opts.preferBootstrapToken = false;
862
+ }
863
+ };
864
+ let stored = void 0;
865
+ if (authInfo?.deviceToken && this.opts.deviceIdentity) {
866
+ const tokenRole = authInfo.role ?? role;
867
+ const scopes = tokenRole === role && authInfo.deviceToken === assembled.storedToken ? assembled.storedScopes ?? authInfo.scopes ?? [] : authInfo.scopes ?? [];
868
+ if (tokenRole === role && observation) observation.receiptToken = authInfo.deviceToken;
869
+ stored = this.deviceAuth.store({
870
+ deviceId: this.opts.deviceIdentity.deviceId,
871
+ role: tokenRole,
872
+ token: authInfo.deviceToken,
873
+ scopes,
874
+ env: this.opts.env,
875
+ ...tokenRole === role ? { expectedToken: assembled.storedToken ?? null } : {}
876
+ }, persisted, (error) => {
877
+ assembled.persistenceFailed = true;
878
+ const reported = this.notifyConnectError(error);
879
+ this.logError(`gateway device token persistence failed: ${formatGatewayClientErrorForLog(error)}`);
880
+ return reported;
881
+ });
882
+ if (observation && stored instanceof Promise) observation.persistence = stored;
883
+ } else persisted();
884
+ const complete = () => {
885
+ if (authority.signal.aborted || !this.protocol.connected) return;
886
+ authority.assertCurrent();
887
+ const reconnectWithCurrentNodeProtocol = this.useLegacyNodeProtocolEnvelope && shouldNegotiateLegacyNodeProtocol(this.opts) && helloOk.protocol > MIN_NODE_PROTOCOL_VERSION;
888
+ if (reconnectWithCurrentNodeProtocol) this.useLegacyNodeProtocolEnvelope = false;
889
+ this.nodeProtocolTransitionPending = false;
890
+ this.pendingDeviceTokenRetry = false;
891
+ this.deviceTokenRetryBudgetUsed = false;
892
+ this.suppressedTransientPreHelloCleanCloses = 0;
893
+ this.tickIntervalMs = typeof helloOk.policy?.tickIntervalMs === "number" ? helloOk.policy.tickIntervalMs : 3e4;
894
+ if (reconnectWithCurrentNodeProtocol) {
895
+ this.protocol.resetReconnectBackoff(250);
896
+ this.protocol.closeSocket(1012, "gateway protocol upgraded");
897
+ return;
898
+ }
899
+ this.lastTick = Date.now();
900
+ this.startTickWatch();
901
+ };
902
+ return stored instanceof Promise ? stored.then(complete) : complete();
903
+ },
738
904
  onHello: (hello) => {
739
905
  this.opts.onHelloOk?.(hello);
740
906
  },
741
- onConnectFailure: (error, context) => this.handleConnectRequestFailure(error, context.plan),
907
+ onConnectFailure: (error, context) => {
908
+ const assembled = context.plan;
909
+ if (assembled.persistenceFailed) return {
910
+ closeCode: 1008,
911
+ closeReason: "connect failed"
912
+ };
913
+ const detailCode = error instanceof GatewayClientRequestError ? readConnectErrorDetailCode(error.details) : null;
914
+ const cleared = this.opts.deviceIdentity && assembled.usingStoredDeviceToken && detailCode === ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH ? this.clearDeviceToken(this.opts.deviceIdentity.deviceId, { token: assembled.storedToken }) : void 0;
915
+ const decision = this.resolveConnectRequestFailure(error, assembled);
916
+ return cleared instanceof Promise ? cleared.then(() => decision) : decision;
917
+ },
742
918
  resolveClose: (context) => this.resolveClose(context),
743
919
  onClose: (context, decision) => {
744
- if (this.tickTimer) {
745
- clearInterval(this.tickTimer);
746
- this.tickTimer = null;
747
- }
920
+ clearInterval(this.tickTimer ?? void 0);
921
+ this.tickTimer = null;
748
922
  if (decision.notify) this.opts.onClose?.(context.code, context.reason, this.closeInfo(context));
749
923
  },
750
924
  notifyStoppedClose: true,
@@ -833,15 +1007,14 @@ var GatewayClient = class {
833
1007
  let ws;
834
1008
  let unregisterGatewayLoopbackBypass;
835
1009
  try {
836
- unregisterGatewayLoopbackBypass = this.deps.registerGatewayLoopbackBypass(url);
837
- } catch (error) {
838
- throw new GatewayClientTransportPolicyError(error instanceof Error ? error.message : String(error));
839
- }
840
- try {
1010
+ try {
1011
+ unregisterGatewayLoopbackBypass = this.deps.registerGatewayLoopbackBypass(url);
1012
+ this.opts.assertConnectionCurrent?.();
1013
+ } catch (error) {
1014
+ throw new GatewayClientTransportPolicyError(error instanceof Error ? error.message : String(error));
1015
+ }
841
1016
  ws = new WebSocket(url, transport.options);
842
1017
  ws.binaryType = "nodebuffer";
843
- } catch (error) {
844
- throw error instanceof Error ? error : new Error(String(error));
845
1018
  } finally {
846
1019
  unregisterGatewayLoopbackBypass?.();
847
1020
  }
@@ -862,12 +1035,8 @@ var GatewayClient = class {
862
1035
  ws.on("unexpected-response", (request, response) => {
863
1036
  readUpgradeErrorBody(response).then((body) => {
864
1037
  const statusCode = response.statusCode;
865
- let gatewayError;
866
- try {
867
- const parsed = JSON.parse(body);
868
- const parsedError = isRecord(parsed) ? parsed.error : void 0;
869
- gatewayError = isRecord(parsedError) ? parsedError : void 0;
870
- } catch {}
1038
+ const parsedError = safeParseJsonRecord(body)?.error;
1039
+ const gatewayError = isRecord(parsedError) ? parsedError : void 0;
871
1040
  const rawLocation = response.headers.location;
872
1041
  const location = rawLocation ? redactSensitiveUrlLikeString(Array.isArray(rawLocation) ? rawLocation[0] ?? "" : rawLocation) : void 0;
873
1042
  upgradeError = new GatewayClientRequestError({
@@ -897,7 +1066,10 @@ var GatewayClient = class {
897
1066
  });
898
1067
  return {
899
1068
  isOpen: () => ws.readyState === WebSocket.OPEN,
900
- send: (data) => ws.send(data),
1069
+ send: (data) => {
1070
+ this.opts.assertConnectionCurrent?.();
1071
+ ws.send(data);
1072
+ },
901
1073
  close: (code, reason) => ws.close(code, reason)
902
1074
  };
903
1075
  }
@@ -919,10 +1091,8 @@ var GatewayClient = class {
919
1091
  this.stopped = true;
920
1092
  this.pendingDeviceTokenRetry = false;
921
1093
  this.deviceTokenRetryBudgetUsed = false;
922
- if (this.tickTimer) {
923
- clearInterval(this.tickTimer);
924
- this.tickTimer = null;
925
- }
1094
+ clearInterval(this.tickTimer ?? void 0);
1095
+ this.tickTimer = null;
926
1096
  if (this.pendingStop) return this.pendingStop.promise;
927
1097
  const ws = this.ws;
928
1098
  this.ws = null;
@@ -969,182 +1139,18 @@ var GatewayClient = class {
969
1139
  logError(message) {
970
1140
  this.deps.logError(this.deps.redactForLog(message));
971
1141
  }
972
- assembleConnectParams(params) {
973
- const { role, nonce, signedAtMs } = params;
974
- const selectedAuth = this.selectConnectAuth(params.storedAuth);
975
- const { authDeviceToken, authApprovalRuntimeToken, authAgentRuntimeIdentityToken, signatureToken, resolvedDeviceToken, storedToken, storedScopes, usingStoredDeviceToken } = selectedAuth;
976
- if (this.pendingDeviceTokenRetry && authDeviceToken) this.pendingDeviceTokenRetry = false;
977
- const auth = buildGatewayConnectAuth(selectedAuth);
978
- const scopes = resolveGatewayConnectScopes({
979
- requestedScopes: this.opts.scopes,
980
- usingStoredDeviceToken,
981
- storedScopes,
982
- defaultScopes: ["operator.admin"]
983
- });
984
- const clientMode = this.opts.mode ?? GATEWAY_CLIENT_MODES.BACKEND;
985
- const clientId = this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;
986
- const isBuiltInNodeHost = role === "node" && clientMode === GATEWAY_CLIENT_MODES.NODE && clientId === GATEWAY_CLIENT_NAMES.NODE_HOST;
987
- const negotiatesNodeProtocol = this.shouldNegotiateLegacyNodeProtocol();
988
- const useLegacyNodeProtocolEnvelope = isBuiltInNodeHost && (this.useLegacyNodeProtocolEnvelope || this.opts.maxProtocol === MIN_NODE_PROTOCOL_VERSION && (this.opts.minProtocol ?? MIN_NODE_PROTOCOL_VERSION) <= MIN_NODE_PROTOCOL_VERSION);
989
- const minProtocol = useLegacyNodeProtocolEnvelope ? MIN_NODE_PROTOCOL_VERSION : negotiatesNodeProtocol ? PROTOCOL_VERSION : this.opts.minProtocol ?? (clientMode === GATEWAY_CLIENT_MODES.PROBE ? MIN_PROBE_PROTOCOL_VERSION : role === "node" && clientMode === GATEWAY_CLIENT_MODES.NODE ? MIN_NODE_PROTOCOL_VERSION : MIN_CLIENT_PROTOCOL_VERSION);
990
- const maxProtocol = useLegacyNodeProtocolEnvelope ? MIN_NODE_PROTOCOL_VERSION : negotiatesNodeProtocol ? PROTOCOL_VERSION : this.opts.maxProtocol ?? PROTOCOL_VERSION;
991
- const configuredPlatform = this.opts.platform ?? process.platform;
992
- const platform = useLegacyNodeProtocolEnvelope ? resolveLegacyNodePlatform(configuredPlatform) ?? configuredPlatform : configuredPlatform;
993
- const deviceFamily = useLegacyNodeProtocolEnvelope ? void 0 : this.opts.deviceFamily;
994
- return {
995
- params: {
996
- minProtocol,
997
- maxProtocol,
998
- client: {
999
- id: clientId,
1000
- displayName: this.opts.clientDisplayName,
1001
- version: this.opts.clientVersion ?? DEFAULT_CLIENT_VERSION,
1002
- buildId: this.opts.clientBuildId,
1003
- platform,
1004
- deviceFamily,
1005
- modelIdentifier: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.modelIdentifier,
1006
- mode: clientMode,
1007
- instanceId: this.opts.instanceId
1008
- },
1009
- ...resolveModelCatalogConnect({
1010
- caps: Array.isArray(this.opts.caps) ? this.opts.caps : [],
1011
- modelCatalog: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.modelCatalog,
1012
- serverCapabilities: params.serverCapabilities
1013
- }),
1014
- commands: Array.isArray(this.opts.commands) ? this.opts.commands : void 0,
1015
- computerUse: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.computerUse,
1016
- workerRuns: useLegacyNodeProtocolEnvelope ? void 0 : this.opts.workerRuns,
1017
- permissions: this.opts.permissions && typeof this.opts.permissions === "object" ? this.opts.permissions : void 0,
1018
- pathEnv: this.opts.pathEnv,
1019
- auth,
1020
- role,
1021
- scopes,
1022
- device: this.buildDeviceConnectParams({
1023
- nonce,
1024
- role,
1025
- scopes,
1026
- signatureToken,
1027
- signedAtMs,
1028
- platform,
1029
- deviceFamily,
1030
- clientMode
1031
- })
1032
- },
1033
- authApprovalRuntimeToken,
1034
- authAgentRuntimeIdentityToken,
1035
- resolvedDeviceToken,
1036
- storedScopes,
1037
- storedToken,
1038
- usingStoredDeviceToken
1039
- };
1040
- }
1041
- shouldNegotiateLegacyNodeProtocol() {
1042
- if (this.opts.role !== "node" || this.opts.mode !== GATEWAY_CLIENT_MODES.NODE || this.opts.clientName !== GATEWAY_CLIENT_NAMES.NODE_HOST) return false;
1043
- return (this.opts.minProtocol ?? MIN_NODE_PROTOCOL_VERSION) === MIN_NODE_PROTOCOL_VERSION && (this.opts.maxProtocol ?? PROTOCOL_VERSION) === PROTOCOL_VERSION;
1044
- }
1045
1142
  shouldRetryWithAlternateNodeProtocol(error) {
1046
- if (!this.shouldNegotiateLegacyNodeProtocol() || !(error instanceof GatewayClientRequestError)) return false;
1143
+ if (!shouldNegotiateLegacyNodeProtocol(this.opts) || !(error instanceof GatewayClientRequestError)) return false;
1047
1144
  const detailCode = readConnectErrorDetailCode(error.details);
1048
1145
  return error.details?.expectedProtocol === (this.useLegacyNodeProtocolEnvelope ? PROTOCOL_VERSION : MIN_NODE_PROTOCOL_VERSION) && (detailCode === ConnectErrorDetailCodes.PROTOCOL_MISMATCH || normalizeLowercaseStringOrEmpty(error.message).includes("protocol mismatch"));
1049
1146
  }
1050
- buildDeviceConnectParams(params) {
1051
- if (!this.opts.deviceIdentity) return;
1052
- const { nonce, role, scopes, signatureToken, signedAtMs, platform, deviceFamily, clientMode } = params;
1053
- const payload = buildDeviceAuthPayloadV3({
1054
- deviceId: this.opts.deviceIdentity.deviceId,
1055
- clientId: this.opts.clientName ?? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,
1056
- clientMode,
1057
- role,
1058
- scopes,
1059
- signedAtMs,
1060
- token: signatureToken ?? null,
1061
- nonce,
1062
- platform,
1063
- deviceFamily
1064
- });
1065
- const signature = this.deps.signDevicePayload(this.opts.deviceIdentity.privateKeyPem, payload);
1066
- return {
1067
- id: this.opts.deviceIdentity.deviceId,
1068
- publicKey: this.deps.publicKeyRawBase64UrlFromPem(this.opts.deviceIdentity.publicKeyPem),
1069
- signature,
1070
- signedAt: signedAtMs,
1071
- nonce
1072
- };
1073
- }
1074
- handleConnectHello(helloOk, assembled, authority) {
1075
- authority.assertCurrent();
1076
- const role = this.opts.role ?? "operator";
1077
- const authInfo = helloOk.auth;
1078
- const observation = this.connectionStoredToken;
1079
- const persisted = () => {
1080
- if (authInfo?.deviceToken && (authInfo.role ?? role) === role && observation) observation.token = authInfo.deviceToken;
1081
- if (this.opts.preferBootstrapToken) {
1082
- this.opts.token = void 0;
1083
- this.opts.bootstrapToken = void 0;
1084
- this.opts.password = void 0;
1085
- this.opts.preferBootstrapToken = false;
1086
- }
1087
- };
1088
- let stored = void 0;
1089
- if (authInfo?.deviceToken && this.opts.deviceIdentity) {
1090
- const tokenRole = authInfo.role ?? role;
1091
- const scopes = tokenRole === role && authInfo.deviceToken === assembled.storedToken ? assembled.storedScopes ?? authInfo.scopes ?? [] : authInfo.scopes ?? [];
1092
- if (tokenRole === role && observation) observation.receiptToken = authInfo.deviceToken;
1093
- stored = this.deviceAuth.store({
1094
- deviceId: this.opts.deviceIdentity.deviceId,
1095
- role: tokenRole,
1096
- token: authInfo.deviceToken,
1097
- scopes,
1098
- env: this.opts.env,
1099
- ...tokenRole === role ? { expectedToken: assembled.storedToken ?? null } : {}
1100
- }, persisted, (error) => {
1101
- assembled.persistenceFailed = true;
1102
- const reported = this.notifyConnectError(error);
1103
- this.logError(`gateway device token persistence failed: ${formatGatewayClientErrorForLog(error)}`);
1104
- return reported;
1105
- });
1106
- if (observation && stored instanceof Promise) observation.persistence = stored;
1107
- } else persisted();
1108
- const complete = () => {
1109
- if (authority.signal.aborted || !this.protocol.connected) return;
1110
- authority.assertCurrent();
1111
- this.completeConnectHello(helloOk);
1112
- };
1113
- return stored instanceof Promise ? stored.then(complete) : complete();
1114
- }
1115
- completeConnectHello(helloOk) {
1116
- const reconnectWithCurrentNodeProtocol = this.useLegacyNodeProtocolEnvelope && this.shouldNegotiateLegacyNodeProtocol() && helloOk.protocol > MIN_NODE_PROTOCOL_VERSION;
1117
- if (reconnectWithCurrentNodeProtocol) this.useLegacyNodeProtocolEnvelope = false;
1118
- this.nodeProtocolTransitionPending = false;
1119
- this.pendingDeviceTokenRetry = false;
1120
- this.deviceTokenRetryBudgetUsed = false;
1121
- this.suppressedTransientPreHelloCleanCloses = 0;
1122
- this.tickIntervalMs = typeof helloOk.policy?.tickIntervalMs === "number" ? helloOk.policy.tickIntervalMs : 3e4;
1123
- if (reconnectWithCurrentNodeProtocol) {
1124
- this.protocol.resetReconnectBackoff(250);
1125
- this.protocol.closeSocket(1012, "gateway protocol upgraded");
1126
- return;
1127
- }
1128
- this.lastTick = Date.now();
1129
- this.startTickWatch();
1130
- }
1131
- handleConnectRequestFailure(error, assembled) {
1132
- if (assembled.persistenceFailed) return {
1133
- closeCode: 1008,
1134
- closeReason: "connect failed"
1135
- };
1136
- const detailCode = error instanceof GatewayClientRequestError ? readConnectErrorDetailCode(error.details) : null;
1137
- const cleared = this.opts.deviceIdentity && assembled.usingStoredDeviceToken && detailCode === ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH ? this.clearDeviceToken(this.opts.deviceIdentity.deviceId, { token: assembled.storedToken }) : void 0;
1138
- const decision = this.resolveConnectRequestFailure(error, assembled);
1139
- return cleared instanceof Promise ? cleared.then(() => decision) : decision;
1140
- }
1141
1147
  resolveConnectRequestFailure(error, assembled) {
1142
1148
  if (this.shouldRetryWithAlternateNodeProtocol(error)) {
1143
1149
  const resetBackoff = !this.nodeProtocolTransitionPending;
1144
1150
  this.useLegacyNodeProtocolEnvelope = !this.useLegacyNodeProtocolEnvelope;
1145
1151
  this.nodeProtocolTransitionPending = true;
1146
1152
  if (resetBackoff) this.protocol.resetReconnectBackoff(250);
1147
- this.logDebug(this.useLegacyNodeProtocolEnvelope ? "gateway rejected protocol v4; retrying node host with protocol v3" : "gateway rejected protocol v3; retrying node host with protocol v4");
1153
+ this.logDebug(this.useLegacyNodeProtocolEnvelope ? `gateway rejected protocol v${PROTOCOL_VERSION}; retrying node host with protocol v${MIN_NODE_PROTOCOL_VERSION}` : `gateway rejected protocol v${MIN_NODE_PROTOCOL_VERSION}; retrying node host with protocol v${PROTOCOL_VERSION}`);
1148
1154
  return {
1149
1155
  closeCode: 1008,
1150
1156
  closeReason: "connect retry"
@@ -1317,23 +1323,8 @@ var GatewayClient = class {
1317
1323
  return false;
1318
1324
  }
1319
1325
  }
1320
- selectConnectAuth(storedAuth) {
1321
- return selectGatewayConnectAuth({
1322
- token: this.opts.token,
1323
- bootstrapToken: this.opts.bootstrapToken,
1324
- preferBootstrapToken: this.opts.preferBootstrapToken,
1325
- deviceToken: this.opts.deviceToken,
1326
- password: this.opts.password,
1327
- approvalRuntimeToken: this.approvalRuntimeTokenCompatibilityDisabled ? void 0 : this.opts.approvalRuntimeToken,
1328
- agentRuntimeIdentityToken: this.opts.agentRuntimeIdentityToken,
1329
- storedToken: storedAuth?.token,
1330
- storedScopes: storedAuth?.scopes,
1331
- pendingDeviceTokenRetry: this.pendingDeviceTokenRetry,
1332
- trustedDeviceTokenRetry: this.isTrustedDeviceRetryEndpoint()
1333
- });
1334
- }
1335
1326
  startTickWatch() {
1336
- if (this.tickTimer) clearInterval(this.tickTimer);
1327
+ clearInterval(this.tickTimer ?? void 0);
1337
1328
  const rawMinInterval = this.opts.tickWatchMinIntervalMs;
1338
1329
  const minInterval = typeof rawMinInterval === "number" && Number.isFinite(rawMinInterval) ? Math.max(1, Math.min(3e4, rawMinInterval)) : 1e3;
1339
1330
  const interval = resolveSafeTimeoutDelayMs(Math.max(this.tickIntervalMs, minInterval));
@@ -1350,11 +1341,9 @@ var GatewayClient = class {
1350
1341
  const expectFinal = opts?.expectFinal === true;
1351
1342
  const timeoutMs = opts?.timeoutMs === null ? null : typeof opts?.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : expectFinal ? null : this.requestTimeoutMs;
1352
1343
  return this.protocol.request(method, params, {
1344
+ ...opts,
1353
1345
  expectFinal,
1354
- timeoutMs,
1355
- signal: opts?.signal,
1356
- onSent: opts?.onSent,
1357
- onAccepted: opts?.onAccepted
1346
+ timeoutMs
1358
1347
  });
1359
1348
  }
1360
1349
  };
@@ -1,4 +1,4 @@
1
- import { n as GatewayProtocolRequestOptions, t as GatewayProtocolRequestError } from "./protocol-request-CtVhe3Bj.mjs";
1
+ import { n as GatewayProtocolRequestOptions, t as GatewayProtocolRequestError } from "./protocol-request-CRDNYiYG.mjs";
2
2
  import { GatewayClientMode, GatewayClientName } from "@openclaw/gateway-protocol/client-info";
3
3
  import { ErrorShape, EventFrame, HelloOk } from "@openclaw/gateway-protocol";
4
4
  //#region packages/gateway-client/src/pending-request.d.ts
@@ -161,6 +161,7 @@ declare class GatewayProtocolClient<TPlan> {
161
161
  private reconnectSignal;
162
162
  private socketOpened;
163
163
  private helloReceived;
164
+ private readyForRequests;
164
165
  private connectFailure;
165
166
  private connectTiming;
166
167
  private stoppedSocket?;
@@ -179,15 +180,11 @@ declare class GatewayProtocolClient<TPlan> {
179
180
  resetReconnectBackoff(initialMs: number): void;
180
181
  recordTiming(phase: GatewayProtocolTiming<TPlan>["phase"], generation: number, plan?: TPlan, detail?: unknown): void;
181
182
  private connect;
182
- private handleOpen;
183
- private armHandshakeTimer;
184
183
  private sendConnect;
185
184
  private handleConnectPlanError;
186
185
  private sendConnectPlan;
187
186
  private handleMessage;
188
187
  private dispatchEvent;
189
- private handleClose;
190
- private handleSocketError;
191
188
  private scheduleReconnect;
192
189
  private closeContext;
193
190
  private isConnectCurrent;
@@ -8,6 +8,8 @@ type GatewayProtocolRequestOptions = {
8
8
  onSent?: (requestId: string) => void;
9
9
  onAccepted?: (payload: unknown) => void;
10
10
  signal?: AbortSignal;
11
+ /** Abort unsent/retry work while retaining a sent write's result and original deadline. */
12
+ retainSentResultOnAbort?: boolean;
11
13
  };
12
14
  declare class GatewayProtocolRequestError extends Error {
13
15
  readonly code: string;