UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

690 lines (689 loc) • 28.8 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { s as isVitestRuntimeEnv } from "./env-HehwidXj.mjs"; import { l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as SUBAGENT_EXEC_ENV_VAR } from "./openclaw-exec-env-BPYcT7Dr.mjs"; import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { i as createAbortError } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { b as resolveGatewayPort, m as resolveConfigPath } from "./paths-DAcAg5aV.mjs"; import { t as VERSION } from "./version-GlxUMdxI.mjs"; import { a as getRuntimeConfigSnapshot } from "./runtime-snapshot-WbwbY5b7.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs"; import { t as ADMIN_SCOPE, u as WRITE_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import { o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs"; import { a as isGatewayMethodClassified, s as resolveLeastPrivilegeOperatorScopesForMethod, t as CLI_DEFAULT_OPERATOR_SCOPES } from "./method-scopes-Dpyb0Ck-.mjs"; import { o as isLoopbackGatewayUrl } from "./net-BgRayX-P.mjs"; import { c as readMissingScopeErrorDetails } from "./gateway-error-details-B69XiHdh.mjs"; import { i as PROTOCOL_VERSION, t as MIN_CLIENT_PROTOCOL_VERSION } from "./version-CwNT1gaY.mjs"; import { r as trimToUndefined } from "./credential-planner-DCQbkiQO.mjs"; import { n as isGatewaySecretRefUnavailableError, r as resolveExplicitGatewayAuth } from "./credentials-UDpmcQCV.mjs"; import { a as resolveGatewayAuthFromCredentials, i as resolveGatewayAuthForConfig } from "./auth-resolve-C6_i-P4T.mjs"; import { t as ConnectErrorDetailCodes, u as readConnectErrorDetailCode } from "./connect-error-details-BdhXf496.mjs"; import { c as resolveSafeTimeoutDelayMs, s as resolvePreauthHandshakeTimeoutMs } from "./timeouts-nwfOzsiL.mjs"; import { i as loadDeviceAuthTokenReadOnly, o as loadOriginDeviceToken, r as loadDeviceAuthToken, s as loadOriginDeviceTokenReadOnly } from "./device-auth-store-B3F61F1r.mjs"; import { r as isGatewayConnectAssemblyError } from "./request-error-C4C6eD0S.mjs"; import { n as loadDeviceIdentityIfPresentAsync, r as loadOrCreateDeviceIdentityAsync } from "./device-identity-async-B1EfjFkw.mjs"; import { i as projectGatewayUrlForDiagnostics, r as projectGatewayConnectionDetailsForDiagnostics, t as buildGatewayConnectionDetailsWithResolvers } from "./connection-details-BWzGtdxz.mjs"; import { a as firstGatewayErrorLine, c as isGatewayUnreachableSocketError, i as createGatewayUnreachableTransportError, n as createGatewayCloseTransportError, r as createGatewayTimeoutTransportError, s as isGatewayTransportError } from "./transport-error-BL_kuysc.mjs"; import { t as GatewayClient } from "./client-cXg8kULv.mjs"; import { t as startGatewayClientWhenEventLoopReady } from "./readiness-tJvtmnC1.mjs"; import { n as readGatewayDispatchConfigWithShellEnvFallback, t as readGatewayDispatchConfig } from "./gateway-dispatch-config-NmsdoFuC.mjs"; import "./credentials-secret-inputs-BBRl7DaH.mjs"; import { i as resolveGatewayUrlOverride, r as resolveGatewayClientBootstrap } from "./client-bootstrap-BzJO9FYk.mjs"; import { n as normalizeEdgeAuthHeadersConfig, r as resolveEdgeAuthHeaders, t as gatewayEdgeAuthValueForTarget } from "./edge-auth-ClCUj4kR.mjs"; import { randomUUID } from "node:crypto"; //#region 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("\n")); 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 resolveReadOnlyLocalGatewayAuth(e) { const { auth: t, authNone: n, env: r } = e; const i = n || t?.token || t?.password ? null : await loadDeviceIdentityIfPresentAsync({ env: r }); const a = await loadStoredOperatorDeviceAuthToken(i, void 0, "read-only", r); return { token: t?.token, password: t?.password, skipImplicitAuth: true, clientName: n ? GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT : GATEWAY_CLIENT_NAMES.CLI, mode: n ? GATEWAY_CLIENT_MODES.BACKEND : GATEWAY_CLIENT_MODES.CLI, requireLocalBackendSharedAuth: n, deviceIdentity: a ? i : null, preparedDeviceAuth: a ?? void 0, sharedStateMode: "read-only" }; } 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; } } //#endregion //#region 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.`); } //#endregion //#region 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:"; } /** * True when the caller fully addressed the Gateway with flags. Config is then * consulted only for gateway.remote.edgeAuth, so a broken config must not block * the connection: this is the historical recovery path for an invalid config. */ function isExplicitGatewayConnection(e) { return !e.config && Boolean(trimToUndefined(e.urlOverride)) && hasExplicitGatewayConnectionAuth(e.explicitAuth); } /** Returns true when url/auth flags are sufficient and loading OpenClaw config is unnecessary. */ function canSkipGatewayConfigLoad(e) { const t = trimToUndefined(e.urlOverride); if (!t || e.config || !hasExplicitGatewayConnectionAuth(e.explicitAuth)) return false; return !targetMayRequireConfiguredEdgeAuth(t); } /** Preserve configured server inference unless this connection actually skipped config. */ function resolveGatewayConnectionAuth(e) { return e.configSkipped ? resolveGatewayAuthFromCredentials({ authConfig: {}, ...e.auth }) : resolveGatewayAuthForConfig({ config: e.config, tailscaleMode: e.config.gateway?.tailscale?.mode }); } //#endregion //#region src/gateway/operator-cli-message-input.ts /** Operator message RPCs cannot preserve the source of an agent's shell report. */ 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.`); } //#endregion //#region src/gateway/call.ts function formatGatewayTransportErrorJson(e) { if (!isGatewayTransportError(e)) return null; const t = projectGatewayConnectionDetailsForDiagnostics(e.connectionDetails); return { ok: false, error: { type: "gateway_transport_error", kind: e.kind, message: redactSensitiveUrlLikeString(firstGatewayErrorLine(e.message)), ...e.code !== void 0 ? { code: e.code } : {}, ...e.reason !== void 0 ? { reason: redactSensitiveUrlLikeString(e.reason) } : {}, ...e.timeoutMs !== void 0 ? { timeoutMs: e.timeoutMs } : {} }, gateway: { url: t.url, urlSource: t.urlSource, ...t.bindDetail ? { bindDetail: t.bindDetail } : {}, ...t.remoteFallbackNote ? { remoteFallbackNote: t.remoteFallbackNote } : {} } }; } function formatGatewayClientRequestErrorJson(e) { if (!isGatewayClientRequestError(e)) return null; const t = e; return { ok: false, error: { type: "gateway_request_error", code: t.gatewayCode, message: t.message, ...t.details !== void 0 ? { details: t.details } : {}, retryable: t.retryable, ...t.retryAfterMs !== void 0 ? { retryAfterMs: t.retryAfterMs } : {} } }; } function isGatewayClientRequestError(e) { if (!(e instanceof Error) || e.name !== "GatewayClientRequestError") return false; const t = e; if (typeof t.gatewayCode !== "string" || t.gatewayCode.length === 0 || t.message.length === 0 || typeof t.retryable !== "boolean" || t.retryAfterMs !== void 0 && (typeof t.retryAfterMs !== "number" || !Number.isInteger(t.retryAfterMs) || t.retryAfterMs < 0)) return false; return true; } /** Preserve machine-readable output for auth failures raised before transport startup. */ function formatGatewayAuthErrorJson(e) { if (!isGatewayCredentialsRequiredError(e) && !isGatewayExplicitAuthRequiredError(e) && !isGatewaySecretRefUnavailableError(e)) return null; return { ok: false, error: { type: "gateway_credentials_required", message: e.message } }; } function isGatewayCredentialsRequiredError(e) { if (e instanceof GatewayCredentialsRequiredError) return true; if (!(e instanceof Error) || e.name !== "GatewayCredentialsRequiredError") return false; const t = e; return typeof t.method === "string" && typeof t.configPath === "string"; } function isGatewayExplicitAuthRequiredError(e) { return e instanceof Error && e.name === "GatewayExplicitAuthRequiredError"; } 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"; } /** * Load config for a fully flag-addressed connection. Config only supplies * gateway.remote.edgeAuth here, so an unreadable or invalid config degrades to * empty rather than blocking a connection the flags already describe. */ 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 }; } /** Whether the caller selected the configured local Gateway without a URL override. */ async function isImplicitLocalGatewayTarget(e) { if (resolveGatewayUrlOverride({ gatewayUrl: e.url, env: process.env, ignoreEnvUrlOverride: e.ignoreEnvUrlOverride, localPortOverride: e.localPortOverride }).url) return false; const t = e.config ?? await loadGatewayConfig(); return e.localPortOverride !== void 0 || t.gateway?.mode !== "remote"; } 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("\n")); } 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, n = false) { const r = await resolveGatewayCallContext(e); const { timeoutMs: i, startupTimeoutMs: a, safeTimerTimeoutMs: o } = resolveGatewayCallTimeout(e.timeoutMs); const s = resolveGatewayUrlOverride({ gatewayUrl: e.url, env: process.env, ignoreEnvUrlOverride: e.ignoreEnvUrlOverride, localPortOverride: e.localPortOverride }).source; if (e.requireLocalBackendSharedAuth && (s || r.isRemoteMode)) throw new GatewayLocalBackendSharedAuthUnavailableError("local backend shared auth is limited to the configured local gateway"); const c = e.useStoredDeviceAuth === true; const l = Boolean(r.explicitAuth.token || r.explicitAuth.password); const u = c && !l; const d = await resolveGatewayClientBootstrap({ ...gatewayCallBootstrapOptions(e, r), skipImplicitAuth: u || e.skipImplicitAuth === true, ...u ? {} : { overrideAuthErrorHint: "Fix: pass --token or --password with --url (or gatewayToken in tools)." } }); ensureRemoteModeUrlConfigured({ context: r, urlOverrideSource: d.urlOverrideSource }); const f = d.connectionDetails; const p = d.url; if (e.expectUrl !== void 0 && p !== e.expectUrl) throw new Error("Gateway destination changed. Refresh the selected Gateway before retrying."); const m = d.deviceAuthScope; const h = u ? void 0 : d.auth.token; const g = u ? void 0 : d.auth.password; const _ = resolveGatewayConnectionAuth({ config: r.config, configSkipped: r.configSkipped, auth: { token: h, password: g } }); const { clientOptions: v, omitDeviceIdentity: y, deviceIdentity: b } = await resolveGatewayCallDeviceAuth({ opts: e, url: p, authMode: _.mode, isImplicitLocalTarget: !s && !r.isRemoteMode, token: h, password: g }); const x = { ...e, ...v }; let S = x.preparedDeviceAuth; if (u) { S ??= await loadStoredOperatorDeviceAuthToken(b, m, x.sharedStateMode); if (!S?.token && m) throw new GatewayStoredDeviceAuthUnavailableError(["No stored device auth for this gateway origin.", `Run \`openclaw tui${d.sshTunnel ? "" : ` --url ${projectGatewayUrlForDiagnostics(p)}`}\` to send a pairing request, approve it in that gateway's Control UI (Settings -> Devices) or run \`openclaw devices approve --latest\` on the gateway host, then retry.`].join("\n")); } const C = d.tlsFingerprint; const w = normalizeEdgeAuthHeadersConfig(gatewayEdgeAuthValueForTarget({ config: r.config, targetUrl: p })); const T = await resolveEdgeAuthHeaders({ config: r.config, value: w, targetUrl: p, env: process.env }); if (u) { if (!S?.token) throw new GatewayCredentialsRequiredError({ method: x.method, configPath: r.configPath }); if (Array.isArray(x.requiredStoredDeviceAuthScopes) && !roleScopesAllow({ role: "operator", requestedScopes: x.requiredStoredDeviceAuthScopes, allowedScopes: S.scopes })) throw new GatewayStoredDeviceAuthUnavailableError("stored device auth does not grant the required operator scopes"); } if ((_.mode === "token" || _.mode === "password") && !h && !g && !x.approvalRuntimeToken && !_.allowTailscale) { if (!(S === void 0 ? await loadStoredOperatorDeviceAuthToken(b, m, x.sharedStateMode) : S)?.token) throw new GatewayCredentialsRequiredError({ method: x.method, configPath: r.configPath }); } const E = c && l && x.requiredStoredDeviceAuthScopes ? x.requiredStoredDeviceAuthScopes : u ? void 0 : n && y && !b ? [ADMIN_SCOPE] : t; const D = u || x.requireLocalBackendSharedAuth === true || Boolean(x.agentRuntimeIdentityToken); return await new Promise((e, t) => { if (x.signal?.aborted) { t(createGatewayRequestAbortError(x.method)); return; } let n = false; let r; let s; const c = new AbortController(); let l = false; let u = 0; let _ = 0; const cleanup = () => { c.abort(); x.signal?.removeEventListener("abort", abortHandler); clearTimeout(r); }; const stopClientThenSettle = (n, r) => { const complete = () => { if (n) t(n); else e(r); }; const i = s; const a = stopGatewayClient(v); if (i) Promise.allSettled([a, i]).then(complete); else a.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(x.method); const stopAfterAbortHook = () => stopClientThenSettle(e); if (!x.onSignalAbort || !l) { stopAfterAbortHook(); return; } const t = v.request.bind(v); Promise.resolve().then(() => x.onSignalAbort?.(t)).catch(() => {}).finally(stopAfterAbortHook); }; x.signal?.addEventListener("abort", abortHandler, { once: true }); const v = new GatewayClient({ url: p, sshTunnel: d.sshTunnel, token: h, password: g, edgeAuthHeaders: T, tlsFingerprint: C, preauthHandshakeTimeoutMs: x.preauthHandshakeTimeoutMs, assertConnectionCurrent: x.assertConnectionCurrent, instanceId: x.instanceId ?? randomUUID(), clientName: x.clientName ?? GATEWAY_CLIENT_NAMES.CLI, clientDisplayName: resolveGatewayClientDisplayName(x), clientVersion: x.clientVersion ?? VERSION, caps: ["ultrafast", ...x.caps ?? []], platform: x.platform, mode: x.mode ?? GATEWAY_CLIENT_MODES.CLI, ...x.approvalRuntimeToken ? { approvalRuntimeToken: x.approvalRuntimeToken } : {}, ...x.agentRuntimeIdentityToken ? { agentRuntimeIdentityToken: x.agentRuntimeIdentityToken } : {}, role: "operator", ...Array.isArray(E) ? { scopes: E } : {}, deviceIdentity: b, ...m ? { deviceAuthScope: m } : {}, ...S ? { preparedDeviceAuth: S } : {}, ...x.sharedStateMode ? { sharedStateMode: x.sharedStateMode } : {}, minProtocol: x.minProtocol ?? 4, maxProtocol: x.maxProtocol ?? 4, onHelloOk: (e) => { const t = ++_; if (i === null && r) { clearTimeout(r); r = void 0; } try { x.onHelloOk?.(e); } catch {} if (n) return; (async () => { try { ensureGatewaySupportsRequiredFeatures({ kind: "method", required: Array.isArray(x.requiredMethods) ? x.requiredMethods : [], supported: Array.isArray(e.features?.methods) ? e.features.methods : [], attemptedMethod: x.method }); ensureGatewaySupportsRequiredFeatures({ kind: "capability", required: x.requiredCapabilities, supported: e.features?.capabilities, attemptedMethod: x.method }); if (x.prepareDispatchCurrent) await x.prepareDispatchCurrent(); if (n || x.signal?.aborted || t !== _) return; x.assertDispatchCurrent?.(); l = true; const r = await v.request(x.method, x.params, { expectFinal: x.expectFinal, timeoutMs: x.timeoutMs, signal: x.signal, onAccepted: x.onAccepted }); if (x.onResponse) { const e = x.onResponse; s = Promise.resolve().then(() => e(v.request.bind(v), c.signal)); await s; } stop(void 0, r); } catch (e) { if (n || t !== _) return; stop(e); } })(); }, onClose: (e, t, r) => { _ += 1; if (n) return; if (r?.connectError) { stop(isGatewayUnreachableSocketError(r.connectError) ? createGatewayUnreachableTransportError({ cause: r.connectError, connectionDetails: f }) : r.connectError); return; } if (!l && r?.transientPreHelloCleanClose === true && u < 1) { u += 1; return; } stop(createGatewayCloseTransportError({ code: e, reason: t, connectionDetails: f, requestDispatched: l })); }, onConnectError: (e) => { const t = e.name === "GatewayClientRequestError"; const r = Boolean(x.agentRuntimeIdentityToken) && isRequiredAgentRuntimeIdentityConnectError(e); const i = isGatewayConnectAssemblyError(e) || r || isAllowlistedGatewayConnectRequestError(e) || D && t; if (n || !i) return; stop(e); } }); const y = i ?? a; r = setTimeout(() => { stop(createGatewayTimeoutTransportError({ timeoutMs: y, connectionDetails: f, requestDispatched: l })); }, o); startGatewayClientWhenEventLoopReady(v, { timeoutMs: o, signal: c.signal }).then((e) => { if (n || e.ready || e.aborted) return; stop(createGatewayTimeoutTransportError({ timeoutMs: a, connectionDetails: f, requestDispatched: false })); }).catch((e) => { if (n) return; stop(e instanceof Error ? e : new Error(String(e))); }); }); } async function buildGatewayProbeConnectionDetails(e = {}) { const t = await resolveGatewayCallContext({ ...e, method: "status" }); const n = await resolveGatewayClientBootstrap({ ...gatewayCallBootstrapOptions(e, t), skipImplicitAuth: true }); ensureRemoteModeUrlConfigured({ context: t, urlOverrideSource: n.urlOverrideSource }); return { ...n.connectionDetails, ...n.tlsFingerprint ? { tlsFingerprint: n.tlsFingerprint } : {} }; } 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 callGatewayWithScopeEscalation(e, t) { try { return await callGatewayWithScopes(e, t); } catch (n) { if (!shouldEscalateSessionCreateCwdScope({ opts: e, scopes: t, error: n })) throw n; return await callGatewayWithScopes(e, [ADMIN_SCOPE]); } } async function callGatewayCli(e) { assertGatewayCliMessageContext(e.method, e.params); if (Array.isArray(e.scopes)) return await callGatewayWithScopes(e, e.scopes); const t = isGatewayMethodClassified(e.method) ? resolveLeastPrivilegeOperatorScopesForMethod(e.method, e.params) : CLI_DEFAULT_OPERATOR_SCOPES; if (e.method === "chat.abort" || e.method === "sessions.abort") return await callGatewayWithScopes(e, t, true); return await callGatewayWithScopeEscalation(e, t); } async function callGatewayLeastPrivilege(e) { return await callGatewayWithScopeEscalation(e, resolveLeastPrivilegeOperatorScopesForMethod(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) : await callGatewayLeastPrivilege(r); } function randomIdempotencyKey() { return randomUUID(); } //#endregion export { GatewayStoredDeviceAuthUnavailableError as _, callGatewayLeastPrivilege as a, formatGatewayTransportErrorJson as c, isGatewayExplicitAuthRequiredError as d, isImplicitLocalGatewayTarget as f, GatewayLocalBackendSharedAuthUnavailableError as g, GatewayCredentialsRequiredError as h, callGatewayCli as i, isGatewayClientRequestError as l, assertGatewayCliMessageContext as m, buildGatewayProbeConnectionDetails as n, formatGatewayAuthErrorJson as o, randomIdempotencyKey as p, callGateway as r, formatGatewayClientRequestErrorJson as s, buildGatewayConnectionDetails as t, isGatewayCredentialsRequiredError as u, resolveDeviceIdentityForGatewayCall as v, resolveReadOnlyLocalGatewayAuth as y };