UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

148 lines • 149 kB
import{d as isRfc8215LocalUseNat64Ipv6Address,l as isLoopbackIpAddress,p as normalizeIpAddress,u as isPrivateOrLoopbackIpAddress$1}from"./ip-D5sFl_15.mjs";import{y as toStringifiedError}from"./sqlite-readonly-worker-BWA2KeVB.mjs";import{a as extractErrorCodeOrErrno}from"./error-coercion-B-1Loz4b.mjs";import{a as isRecord,i as asRecord,t as asNullableRecord}from"./record-coerce-DwDZngEy.mjs";import{a as normalizeOptionalString,l as resolveGlobalSingleton,n as normalizeLowercaseStringOrEmpty}from"./string-coerce-BBqv4GXj.mjs";import{a as asNonNegativeInteger,s as asPositiveInteger}from"./number-coercion-DIhBGkET.mjs";import{a as raceWithTimeout,n as createAbortError,o as resolveSleepDelayMs,s as sleepWithAbort,t as RetrySupervisor}from"./src-CY_qXgOR.mjs";import"./sleep-BeLUM6My.mjs";import{a as resolvePreauthHandshakeTimeoutMs,i as resolveFiniteTimeoutDelayMs,n as clearGatewayConnectTimeout,o as resolveSafeTimeoutDelayMs,r as resolveConnectChallengeTimeoutMs,s as startGatewayConnectTimeout,t as DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS}from"./timeouts-_PMLOAsc.mjs";import{P as parseJsonWithJson5Fallback,R as redactSensitiveUrlLikeString,S as resolveSecretInputRef,b as normalizeSecretInputString,g as containsEnvVarReference,h as resolveConfigIncludes,i as redactToolPayloadText,s as registerSecretValueForRedaction,v as hasConfiguredSecretInput,x as parseSecretRef,y as normalizeRequiredSecretInput}from"./redact-LQdRaLFO.mjs";import{n as safeParseJsonRecord}from"./json-coercion-CWOIS8T7.mjs";import{i as normalizeOptionalTrimmedStringList,n as filterStringEntries,s as normalizeTrimmedStringList}from"./string-normalization-mfgVoo8i.mjs";import{t as resolveStateDir}from"./state-dir-C22DK7p0.mjs";import{s as sanitizeTerminalText}from"./utils-CfSlIBx_.mjs";import{a as resolveIncludeRoots,i as resolveGatewayPort,t as resolveConfigPath}from"./paths-BFN5qw21.mjs";import{t as createSubsystemLogger}from"./subsystem-BMw5Czn-.mjs";import{t as VERSION}from"./version-D4mobxtZ.mjs";import{r as settleWithCleanup}from"./error-graph-internal-CZk3K2nJ.mjs";import{n as getAsyncWorkSignal}from"./async-work-scope-DYLSvs89.mjs";import{m as resolveDatabasePathKeyAsync}from"./sqlite-worker-identity-gGA4fE_R.mjs";import{a as GATEWAY_CLIENT_NAMES,i as GATEWAY_CLIENT_MODES,n as roleScopesAllow}from"./operator-scope-compat-BZZnt_Ml.mjs";import{l as WRITE_SCOPE,t as ADMIN_SCOPE,u as isOperatorScope}from"./operator-scopes-DNKhVEQF.mjs";import"./env-BVwgaeaj.mjs";import{F as isVitestRuntimeEnv,t as captureRuntimeConfigWithSource}from"./runtime-config-capture-state-CRekXoN8.mjs";import{o as resolveRuntimeProcessEntrypointUrl}from"./runtime-process-url-D05pNtC5.mjs";import{s as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-db-async-lifecycle-CLe5OGzr.mjs";import{n as resolveDatabaseFamilyEngines}from"./registry-C9Ag6oZl.mjs";import{n as getDatabaseEngineSelection,r as withDatabaseEngineSelection}from"./context-B7I7J9si.mjs";import"./crypto-digest-DDqGMAqd.mjs";import"./session-row-changes-CbypkYZd.mjs";import{t as SUBAGENT_EXEC_ENV_VAR}from"./openclaw-exec-env-JmVkz0uo.mjs";import"./config-env-vars-DC4WV43c.mjs";import{t as enqueueKeyedTask}from"./keyed-async-queue-CyGbEpfs.mjs";import{a as signEd25519Payload,i as publicKeyRawBase64UrlFromEd25519Pem}from"./ed25519-signature-V8QNyEcj.mjs";import{c as DeviceIdentityStorageError,d as normalizeIdentityKey,i as resolveConfigForRead,l as generateStoredDeviceIdentity,m as storedDeviceIdentityToRow,o as resolveClientCredentialStorePath,u as identityFromCredentialResult}from"./io.read-helpers-B1azzojZ.mjs";import{a as getConfigResolutionFacts,c as setConfigResolutionFacts,i as getAuthoredConfigSecretRef,n as copyConfigResolutionFactsExcept,o as hasUnresolvedConfigPath,s as resolveConfigSecretRef,t as cloneConfigWithResolutionFacts}from"./resolution-facts-BKHp-Zw8.mjs";import"./executable-path-B-jCEsO4.mjs";import{a as parseHostForAddressChecks,i as parseGatewayIpAddress,n as isGatewayClientStoppedError,o as requireTlsFingerprint,r as normalizeTlsFingerprint,t as formatGatewayClientErrorForLog}from"./client-address-utils-C1XJsd6v.mjs";import{r as isSecretResolutionError}from"./resolve-errors-oT_xFkWZ.mjs";import{n as resolveCanonicalConfiguredSecretInputWithFallback}from"./resolve-configured-secret-input-string-Dj6nQYAa.mjs";import{n as logError,t as logDebug}from"./logger-DmLqrh-9.mjs";import{c as resolveActiveManagedProxyTlsOptions,d as getActiveManagedProxyLoopbackMode,f as resolveEnvHttpProxyAgentOptions,i as loadUndiciGlobalDispatcherDeps,l as loadManagedProxyTlsOptionsSync,n as createHttp1EnvHttpProxyAgent,t as createHttp1Agent,u as resolveManagedProxyCaFileForUrl}from"./undici-runtime-CiEGgc_q.mjs";import{createRequire}from"node:module";import{isDeepStrictEqual}from"node:util";import fsSync from"node:fs";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import os from"node:os";import{Buffer as Buffer$1}from"node:buffer";import net,{isIP}from"node:net";import{TLSSocket,checkServerIdentity}from"node:tls";import{isProxylineDispatcher}from"@openclaw/proxyline/dispatcher-brand";
//!packages/gateway-client/src/event-loop-ready.ts
const DEFAULT_MAX_WAIT_MS=1e4;const DEFAULT_INTERVAL_MS=1;const DEFAULT_DRIFT_THRESHOLD_MS=200;const DEFAULT_CONSECUTIVE_READY_CHECKS=2;function resolvePositiveInteger(e,t){return Number.isFinite(e)&&e!==void 0?Math.max(1,Math.floor(e)):t}async function waitForEventLoopReady(e={}){const t=resolveFiniteTimeoutDelayMs(e.maxWaitMs,DEFAULT_MAX_WAIT_MS,{minMs:0});const n=resolveFiniteTimeoutDelayMs(e.intervalMs,DEFAULT_INTERVAL_MS);const r=resolvePositiveInteger(e.driftThresholdMs,DEFAULT_DRIFT_THRESHOLD_MS);const i=resolvePositiveInteger(e.consecutiveReadyChecks,DEFAULT_CONSECUTIVE_READY_CHECKS);const a=e.signal;const o=Date.now();let s=0;let c=0;let l=0;return await new Promise(e=>{let u=null;const finish=(t,n=false)=>{if(u){clearTimeout(u);u=null}a?.removeEventListener(`abort`,onAbort);e({ready:t,elapsedMs:Math.max(0,Date.now()-o),maxDriftMs:l,checks:c,aborted:n})};const onAbort=()=>{finish(false,true)};if(a?.aborted){finish(false,true);return}a?.addEventListener(`abort`,onAbort,{once:true});const scheduleNext=()=>{const e=Math.max(0,Date.now()-o);const a=t-e;if(a<=0){finish(false);return}const d=Math.min(n,a);const f=Date.now();u=setTimeout(()=>{u=null;c+=1;const e=Math.max(0,Date.now()-f-d);l=Math.max(l,e);if(e>r)s=0;else s+=1;if(s>=i){finish(true);return}scheduleNext()},d)};scheduleNext()})}
//!packages/gateway-client/src/readiness.ts
async function startGatewayClientWithReadinessWait(e,t,n={}){let r;if(typeof n.timeoutMs===`number`&&Number.isFinite(n.timeoutMs))r=n.timeoutMs;else{const e=n.clientOptions??{};r=resolveConnectChallengeTimeoutMs(e.connectChallengeTimeoutMs,{env:e.env,configuredTimeoutMs:e.preauthHandshakeTimeoutMs})}const i=await e({maxWaitMs:r,signal:n.signal});if(i.ready&&!i.aborted&&n.signal?.aborted!==true)t.start();return i}async function startGatewayClientWhenEventLoopReady(e,t={}){return startGatewayClientWithReadinessWait(waitForEventLoopReady,e,t)}
//!packages/gateway-protocol/src/protocol-value-normalization.ts
function isNonEmptyProtocolString(e){return typeof e===`string`&&e.length>0}
//!packages/gateway-protocol/src/connect-error-details.ts
const accessCauses={"access-record-inactive":false,"profile-invalidated":false,"plugin-lifetime-retired":true,"policy-unavailable":true,"policy-set-changed":true,"policy-check-failed":false,"grant-revoked":false};function readGatewayOperatorAccessCause(e){return typeof e===`string`&&Object.hasOwn(accessCauses,e)?e:null}function accessError(e,t){const n=accessCauses[e];return{code:`FORBIDDEN`,message:t,details:{code:ConnectErrorDetailCodes.OPERATOR_ACCESS_DENIED,accessCause:e},retryable:n,retryAfterMs:n?3e4:void 0}}function isGatewayOperatorAccessRetryable(e){const t=isRecord(e)?readGatewayOperatorAccessCause(e.accessCause):null;return t!==null&&accessCauses[t]}function readGatewayOperatorAccessClose(e,t){if(e!==4001)return null;const n=/^Gateway access (?:stopped \[access-cause=([a-z-]+)\]; |is not active for this account;)/.exec(t);return n?accessError(readGatewayOperatorAccessCause(n[1])??`policy-check-failed`,t):null}const ConnectErrorDetailCodes={AUTH_REQUIRED:`AUTH_REQUIRED`,AUTH_UNAUTHORIZED:`AUTH_UNAUTHORIZED`,AUTH_TOKEN_MISSING:`AUTH_TOKEN_MISSING`,AUTH_TOKEN_MISMATCH:`AUTH_TOKEN_MISMATCH`,AUTH_TOKEN_NOT_CONFIGURED:`AUTH_TOKEN_NOT_CONFIGURED`,AUTH_PASSWORD_MISSING:`AUTH_PASSWORD_MISSING`,AUTH_PASSWORD_MISMATCH:`AUTH_PASSWORD_MISMATCH`,AUTH_PASSWORD_NOT_CONFIGURED:`AUTH_PASSWORD_NOT_CONFIGURED`,AUTH_BOOTSTRAP_TOKEN_INVALID:`AUTH_BOOTSTRAP_TOKEN_INVALID`,AUTH_DEVICE_TOKEN_MISMATCH:`AUTH_DEVICE_TOKEN_MISMATCH`,AUTH_SCOPE_MISMATCH:`AUTH_SCOPE_MISMATCH`,AUTH_RATE_LIMITED:`AUTH_RATE_LIMITED`,AUTH_TAILSCALE_IDENTITY_MISSING:`AUTH_TAILSCALE_IDENTITY_MISSING`,AUTH_TAILSCALE_PROXY_MISSING:`AUTH_TAILSCALE_PROXY_MISSING`,AUTH_TAILSCALE_WHOIS_FAILED:`AUTH_TAILSCALE_WHOIS_FAILED`,AUTH_TAILSCALE_IDENTITY_MISMATCH:`AUTH_TAILSCALE_IDENTITY_MISMATCH`,AUTH_IDENTITY_HEADER_REQUIRED:`AUTH_IDENTITY_HEADER_REQUIRED`,AUTH_VERIFIED_USER_REQUIRED:`AUTH_VERIFIED_USER_REQUIRED`,AUTHENTICATED_PROFILE_UNAVAILABLE:`AUTHENTICATED_PROFILE_UNAVAILABLE`,OPERATOR_ACCESS_DENIED:`OPERATOR_ACCESS_DENIED`,CONTROL_UI_BUILD_MISMATCH:`CONTROL_UI_BUILD_MISMATCH`,CONTROL_UI_ORIGIN_NOT_ALLOWED:`CONTROL_UI_ORIGIN_NOT_ALLOWED`,PROTOCOL_MISMATCH:`PROTOCOL_MISMATCH`,CONTROL_UI_DEVICE_IDENTITY_REQUIRED:`CONTROL_UI_DEVICE_IDENTITY_REQUIRED`,DEVICE_IDENTITY_REQUIRED:`DEVICE_IDENTITY_REQUIRED`,DEVICE_AUTH_INVALID:`DEVICE_AUTH_INVALID`,DEVICE_AUTH_DEVICE_ID_MISMATCH:`DEVICE_AUTH_DEVICE_ID_MISMATCH`,DEVICE_AUTH_SIGNATURE_EXPIRED:`DEVICE_AUTH_SIGNATURE_EXPIRED`,DEVICE_AUTH_NONCE_REQUIRED:`DEVICE_AUTH_NONCE_REQUIRED`,DEVICE_AUTH_NONCE_MISMATCH:`DEVICE_AUTH_NONCE_MISMATCH`,DEVICE_AUTH_SIGNATURE_INVALID:`DEVICE_AUTH_SIGNATURE_INVALID`,DEVICE_AUTH_PUBLIC_KEY_INVALID:`DEVICE_AUTH_PUBLIC_KEY_INVALID`,PAIRING_REQUIRED:`PAIRING_REQUIRED`,PAIRING_REJECTED:`PAIRING_REJECTED`,PAIRING_EXPIRED:`PAIRING_EXPIRED`,CLIENT_VERSION_MISMATCH:`CLIENT_VERSION_MISMATCH`};const CONNECT_RECOVERY_NEXT_STEP_VALUES=[`retry_with_device_token`,`update_auth_configuration`,`update_auth_credentials`,`wait_then_retry`,`review_auth_configuration`];const PAIRING_CONNECT_REQUEST_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;const PAIRING_CONNECT_REASON_METADATA={"not-paired":{message:`device pairing required`,requirement:`device is not approved yet`,remediationHint:`Approve this device from the pending pairing requests.`,recoveryTitle:`Gateway pairing approval required.`},"role-upgrade":{message:`role upgrade pending approval`,requirement:`device is asking for a higher role than currently approved`,remediationHint:`Review the requested role upgrade, then approve the pending request.`,recoveryTitle:`Gateway role upgrade approval required.`},"scope-upgrade":{message:`scope upgrade pending approval`,requirement:`device is asking for more scopes than currently approved`,remediationHint:`Review the requested scopes, then approve the pending upgrade.`,recoveryTitle:`Gateway scope upgrade approval required.`},"metadata-upgrade":{message:`device metadata change pending approval`,requirement:`device identity changed and must be re-approved`,remediationHint:`Review the refreshed device details, then approve the pending request.`,recoveryTitle:`Gateway device refresh approval required.`}};const AUTH_CONNECT_ERROR_CODES=/* @__PURE__ */ new Map([[`token_missing`,ConnectErrorDetailCodes.AUTH_TOKEN_MISSING],[`token_mismatch`,ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH],[`token_missing_config`,ConnectErrorDetailCodes.AUTH_TOKEN_NOT_CONFIGURED],[`password_missing`,ConnectErrorDetailCodes.AUTH_PASSWORD_MISSING],[`password_mismatch`,ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH],[`password_missing_config`,ConnectErrorDetailCodes.AUTH_PASSWORD_NOT_CONFIGURED],[`bootstrap_token_invalid`,ConnectErrorDetailCodes.AUTH_BOOTSTRAP_TOKEN_INVALID],[`tailscale_user_missing`,ConnectErrorDetailCodes.AUTH_TAILSCALE_IDENTITY_MISSING],[`tailscale_proxy_missing`,ConnectErrorDetailCodes.AUTH_TAILSCALE_PROXY_MISSING],[`tailscale_whois_failed`,ConnectErrorDetailCodes.AUTH_TAILSCALE_WHOIS_FAILED],[`tailscale_user_mismatch`,ConnectErrorDetailCodes.AUTH_TAILSCALE_IDENTITY_MISMATCH],[`rate_limited`,ConnectErrorDetailCodes.AUTH_RATE_LIMITED],[`device_token_mismatch`,ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH],[`scope_mismatch`,ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH],[void 0,ConnectErrorDetailCodes.AUTH_REQUIRED]]);const DEVICE_AUTH_CONNECT_ERROR_CODES=/* @__PURE__ */ new Map([[`device-id-mismatch`,ConnectErrorDetailCodes.DEVICE_AUTH_DEVICE_ID_MISMATCH],[`device-signature-stale`,ConnectErrorDetailCodes.DEVICE_AUTH_SIGNATURE_EXPIRED],[`device-nonce-missing`,ConnectErrorDetailCodes.DEVICE_AUTH_NONCE_REQUIRED],[`device-nonce-mismatch`,ConnectErrorDetailCodes.DEVICE_AUTH_NONCE_MISMATCH],[`device-signature`,ConnectErrorDetailCodes.DEVICE_AUTH_SIGNATURE_INVALID],[`device-public-key`,ConnectErrorDetailCodes.DEVICE_AUTH_PUBLIC_KEY_INVALID]]);function readConnectErrorDetailCode(e){if(!isRecord(e))return null;return normalizeOptionalString(e.code)??null}function readConnectErrorRecoveryAdvice(e){if(!isRecord(e))return{};return{canRetryWithDeviceToken:typeof e.canRetryWithDeviceToken===`boolean`?e.canRetryWithDeviceToken:void 0,recommendedNextStep:normalizeConnectRecoveryNextStep(e.recommendedNextStep)}}function normalizeConnectRecoveryNextStep(e){const t=normalizeOptionalString(e)??``;return CONNECT_RECOVERY_NEXT_STEP_VALUES.find(e=>e===t)}function normalizePairingConnectReason(e){const t=normalizeOptionalString(e)??``;return Object.hasOwn(PAIRING_CONNECT_REASON_METADATA,t)?t:void 0}function normalizePairingConnectRequestId(e){const t=normalizeOptionalString(e);return t&&PAIRING_CONNECT_REQUEST_ID_PATTERN.test(t)?t:void 0}function createPairingConnectErrorDetails(e){return{code:ConnectErrorDetailCodes.PAIRING_REQUIRED,...e.reason?{reason:e.reason}:{},...e.requestId?{requestId:e.requestId}:{},...e.remediationHint?{remediationHint:e.remediationHint}:{},...e.recommendedNextStep?{recommendedNextStep:e.recommendedNextStep}:{},...e.retryable!==void 0?{retryable:e.retryable}:{},...e.pauseReconnect!==void 0?{pauseReconnect:e.pauseReconnect}:{},...e.waitForResolution!==void 0?{waitForResolution:e.waitForResolution}:{},...e.deviceId?{deviceId:e.deviceId}:{},...e.requestedRole?{requestedRole:e.requestedRole}:{},...e.requestedScopes?{requestedScopes:e.requestedScopes}:{},...e.approvedRoles?{approvedRoles:e.approvedRoles}:{},...e.approvedScopes?{approvedScopes:e.approvedScopes}:{}}}function normalizePairingConnectMetadata(e,t){return{requestId:normalizePairingConnectRequestId(e.requestId),remediationHint:normalizeOptionalString(e.remediationHint)??(t?PAIRING_CONNECT_REASON_METADATA[t].remediationHint:`Approve the pending device request before retrying.`),deviceId:normalizeOptionalString(e.deviceId),requestedRole:normalizeOptionalString(e.requestedRole),requestedScopes:normalizeOptionalTrimmedStringList(e.requestedScopes),approvedRoles:normalizeOptionalTrimmedStringList(e.approvedRoles),approvedScopes:normalizeOptionalTrimmedStringList(e.approvedScopes)}}function readPairingConnectErrorDetails(e){if(readConnectErrorDetailCode(e)!==ConnectErrorDetailCodes.PAIRING_REQUIRED)return null;if(!isRecord(e))return null;const t=normalizePairingConnectReason(e.reason);return createPairingConnectErrorDetails({...normalizePairingConnectMetadata(e,t),reason:t,recommendedNextStep:normalizeConnectRecoveryNextStep(e.recommendedNextStep),retryable:typeof e.retryable===`boolean`?e.retryable:void 0,pauseReconnect:typeof e.pauseReconnect===`boolean`?e.pauseReconnect:void 0,waitForResolution:typeof e.waitForResolution===`boolean`?e.waitForResolution:void 0})}function formatConnectPairingRequiredMessage(e){const t=readPairingConnectErrorDetails(e);const n=PAIRING_CONNECT_REASON_METADATA[t?.reason??`not-paired`].message;return t?.requestId?`${n} (requestId: ${t.requestId})`:n}function formatConnectErrorMessage(e){const t=readConnectErrorDetailCode(e.details);if(t===ConnectErrorDetailCodes.PAIRING_REQUIRED)return formatConnectPairingRequiredMessage(e.details);if(t===ConnectErrorDetailCodes.PROTOCOL_MISMATCH)return formatProtocolMismatchMessage(e.message,e.details);return normalizeOptionalString(e.message)??`gateway request failed`}function formatProtocolMismatchMessage(e,t){const n=t;const r=asPositiveInteger(n.clientMinProtocol);const i=asPositiveInteger(n.clientMaxProtocol);const a=asPositiveInteger(n.expectedProtocol);const o=asPositiveInteger(n.minimumProbeProtocol);const s=[];if(r!==void 0&&i!==void 0)s.push(r===i?`Web app v${r}`:`Web app v${r}-v${i}`);if(a!==void 0)s.push(`Gateway v${a}`);if(o!==void 0)s.push(`connection check min v${o}`);const c=normalizeOptionalString(e)??`protocol mismatch`;return s.length>0?`${c}: ${s.join(`, `)}`:c}
//!src/config/gateway-dispatch-config.ts
const GATEWAY_DISPATCH_SHELL_ENV_EXPECTED_KEYS=[`OPENCLAW_GATEWAY_TOKEN`,`OPENCLAW_GATEWAY_PASSWORD`];const GATEWAY_DISPATCH_TOP_LEVEL_KEYS=[`agents`,`database`,`env`,`gateway`,`plugins`,`secrets`,`session`];function resolveGatewayDispatchConfig(e,t){if(!isRecord(e))return{};const n={};for(const t of GATEWAY_DISPATCH_TOP_LEVEL_KEYS)if(Object.hasOwn(e,t))n[t]=e[t];const{resolvedConfigRaw:r,resolutionFacts:i}=resolveConfigForRead(n,t);const a=r;if(a.session?.mainKey!==void 0)a.session.mainKey=`main`;setConfigResolutionFacts(a,i);return a}function readRawGatewayDispatchConfig(e={}){const t=e.env??process.env;const n=e.configPath??resolveConfigPath(t);if(!fsSync.existsSync(n))return{config:{},configPath:n};const r=fsSync.readFileSync(n,`utf-8`);const i=parseJsonWithJson5Fallback(r);return{config:resolveGatewayDispatchConfig(resolveConfigIncludes(i,n,void 0,{allowedRoots:resolveIncludeRoots(t)}),t),configPath:n}}function readGatewayDispatchConfig(e={}){return readRawGatewayDispatchConfig(e).config}async function readGatewayDispatchConfigWithShellEnvFallback(e={}){const t=e.env??process.env;const n=readRawGatewayDispatchConfig(e);const{loadShellEnvFallback:r,resolveShellEnvFallbackTimeoutMs:i,shouldDeferShellEnvFallback:a,shouldEnableShellEnvFallback:o}=await import(`./shell-env-kQE0_GwA.mjs`);if((o(t)||n.config.env?.shellEnv?.enabled===true)&&!a(t)){if(r({env:t,expectedKeys:[...GATEWAY_DISPATCH_SHELL_ENV_EXPECTED_KEYS],timeoutMs:n.config.env?.shellEnv?.timeoutMs??i(t)}).length>0)return readGatewayDispatchConfig({...e,configPath:path.resolve(n.configPath)})}return n.config}
//!src/config/runtime-snapshot.ts
let runtimeConfigSnapshot=null;let runtimeConfigCapturedSnapshot=null;let runtimeConfigSourceSnapshot=null;function getRuntimeConfigSnapshot(e){if(e?.capture&&runtimeConfigSnapshot)return runtimeConfigCapturedSnapshot??=captureRuntimeConfigWithSource(runtimeConfigSnapshot,runtimeConfigSourceSnapshot??runtimeConfigSnapshot);return runtimeConfigSnapshot}
//!packages/gateway-protocol/src/missing-scope-error.ts
const MISSING_SCOPE_ERROR_CODE=`MISSING_SCOPE`;function readMissingScopeErrorDetails(e){const t=asNullableRecord(e);if(t?.code!==`MISSING_SCOPE`)return null;const n=typeof t.missingScope===`string`?t.missingScope.trim():``;const r=Array.isArray(t.requiredScopes)?t.requiredScopes.map(e=>typeof e===`string`?e.trim():``):[];if(!n||r.length===0||r.some(e=>!e))return null;return{code:MISSING_SCOPE_ERROR_CODE,missingScope:n,requiredScopes:r}}
//!src/shared/device-auth.ts
function normalizeDeviceAuthRole(e){return e.trim()}function normalizeDeviceAuthScopes(e){const t=new Set(normalizeTrimmedStringList(e));if(t.has(`operator.admin`)){t.add(`operator.read`);t.add(`operator.write`)}else if(t.has(`operator.write`))t.add(`operator.read`);return[...t].toSorted()}
//!src/infra/client-credential-async.ts
const queues=resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialOperations`),()=>/* @__PURE__ */ new Map);const runtime=resolveGlobalSingleton(Symbol.for(`openclaw.clientCredentialWorker`),()=>({resources:/* @__PURE__ */ new Map}),()=>closeClientCredentialWorker());function closeClientCredentialWorker(){runtime.closing??=(async()=>{await Promise.all(queues.values());await runtime.pool?.close();runtime.pool=void 0;for(const e of runtime.resources.values())e.unregister();runtime.resources.clear()})().finally(()=>{runtime.closing=void 0});return runtime.closing}async function runClientCredentialOperationAsync(e,t,n={}){return runClientCredentialTaskAsync(e,t,n)}async function runClientCredentialTaskAsync(e,t,n={}){n.signal?.throwIfAborted();n.assertCurrent?.();const r=await enqueueKeyedTask({tails:queues,key:`\0credential-root-resolution`,task:()=>resolveDatabasePathKeyAsync(path.resolve(resolveStateDir(e)))});n.signal?.throwIfAborted();n.assertCurrent?.();const i={HOME:e.HOME,USERPROFILE:e.USERPROFILE,OPENCLAW_PROFILE:e.OPENCLAW_PROFILE,OPENCLAW_STATE_DIR:r};const a=resolveClientCredentialStorePath({OPENCLAW_STATE_DIR:r});const assertCurrent=()=>{n.signal?.throwIfAborted();n.assertCurrent?.()};assertCurrent();return enqueueKeyedTask({tails:queues,key:r,task:async()=>{const offline=async()=>{const[{registerOpenClawAgentDatabaseReadCandidateResource:e},{hydrateOpenClawStateWorkerError:i,retainOpenClawStateWorkerErrorPayload:o},{acquireStateDatabaseSchemaLease:s,captureStateDatabaseAccess:c},{retainSqliteWriteAdmissionService:l},{createSqliteWorkerOperationAdmission:u},{WorkerTaskPool:d}]=await Promise.all([import(`./openclaw-agent-db-resources-Df9mjzST.mjs`),import(`./openclaw-state-worker-error-XC-hCXUK.mjs`),import(`./gateway-state-owner-Wg4KkEik.mjs`),import(`./sqlite-transaction-BsCWDAFG.mjs`),import(`./sqlite-worker-operation-admission-sH2qK-Ix.mjs`),import(`./worker-task-pool-CJ7oLu70.mjs`)]);assertCurrent();if(runtime.closing)throw new Error(`Client credential worker is closing.`);let f=runtime.resources.get(a);if(!f){const t=await c(a);assertCurrent();if(runtime.closing)throw new Error(`Client credential worker is closing.`);f={access:t,unregister:e({path:a,revoke(){closeClientCredentialWorker().catch(()=>{})},close:closeClientCredentialWorker})};runtime.resources.set(a,f)}const p=getOpenClawDatabaseMaintenanceScope();const m=await f.access.prepareAccess({maintenanceScope:p});assertCurrent();let h;const assertAccess=()=>{assertCurrent();p?.assertAdmission();m({maintenanceScope:p,schemaLease:h})};const g=u((e,t)=>{assertAccess();if(!t())throw new Error(`Client credential operation authority expired.`)});g.bindDatabaseAuthority({databasePath:a,assertRequest:assertCurrent,assertAccess,acquireSchema(){assertAccess();const acquire=()=>s(a);const e=p?p.run(acquire):acquire();h=e;p?.own(e,`shared-resources`,()=>e.release());return e}});const _=l([a],()=>g.service());return settleWithCleanup((async()=>{try{runtime.pool??=new d({workerUrl:resolveRuntimeProcessEntrypointUrl(`clientCredentials`),workerClass:`singleton`});const e=await runtime.pool.run({root:r,operation:t,admission:g.port},{signal:n.signal,transferList:e=>[e.admission]});assertAccess();if(e.kind===`error`){const t=/* @__PURE__ */ new Error(`Client credential operation failed`);o(t,e.error);throw i(t,{includeOrdinary:true})}return e}catch(e){throw g.failure??e}})(),async()=>{try{await g.finish()}finally{_()}},`Client credential operation and admission cleanup failed`)};const e=getOpenClawDatabaseMaintenanceScope();if(e?.ownsSchemaMaintenance)e.assertAdmission();else{const{requestClientCredentialsFromApp:e}=await import(`./client-credential-ipc-CHUJ-TTk.mjs`);assertCurrent();const r=await e(i,t.kind===`startup.prepare`?{kind:`identity.read`,identity_key:`primary`}:t,n.signal,assertCurrent);assertCurrent();if(r)return t.kind===`startup.prepare`?{kind:`preparation`,state:`ready`}:r}const o=await offline();if(o.kind===`result`)return o.result;throw new Error(`Client credentials are busy; retry after the current owner finishes.`)}})}
//!src/infra/device-auth-store.kernel.ts
function deviceAuthEntryFromRow(e){try{const t=JSON.parse(e.scopes_json);if(!Array.isArray(t))return null;return{token:e.token,role:e.role,scopes:normalizeDeviceAuthScopes(t),updatedAtMs:e.updated_at_ms}}catch{return null}}function createDeviceAuthEntry(e){return{token:e.token,role:normalizeDeviceAuthRole(e.role),scopes:normalizeDeviceAuthScopes(e.scopes),updatedAtMs:e.updatedAtMs??Date.now()}}
//!src/infra/device-auth-store.ts
function captureDeviceAuthOperation(e){const t={...e.env??process.env};const{signal:n,assertCurrent:r}=e;const assertActive=()=>{n?.throwIfAborted();r?.()};assertActive();return{env:t,signal:n,assertCurrent:assertActive}}function tokenKey(e,t){return{device_id:e.deviceId,role:normalizeDeviceAuthRole(e.role),...t===void 0?{}:{gateway_scope:t}}}async function readDeviceAuth(e,t){const n=captureDeviceAuthOperation(e);const r=await runClientCredentialOperationAsync(n.env,{kind:`token.read`,key:tokenKey(e,t)},n);if(r.kind!==`token`)throw new Error(`Client credential owner returned an unexpected token result.`);n.assertCurrent();const i={entry:r.token?deviceAuthEntryFromRow(r.token):null,expectedToken:r.token?.token??null};e.onSnapshot?.(i);return i.entry}function loadDeviceAuthToken(e){return readDeviceAuth(e)}const loadDeviceAuthTokenReadOnly=loadDeviceAuthToken;async function storeToken(e,t){const n=captureDeviceAuthOperation(e);const r=createDeviceAuthEntry(e);const i=await runClientCredentialOperationAsync(n.env,{kind:`token.replace`,key:tokenKey(e,t),expectedToken:e.expectedToken,token:{device_id:e.deviceId,role:r.role,token:r.token,scopes_json:JSON.stringify(r.scopes),updated_at_ms:r.updatedAtMs}},n);if(i.kind!==`changed`)throw new Error(`Client credential owner returned an unexpected token write result.`);return i.changed?r:null}async function clearToken(e,t){const n=captureDeviceAuthOperation(e);const r=await runClientCredentialOperationAsync(n.env,{kind:`token.remove`,key:tokenKey(e,t),expectedToken:e.expectedToken,observedToken:e.observedToken},n);if(r.kind!==`changed`)throw new Error(`Client credential owner returned an unexpected token removal result.`);return r.changed}function storeDeviceAuthToken(e){return storeToken(e)}function clearDeviceAuthToken(e){return clearToken(e)}function loadOriginDeviceToken(e){return readDeviceAuth(e,e.gatewayScope)}const loadOriginDeviceTokenReadOnly=loadOriginDeviceToken;function storeOriginDeviceToken(e){return storeToken(e,e.gatewayScope)}function clearOriginDeviceToken(e){return clearToken(e,e.gatewayScope)}
//!src/infra/device-identity-store-options.ts
function resolveDeviceIdentityStore(e={}){const t=path.resolve(e.path??resolveClientCredentialStorePath(e.env??process.env));if(path.basename(t)!==`credentials.sqlite`||path.basename(path.dirname(t))!==`client`)throw new DeviceIdentityStorageError(`Device identity path must be <client-root>/client/credentials.sqlite; pass env.OPENCLAW_STATE_DIR to select the client root.`);return{databasePath:t,identityKey:normalizeIdentityKey(e.identityKey)}}function resolveDeviceIdentityEnvironment(e){const{databasePath:t}=resolveDeviceIdentityStore(e);return{...e.env??process.env,OPENCLAW_STATE_DIR:path.dirname(path.dirname(t))}}
//!src/infra/device-identity-async.ts
const log=createSubsystemLogger(`gateway/chat`);async function loadOrCreateDeviceIdentityAsync(e={}){const{identityKey:t}=resolveDeviceIdentityStore(e);const n=resolveDeviceIdentityEnvironment(e);const r=identityFromCredentialResult(await runClientCredentialOperationAsync(n,{kind:`identity.create`,identity:storedDeviceIdentityToRow(t,generateStoredDeviceIdentity())}));if(!r)throw new Error(`Client credential owner did not persist identity "${t}".`);return{deviceId:r.deviceId,publicKeyPem:r.publicKeyPem,privateKeyPem:r.privateKeyPem}}async function loadDeviceIdentityIfPresentAsync(e={}){const{identityKey:t}=resolveDeviceIdentityStore(e);const n=identityFromCredentialResult(await runClientCredentialOperationAsync(resolveDeviceIdentityEnvironment(e),{kind:`identity.read`,identity_key:t}));return n?{deviceId:n.deviceId,publicKeyPem:n.publicKeyPem,privateKeyPem:n.privateKeyPem}:null}
//!packages/gateway-client/src/gateway-origin-scope.ts
function normalizeGatewayScope(e,t){const n=e.trim();if(!n)return`default`;const r=globalThis.location;const i=r?`${r.protocol}//${r.host}${r.pathname||`/`}`:void 0;const a=URL.parse(n,i);if(!a)return n;const o=a.pathname===`/`?``:a.pathname.replace(/\/+$/,``)||a.pathname;return`${a.protocol}//${a.host}${o}${t?a.search:``}`}function gatewayOriginScope(e){return normalizeGatewayScope(e,false)}
//!src/gateway/websocket-protocol.ts
function normalizeWebSocketProtocol(e){return e===`https:`?`wss:`:e===`http:`?`ws:`:e}
//!src/gateway/net.ts
function isLoopbackAddress(e){return isLoopbackIpAddress(e)}function isPrivateOrLoopbackAddress(e){return isPrivateOrLoopbackIpAddress$1(e)&&!isRfc8215LocalUseNat64Ipv6Address(e)}function isLoopbackHost(e){const t=typeof e===`string`?parseHostForAddressChecks(e):null;if(!t)return false;if(t.isLocalhost)return true;return isLoopbackAddress(t.unbracketedHost)}function isLoopbackGatewayUrl(e){try{const t=new URL(e).hostname.toLowerCase();const n=t.startsWith(`[`)&&t.endsWith(`]`)?t.slice(1,-1):t;return n===`localhost`||isLoopbackIpAddress(n)}catch{return false}}function isPrivateOrLoopbackHost$1(e){const t=typeof e===`string`?parseHostForAddressChecks(e):null;if(!t)return false;if(t.isLocalhost)return true;const n=normalizeIpAddress(t.unbracketedHost);if(!n||!isPrivateOrLoopbackAddress(n))return false;if(net.isIP(n)===6){if(n.startsWith(`ff`))return false;if(n===`::`)return false}return true}function isSecureWebSocketUrl$1(e,t){let n;try{n=new URL(e)}catch{return false}const r=normalizeWebSocketProtocol(n.protocol);if(r===`wss:`)return true;if(r!==`ws:`)return false;if(isLoopbackHost(n.hostname))return true;if(isTrustedPlaintextWebSocketHost$1(n.hostname))return true;if(t?.allowPrivateWs){const e=n.hostname.startsWith(`[`)&&n.hostname.endsWith(`]`)?n.hostname.slice(1,-1):n.hostname;return net.isIP(e)===0}return false}function isTrustedPlaintextWebSocketHost$1(e){if(isPrivateOrLoopbackHost$1(e))return true;const t=normalizeLowercaseStringOrEmpty(e).replace(/\.+$/,``);return t.endsWith(`.local`)||t.endsWith(`.ts.net`)}
//!src/gateway/connection-details.ts
function resolveGatewaySshRemotePort(e,t=e.gateway?.remote?.url){if(e.gateway?.remote?.remotePort!==void 0)return e.gateway.remote.remotePort;const n=t?.trim();if(n&&URL.canParse(n)){const e=new URL(n.replace(/^wss?:/iu,`openclaw-ssh:`)).port;if(e)return Number(e)}return resolveGatewayPort(e)}function resolveGatewayDeviceAuthRoute(e){if(!e.remote)return{bound:false};const t=e.url.trim();const n=gatewayOriginScope(t);if(!URL.canParse(t))return{deviceAuthScope:n,bound:false};const r=new URL(t);if(!isLoopbackHost(r.hostname))return{deviceAuthScope:n,bound:true};const i=e.config.gateway?.remote;const a=normalizeOptionalString(i?.sshTarget);const o=normalizeOptionalString(i?.sshIdentity);const s=e.configuredRemote&&a&&i?.transport!==`direct`&&i?.url?.trim()===t?{target:a,remotePort:resolveGatewaySshRemotePort(e.config,t),...o?{identity:o}:{},...i.sshHostKeyPolicy?{hostKeyPolicy:i.sshHostKeyPolicy}:{}}:void 0;const c=e.sshRoute??s;if(c){const e={...c,target:c.target.trim()};const t=`${e.target}:gateway-port:${e.remotePort}`;return{deviceAuthScope:`remote:ssh:${createHash(`sha256`).update(t).digest(`hex`)}`,sshTunnel:e,bound:true}}const l=normalizeTlsFingerprint(e.tlsFingerprint);if(r.protocol===`wss:`&&l)return{deviceAuthScope:`remote:tls:${createHash(`sha256`).update(`${n}:tls-sha256:${l}`).digest(`hex`)}`,bound:true};return{deviceAuthScope:n,bound:false}}function projectGatewayUrlForDiagnostics(e){return redactSensitiveUrlLikeString(e)}const GATEWAY_PAIRING_APPROVAL_HINT="On the Gateway host, run `openclaw devices approve --latest` to preview the pending request. Review the preview, then run the printed `openclaw devices approve <requestId>` command to approve it. Or approve it in that Gateway's Control UI (Settings -> Devices). Then retry.";function buildGatewayConnectionDetailsWithResolvers(e={},t={}){const n=e.config??t.getRuntimeConfig?.()??{};const r=e.configPath??t.resolveConfigPath?.(process.env)??resolveConfigPath(process.env);const i=e.localPortOverride===void 0&&n.gateway?.mode===`remote`;const a=i?n.gateway?.remote:void 0;const o=n.gateway?.tls?.enabled===true;const s=e.localPortOverride??t.resolveGatewayPort?.(n,process.env)??resolveGatewayPort(n);const c=n.gateway?.bind??`loopback`;const l=`${o?`wss`:`ws`}://127.0.0.1:${s}`;const u=normalizeOptionalString(e.url);const d=normalizeOptionalString(e.serviceTargetUrl);const f=u||d||e.ignoreEnvUrlOverride||e.localPortOverride!==void 0?void 0:normalizeOptionalString(process.env.OPENCLAW_GATEWAY_URL);const p=u??f;const m=normalizeOptionalString(a?.url);const h=i&&!p&&!d&&!m;const g=e.urlSource??(u?`cli`:f?`env`:void 0);const _=p||d||m||l;const v=redactSensitiveUrlLikeString(_);const y=p?g===`env`?`env OPENCLAW_GATEWAY_URL`:`cli --url`:d?`service target`:m?`config gateway.remote.url`:h?`missing gateway.remote.url (fallback local)`:`local loopback`;const b=!p&&(d||!m)?`Bind: ${c}`:void 0;const x=h?`Warn: gateway.mode=remote but gateway.remote.url is missing; set gateway.remote.url or switch gateway.mode=local.`:void 0;const S=process.env.OPENCLAW_ALLOW_INSECURE_PRIVATE_WS===`1`;if(!isSecureWebSocketUrl$1(_,{allowPrivateWs:S}))throw new Error([`SECURITY ERROR: Gateway URL "${v}" uses plaintext ws:// to a non-loopback address.`,`Both credentials and chat data would be exposed to network interception.`,`Source: ${y}`,`Config: ${r}`,`Fix: Use wss:// for remote gateway URLs.`,`Safe remote access defaults:`,`- keep gateway.bind=loopback and use an SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host)`,`- or use Tailscale Serve/Funnel for HTTPS remote access`,S?void 0:`Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1`,`Doctor: openclaw doctor --fix`,`Docs: https://docs.openclaw.ai/gateway/remote`].join(`
`));return{url:_,urlSource:y,bindDetail:b,remoteFallbackNote:x,message:[`Gateway target: ${v}`,`Source: ${y}`,`Config: ${r}`,b,x].filter(Boolean).join(`
`)}}
//!src/gateway/call-device-auth.ts
var GatewayCredentialsRequiredError=class extends Error{constructor(e){super([`gateway ${e.method} requires credentials before opening a websocket`,`Fix: configure gateway.auth token/password, pair this device, or pass --token/--password.`,`Config: ${e.configPath}`].join(`
`));this.name=`GatewayCredentialsRequiredError`;this.method=e.method;this.configPath=e.configPath}};var GatewayStoredDeviceAuthUnavailableError=class extends Error{constructor(e){super(e);this.name=`GatewayStoredDeviceAuthUnavailableError`}};var GatewayLocalBackendSharedAuthUnavailableError=class extends Error{constructor(e){super(e);this.name=`GatewayLocalBackendSharedAuthUnavailableError`}};async function resolveDeviceIdentityForGatewayCall(e){try{return e===`read-only`?await loadDeviceIdentityIfPresentAsync():await loadOrCreateDeviceIdentityAsync()}catch(e){throw new Error(`Cannot load device identity. Check access to your OpenClaw state directory and run "openclaw doctor --fix", then retry.`,{cause:e})}}async function resolveGatewayCallDeviceAuth(e){const{opts:t}=e;const n=isLoopbackGatewayUrl(e.url);const r={clientName:t.clientName,mode:t.mode,requireLocalBackendSharedAuth:t.requireLocalBackendSharedAuth};if(t.allowLocalBackendAuthNone&&e.authMode===`none`&&e.isImplicitLocalTarget&&n&&t.clientName===GATEWAY_CLIENT_NAMES.CLI&&t.mode===GATEWAY_CLIENT_MODES.CLI&&t.deviceIdentity===void 0&&!t.useStoredDeviceAuth&&!t.preparedDeviceAuth&&!t.approvalRuntimeToken&&!t.agentRuntimeIdentityToken){r.clientName=GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;r.mode=GATEWAY_CLIENT_MODES.BACKEND;r.requireLocalBackendSharedAuth=true}const i=r.mode??GATEWAY_CLIENT_MODES.CLI;const a=r.clientName??GATEWAY_CLIENT_NAMES.CLI;const o=r.requireLocalBackendSharedAuth===true&&e.authMode===`none`;const s=e.authMode===`token`&&Boolean(e.token)||e.authMode===`password`&&Boolean(e.password);const c=i===GATEWAY_CLIENT_MODES.BACKEND&&a===GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT&&(s||o)&&n;const l=i===GATEWAY_CLIENT_MODES.CLI&&a===GATEWAY_CLIENT_NAMES.CLI&&s&&n;const u=c||l;if(r.requireLocalBackendSharedAuth&&!u)throw new GatewayLocalBackendSharedAuthUnavailableError(`local backend shared auth requires a loopback gateway with token/password credentials or auth mode none`);if(t.deviceIdentity===void 0&&!u)await t.beforeDeviceIdentityLoad?.();return{clientOptions:r,omitDeviceIdentity:u,deviceIdentity:t.deviceIdentity===void 0?u?null:await resolveDeviceIdentityForGatewayCall(t.sharedStateMode):t.deviceIdentity}}async function loadStoredOperatorDeviceAuthToken(e,t,n,r=process.env){if(!e)return null;try{if(t)return await(n===`read-only`?loadOriginDeviceTokenReadOnly:loadOriginDeviceToken)({gatewayScope:t,deviceId:e.deviceId,role:`operator`,env:r});return await(n===`read-only`?loadDeviceAuthTokenReadOnly:loadDeviceAuthToken)({deviceId:e.deviceId,role:`operator`,env:r})}catch{return null}}function withEdgeAuthPairingHint(e,t,n,r){const i=`details`in e?e.details:void 0;if(t&&!n&&readMissingScopeErrorDetails(i)){const t=r?`openclaw tui --url ${projectGatewayUrlForDiagnostics(r)}`:`openclaw tui`;e.message=`${e.message}\nFix: this device is not paired with this Gateway yet. Run \`${t}\` once to pair this device, approve the request in that Gateway's Control UI (Settings -> Devices), then retry.`}return e}
//!src/gateway/call-required-features.ts
function ensureGatewaySupportsRequiredFeatures(e){const t=(e.required??[]).map(e=>e.trim()).filter(Boolean);if(t.length===0)return;const n=new Set((e.supported??[]).map(e=>e.trim()).filter(Boolean));for(const r of t)if(!n.has(r))throw new Error(`active gateway does not support required ${e.kind} "${r}" for "${e.attemptedMethod}". Update or restart the active gateway and try again.`)}
//!src/gateway/call-scopes.ts
function shouldEscalateSessionCreateCwdScope(e){if(e.opts.method!==`sessions.create`||!isRecord(e.opts.params)||!normalizeOptionalString(e.opts.params.cwd)||e.scopes.length!==1||e.scopes[0]!==`operator.write`)return false;const t=isRecord(e.error)?e.error:void 0;const n=readMissingScopeErrorDetails(t?.details);return n?.missingScope===`operator.admin`&&n.requiredScopes.includes(`operator.admin`)}async function fitScopesToGrant(e,t,n){const{fitOperatorScopesToGrant:r}=await import(`./method-scopes-AEq16uaH.mjs`);return r({method:e.method,requestParams:e.params,scopes:t,grantedScopes:n})}async function fitScopesToStoredDeviceGrant(e){const{opts:t,scopes:n}=e;if(!n||e.keepRequest)return n;const r=(await e.loadGrant())?.scopes;return r?.length?await fitScopesToGrant(t,n,r):n}async function resolveCliScopeRetry(e){const{opts:t}=e;if(shouldEscalateSessionCreateCwdScope(e))return{opts:t,scopes:[ADMIN_SCOPE]};const n=readPairingConnectErrorDetails(isRecord(e.error)?e.error.details:void 0);if(n?.reason!==`scope-upgrade`||!n.approvedScopes?.length)return;const r=n.approvedScopes.filter(isOperatorScope);return await fitScopesToGrant(t,e.scopes,r)===e.scopes?void 0:{opts:t,scopes:r}}
//!src/gateway/cli-read-policy.ts
const READ_ONLY_GATEWAY_CLI_METHODS={health:true,status:true,"system-presence":true,"system.info":true,"usage.cost":true,"diagnostics.stability":true,"diagnostics.capabilities":true,"diagnostics.lanes":true,"logs.tail":true,"config.get":true,"config.schema":true,"config.schema.lookup":true,"node.list":true,"node.describe":true,"node.pair.list":true,"device.pair.list":true,"last-heartbeat":true,"tts.status":true,"tts.providers":true,"tts.personas":true,"agents.list":true,"agents.files.list":true,"agents.files.get":true,"users.list":true,"toolUsage.status":true,"skills.library.list":true,"skills.library.read":true,"voicewake.get":true,"voicewake.routing.get":true,"exec.approvals.get":true,"exec.approvals.node.get":true,"exec.approval.get":true,"exec.approval.list":true,"exec.approval.grants.list":true,"plugin.approval.list":true,"openclaw.approval.list":true,"approval.get":true,"cron.status":true,"cron.list":true,"cron.get":true,"cron.runs":true,"cron.scratch.get":true};function isReadOnlyGatewayCliCall(e,t){if(e===`device.pair.code`)return isRecord(t)&&t.decision===void 0&&t.requestId===void 0;return Object.hasOwn(READ_ONLY_GATEWAY_CLI_METHODS,e)}
//!src/config/gateway-public-origin.ts
function resolveGatewayPublicOrigin(e){const t=e?.gateway?.publicOrigin?.trim();if(!t)return;try{const e=new URL(t);return e.pathname===`/`&&!e.search&&!e.hash?e.origin:void 0}catch{return}}
//!src/gateway/credential-planner.ts
const trimToUndefined=normalizeOptionalString;function trimCredentialToUndefined(e){const t=trimToUndefined(e);if(t&&containsEnvVarReference(t))return;return t}function createGatewayCredentialPlan(e){const t=e.env??process.env;const n=e.config.gateway;const r=n?.remote;const i=e.defaults??e.config.secrets?.defaults;const a=n?.auth?.mode;const o=trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);const s=trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);function resolveInput(t,n){const r=getConfigResolutionFacts(e.config);if(hasUnresolvedConfigPath(e.config,t)||getAuthoredConfigSecretRef(e.config,t))return{path:t,configured:true,refPath:t,hasSecretRef:false};if(r!==null&&typeof n===`string`)return{path:t,configured:Boolean(trimToUndefined(n)),value:trimToUndefined(n),hasSecretRef:false};const a=resolveSecretInputRef({value:n,defaults:i}).ref;return{path:t,configured:hasConfiguredSecretInput(n,i),value:a?void 0:trimToUndefined(n),refPath:a?t:void 0,hasSecretRef:a!==null}}const c=resolveInput(`gateway.auth.token`,n?.auth?.token);const l=resolveInput(`gateway.auth.password`,n?.auth?.password);const u=resolveInput(`gateway.remote.token`,r?.token);const d=resolveInput(`gateway.remote.password`,r?.password);const f=a!==`password`&&a!==`none`&&a!==`trusted-proxy`;const p=a===`password`||a===`trusted-proxy`||a!==`token`&&a!==`none`&&!(o||c.configured);const m=Boolean(o||c.configured||u.configured);const h=a===`password`||a===`trusted-proxy`||a!==`token`&&a!==`none`&&!m;const g=f&&(a===`token`||a===void 0&&!(s||l.configured));const _=n?.mode===`remote`;const v=Boolean(trimToUndefined(r?.url));const y=n?.tailscale?.mode===`serve`||n?.tailscale?.mode===`funnel`;const b=_||v||y;const x=f&&!o&&!c.configured;const S=a!==`trusted-proxy`&&!s&&!l.configured&&h;return{configuredMode:n?.mode===`remote`?`remote`:`local`,authMode:a,envToken:o,envPassword:s,localToken:c,localPassword:l,remoteToken:u,remotePassword:d,localTokenCanWin:f,localPasswordCanWin:p,localTokenSurfaceActive:g,tokenCanWin:m,passwordCanWin:h,remoteMode:_,remoteUrlConfigured:v,tailscaleRemoteExposure:y,remoteConfiguredSurface:b,remoteTokenFallbackActive:x,remoteTokenActive:b||x,remotePasswordFallbackActive:S,remotePasswordActive:b||S}}
//!src/gateway/credentials.ts
function resolveExplicitGatewayAuth(e){return{token:trimToUndefined(e?.token),password:trimToUndefined(e?.password)}}const GATEWAY_SECRET_REF_UNAVAILABLE_ERROR_CODE=`GATEWAY_SECRET_REF_UNAVAILABLE`;var GatewaySecretRefUnavailableError=class extends Error{constructor(e){super([`${e} is configured as a secret reference but is unavailable in this command path.`,`Fix: set OPENCLAW_GATEWAY_TOKEN/OPENCLAW_GATEWAY_PASSWORD, pass explicit --token/--password,`,`or run a gateway command path that resolves secret references before credential selection.`].join(`
`));this.code=GATEWAY_SECRET_REF_UNAVAILABLE_ERROR_CODE;this.name=`GatewaySecretRefUnavailableError`;this.path=e}};function resolveGatewayCredentialsFromValues(e){const t=e.env??process.env;const n=trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);const r=trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);const i=trimCredentialToUndefined(e.configToken);const a=trimCredentialToUndefined(e.configPassword);const o=e.tokenPrecedence??`env-first`;const s=e.passwordPrecedence??`env-first`;return{token:o===`config-first`?i||n:n||i,password:s===`config-first`?a||r:r||a}}function resolveLocalGatewayCredentials(e){const{plan:t,localPrecedence:n}=e;const resolveCredential=(e,t,r)=>{const i=e.configured?e.value:r;return n===`config-first`?e.value||t||(e.configured?void 0:r):t||i};const r=resolveCredential(t.localToken,t.envToken,t.remoteToken.value);const i=resolveCredential(t.localPassword,t.envPassword,t.authMode===`trusted-proxy`?void 0:t.remotePassword.value);const a={token:r,password:i};const o=e.plan.authMode===`password`||e.plan.authMode===`trusted-proxy`||e.plan.authMode!==`token`&&e.plan.authMode!==`none`&&!a.token;const s=e.plan.authMode===`token`||e.plan.authMode!==`password`&&e.plan.authMode!==`none`&&e.plan.authMode!==`trusted-proxy`&&!a.password;const c=[{credential:t.localToken,env:t.envToken,value:r,canWin:s},{credential:t.localPassword,env:t.envPassword,value:i,canWin:o}].filter(({credential:e,canWin:t})=>e.refPath&&t);const l=(n===`config-first`?c.find(({credential:e,env:t})=>!e.value&&Boolean(t)):void 0)??c.find(({value:e,env:t})=>!e&&!t);if(l?.credential.refPath)throw new GatewaySecretRefUnavailableError(l.credential.refPath);return a}function resolveGatewayCredentialsFromConfig(e){const t=e.env??process.env;const n=resolveExplicitGatewayAuth(e.explicitAuth);if(n.token||n.password)return n;if(trimToUndefined(e.urlOverride))return e.urlOverrideSource===`env`?resolveGatewayCredentialsFromValues({env:t}):{};const r=createGatewayCredentialPlan({config:e.cfg,env:t});if((e.modeOverride??r.configuredMode)===`local`)return resolveLocalGatewayCredentials({plan:r,localPrecedence:e.localPrecedence??`config-first`});const i=e.remoteTokenFallback??`remote-env-local`;const a=e.remotePasswordFallback??`remote-env-local`;const o=e.remoteTokenPrecedence??`remote-first`;const s=e.remotePasswordPrecedence??`env-first`;const resolveCredential=e=>{const t=r[`remote${e}`].value;if((e===`Token`?i:a)===`remote-only`)return t;const n=r[`env${e}`];const c=r[`local${e}`].value;return(e===`Token`?o:s)===`env-first`?n||t||c:t||n||c};const c=resolveCredential(`Token`);const l=resolveCredential(`Password`);const u=i!==`remote-only`;const d=i===`remote-only`?void 0:r.localToken.value;const f=a===`remote-only`?void 0:r.localPassword.value;if(r.remoteToken.refPath&&!c&&!r.envToken&&!d&&!l)throw new GatewaySecretRefUnavailableError(r.remoteToken.refPath);if(r.remotePassword.refPath&&!l&&!r.envPassword&&!f&&!c)throw new GatewaySecretRefUnavailableError(r.remotePassword.refPath);if(r.localToken.refPath&&u&&!c&&!l&&!r.envToken&&!r.remoteToken.value&&r.localTokenCanWin)throw new GatewaySecretRefUnavailableError(r.localToken.refPath);return{token:c,password:l}}
//!src/gateway/secret-input-paths.ts
const GATEWAY_AUTH_SURFACE_PATHS=[`gateway.auth.token`,`gateway.auth.password`,`gateway.remote.token`,`gateway.remote.password`];const ALL_GATEWAY_SECRET_INPUT_PATHS=[...GATEWAY_AUTH_SURFACE_PATHS];function isSupportedGatewaySecretInputPath(e){return ALL_GATEWAY_SECRET_INPUT_PATHS.includes(e)}function readGatewaySecretInputValue(e,t){if(t===`gateway.auth.token`)return e.gateway?.auth?.token;if(t===`gateway.auth.password`)return e.gateway?.auth?.password;if(t===`gateway.remote.token`)return e.gateway?.remote?.token;return e.gateway?.remote?.password}function assignResolvedGatewaySecretInput(e){const{config:t,path:n,value:r}=e;const i=n===`gateway.auth.token`||n===`gateway.auth.password`?t.gateway?.auth:t.gateway?.remote;if(i){i[isTokenGatewaySecretInputPath(n)?`token`:`password`]=r;copyConfigResolutionFactsExcept(t,t,[n])}}function isTokenGatewaySecretInputPath(e){return e===`gateway.auth.token`||e===`gateway.remote.token`}
//!src/gateway/auth-surface-resolution.ts
function createGatewayCredentialResolver(e){return async t=>{const n=await resolveCanonicalConfiguredSecretInputWithFallback({config:e.config,env:e.env,value:readGatewaySecretInputValue(e.config,t),path:t,unresolvedReasonStyle:`detailed`});if(n.unresolvedRefReason)e.diagnostics.push({message:n.unresolvedRefReason,code:n.unresolvedRefCode});return n}}function withDiagnostics(e,t){return e.length>0?{...t,diagnostics:e.map(({message:e})=>e),...e.some(({code:e})=>e===`SECRET_REF_REDACTED_VALUE`)?{warningCode:`SECRET_REF_REDACTED_VALUE`}:{}}:t}async function resolveGatewayProbeSurfaceAuth(e){const t=e.env??process.env;const n=[];const r=createGatewayCredentialResolver({config:e.config,env:t,diagnostics:n});const i=e.config.gateway?.auth?.mode;if(e.surface===`remote`){const e=await r(`gateway.remote.token`);const i=e.value?{value:void 0,secretRefConfigured:false}:await r(`gateway.remote.password`);const a=trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);const o=trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);const s=Boolean(e.value||i.value);const c=!s&&n.length===0;return withDiagnostics(n,{token:e.value??(c?a:void 0),password:i.value??(c?o:void 0),...s?{source:`config`}:c&&(a||o)&&{source:`env`}})}if(i===`none`||i===`trusted-proxy`)return{};const a=trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);const o=trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);if(i===`token`||i===`password`){const e=await r(`gateway.auth.${i}`);if(e.value)return withDiagnostics(n,{[i]:e.value,source:`config`});const t=i===`token`?a:o;return!e.secretRefConfigured&&t?{[i]:t,source:`env`}:withDiagnostics(n,{})}const s=await r(`gateway.auth.token`);if(s.value)return withDiagnostics(n,{token:s.value,source:`config`});if(s.secretRefConfigured)return withDiagnostics(n,{});const c=await r(`gateway.auth.password`);if(c.secretRefConfigured)return withDiagnostics(n,c.value?{password:c.value,source:`config`}:{});if(a)return{token:a,source:`env`};if(o)return withDiagnostics(n,{password:o,source:`env`});return withDiagnostics(n,{token:s.value,password:c.value,...c.value&&{source:`config`}})}async function resolveGatewayInteractiveSurfaceAuth(e){const t=e.env??process.env;const n=createGatewayCredentialResolver({config:e.config,env:t,diagnostics:[]});const r=trimToUndefined(e.explicitAuth?.token);const i=trimToUndefined(e.explicitAuth?.password);const a=createGatewayCredentialPlan({config:e.config,env:t});const o=e.config.gateway?.auth?.mode;const s=e.surface===`remote`?a.remoteToken.hasSecretRef||a.remotePassword.hasSecretRef:a.localTokenCanWin&&a.localToken.hasSecretRef||(o===`password`||o===void 0)&&a.localPassword.hasSecretRef;if((r||i)&&s)return{token:r,password:i};const c=e.suppressEnvAuthFallback?void 0:trimToUndefined(t.OPENCLAW_GATEWAY_TOKEN);const l=e.suppressEnvAuthFallback?void 0:trimToUndefined(t.OPENCLAW_GATEWAY_PASSWORD);if(e.surface===`remote`){const e=r?{value:r,secretRefConfigured:false}:await n(`gateway.remote.token`);if(e.value&&(e.secretRefConfigured||a.remotePassword.hasSecretRef))return{token:e.value,password:void 0};const t=i?{value:i,secretRefConfigured:false}:await n(`gateway.remote.password`);const o=e.secretRefConfigured||t.secretRefConfigured;const s=e.value??(o?void 0:c);const u=i??(o?t.value:l??t.value);return s||u?{token:s,password:u}:{failureReason:e.unresolvedRefReason??t.unresolvedRefReason??`Missing gateway auth credentials.`}}if(o===`none`||o===`trusted-proxy`)return{token:r??c,password:i??l};const u=o===`password`||o!==`token`&&(Boolean(i??l)&&!a.localToken.hasSecretRef||a.localPassword.configured&&!a.localToken.configured);const d=u?`password`:`token`;const f=u?i:r;const p=u?l:c;const m=f?{value:f,secretRefConfigured:false}:await n(`gateway.auth.${d}`);const h=m.value??(m.secretRefConfigured?void 0:p);return{token:u?m.secretRefConfigured?void 0:r??c:h,password:u?h:m.secretRefConfigured?void 0:i??l,failureReason:h?void 0:m.unresolvedRefReason??`Missing gateway auth ${d}.`}}
//!src/gateway/control-ui-shared.ts
function normalizeControlUiBasePath(e){const t=e?.trim()??``;if(!t||t===`/`)return``;const n=t.startsWith(`/`)?t:`/${t}`;return n.endsWith(`/`)?n.slice(0,-1):n}
//!src/secrets/resolve-secret-input-string.ts
async function materializeSecretInput(e){const t=e.normalize??normalizeSecretInputString;const n=parseSecretRef(e.value,e.config.secrets?.defaults);if(!n)return t(e.value);let r;try{const{resolveSecretRefString:t}=await import(`./resolve-7A0YrgZA.mjs`);r=await t(n,{config:e.config,env:e.env})}catch(t){if(e.onResolveRefError)return e.onResolveRefError(t,n);throw t}return t(r)}
//!src/gateway/credentials-secret-inputs.ts
async function resolveConfiguredGatewaySecretInput(e){const t=readGatewaySecretInputValue(e.config,e.path);const n=resolveConfigSecretRef({config:e.config,path:e.path,value:t,defaults:e.config.secrets?.defaults});const materialize=()=>materializeSecretInput({config:e.config,value:n??t,env:e.env,normalize:trimToUndefined,onResolveRefError:t=>{if(isSecretResolutionError(t)&&t.code===`SECRET_REF_REDACTED_VALUE`)throw t;throw new GatewaySecretRefUnavailableError(e.path)}});const r=n?.source===`store`&&!getDatabaseEngineSelection()&&resolveDatabaseFamilyEngines(e.config).state===`postgres`?await withDatabaseEngineSelection(await resolveConfiguredDatabaseEngineSelection(e),materialize):await materialize();if(!r)throw new Error(`${e.path} resolved to an empty or non-string value.`);return r}async function resolveConfiguredDatabaseEngineSelection(e){const{resolveDatabaseEngineSelection:t}=await import(`./config-COxQZ809.mjs`);try{return await t(e.config,e.env)}catch{throw new GatewaySecretRefUnavailableError(e.path)}}function hasConfiguredGatewaySecretRef(e,t){return Boolean(resolveConfigSecretRef({config:e,path:t,value:readGatewaySecretInputValue(e,t),defaults:e.secrets?.defaults}))}function localAuthModeAllowsGatewaySecretInputPath(e){const{authMode:t,path:n}=e;if(t===`none`)return false;if(t===`trusted-proxy`)return!isTokenGatewaySecretInputPath(n);if(t===`token`)return isTokenGatewaySecretInputPath(n);if(t===`password`)return!isTokenGatewaySecretInputPath(n);return true}function canGatewaySecretInputPathWin(e){if(!hasConfiguredGatewaySecretRef(e.config,e.path))return false;const t=e.options.modeOverride??(e.config.gateway?.mode===`remote`?`remote`:`local`);if(t===`local`&&!localAuthModeAllowsGatewaySecretInputPath({authMode:e.config.gateway?.auth?.mode,path:e.path}))return false;const n=`__OPENCLAW_GATEWAY_SECRET_REF_PROBE_${e.path.replaceAll(`.`,`_`)}__`;const r=cloneConfigWithResolutionFacts(e.config);for(const e of ALL_GATEWAY_SECRET_INPUT_PATHS){if(!hasConfiguredGatewaySecretRef(r,e))continue;assignResolvedGatewaySecretInput({config:r,path:e,value:void 0})}assignResolvedGatewaySecretInput({config:r,path:e.path,value:n});try{const i=resolveGatewayCredentialsFromConfig({...e.options,cfg:r,env:e.env});const a=e.config.gateway?.auth?.mode;const o=i.token===n&&(t===`local`&&a===`token`||!i.password);const s=i.password===n&&(t===`local`&&(a===`password`||a===`trusted-proxy`)||!i.token);return o||s}catch{return false}}async function resolveGatewayCredentialsWithSecretInputs(e){const t=resolveExplicitGatewayAuth(e.explicitAuth);if(t.token||t.password)return t;const n={...e,explicitAuth:t};const r=n.env??process.env;const i=n.config;let a=i;const resolvePath=async e=>{const t=await resolveConfiguredGatewaySecretInput({config:a,path:e,env:r});assignResolvedGatewaySecretInput({config:a,path:e,value:t})};for(const e of ALL_GATEWAY_SECRET_INPUT_PATHS){if(!canGatewaySecretInputPathWin({options:n,env:r,config:a,path:e}))continue;if(a===i)a=cloneConfigWithResolutionFacts(i);try{await resolvePath(e)}catch(e){if(isSecretResolutionError(e)&&e.code===`SECRET_REF_REDACTED_VALUE`)throw e}}const o=/* @__PURE__ */ new Set;for(;;)try{return resolveGatewayCredentialsFromConfig({...n,cfg:a,env:r})}catch(e){if(!(e instanceof GatewaySecretRefUnavailableError))throw e;const t=e.path;if(!isSupportedGatewaySecretInputPath(t)||o.has(t))throw e;if(a===i)a=cloneConfigWithResolutionFacts(i);await resolvePath(t);o.add(t)}}
//!src/shared/gateway-edge-auth-headers.ts
const HTTP_HEADER_NAME_PATTERN=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/u;const TRANSPORT_OWNED_HEADERS=/* @__PURE__ */ new Set([`host`,`connection`,`upgrade`,`content-length`,`sec-websocket-key`,`sec-websocket-version`,`sec-websocket-protocol`,`sec-websocket-extensions`]);function findEdgeAuthIssue(e){const t=Object.entries(e);if(t.length===0)return{message:`invalid gateway.remote.edgeAuth: header map must not be empty`};const n=/* @__PURE__ */ new Map;for(const[e]of t){if(!HTTP_HEADER_NAME_PATTERN.test(e))return{headerName:e,message:`invalid gateway.remote.edgeAuth header name: ${JSON.stringify(e)}`};const t=e.toLowerCase();if(TRANSPORT_OWNED_HEADERS.has(t))return{headerName:e,message:`gateway.remote.edgeAuth cannot set transport-owned header "${e}"`};const r=n.get(t);if(r)return{headerName:e,message:`gateway.remote.edgeAuth header names "${r}" and "${e}" differ only by case`};n.set(t,e)}return null}
//!src/gateway/edge-auth.ts
function normalizeEdgeAuthHeadersConfig(e){if(e===void 0||e===null)return;if(!isRecord(e))throw new Error(`invalid gateway.remote.edgeAuth: expected a header map`);const t=findEdgeAuthIssue(e);if(t)throw new Error(t.message);const n=Object.entries(e).map(([e,t])=>{return[e,normalizeRequiredSecretInput(t,`gateway.remote.edgeAuth header "${e}"`)]});return Object.fromEntries(n)}async function resolveEdgeAuthHeaders(e){if(!e.value)return;if(URL.parse(e.targetUrl)?.protocol!==`wss:`)throw new Error(`gateway.remote.edgeAuth requires a wss:// connection target`);const t=await Promise.all(Object.entries(e.value).map(async([t,n])=>{const r=await materializeSecretInput({config:e.config,value:n,env:e.env});if(!r)throw new Error(`gateway.remote.edgeAuth header "${t}" resolved empty`);registerSecretValueForRedaction(r);return[t,r]}));return Object.freeze(Object.fromEntries(t))}function gatewayEdgeAuthValueForTarget(e){const t=e.config.gateway?.remote;if(!t?.url||gatewayOriginScope(e.targetUrl)!==gatewayOriginScope(t.url))return;return t.edgeAuth}
//!packages/net-policy/src/url-protocol.ts
function parseUrl(e){return e instanceof URL?e:URL.parse(e)}function isHttpUrl(e){const t=parseUrl(e);return t?.protocol===`http:`||t?.protocol===`https:`}function isWebSocketUrl(e){const t=parseUrl(e);return t?.protocol===`ws:`||t?.protocol===`wss:`}function isWssUrl(e){return parseUrl(e)?.protocol===`wss:`}
//!src/gateway/tls-fingerprint.ts
async function resolveGatewayConnectionTlsFingerprint(e){const t=e.explicitTlsFingerprint?requireTlsFingerprint(e.explicitTlsFingerprint):void 0;if(t)return t;const n=e.config.gateway?.mode===`remote`&&(e.urlSource===`config gateway.remote.url`||e.urlSource===`env OPENCLAW_GATEWAY_URL`)?e.config.gateway.remote?.tlsFingerprint?requireTlsFingerprint(e.config.gateway.remote.tlsFingerprint):void 0:void 0;if(n)return n;if(!isWssUrl(e.url))return;if(!(e.urlSource===`local loopback`||e.urlSource===`missing gateway.remote.url (fallback local)`)||e.config.gateway?.tls?.enabled!==true)return;const{inspectGatewayTlsCertificate:r}=await import(`./gateway-ROSz_8kD.mjs`);const i=await r(e.config.gateway.tls);return i.ok?i.value.fingerprintSha256:void 0}
//!src/gateway/client-bootstrap.ts
var GatewayExplicitAuthRequiredError=class extends Error{constructor(e){super(e);this.name=`GatewayExplicitAuthRequiredError`}};async function ensureExplicitGatewayAuth(e){if(!e.urlOverride||!e.urlOverrideSource)return;if(e.explicitAuth?.token||e.explicitAuth?.password)return;if(e.urlOverrideSource===`env`&&(e.resolvedAuth?.token||e.resolvedAuth?.password))return;if(e.deviceAuthScope&&await e.allowStoredOriginAuth?.(e.deviceAuthScope)===true)return;const t=e.urlOverrideSource===`env`?`Set OPENCLAW_GATEWAY_TOKEN or OPENCLAW_GATEWAY_PASSWORD alongside OPENCLAW_GATEWAY_URL; config credentials are intentionally not reused.`:`For the default local or SSH-tunneled Gateway, remove --url to use the configured target.`;throw new GatewayExplicitAuthRequiredError([`gateway url override requires explicit credentials`,e.errorHint,t,e.configPath?`Config: ${e.configPath}`:void 0].filter(Boolean).join(`
`))}function resolveGatewayUrlOverride(e){const t=trimToUndefined(e.gatewayUrl);if(t)return{url:t,source:`cli`};if(e.ignoreEnvUrlOverride||e.localPortOverride!==void 0)return{};const n=trimToUndefined((e.env??process.env).OPENCLAW_GATEWAY_URL);return n?{url:n,source:`env`}:{}}async function resolveGatewayClientBootstrap(e){const t=e.env??process.env;const n=resolveExplicitGatewayAuth(e.explicitAuth);const r=resolveGatewayUrlOverride({gatewayUrl:e.gatewayUrl,env:t,ignoreEnvUrlOverride:e.ignoreEnvUrlOverride,localPortOverride:e.localPortOverride});const i=e.buildConnectionDetails??buildGatewayConnectionDetailsWithResolvers;const a=i({config:e.config,url:r.url,...e.configPath?{configPath:e.configPath}:{},...r.source?{urlSource:r.source}:{},ignoreEnvUrlOverride:true,...e.localPortOverride!==void 0?{localPortOverride:e.localPortOverride}:{},...e.serviceTargetUrl?{serviceTargetUrl:e.serviceTargetUrl}:{}});const o=a.urlSource===`cli --url`?`cli`:a.urlSource===`env OPENCLAW_GATEWAY_URL`?`env`:void 0;const s=r.source??o;let c;if(e.allowConfiguredAuthForExactTarget&&s===`cli`){if(e.config.gateway?.mode===`remote`){const t=trimToUndefined(e.config.gateway.remote?.url);if(t&&t===a.url)c={authSurface:`remote`,tlsSource:`config gateway.remote.url`}}else{const t={...e.config.gateway,mode:`local`};delete t.remote;const n=i({config:{...e.config,gateway:t},ignoreEnvUrlOverride:true,...e.localPortOverride!==void 0?{localPortOverride:e.localPortOverride}:{}}).url;const r=normalizeControlUiBasePath(e.config.gateway?.controlUi?.basePath??``);if(`${n}${r}`===a.url)c={authSurface:`local`,tlsSource:`local loopback`};else{const t=resolveGatewayPublicOrigin(e.config);if(t&&`${t.replace(/^https:/u,`wss:`).replace(/^http:/u,`ws:`)}${r}`===a.url)c={authSurface:`local`}}}}const l=c?.tlsSource??a.urlSource;const u=await resolveGatewayConnectionTlsFingerprint({config:e.config,url:a.url,urlSource:l,explicitTlsFingerprint:e.explicitTlsFingerprint});const d=c?.authSurface??e.modeOverride??(e.localPortOverride!==void 0?`local`:e.config.gateway?.mode===`remote`?`remote`:`local`);let f;if(e.skipImplicitAuth)f=n;else if(s&&!c)f=e.suppressEnvAuthFallback?n:await resolveGatewayCredentialsWithSecretInputs({config:e.config,explicitAuth:n,env:t,urlOverride:a.url,urlOverrideSource:s,modeOverride:e.modeOverride});else if(e.authPolicy===`probe`)f=await resolveGatewayProbeSurfaceAuth({config:e.config,env:t,surface:d});else if(e.authPolicy===`interactive`)f=await resolveGatewayInteractiveSurfaceAuth({config:e.config,env:t,explicitAuth:n,suppressEnvAuthFallback:e.suppressEnvAuthFallback,surface:d});else f=await resolveGatewayCredentialsWithSecretInputs({config:e.config,explicitAuth:n,env:t,urlOverride:s?a.url:void 0,urlOverrideSource:s,modeOverride:d});const{deviceAuthScope:p,sshTunnel:m}=resolveGatewayDeviceAuthRoute({config:e.config,url:a.url,remote:Boolean(s||a.urlSource===`config gateway.remote.url`),configuredRemote:!s&&a.urlSource===`config gateway.remote.url`||c?.authSurface===`remote`,tlsFingerprint:u});const h=gatewayEdgeAuthValueForTarget({config:e.config,targetUrl:a.url})!==void 0;if(e.overrideAuthErrorHint&&!c&&!h)await ensureExplicitGatewayAuth({urlOverride:s?a.url:void 0,urlOverrideSource:s,explicitAuth:n,resolvedAuth:f,deviceAuthScope:p,allowStoredOriginAuth:e.allowStoredOriginAuth,errorHint:e.overrideAuthErrorHint,configPath:e.configPath});return{url:a.url,urlSource:a.urlSource,connectionDetails:a,...s?{urlOverrideSource:s}:{},...p?{deviceAuthScope:p}:{},...m?{sshTunnel:m}:{},...f.failureReason?{authFailureReason:f.failureReason}:{},...u?{tlsFingerprint:u}:{},auth:{token:f.token,password:f.password}}}
//!packages/gateway-protocol/src/startup-unavailable.ts
const GATEWAY_STARTUP_UNAVAILABLE_REASON=`startup-sidecars`;const GATEWAY_STARTUP_RETRY_AFTER_MS=500;const GATEWAY_STARTUP_RETRY_MIN_MS=100;const GATEWAY_STARTUP_RETRY_MAX_MS=2e3;function isGatewayStartupUnavailableDetails(e){return typeof e===`object`&&e!==null&&e.reason===`startup-sidecars`}function isRetryableGatewayStartupUnavailableError(e){if(!e||typeof e!==`object`)return false;const t=e;return(t.gatewayCode??t.code)===`UNAVAILABLE`&&t.retryable===true&&isGatewayStartupUnavailableDetails(t.details)}function resolveGatewayStartupRetryAfterMs(e){if(!isRetryableGatewayStartupUnavailableError(e))return null;const t=e.retryAfterMs;return Math.min(Math.max(Math.floor(typeof t===`number`&&Number.isFinite(t)?t:500),GATEWAY_STARTUP_RETRY_MIN_MS),GATEWAY_STARTUP_RETRY_MAX_MS)}
//!packages/gateway-client/src/client-device-auth.ts
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}};
//!packages/gateway-client/src/client-host-deps.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]))}
//!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)})}
//!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}
//!packages/gateway-client/src/device-auth.ts
function normalizeDeviceMetadataForAuth(e){if(typeof e!==`string`)return``;return e.trim().replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function buildDeviceAuthPayloadV3(e){const t=e.scopes.join(`,`);const n=e.token??``;const r=normalizeDeviceMetadataForAuth(e.platform);const i=normalizeDeviceMetadataForAuth(e.deviceFamily);return[`v3`,e.deviceId,e.clientId,e.clientMode,e.role,t,String(e.signedAtMs),n,e.nonce,r,i].join(`|`)}
//!packages/gateway-client/src/model-catalog-connect.ts
const MODEL_CATALOG_SNAPSHOT=`model-catalog-snapshot`;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]}}
//!packages/gateway-client/src/node-protocol.ts
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}
//!packages/gateway-client/src/protocol-client-contract.ts
function describeGatewayClientClose(e,t,n=e.connectFailure?.error){return{phase:e.helloReceived?`post-hello`:`pre-hello`,socketOpened:e.socketOpened,transportValidated:t,connectRequestSent:e.connectRequestSent,transientPreHelloCleanClose:!e.helloReceived&&e.code===1e3&&e.reason===``,...n?{connectError:n}:{}}}
//!packages/gateway-protocol/src/payload-limits.ts
const MAX_PREAUTH_PAYLOAD_BYTES=65536;
//!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)}
//!packages/gateway-client/src/event-listeners.ts
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}};
//!packages/gateway-protocol/src/restart-unavailable.ts
const GATEWAY_RESTART_UNAVAILABLE_REASON=`gateway-restarting`;const GATEWAY_SUSPEND_UNAVAILABLE_REASON=`gateway-suspending`;const GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS=6e4;function isGatewayRestartUnavailableError(e){return hasUnavailableReason(e,GATEWAY_RESTART_UNAVAILABLE_REASON)}function isGatewaySuspendUnavailableError(e){return hasUnavailableReason(e,GATEWAY_SUSPEND_UNAVAILABLE_REASON)}function hasUnavailableReason(e,t){if(!e||typeof e!==`object`||!(`details`in e))return false;const n=e.details;return typeof n===`object`&&n!==null&&`reason`in n&&n.reason===t}
//!packages/gateway-client/src/protocol-request.ts
const gatewayResponseErrors=/* @__PURE__ */ new WeakSet;var GatewayPayloadLimitError=class extends Error{constructor(e,t){super(`Request exceeds the Gateway payload limit (${e} > ${t} bytes). Shorten the message or remove one or more attachments and retry.`);this.name=`GatewayPayloadLimitError`}};var GatewayProtocolRequestError=class extends Error{constructor(e){super(e.message??`request failed`);this.name=`GatewayProtocolRequestError`;this.code=e.code??`UNAVAILABLE`;this.gatewayCode=this.code;this.details=e.details;this.retryable=e.retryable===true;this.retryAfterMs=e.retryAfterMs}};function retainGatewayResponsePayload(e,t){gatewayResponseErrors.add(e);Object.defineProperty(e,"responsePayload",{value:t,enumerable:false,configurable:true})}var GatewayProtocolRequestTimeoutError=class extends Error{constructor(e,t=`gateway request timed out after ${e.timeoutMs}ms: ${e.method}`){super(t);this.code=`CLIENT_TIMEOUT`;this.name=`GatewayProtocolRequestTimeoutError`;this.method=e.method;this.timeoutMs=e.timeoutMs;this.requestSent=e.requestSent}};
//!packages/gateway-client/src/pending-request.ts
var GatewayPendingRequests=class{constructor(e){this.opts=e;this.maxPayloadBytes=MAX_PREAUTH_PAYLOAD_BYTES;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=0;let f=false;let p=false;const m={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:()=>{p=false;f=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===m){this.bootstrapPause.probe=void 0;this.drainBootstrapRequests()}};const retire=e=>{if(this.pending.get(a)!==m)return false;this.pending.delete(a);cleanup();this.finishTiming(a,m,false,e);return true};const onAbort=()=>{if(r?.retainSentResultOnAbort&&p)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}m.cleanup=cleanup;if(s!==void 0){l=setTimeout(()=>{if(!retire(`CLIENT_TIMEOUT`))return;c(this.opts.createRequestTimeoutError?.(t,s,f)??new GatewayProtocolRequestTimeoutError({method:t,timeoutMs:s,requestSent:f}))},s);l.unref?.()}r?.signal?.addEventListener(`abort`,onAbort,{once:true});this.pending.set(a,m);try{const o=JSON.stringify({type:`req`,id:a,method:t,params:n});const send=()=>{if(this.pending.get(a)!==m||r?.signal?.aborted||s!==void 0&&this.opts.nowMs()-m.startedAtMs>=s)return;const t=m.resend?this.bootstrapPause:void 0;if(t&&!t.announced&&!t.timer&&!t.probe)t.probe={pending:m,revision:t.revision};m.waitingForResume=Boolean(t&&(t.announced||t.probe?.pending!==m));if(m.waitingForResume)return;try{const t=this.maxPayloadBytes;const n=new TextEncoder().encode(o).byteLength;if(t!==void 0&&n>t)throw new GatewayPayloadLimitError(n,t);p=true;e.send(o);if(this.pending.get(a)!==m)return;f=p;this.invoke(`sent`,()=>r?.onSent?.(a))}catch(e){if(retire(`CLIENT_SEND_ERROR`))c(toStringifiedError(e))}};m.retryStartup=e=>{m.resend=send;clearTimeout(u);d=Math.max(resolveFiniteTimeoutDelayMs(e,GATEWAY_SUSPEND_IDENTITY_RETRY_AFTER_MS),Math.min(8e3,d*2));u=setTimeout(send,d);u.unref?.()};if(t===`agent.identity.get`||t===`sessions.subscribe`||t===`sessions.groups.list`||t===`question.list`||t===`sessions.list`)m.resend=send;if(i)m.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){this.maxPayloadBytes=MAX_PREAUTH_PAYLOAD_BYTES;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)}}};
//!packages/gateway-client/src/protocol-client.ts
const DEFAULT_CONNECT_FAILURE=Object.freeze({closeCode:1008,closeReason:`connect failed`});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}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=a.pendingError??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.maxPayloadBytes=i.policy?.maxPayload;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)}}};
//!packages/gateway-client/src/reconnect-policy.ts
const NON_RECOVERABLE_AUTH_ERRORS=/* @__PURE__ */ new Set([ConnectErrorDetailCodes.AUTH_TOKEN_MISSING,ConnectErrorDetailCodes.AUTH_TOKEN_NOT_CONFIGURED,ConnectErrorDetailCodes.AUTH_BOOTSTRAP_TOKEN_INVALID,ConnectErrorDetailCodes.AUTH_PASSWORD_MISSING,ConnectErrorDetailCodes.AUTH_PASSWORD_NOT_CONFIGURED,ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH,ConnectErrorDetailCodes.AUTH_RATE_LIMITED,ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH,ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH,ConnectErrorDetailCodes.AUTH_VERIFIED_USER_REQUIRED,ConnectErrorDetailCodes.CONTROL_UI_ORIGIN_NOT_ALLOWED,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;if(t===ConnectErrorDetailCodes.OPERATOR_ACCESS_DENIED)return!isGatewayOperatorAccessRetryable(e.details);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}
//!packages/gateway-client/src/request-error.ts
var GatewayClientRequestError=class extends GatewayProtocolRequestError{constructor(e){super({...e,message:formatConnectErrorMessage({message:e.message,details:e.details})});this.name=`GatewayClientRequestError`}};var GatewayClientRequestTimeoutError=class extends GatewayProtocolRequestTimeoutError{constructor(e){super(e,`gateway request timeout for ${e.method}`);this.name=`GatewayClientRequestTimeoutError`}};const GATEWAY_CONNECT_ASSEMBLY_ERROR=Symbol(`gateway.connectAssemblyError`);function markGatewayConnectAssemblyError(e){Object.defineProperty(e,GATEWAY_CONNECT_ASSEMBLY_ERROR,{configurable:true,value:true});return e}function isGatewayConnectAssemblyError(e){return e instanceof Error&&e[GATEWAY_CONNECT_ASSEMBLY_ERROR]===true}
//!packages/gateway-client/src/websocket-data.ts
function rawDataToString(e,t=`utf8`){if(Array.isArray(e))return Buffer$1.concat(e).toString(t);return e instanceof ArrayBuffer?Buffer$1.from(e).toString(t):e.toString(t)}
//!packages/gateway-client/src/unix-target.ts
function parseUnixGatewayUrl(e){if(!e.startsWith(`ws+unix:`))return;const t=e.indexOf(`:`,8);const n=e.slice(8,t);const r=e.slice(t+1);if(t<0||!path.isAbsolute(n)||!r.startsWith(`/`)||/[\r\n\0?#]/u.test(n))throw new Error(`invalid Unix Gateway URL`);return{socketPath:n,path:r}}
//!packages/gateway-client/src/websocket-transport.ts
const PRIVATE_OR_LOOPBACK_IPV4_RANGES=/* @__PURE__ */ new Set([`loopback`,`private`,`linkLocal`,`carrierGradeNat`]);const PRIVATE_OR_LOOPBACK_IPV6_RANGES=/* @__PURE__ */ new Set([`loopback`,`linkLocal`,`uniqueLocal`,`deprecatedSiteLocal`]);function isPrivateOrLoopbackIpAddress(e){return(e.kind()===`ipv4`?PRIVATE_OR_LOOPBACK_IPV4_RANGES:PRIVATE_OR_LOOPBACK_IPV6_RANGES).has(e.range())}function isGatewayLoopbackHost(e){const t=parseHostForAddressChecks(e);return Boolean(t&&(t.isLocalhost||isLoopbackIpAddress(t.unbracketedHost)))}function isPrivateOrLoopbackHost(e){const t=parseHostForAddressChecks(e);if(!t)return false;if(t.isLocalhost)return true;const n=parseGatewayIpAddress(t.unbracketedHost);return Boolean(n&&isPrivateOrLoopbackIpAddress(n))}function isTrustedPlaintextWebSocketHost(e){if(isPrivateOrLoopbackHost(e))return true;const t=e.toLowerCase().trim().replace(/\.+$/,``);return t.endsWith(`.local`)||t.endsWith(`.ts.net`)}function isSecureWebSocketUrl(e,t){const n=URL.parse(e);if(!n)return false;const r=n.protocol===`https:`?`wss:`:n.protocol===`http:`?`ws:`:n.protocol;if(r===`wss:`)return true;if(r!==`ws:`)return false;if(isTrustedPlaintextWebSocketHost(n.hostname))return true;if(t?.allowPrivateWs===true){const e=n.hostname.startsWith(`[`)&&n.hostname.endsWith(`]`)?n.hostname.slice(1,-1):n.hostname;return parseGatewayIpAddress(e)===void 0}return false}var GatewayWebSocketTransportConfigurationError=class extends Error{};var GatewayWebSocketTlsPinError=class extends Error{};function resolveGatewayWebSocketTransport(e){if(parseUnixGatewayUrl(e.url)){if(e.tlsFingerprint||e.tlsServerName)throw new GatewayWebSocketTransportConfigurationError(`Unix Gateway transport does not use TLS options`);return{options:{...e.options,followRedirects:false}}}const t=isWssUrl(e.url);if(e.tlsFingerprint&&!t)throw new GatewayWebSocketTransportConfigurationError(`gateway tls fingerprint requires wss:// gateway url`);const n=(e.env??process.env).OPENCLAW_ALLOW_INSECURE_PRIVATE_WS===`1`;if(!isSecureWebSocketUrl(e.url,{allowPrivateWs:n})){const t=URL.parse(e.url)?.hostname||e.url;throw new GatewayWebSocketTransportConfigurationError(`SECURITY ERROR: Cannot connect to "${t}" over plaintext ws://. Both credentials and chat data would be exposed to network interception. Use wss:// for remote URLs. Safe defaults: keep gateway.bind=loopback and connect via SSH tunnel (ssh -N -L 18789:127.0.0.1:18789 user@gateway-host), or use Tailscale Serve/Funnel. `+(n?``:`Break-glass (trusted private networks only): set OPENCLAW_ALLOW_INSECURE_PRIVATE_WS=1. `)+"Run `openclaw doctor --fix` for guidance.")}const r=e.normalizeTlsFingerprint??normalizeTlsFingerprint;const i=e.tlsFingerprint?normalizeTlsFingerprint(e.tlsFingerprint):void 0;if(e.tlsFingerprint&&!i)throw new GatewayWebSocketTransportConfigurationError(`gateway tls fingerprint must be a SHA-256 fingerprint`);const a={...e.options};if(t&&e.tlsServerName){const t=e.tlsServerName;a.servername=isIP(t)?``:t;a.checkServerIdentity=(e,n)=>checkServerIdentity(t,n)}if(t&&i)applyGatewayWebSocketTlsPin(a,i,r);return{options:a}}function applyGatewayWebSocketTlsPin(e,t,n=normalizeTlsFingerprint){e.rejectUnauthorized=false;const r={...e.headers};const i=Object.entries(r).filter(([e])=>e.toLowerCase()===`expect`);for(const[e]of i)delete r[e];e.headers=r;e.finishRequest=e=>{e.once(`socket`,r=>{if(!(r instanceof TLSSocket)){e.destroy(new GatewayWebSocketTlsPinError(`gateway tls fingerprint unavailable`));return}const validatePin=()=>{if(e.destroyed)return;const a=normalizeTlsFingerprint(r.getPeerCertificate()?.fingerprint256);const o=a?n(a):``;if(!o||o!==n(t)){e.destroy(new GatewayWebSocketTlsPinError(o?`gateway tls fingerprint mismatch`:`gateway tls fingerprint unavailable`));return}for(const[t,n]of i)if(n!==void 0)e.setHeader(t,n);e.end()};if(r.secureConnecting){r.once(`secureConnect`,validatePin);e.once(`close`,()=>r.off(`secureConnect`,validatePin))}else validatePin()})}}
//!packages/gateway-client/src/websocket.ts
const require=createRequire(import.meta.url);const wsPackageRoot=path.dirname(require.resolve(`ws/package.json`));const WebSocket=require(path.join(wsPackageRoot,`lib/websocket.js`));const WebSocketServer=require(path.join(wsPackageRoot,`lib/websocket-server.js`));const createWebSocketStream=require(path.join(wsPackageRoot,`lib/stream.js`));
//!packages/gateway-client/src/client.ts
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.approvedGrantRetryPending=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){const n=t.pendingError instanceof GatewayClientRequestError?t.pendingError:void 0;this.opts.onClose?.(e.code,e.reason,describeGatewayClientClose(e,this.transportValidated,n))}},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})}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`))}resolveApprovedGrantScopes(e){const t=this.opts.fitScopesToApprovedGrant&&e instanceof GatewayClientRequestError?readPairingConnectErrorDetails(e.details):null;if(t?.reason!==`scope-upgrade`||!t.approvedScopes?.length)return;const n=this.opts.fitScopesToApprovedGrant?.(t.approvedScopes);const r=new Set(this.opts.scopes??[]);return n&&(n.length!==r.size||n.some(e=>!r.has(e)))?n:void 0}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=this.resolveApprovedGrantScopes(e);if(n){this.opts={...this.opts,scopes:n};this.approvedGrantRetryPending=true;this.protocol.resetReconnectBackoff(250);this.logDebug(`gateway refused a scope upgrade; retrying within the approved grant`);return{closeCode:1008,closeReason:`connect retry`}}const r=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 i=resolveGatewayStartupRetryAfterMs(e);if(i!==null){this.logDebug(`gateway connect failed: ${formatGatewayClientErrorForLog(e)}`);return{closeCode:1013,closeReason:`gateway starting`,reconnectDelayMs:i}}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 a=`gateway connect failed: ${formatGatewayClientErrorForLog(e)}`;if(this.opts.mode===GATEWAY_CLIENT_MODES.PROBE||isGatewayClientStoppedError(e)||r===ConnectErrorDetailCodes.AUTH_RATE_LIMITED)this.logDebug(a);else this.logError(a);return{closeCode:1008,closeReason:`connect failed`}}resolveClose(e){const t=readGatewayOperatorAccessClose(e.code,e.reason);const n=t?new GatewayClientRequestError(t):e.connectFailure?.error;const r=n instanceof GatewayClientRequestError?n.details:void 0;const i=readConnectErrorDetailCode(r);const a=describeGatewayClientClose(e,this.transportValidated,n);if(this.approvedGrantRetryPending){this.approvedGrantRetryPending=false;return{retry:true,notify:false}}if(e.code===1013&&e.connectFailure?.reconnectDelayMs!==void 0)return{retry:true,notify:this.opts.notifyOnStartupRetry===true,reconnectDelayMs:e.connectFailure.reconnectDelayMs};if(a.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(a.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:i});return{retry:false,notify:true,pendingError:n}}return{retry:true,notify:true,reconnectDelayMs:e.connectFailure?.reconnectDelayMs,pendingError:n}}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})}};
//!src/infra/net/proxyline-runtime.ts
function loadProxyline(){return createRequire(import.meta.url)(`@openclaw/proxyline`)}
//!src/infra/net/undici-global-dispatcher.ts
const HTTP1_ONLY_DISPATCHER_OPTIONS=Object.freeze({allowH2:false});let lastAppliedTimeoutKey=null;let lastAppliedProxyBootstrapKey=null;const timedProxylineManagedDispatchers=/* @__PURE__ */ new WeakMap;function isTimedProxylineManagedDispatcher(e){return typeof e===`object`&&e!==null?timedProxylineManagedDispatchers.has(e):false}function resolveDispatcherKind(e){const t=e?.constructor?.name;if(typeof t!==`string`||t.length===0)return`unsupported`;if(t.includes(`EnvHttpProxyAgent`))return`env-proxy`;if(isTimedProxylineManagedDispatcher(e)||isProxylineDispatcher(e))return`proxyline-managed`;if(t.includes(`ProxyAgent`))return`unsupported`;if(t.includes(`Agent`))return`agent`;return`unsupported`}function resolveEnvProxyBootstrapKey(e){const t=[.../* @__PURE__ */ new Set([e.httpProxy,e.httpsProxy])].map(e=>e?resolveActiveManagedProxyTlsOptions({proxyUrl:e}):void 0);return JSON.stringify([e.httpProxy,e.httpsProxy,t])}function resolveCurrentDispatcherInfo(e){let t;try{t=e.getGlobalDispatcher()}catch{return null}const n=resolveDispatcherKind(t);if(n===`unsupported`)return null;return{kind:n,dispatcher:t}}function forceResetGlobalDispatcher(e){lastAppliedTimeoutKey=null;const t=resolveEnvHttpProxyAgentOptions();if(!t){if(lastAppliedProxyBootstrapKey===null)return;lastAppliedProxyBootstrapKey=null;try{const{setGlobalDispatcher:e}=loadUndiciGlobalDispatcherDeps();e(createHttp1Agent())}catch{}return}try{const n=loadUndiciGlobalDispatcherDeps();const{setGlobalDispatcher:r}=n;if(e?.preserveProxylineManaged){if(resolveCurrentDispatcherInfo(n)?.kind===`proxyline-managed`){lastAppliedProxyBootstrapKey=resolveEnvProxyBootstrapKey(t);return}}r(createHttp1EnvHttpProxyAgent(t));lastAppliedProxyBootstrapKey=resolveEnvProxyBootstrapKey(t)}catch{}}
//!src/infra/net/proxy/proxy-lifecycle.ts
const PROXY_ENV_KEYS=[`http_proxy`,`https_proxy`,`HTTP_PROXY`,`HTTPS_PROXY`];const NO_PROXY_ENV_KEYS=[`no_proxy`,`NO_PROXY`];const LOOPBACK_NO_PROXY=`127.0.0.1,localhost,localhost.,::1,[::1],127.0.0.0/8`;const managedLoopbackBypassPolicy=({url:e})=>getActiveManagedProxyLoopbackMode()===`gateway-only`&&isLoopbackProxyUrl(e);const PROXY_ACTIVE_KEYS=[`OPENCLAW_PROXY_ACTIVE`,`OPENCLAW_PROXY_LOOPBACK_MODE`,`OPENCLAW_PROXY_CA_FILE`];const ALL_PROXY_ENV_KEYS=[...PROXY_ENV_KEYS,...NO_PROXY_ENV_KEYS,...PROXY_ACTIVE_KEYS];let proxylineHandle=null;const MANAGED_PROXY_UNDICI_OPTIONS=Object.freeze({allowH2:false});function applyProxyEnv(e,t,n){for(const t of PROXY_ENV_KEYS)process.env[t]=e;process.env[`OPENCLAW_PROXY_ACTIVE`]=`1`;process.env[`OPENCLAW_PROXY_LOOPBACK_MODE`]=t;if(n)process.env[`OPENCLAW_PROXY_CA_FILE`]=n;else delete process.env[`OPENCLAW_PROXY_CA_FILE`];for(const e of NO_PROXY_ENV_KEYS)process.env[e]=t===`gateway-only`?LOOPBACK_NO_PROXY:``}function ensureInheritedManagedProxyRoutingActive(){if(process.env[`OPENCLAW_PROXY_ACTIVE`]!==`1`)return;const e=process.env[`HTTP_PROXY`];if(!e||!isHttpUrl(e))return;const t=resolveManagedProxyCaFileForUrl({proxyUrl:e,caFileOverride:process.env[`OPENCLAW_PROXY_CA_FILE`]});const n=loadManagedProxyTlsOptionsSync(t);applyProxyEnv(e,getActiveManagedProxyLoopbackMode()??`gateway-only`,t);proxylineHandle=loadProxyline().installGlobalProxy({mode:`managed`,proxyUrl:e,...n?{proxyTls:n}:{},ifActive:`reuse-compatible`,bypassPolicy:managedLoopbackBypassPolicy,undici:MANAGED_PROXY_UNDICI_OPTIONS});forceResetGlobalDispatcher({preserveProxylineManaged:true})}function isLoopbackProxyUrl(e){const t=URL.parse(e);if(!t)return false;const n=t.hostname.toLowerCase().replace(/\.+$/,``);return(isHttpUrl(t)||isWebSocketUrl(t))&&(n===`localhost`||isLoopbackIpAddress(n))}function assertManagedProxyAllowsLoopback(e,t){if(isLoopbackProxyUrl(e)&&getActiveManagedProxyLoopbackMode()===`block`)throw new Error(`proxy: ${t} connections are blocked by proxy.loopbackMode; run openclaw config set proxy.loopbackMode gateway-only to allow local runtime traffic.`)}function registerManagedProxyGatewayLoopbackBypass(e){assertManagedProxyAllowsLoopback(e,`Gateway loopback control-plane`)}
//!src/shared/gateway-client-platform.ts
function resolveGatewayClientPlatformIdentity(e){switch(e){case`darwin`:return{platform:`macos`,deviceFamily:`Mac`};case`win32`:return{platform:`windows`,deviceFamily:`Windows`};case`linux`:return{platform:e,deviceFamily:`Linux`};default:return{platform:e}}}
//!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-BMFKybbO.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`))}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}}};
//!src/gateway/auth-resolve.ts
function mergeGatewayAuthConfig(e,t){const n={...e};if(!t)return n;for(const e of[`mode`,`token`,`password`,`allowTailscale`,`rateLimit`,`trustedProxy`])if(t[e]!==void 0)Object.assign(n,{[e]:t[e]});return n}function resolveGatewayAuthFromCredentials(e){const{authConfig:t,authOverride:n,token:r,password:i}=e;const a=n?.mode??t.mode??(i?`password`:`token`);return{mode:a,modeSource:n?.mode!==void 0?`override`:t.mode?`config`:i?`password`:r?`token`:`default`,token:r,password:i,allowTailscale:t.allowTailscale??(e.tailscaleMode===`serve`&&a!==`password`&&a!==`trusted-proxy`),trustedProxy:t.trustedProxy}}function resolveGatewayAuthForConfig(e){const t=e.authOverride??void 0;const n=mergeGatewayAuthConfig(e.config.gateway?.auth,t);const r={...e.config,gateway:{...e.config.gateway,auth:n}};const i=[...t?.token!==void 0?[`gateway.auth.token`]:[],...t?.password!==void 0?[`gateway.auth.password`]:[]];copyConfigResolutionFactsExcept(e.config,r,i);const a=createGatewayCredentialPlan({config:r,env:e.env});return resolveGatewayAuthFromCredentials({authConfig:n,authOverride:t,token:a.localToken.hasSecretRef?void 0:a.localToken.value??a.envToken??a.remoteToken.value,password:a.localPassword.hasSecretRef?void 0:a.localPassword.value??a.envPassword??(a.authMode===`trusted-proxy`?void 0:a.remotePassword.value),tailscaleMode:e.tailscaleMode})}
//!src/gateway/explicit-connection-policy.ts
function hasExplicitGatewayConnectionAuth(e){return Boolean(trimToUndefined(e?.token)||trimToUndefined(e?.password))}function targetMayRequireConfiguredEdgeAuth(e){const t=URL.parse(e)?.protocol;return t===`wss:`||t===`https:`}function isExplicitGatewayConnection(e){return!e.config&&Boolean(trimToUndefined(e.urlOverride))&&hasExplicitGatewayConnectionAuth(e.explicitAuth)}function canSkipGatewayConfigLoad(e){const t=trimToUndefined(e.urlOverride);if(!t||e.config||!hasExplicitGatewayConnectionAuth(e.explicitAuth))return false;return!targetMayRequireConfiguredEdgeAuth(t)}function resolveGatewayConnectionAuth(e){return e.configSkipped?resolveGatewayAuthFromCredentials({authConfig:{},...e.auth}):resolveGatewayAuthForConfig({config:e.config,tailscaleMode:e.config.gateway?.tailscale?.mode})}
//!src/gateway/operator-cli-message-input.ts
function assertGatewayCliMessageContext(e,t){const n=process.env.OPENCLAW_SHELL===`exec`;const r=process.env[SUBAGENT_EXEC_ENV_VAR]===`1`;if(!n&&!r)return;const i=[`sessions.send`,`sessions.steer`,`chat.send`].includes(e);if(r&&i)throw new Error(`Subagent session messages must use the task completion path. Return your result or blocker in the child turn; do not use the CLI to contact other sessions.`);if(!n)return;const a=e===`sessions.create`?asNullableRecord(t):null;if(a&&([a.message,a.task].some(e=>typeof e===`string`&&e.trim())||Array.isArray(a.attachments)&&a.attachments.length>0)||i||e===`agent`)throw new Error(`Gateway ${e} from agent exec would lose inter-session attribution. Use the attributed session-messaging tool available to this run, or return the result through normal subagent completion. Do not retry through another CLI route or remove the exec marker.`)}
//!src/gateway/transport-error.ts
var GatewayTransportError=class extends Error{constructor(e){super(e.message);this.name=`GatewayTransportError`;this.kind=e.kind;this.connectionDetails=e.connectionDetails;if(e.code!==void 0)this.code=e.code;if(e.reason!==void 0)this.reason=e.reason;if(e.timeoutMs!==void 0)this.timeoutMs=e.timeoutMs;if(e.requestDispatched!==void 0)this.requestDispatched=e.requestDispatched}};const DISPATCHED_REQUEST_OUTCOME_GUIDANCE=`The request was already sent to the gateway, so the operation may have been applied even though no response arrived; its outcome is unknown. Verify the current state (for example, re-run the equivalent read-only command) before retrying, especially for write actions.`;function createGatewayCloseTransportError(e){const{code:t,connectionDetails:n,requestDispatched:r}=e;const i=normalizeOptionalString(e.reason)||`no close reason`;const a=t===1006?`abnormal closure (no close frame)`:t===1e3?`normal closure`:``;let o=`gateway closed (${t}${a?` ${a}`:``}): ${i}\n${n.message}`;if(t===1006)o+=`\n\nPossible causes:\n${r?`- Connection dropped without a close frame (check network and gateway load)`:`- Connection dropped without a close frame (retry; check network and gateway load)
- Gateway not yet ready to accept connections (retry after a moment)
- TLS mismatch (connecting with ws:// to a wss:// gateway, or vice versa)`}
- Gateway process stopped or became unreachable (confirm it is still running)
Run \`openclaw doctor\` for diagnostics.`;return new GatewayTransportError({kind:`closed`,code:t,reason:i,connectionDetails:n,requestDispatched:r,message:r?`${o}\n\n${DISPATCHED_REQUEST_OUTCOME_GUIDANCE}`:o})}function createGatewayTimeoutTransportError(e){const{timeoutMs:t,connectionDetails:n,requestDispatched:r}=e;const i=`gateway timeout after ${t}ms\n${n.message}`;return new GatewayTransportError({kind:`timeout`,timeoutMs:t,connectionDetails:n,requestDispatched:r,message:r?`${i}\n\n${DISPATCHED_REQUEST_OUTCOME_GUIDANCE}`:i})}function firstGatewayErrorLine(e){return e.split(`
`,1)[0]?.trim()||e}const GATEWAY_UNREACHABLE_SOCKET_CODES=/* @__PURE__ */ new Set([`ECONNREFUSED`,`ECONNRESET`,`EHOSTUNREACH`,`ENETUNREACH`,`ENOTFOUND`,`ETIMEDOUT`]);function isGatewayUnreachableSocketError(e){const t=extractErrorCodeOrErrno(e);return t!==void 0&&GATEWAY_UNREACHABLE_SOCKET_CODES.has(t)}function createGatewayUnreachableTransportError(e){const t=extractErrorCodeOrErrno(e.cause);return new GatewayTransportError({kind:`closed`,reason:firstGatewayErrorLine(e.cause.message),connectionDetails:e.connectionDetails,message:[`Gateway not reachable at ${projectGatewayUrlForDiagnostics(e.connectionDetails.url)}${t?` (${t})`:``}.`,"Start it with `openclaw gateway run` or check `openclaw gateway status`.",e.connectionDetails.message].join(`
`)})}
//!src/gateway/call.ts
async function loadGatewayConfig(){return getRuntimeConfigSnapshot()??await readGatewayDispatchConfigWithShellEnvFallback()}async function stopGatewayClient(e){try{await e.stopAndWait({timeoutMs:1e3})}catch{e.stop()}}function resolveGatewayClientDisplayName(e){if(e.clientDisplayName)return e.clientDisplayName;const t=e.clientName??GATEWAY_CLIENT_NAMES.CLI;if((e.mode??GATEWAY_CLIENT_MODES.CLI)!==GATEWAY_CLIENT_MODES.BACKEND&&t!==GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT)return;const n=e.method.trim();return n?`gateway:${n}`:`gateway:request`}async function loadGatewayConfigForExplicitConnection(){try{return await loadGatewayConfig()}catch{return{}}}function resolveGatewayConfigPath(e){return resolveConfigPath(e,resolveStateDir(e))}function buildGatewayConnectionDetails(e={}){return buildGatewayConnectionDetailsWithResolvers(e,{getRuntimeConfig:readGatewayDispatchConfig,resolveConfigPath:resolveGatewayConfigPath,resolveGatewayPort})}function resolveGatewayCallTimeout(e){const t=Boolean(process.env.OPENCLAW_HANDSHAKE_TIMEOUT_MS)||Boolean(isVitestRuntimeEnv()&&process.env.OPENCLAW_TEST_HANDSHAKE_TIMEOUT_MS)?resolvePreauthHandshakeTimeoutMs():void 0;const n=typeof t===`number`&&t>1e4?t:1e4;const r=typeof e===`number`&&Number.isFinite(e)?e:void 0;const i=r??n;const a=e===null?null:r??n;return{timeoutMs:a,startupTimeoutMs:i,safeTimerTimeoutMs:resolveSafeTimeoutDelayMs(a??i)}}async function resolveGatewayCallContext(e){const t=resolveExplicitGatewayAuth({token:e.token,password:e.password});const n=resolveGatewayUrlOverride({gatewayUrl:e.url,env:process.env,ignoreEnvUrlOverride:e.ignoreEnvUrlOverride,localPortOverride:e.localPortOverride}).url;const r={config:e.config,urlOverride:n,explicitAuth:t};const i=canSkipGatewayConfigLoad(r);const a=isExplicitGatewayConnection(r);const o=e.config??(i?{}:a?await loadGatewayConfigForExplicitConnection():await loadGatewayConfig());return{config:o,configSkipped:i,configPath:e.configPath??resolveGatewayConfigPath(process.env),isRemoteMode:e.localPortOverride===void 0&&o.gateway?.mode===`remote`,explicitAuth:t}}function gatewayCallBootstrapOptions(e,t){return{config:t.config,gatewayUrl:e.url,explicitAuth:t.explicitAuth,env:process.env,configPath:t.configPath,ignoreEnvUrlOverride:e.localPortOverride!==void 0||e.ignoreEnvUrlOverride===true||e.serviceTargetUrl!==void 0,localPortOverride:e.localPortOverride,explicitTlsFingerprint:e.tlsFingerprint,buildConnectionDetails:buildGatewayConnectionDetails,...e.serviceTargetUrl?{serviceTargetUrl:e.serviceTargetUrl}:{}}}function ensureRemoteModeUrlConfigured(e){if(!e.context.isRemoteMode||e.urlOverrideSource||trimToUndefined(e.context.config.gateway?.remote?.url))return;throw new Error([`gateway remote mode misconfigured: gateway.remote.url missing`,`Config: ${e.context.configPath}`,`Fix: set gateway.remote.url, or set gateway.mode=local.`].join(`
`))}function createGatewayRequestAbortError(e){return createAbortError(`gateway request aborted for ${e}`)}function isRequiredAgentRuntimeIdentityConnectError(e){return e.message.includes(`gateway rejected required agent runtime identity auth field; refusing to retry without it`)}function isAllowlistedGatewayConnectRequestError(e){if(e.name!==`GatewayClientRequestError`)return false;return readConnectErrorDetailCode(e.details)===ConnectErrorDetailCodes.AUTH_RATE_LIMITED}async function callGatewayWithScopes(e,t,{localCliAbort:n=false,explicitScopes:r=false}={}){const i=await resolveGatewayCallContext(e);const{timeoutMs:a,startupTimeoutMs:o,safeTimerTimeoutMs:s}=resolveGatewayCallTimeout(e.timeoutMs);const c=resolveGatewayUrlOverride({gatewayUrl:e.url,env:process.env,ignoreEnvUrlOverride:e.ignoreEnvUrlOverride,localPortOverride:e.localPortOverride}).source;if(e.requireLocalBackendSharedAuth&&(c||i.isRemoteMode))throw new GatewayLocalBackendSharedAuthUnavailableError(`local backend shared auth is limited to the configured local gateway`);const l=e.useStoredDeviceAuth===true;const u=Boolean(i.explicitAuth.token||i.explicitAuth.password);const d=l&&!u;const f=await resolveGatewayClientBootstrap({...gatewayCallBootstrapOptions(e,i),skipImplicitAuth:d||e.skipImplicitAuth===true,...d?{}:{overrideAuthErrorHint:`Fix: pass --token or --password with --url (or gatewayToken in tools).`}});ensureRemoteModeUrlConfigured({context:i,urlOverrideSource:f.urlOverrideSource});const p=f.connectionDetails;const m=f.url;if(e.expectUrl!==void 0&&m!==e.expectUrl)throw new Error(`Gateway destination changed. Refresh the selected Gateway before retrying.`);const h=f.deviceAuthScope;const g=d?void 0:f.auth.token;const _=d?void 0:f.auth.password;const v=resolveGatewayConnectionAuth({config:i.config,configSkipped:i.configSkipped,auth:{token:g,password:_}});const{clientOptions:y,omitDeviceIdentity:b,deviceIdentity:x}=await resolveGatewayCallDeviceAuth({opts:e,url:m,authMode:v.mode,isImplicitLocalTarget:!c&&!i.isRemoteMode,token:g,password:_});const S={...e,...y};let C=S.preparedDeviceAuth;if(d){C??=await loadStoredOperatorDeviceAuthToken(x,h,S.sharedStateMode);if(!C?.token&&h)throw new GatewayStoredDeviceAuthUnavailableError([`No stored device auth for this gateway origin.`,`Run \`openclaw tui${f.sshTunnel?``:` --url ${projectGatewayUrlForDiagnostics(m)}`}\` to send a pairing request.`,GATEWAY_PAIRING_APPROVAL_HINT].join(`
`))}const w=f.tlsFingerprint;const T=await resolveEdgeAuthHeaders({config:i.config,value:normalizeEdgeAuthHeadersConfig(gatewayEdgeAuthValueForTarget({config:i.config,targetUrl:m})),targetUrl:m,env:process.env});if(d){if(!C?.token)throw new GatewayCredentialsRequiredError({method:S.method,configPath:i.configPath});if(Array.isArray(S.requiredStoredDeviceAuthScopes)&&!roleScopesAllow({role:`operator`,requestedScopes:S.requiredStoredDeviceAuthScopes,allowedScopes:C.scopes}))throw new GatewayStoredDeviceAuthUnavailableError(`stored device auth does not grant the required operator scopes`)}if((v.mode===`token`||v.mode===`password`)&&!g&&!_&&!(S.approvalRuntimeToken||v.allowTailscale||T)){if(!(C===void 0?await loadStoredOperatorDeviceAuthToken(x,h,S.sharedStateMode):C)?.token)throw new GatewayCredentialsRequiredError({method:S.method,configPath:i.configPath})}const E=await fitScopesToStoredDeviceGrant({opts:S,scopes:t,keepRequest:r||d||Boolean(g||_),loadGrant:async()=>C??await loadStoredOperatorDeviceAuthToken(x,h,S.sharedStateMode)});const D=l&&u&&S.requiredStoredDeviceAuthScopes?S.requiredStoredDeviceAuthScopes:d?void 0:n&&b&&!x?[ADMIN_SCOPE]:E;const O=d||S.requireLocalBackendSharedAuth===true||Boolean(S.agentRuntimeIdentityToken);return await new Promise((e,t)=>{if(S.signal?.aborted){t(createGatewayRequestAbortError(S.method));return}let n=false;let r;let i;const c=new AbortController;let l=false;let u=0;let d=0;const cleanup=()=>{c.abort();S.signal?.removeEventListener(`abort`,abortHandler);clearTimeout(r)};const stopClientThenSettle=(n,r)=>{const complete=()=>{if(n)t(n);else e(r)};const a=i;const o=stopGatewayClient(v);if(a)Promise.allSettled([o,a]).then(complete);else o.then(complete,complete)};const stop=(e,t)=>{if(n)return;n=true;cleanup();stopClientThenSettle(e,t)};const abortHandler=()=>{if(n)return;n=true;cleanup();const e=createGatewayRequestAbortError(S.method);const stopAfterAbortHook=()=>stopClientThenSettle(e);if(!S.onSignalAbort||!l){stopAfterAbortHook();return}const t=v.request.bind(v);Promise.resolve().then(()=>S.onSignalAbort?.(t)).catch(()=>{}).finally(stopAfterAbortHook)};S.signal?.addEventListener(`abort`,abortHandler,{once:true});const v=new GatewayClient({url:m,sshTunnel:f.sshTunnel,token:g,password:_,edgeAuthHeaders:T,tlsFingerprint:w,preauthHandshakeTimeoutMs:S.preauthHandshakeTimeoutMs,assertConnectionCurrent:S.assertConnectionCurrent,instanceId:S.instanceId??randomUUID(),clientName:S.clientName??GATEWAY_CLIENT_NAMES.CLI,clientDisplayName:resolveGatewayClientDisplayName(S),clientVersion:S.clientVersion??VERSION,caps:[`ultrafast`,...S.caps??[]],platform:S.platform,mode:S.mode??GATEWAY_CLIENT_MODES.CLI,...S.approvalRuntimeToken?{approvalRuntimeToken:S.approvalRuntimeToken}:{},...S.agentRuntimeIdentityToken?{agentRuntimeIdentityToken:S.agentRuntimeIdentityToken}:{},role:`operator`,...Array.isArray(D)?{scopes:D}:{},deviceIdentity:x,...h?{deviceAuthScope:h}:{},...C?{preparedDeviceAuth:C}:{},...S.sharedStateMode?{sharedStateMode:S.sharedStateMode}:{},minProtocol:S.minProtocol??4,maxProtocol:S.maxProtocol??4,onHelloOk:e=>{const t=++d;if(a===null&&r){clearTimeout(r);r=void 0}try{S.onHelloOk?.(e)}catch{}if(n)return;(async()=>{try{ensureGatewaySupportsRequiredFeatures({kind:`method`,required:Array.isArray(S.requiredMethods)?S.requiredMethods:[],supported:Array.isArray(e.features?.methods)?e.features.methods:[],attemptedMethod:S.method});ensureGatewaySupportsRequiredFeatures({kind:`capability`,required:S.requiredCapabilities,supported:e.features?.capabilities,attemptedMethod:S.method});if(S.prepareDispatchCurrent)await S.prepareDispatchCurrent();if(n||S.signal?.aborted||t!==d)return;S.assertDispatchCurrent?.();l=true;const r=await v.request(S.method,S.params,{expectFinal:S.expectFinal,timeoutMs:S.timeoutMs,signal:S.signal,onAccepted:S.onAccepted});if(S.onResponse){const e=S.onResponse;i=Promise.resolve().then(()=>e(v.request.bind(v),c.signal,r));await i}stop(void 0,r)}catch(e){if(n||t!==d)return;stop(withEdgeAuthPairingHint(e,T,x,S.url))}})()},onClose:(e,t,r)=>{d+=1;if(n)return;if(r?.connectError){stop(isGatewayUnreachableSocketError(r.connectError)?createGatewayUnreachableTransportError({cause:r.connectError,connectionDetails:p}):r.connectError);return}if(!l&&r?.transientPreHelloCleanClose===true&&u<1){u+=1;return}stop(createGatewayCloseTransportError({code:e,reason:t,connectionDetails:p,requestDispatched:l}))},onConnectError:e=>{const t=e.name===`GatewayClientRequestError`;const r=Boolean(S.agentRuntimeIdentityToken)&&isRequiredAgentRuntimeIdentityConnectError(e);const i=isGatewayConnectAssemblyError(e)||r||isAllowlistedGatewayConnectRequestError(e)||O&&t;if(n||!i)return;stop(e)}});const y=a??o;r=setTimeout(()=>{stop(createGatewayTimeoutTransportError({timeoutMs:y,connectionDetails:p,requestDispatched:l}))},s);startGatewayClientWhenEventLoopReady(v,{timeoutMs:s,signal:c.signal}).then(e=>{if(n||e.ready||e.aborted)return;stop(createGatewayTimeoutTransportError({timeoutMs:o,connectionDetails:p,requestDispatched:false}))}).catch(e=>{if(n)return;stop(e instanceof Error?e:new Error(String(e)))})})}async function callGatewayWithScopeEscalation(e,t){try{return await callGatewayWithScopes(e,t)}catch(n){const r=await resolveCliScopeRetry({opts:e,scopes:t,error:n});if(!r)throw n;return await callGatewayWithScopes(r.opts,r.scopes)}}async function callGatewayCli(e){assertGatewayCliMessageContext(e.method,e.params);const t=!e.signal&&!e.onAccepted&&!e.onSignalAbort&&!e.onResponse&&isReadOnlyGatewayCliCall(e.method,e.params)?getAsyncWorkSignal():void 0;const n=t?{...e,signal:t}:e;if(Array.isArray(e.scopes))return await callGatewayWithScopes(n,e.scopes,{explicitScopes:true});const{CLI_DEFAULT_OPERATOR_SCOPES:r,isGatewayMethodClassified:i,resolveLeastPrivilegeOperatorScopesForMethod:a}=await import(`./method-scopes-AEq16uaH.mjs`);const o=i(e.method)?a(e.method,e.params):r;if(e.method===`chat.abort`||e.method===`sessions.abort`)return await callGatewayWithScopes(n,o,{localCliAbort:true});return await callGatewayWithScopeEscalation(n,o)}async function callGatewayLeastPrivilege(e){const{resolveLeastPrivilegeOperatorScopesForMethod:t}=await import(`./method-scopes-AEq16uaH.mjs`);return await callGatewayWithScopeEscalation(e,t(e.method,e.params))}async function callGateway(e){const t=e.mode??GATEWAY_CLIENT_MODES.BACKEND;const n=e.clientName??GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT;if(t===GATEWAY_CLIENT_MODES.CLI||n===GATEWAY_CLIENT_NAMES.CLI)return await callGatewayCli(e);const r={...e,mode:t,clientName:n};return Array.isArray(e.scopes)?await callGatewayWithScopes(r,e.scopes,{explicitScopes:true}):await callGatewayLeastPrivilege(r)}export{callGateway};