UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

651 lines (650 loc) • 23.3 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { t as VERSION } from "./version-GlxUMdxI.mjs"; import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES, t as GATEWAY_CLIENT_CAPS } from "./client-info-Cm1BcrMm.mjs"; import { t as captureRuntimeConfigAsyncReader } from "./io.runtime-DsJ2dLCQ.mjs"; import { o as isRetryableGatewayStartupUnavailableError, t as GATEWAY_STARTUP_ADMISSION_WAIT_MS } from "./startup-unavailable-DEGJREFb.mjs"; import { o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs"; import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs"; import { i as PROTOCOL_VERSION, t as MIN_CLIENT_PROTOCOL_VERSION } from "./version-CwNT1gaY.mjs"; import "./config-CMA-J084.mjs"; import { r as resolveExplicitGatewayAuth } from "./credentials-UDpmcQCV.mjs"; import { t as ConnectErrorDetailCodes, u as readConnectErrorDetailCode } from "./connect-error-details-BdhXf496.mjs"; import { o as loadOriginDeviceToken } from "./device-auth-store-B3F61F1r.mjs"; import { n as GatewayClientRequestTimeoutError, t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs"; import { n as loadDeviceIdentityIfPresentAsync } from "./device-identity-async-B1EfjFkw.mjs"; import { s as readActiveGatewayLockPort } from "./gateway-lock-IYOwJQai.mjs"; import { a as resolveGatewayDeviceAuthRoute } from "./connection-details-BWzGtdxz.mjs"; import { t as assertExplicitGatewayAuthModeWhenBothConfigured } from "./auth-mode-policy-Dn8RauUH.mjs"; import { t as GatewayClient } from "./client-cXg8kULv.mjs"; import { t as startGatewayClientWhenEventLoopReady } from "./readiness-tJvtmnC1.mjs"; import { t as buildGatewayConnectionDetails } from "./call-DVCK1deJ.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 { t as mergeChatStreamMessage } from "./chat-stream-message-DRgwUbuJ.mjs"; import { n as isListedTuiSession } from "./tui-session-list-policy-C6O8wHXg.mjs"; import { randomUUID } from "node:crypto"; //#region packages/gateway-client/src/chat-stream-projection.ts /** Connection-owned chat baselines, independent of the selected local view. */ var GatewayChatStreamProjection = class { constructor() { this.runs = /* @__PURE__ */ new Map(); } project(e) { if (e.event !== "chat") return { event: e, missingBaseline: false }; const t = asNullableRecord(e.payload); if (!t || typeof t.runId !== "string" || typeof t.sessionKey !== "string") return { event: e, missingBaseline: false }; if (t.state === "delta") { const n = this.runs.get(t.runId); const r = mergeChatStreamMessage(n?.sessionKey === t.sessionKey && n.agentId === t.agentId ? n.message : void 0, t); if (r !== void 0) this.runs.set(t.runId, { sessionKey: t.sessionKey, agentId: t.agentId, message: r }); return { event: { ...e, payload: { ...t, message: r } }, missingBaseline: r === void 0 }; } if (t.state === "final" || t.state === "error" || t.state === "aborted") this.runs.delete(t.runId); return { event: e, missingBaseline: false }; } retire(e) { for (const [t, n] of this.runs) if (e(n)) this.runs.delete(t); } clear() { this.runs.clear(); } }; //#endregion //#region src/tui/gateway-chat-requests.ts const STARTUP_CHAT_HISTORY_RETRY_TIMEOUT_MS = 6e4; const STARTUP_CHAT_HISTORY_DEFAULT_RETRY_MS = 500; const STARTUP_CHAT_HISTORY_MAX_RETRY_MS = 5e3; function isRetryableStartupUnavailable(e) { if (!(e instanceof GatewayClientRequestError)) return false; if (e.gatewayCode !== "UNAVAILABLE" || !e.retryable) return false; const t = e.details; if (!t || typeof t !== "object") return true; const n = "method" in t ? t.method : void 0; return typeof n !== "string" || n === "chat.history"; } function resolveStartupRetryDelayMs(e) { const t = typeof e.retryAfterMs === "number" ? e.retryAfterMs : STARTUP_CHAT_HISTORY_DEFAULT_RETRY_MS; return Math.min(Math.max(t, 100), STARTUP_CHAT_HISTORY_MAX_RETRY_MS); } function isLegacyParameterError(e, t, n) { if (!(e instanceof GatewayClientRequestError) || e.gatewayCode !== "INVALID_REQUEST") return false; const r = e.message.toLowerCase(); return r.includes(`invalid ${t} params`) && r.includes(n); } /** Owns interactive request cancellation and startup admission lifetimes. */ var GatewayChatRequests = class { constructor(e) { this.client = e; this.lifetime = new AbortController(); this.pendingWrites = /* @__PURE__ */ new Set(); this.signal = this.lifetime.signal; } stop() { this.lifetime.abort(); } cancelPending(e) { const t = e.agentId ?? parseAgentSessionKey(e.sessionKey)?.agentId; for (const n of this.pendingWrites) if (n.sessionKey === e.sessionKey && n.agentId === t && (!e.runId || n.runId === e.runId)) n.controller.abort(); } async write(e, t) { const n = { ...e, agentId: e.agentId ?? parseAgentSessionKey(e.sessionKey)?.agentId, controller: new AbortController() }; const r = AbortSignal.any([this.signal, n.controller.signal]); const i = performance.now() + GATEWAY_STARTUP_ADMISSION_WAIT_MS; this.pendingWrites.add(n); try { return await t((e, t) => { r.throwIfAborted(); const n = i - performance.now(); if (n <= 0) throw new GatewayClientRequestTimeoutError({ method: e, timeoutMs: GATEWAY_STARTUP_ADMISSION_WAIT_MS, requestSent: false }); return this.client.request(e, t, { timeoutMs: n, signal: r, retainSentResultOnAbort: true }); }); } finally { this.pendingWrites.delete(n); } } async abortChat(e) { this.cancelPending(e); const t = { sessionKey: e.sessionKey, ...e.agentId ? { agentId: e.agentId } : {}, ...e.runId ? { runId: e.runId } : {} }; try { return await this.client.request("chat.abort", e.runId ? t : { ...t, preserveSideRuns: true }); } catch (n) { if (e.runId || !isLegacyParameterError(n, "chat.abort", "preservesideruns")) throw n; return await this.client.request("chat.abort", t); } } async loadHistory(e) { const t = performance.now() + STARTUP_CHAT_HISTORY_RETRY_TIMEOUT_MS; for (;;) { this.signal.throwIfAborted(); try { return await this.client.request("chat.history", { sessionKey: e.sessionKey, ...e.agentId ? { agentId: e.agentId } : {}, limit: e.limit }); } catch (e) { if (performance.now() >= t || !isRetryableStartupUnavailable(e)) throw e; await sleep(resolveStartupRetryDelayMs(e), this.signal); } } } }; //#endregion //#region src/tui/gateway-chat.ts function throwGatewayAuthResolutionError(e) { throw new Error([ e, "Fix: set OPENCLAW_GATEWAY_TOKEN/OPENCLAW_GATEWAY_PASSWORD, pass --token/--password,", "or resolve the configured secret provider for this credential." ].join("\n")); } async function hasStoredOriginDeviceAuth(e) { try { const t = await loadDeviceIdentityIfPresentAsync(); return Boolean(t && (await loadOriginDeviceToken({ gatewayScope: e, deviceId: t.deviceId, role: "operator" }))?.token); } catch { return false; } } function tuiGatewayModelCatalogKey(e) { return `${e.agentId ?? ""}\0${e.sessionKey ?? ""}`; } function effectiveCatalogScope(e, t) { return { ...e.agentId ? { agentId: e.agentId } : {}, ...t?.includes(GATEWAY_SERVER_CAPS.SESSION_SCOPED_MODEL_CATALOG) === true && e.sessionKey ? { sessionKey: e.sessionKey } : {} }; } var GatewayChatClient = class GatewayChatClient { constructor(e) { this.chatStream = new GatewayChatStreamProjection(); this.ready = createDeferredCore(); this.modelCatalogs = /* @__PURE__ */ new Map(); this.connection = e; this.client = new GatewayClient({ url: e.url, ...e.deviceAuthScope ? { deviceAuthScope: e.deviceAuthScope } : {}, ...e.sshTunnel ? { sshTunnel: e.sshTunnel } : {}, token: e.token, password: e.password, edgeAuthHeaders: e.edgeAuthHeaders, tlsFingerprint: e.tlsFingerprint, preauthHandshakeTimeoutMs: e.preauthHandshakeTimeoutMs, clientName: GATEWAY_CLIENT_NAMES.TUI, clientDisplayName: "openclaw-tui", clientVersion: VERSION, mode: GATEWAY_CLIENT_MODES.UI, scopes: [ "operator.admin", "operator.read", "operator.write", "operator.approvals" ], caps: [ GATEWAY_CLIENT_CAPS.AGENT_KIND, GATEWAY_CLIENT_CAPS.PLUGIN_APPROVALS, GATEWAY_CLIENT_CAPS.TASK_SUGGESTIONS, GATEWAY_CLIENT_CAPS.TOOL_EVENTS, GATEWAY_CLIENT_CAPS.ULTRAFAST ], instanceId: randomUUID(), minProtocol: 4, maxProtocol: 4, notifyOnStartupRetry: true, onHelloOk: (e) => { this.pendingConnectError = void 0; this.hello = e; this.ready.resolve(); this.onConnected?.(); }, onEvent: (e) => { this.refreshModelsForEvent(e); const t = this.chatStream.project({ event: e.event, payload: e.payload, seq: e.seq }); this.onEvent?.(t.event); }, onClose: (e, t) => { this.chatStream.clear(); this.modelCatalogs.clear(); this.ready = createDeferredCore(); if (this.pendingConnectError && this.onConnectError) { this.pendingConnectError = void 0; return; } this.onDisconnected?.(t); }, onConnectError: (e) => this.notifyConnectError(e), onGap: (e) => { this.onGap?.(e); } }); this.requests = new GatewayChatRequests(this.client); } static async connect(e) { return new GatewayChatClient(await resolveGatewayConnection(e)); } /** Connect to a target already selected and authenticated by a preceding Gateway probe. */ static async connectBound(e) { return new GatewayChatClient(await resolveBoundGatewayConnection(e)); } start() { startGatewayClientWhenEventLoopReady(this.client, { clientOptions: { preauthHandshakeTimeoutMs: this.connection.preauthHandshakeTimeoutMs } }).then((e) => { if (!e.ready && !e.aborted) this.notifyUnclosedConnectError(/* @__PURE__ */ new Error("gateway event loop readiness timeout")); }).catch((e) => { this.notifyUnclosedConnectError(e instanceof Error ? e : new Error(String(e))); }); } notifyConnectError(e) { if (this.pendingConnectError || isRetryableGatewayStartupUnavailableError(e)) return; if (this.connection.deviceAuthScope && readConnectErrorDetailCode(e.details) === ConnectErrorDetailCodes.PAIRING_REQUIRED && !e.message.includes("Pairing request sent.")) e.message = [e.message, "Pairing request sent. Approve it in that gateway's Control UI (Settings -> Devices), or run `openclaw devices approve --latest` on the gateway host, then retry."].join("\n"); materializeErrorStack(e); this.pendingConnectError = e; this.onConnectError?.(e); } notifyUnclosedConnectError(e) { const t = Boolean(this.onConnectError); this.notifyConnectError(e); if (!t) this.onDisconnected?.(e.message); } stop() { this.requests.stop(); this.chatStream.clear(); this.modelCatalogs.clear(); return this.client.stopAndWait(); } async subscribeSessionEvents() { return await this.client.request("sessions.subscribe", {}); } async waitForReady() { await this.ready.promise; } cancelPendingRequests(e) { this.requests.cancelPending(e); } async sendChat(e) { const t = e.runId ?? randomUUID(); const n = await this.requests.write({ sessionKey: e.sessionKey, agentId: e.agentId, runId: t }, (n) => n("chat.send", { sessionKey: e.sessionKey, ...e.agentId ? { agentId: e.agentId } : {}, ...e.sessionId ? { sessionId: e.sessionId } : {}, message: e.message, thinking: e.thinking, deliver: e.deliver, timeoutMs: e.timeoutMs, idempotencyKey: t })); const r = normalizeOptionalString(n?.runId) ?? t; const i = normalizeOptionalString(n?.status); return i ? { runId: r, status: i } : { runId: r }; } async abortChat(e) { return await this.requests.abortChat(e); } async loadHistory(e) { return await this.requests.loadHistory(e); } async loadImage(e) { const { loadGatewayImage: t } = await import("./gateway-image-loader-BQGYmxDM.mjs"); const n = AbortSignal.any([e.signal, this.requests.signal]); const r = [this.hello?.auth.deviceToken, ...this.hello?.auth.method === "password" ? [this.connection.password, this.connection.token] : [this.connection.token, this.connection.password]].filter((e) => Boolean(e)); return await t({ request: { ...e, signal: n }, connection: this.connection, credentials: [...new Set(r)], readMediaBasePath: async (e) => { return (await this.client.request("config.get", {}, { signal: e })).runtimeConfig.gateway?.controlUi?.basePath ?? ""; }, downloadArtifact: (t, n) => this.client.request("artifacts.download", { sessionKey: e.sessionKey, ...e.agentId ? { agentId: e.agentId } : {}, artifactId: t }, { signal: n }) }); } async listSessions(e) { return await this.client.request("sessions.list", e ?? {}); } async resolveSession(e) { return await this.client.request("sessions.resolve", e); } async describeSession(e) { const t = e.agentId ?? parseAgentSessionKey(e.sessionKey)?.agentId; const n = this.requests.signal; for (;;) { n.throwIfAborted(); const r = this.ready; const i = this.hello; const isCurrentConnection = () => r === this.ready && i === this.hello; try { const [r, i] = await Promise.all([this.client.request("sessions.describe", { key: e.sessionKey, ...e.agentId ? { agentId: e.agentId } : {} }, { signal: n }), this.client.request("sessions.list", { agentId: t, limit: 1 }, { signal: n })]); n.throwIfAborted(); if (isCurrentConnection()) { const e = r.session; return { session: e && isListedTuiSession(e) ? e : null, defaults: i.defaults }; } } catch (e) { if (n.aborted || isCurrentConnection()) throw e; } await racePromiseWithAbortSignal(this.ready.promise, n); } } async listAgents() { const e = await this.client.request("agents.list", {}); if (!this.getKnownModels({ agentId: e.defaultId })) this.listModels({ agentId: e.defaultId }).catch(() => {}); return e; } async patchSession(e) { return await this.client.request("sessions.patch", e); } async createSession(e, t = { sessionKey: e.parentSessionKey ?? e.key, agentId: e.agentId }) { const n = { ...e, emitCommandHooks: Boolean(e.parentSessionKey) }; return await this.requests.write(t, async (t) => { try { return await t("sessions.create", n); } catch (r) { if (e.succeedsParent === void 0 || !isLegacyParameterError(r, "sessions.create", "succeedsparent")) throw r; const { succeedsParent: i, ...a } = n; if (!e.succeedsParent) { const { parentSessionKey: e, emitCommandHooks: n, ...r } = a; return await t("sessions.create", r); } return await t("sessions.create", a); } }); } async resetSession(e, t, n) { return await this.client.request("sessions.reset", { key: e, ...n?.agentId ? { agentId: n.agentId } : {}, ...t ? { reason: t } : {} }); } async getGatewayStatus() { return await this.client.request("status"); } getKnownModels(e = {}) { const t = effectiveCatalogScope(e, this.hello?.features.capabilities); return this.modelCatalogs.get(tuiGatewayModelCatalogKey(t))?.models; } listModels(e = {}) { const t = effectiveCatalogScope(e, this.hello?.features.capabilities); const n = this.hello?.features.capabilities?.includes(GATEWAY_SERVER_CAPS.PUBLISHED_MODEL_CATALOG) === true; const r = this.onModelsChanged; const i = tuiGatewayModelCatalogKey(t); let a = this.modelCatalogs.get(i); if (!a) { a = { scope: t }; this.modelCatalogs.set(i, a); } if (a.pending) return a.pending; const o = a; const current = () => this.modelCatalogs.get(i) === o && o.pending === s; const s = this.client.request("models.list", { ...e.agentId ? { agentId: e.agentId } : {}, ...t.sessionKey ? { sessionKey: t.sessionKey } : {}, ...n ? { includeDetails: true } : {} }).then((e) => { if (!current()) return this.modelCatalogs.get(i)?.models ?? []; const a = Array.isArray(e?.models) ? e.models : []; o.models = n ? a : a.map(({ available: e, unavailableReason: t, ...n }) => n); r?.(t); return o.models; }).catch((e) => { if (!current()) return this.modelCatalogs.get(i)?.models ?? []; throw e; }).finally(() => { if (current()) o.pending = void 0; }); o.pending = s; return s; } refreshModelsForEvent(e) { const t = asNullableRecord(e.payload); const n = e.event === "chat.metadata.changed" && t?.modelSelectionChanged === true; const r = e.event === "config.changed" || e.event === "chat.metadata.changed" && t?.modelCatalogChanged !== false; const i = e.event === "models.snapshot" ? asNullableRecord(t?.scope) : null; if (!n && !r && !i) return; for (const e of this.modelCatalogs.values()) { if (i && (i.authProfileId || i.agentId !== e.scope.agentId || i.sessionKey && i.sessionKey !== e.scope.sessionKey)) continue; e.pending = void 0; if (n) { e.models = void 0; this.onModelsChanged?.(e.scope); } this.listModels(e.scope).catch(() => {}); } } async listCommands(e) { const t = await this.client.request("commands.list", e ?? {}); return Array.isArray(t?.commands) ? t.commands : []; } async listPluginApprovals() { return await this.client.request("plugin.approval.list", {}); } async listQuestions() { return await this.client.request("question.list", {}); } async getQuestion(e) { return await this.client.request("question.get", { id: e }); } async resolveQuestion(e) { return await this.client.request("question.resolve", e); } async resolvePluginApproval(e, t) { return await this.client.request("plugin.approval.resolve", { id: e, decision: t }); } getTaskSuggestionActionCapabilities() { const e = this.hello?.auth; const t = this.hello?.features?.methods; const allows = (n, r) => Array.isArray(t) && t.includes(n) && Boolean(e && roleScopesAllow({ role: e.role, requestedScopes: [r], allowedScopes: e.scopes })); return { canAccept: allows("taskSuggestions.accept", "operator.admin"), canDismiss: allows("taskSuggestions.dismiss", "operator.write") }; } async listTaskSuggestions() { if (this.hello?.features?.methods?.includes("taskSuggestions.list") !== true) return []; const e = this.getTaskSuggestionActionCapabilities(); if (!e.canAccept && !e.canDismiss) return []; return (await this.client.request("taskSuggestions.list", {})).suggestions; } async acceptTaskSuggestion(e) { return await this.client.request("taskSuggestions.accept", { taskId: e, mode: "local" }); } async dismissTaskSuggestion(e) { return await this.client.request("taskSuggestions.dismiss", { taskId: e }); } }; function resolveTuiEdgeAuthHeaders(e, t, n) { return resolveEdgeAuthHeaders({ config: e, value: normalizeEdgeAuthHeadersConfig(gatewayEdgeAuthValueForTarget({ config: e, targetUrl: t })), targetUrl: t, env: n }); } /** * Preserve a pre-probed Gateway route across an in-process handoff. This path * deliberately ignores global config and Gateway env overrides, including * credentials, while still applying the normal remote URL safety policy. */ async function resolveBoundGatewayConnection(e) { const t = buildGatewayConnectionDetails({ config: e.config, url: e.url, ignoreEnvUrlOverride: true }).url; const n = resolveExplicitGatewayAuth({ token: e.token, password: e.password }); const r = await resolveTuiEdgeAuthHeaders(e.config, t, process.env); const { deviceAuthScope: i, sshTunnel: a } = resolveGatewayDeviceAuthRoute({ config: e.config, url: t, remote: true, configuredRemote: e.configuredRemote, tlsFingerprint: e.tlsFingerprint }); return { url: t, deviceAuthScope: i, ...a ? { sshTunnel: a } : {}, token: n.token, password: n.password, ...r ? { edgeAuthHeaders: r } : {}, ...e.tlsFingerprint ? { tlsFingerprint: e.tlsFingerprint } : {} }; } async function resolveGatewayConnection(e) { const t = await captureRuntimeConfigAsyncReader()(); const n = process.env; const r = t.gateway?.auth?.mode; const i = t.gateway?.mode === "remote"; const a = resolveGatewayUrlOverride({ gatewayUrl: e.url, env: n }); const o = resolveExplicitGatewayAuth({ token: e.token, password: e.password }); const s = Boolean(a.url || n.OPENCLAW_GATEWAY_PORT?.trim() || i); const c = e.allowConfiguredAuthForExactTarget === true && a.source === "cli" && !i && !n.OPENCLAW_GATEWAY_PORT?.trim(); const l = !s || c ? await readActiveGatewayLockPort() : void 0; if (!a.source && r !== "none" && r !== "trusted-proxy" && !i) try { assertExplicitGatewayAuthModeWhenBothConfigured(t); } catch (e) { throwGatewayAuthResolutionError(formatErrorMessage(e)); } const u = await resolveGatewayClientBootstrap({ config: t, gatewayUrl: a.source === "cli" ? a.url : void 0, explicitAuth: o, env: n, authPolicy: "interactive", allowConfiguredAuthForExactTarget: e.allowConfiguredAuthForExactTarget, suppressEnvAuthFallback: e.suppressEnvAuthFallback, ...l ? { localPortOverride: l } : {}, explicitTlsFingerprint: e.tlsFingerprint, allowStoredOriginAuth: hasStoredOriginDeviceAuth, overrideAuthErrorHint: "Fix: pass --token or --password once to request pairing, approve it in that gateway's Control UI (Settings -> Devices), then retry with the same credential so OpenClaw can store the device token.", buildConnectionDetails: buildGatewayConnectionDetails }); const d = Boolean(u.deviceAuthScope && await hasStoredOriginDeviceAuth(u.deviceAuthScope)); const f = u.authFailureReason === "Missing gateway auth credentials." || u.authFailureReason === "Missing gateway auth token." || u.authFailureReason === "Missing gateway auth password."; if (u.authFailureReason && (!f || !d)) { if (f && !s && l === void 0) throw new Error([ "No Gateway is running on this machine.", "Fix: run `openclaw chat` to chat here without a Gateway, or start one with `openclaw gateway`.", "To use a Gateway on another machine, run `openclaw tui <Gateway URL>` once with that Gateway's token or password, then approve the pairing request in its Control UI." ].join("\n")); throwGatewayAuthResolutionError(u.authFailureReason); } const p = await resolveTuiEdgeAuthHeaders(t, u.url, n); return { url: u.url, deviceAuthScope: u.deviceAuthScope, ...u.sshTunnel ? { sshTunnel: u.sshTunnel } : {}, token: u.auth.token, password: u.auth.password, ...p ? { edgeAuthHeaders: p } : {}, ...u.tlsFingerprint ? { tlsFingerprint: u.tlsFingerprint } : {} }; } //#endregion export { GatewayChatClient };