UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

498 lines (497 loc) • 18.6 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { o as getRuntimeConfigSnapshotMetadata } from "./runtime-snapshot-WbwbY5b7.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { s as operatorSessionCap } from "./operator-role-policy-DhcqVpmG.mjs"; import { k as getSessionRepositoryWorkspaceStore } from "./session-accessor.sqlite-entry-store-DmqxH0lm.mjs"; import { r as resolveRequestedSessionAgentId } from "./session-request-agent-tfwWH53J.mjs"; import { a as resolveConfiguredGitHubHost, i as resolveConfiguredGitHubApiBaseUrl } from "./github-host-CjR25cOO.mjs"; import { n as gitHubPublicApi } from "./github-public-api-C47tI7vQ.mjs"; import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs"; import { _ as prepareSubagentSessionListReadCache, c as getSubagentSessionListReadSnapshotIdentity } from "./subagent-registry-state-CMZQXOjY.mjs"; import { r as createSessionListEntryFilter } from "./session-sharing-read-BqjuH16A.mjs"; import "./session-sharing-BIP3raq1.mjs"; import { n as GitHubIdentityError } from "./github-read-identity-DyhbpOtm.mjs"; import { f as resolveConfiguredGitHubToolIdentity } from "./github-tool-identity-41SK6r8O.mjs"; import { t as runGitReadOperation } from "./git-read-cache-DAtcfAms.mjs"; import { t as assertionSucceeds } from "./assertion-BVvbcE3a.mjs"; import { s as withReadySessionRows } from "./session-row-prepared-read-B4U_T7SO.mjs"; import { r as resolveControlUiSessionPrTarget, t as createControlUiSessionPrRead } from "./control-ui-session-pr-read-DJu6I6Wb.mjs"; import { n as parseControlUiSessionPullRequestsSubscribeParams } from "./control-ui-session-pr-subscriptions-Ck2vpW-r.mjs"; import { t as withControlUiSessionPrSource } from "./control-ui-session-pr-source-BLvs0jy1.mjs"; import { n as truncateOptionalText } from "./text-truncate-BXvItwne.mjs"; import { t as respondError } from "./response-C7fEiIN1.mjs"; import { t as retainGatewaySessionEntryReadOnly } from "./session-utils-read-lifetime-Cx8swkJr.mjs"; import { t as prepareGatewayProjectGitHubIdentity } from "./project-github-identity-C7QItnuD.mjs"; import { t as resolveAgentIdOrRespondError } from "./agent-id-shared-YyMfd879.mjs"; import { t as prepareGitHubReaderIdentity } from "./github-reader-identity-G6HhPtgS.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/gateway/control-ui-session-github-read.ts /** Private presentation borrows the current visible session's existing App reader. */ async function withControlUiSessionGitHubRead(e, t, n, r, i) { const { params: a, client: o, context: s, signal: c, hasCurrentClientAuthority: l } = e; const u = s.getRuntimeConfig(); const d = resolveConfiguredGitHubHost(u); const f = resolveConfiguredGitHubApiBaseUrl(u); const unavailable = () => new gitHubPublicApi.ControlUiGitHubError(404, "GitHub link is outside the current session or unavailable to this reader"); if (!o || typeof a.sessionKey !== "string" || !a.sessionKey.trim() || a.githubHost !== d || d === "github.com") throw unavailable(); const assertClient = () => { c?.throwIfAborted(); if (o.connectionSignal?.aborted || o.invalidated || s.getRuntimeConfig() !== u || (l ? !l() : !o.connId || !s.getClientConnIds?.((e) => e === o).has(o.connId))) throw unavailable(); }; assertClient(); const p = await createControlUiSessionPrRead({ client: o, sessionKey: a.sessionKey, agentId: t, getRuntimeConfig: s.getRuntimeConfig, getSessionRowProjection: () => getSessionRowProjection(s), isCurrentClient: () => assertionSucceeds(assertClient) })?.(); if (!p?.sessionId) throw unavailable(); const m = p.sessionId; return withControlUiSessionPrSource(p.readSource, async (e) => { const assertCurrent = () => { assertClient(); p.assertCurrent?.(); e(); }; assertCurrent(); const a = typeof p.source === "string" ? await runGitReadOperation({ type: "checkout.context", input: { root: p.source, githubHost: d } }) : p.source; assertCurrent(); if (!a || (a.host ?? "github.com") !== d || a.owner.toLowerCase() !== n.owner.toLowerCase() || a.repo.toLowerCase() !== n.repo.toLowerCase()) throw unavailable(); const l = resolveConfiguredGitHubToolIdentity({ config: u, agentId: t, scope: "agent" }) ?? resolveConfiguredGitHubToolIdentity({ config: u, agentId: t, scope: "system" }); const h = l?.kind === "app-installation" && l.app.repositories.find((e) => e.fullName.toLowerCase() === `${n.owner}/${n.repo}`.toLowerCase()); if (!h) throw unavailable(); const g = `https://${d}/${encodeURIComponent(n.owner)}/${encodeURIComponent(n.repo)}/${n.kind === "pull" ? "pull" : n.kind === "issue" ? "issues" : "commit"}/${n.kind === "commit" ? n.sha : n.number}`; const _ = await prepareGatewayProjectGitHubIdentity({ config: u, context: s, client: o, agentId: t, requestedRepository: `${a.owner}/${a.repo}`, assertActive: assertCurrent, factoryCredential: { claim: { purpose: "session-item-read", binding: { kind: "session", agentId: t, sessionKey: p.params.sessionKey, sessionId: m, lifecycleRevision: p.lifecycleRevision ?? null, requestDigest: sha256Hex(g) } }, assertCurrent } }); if (!_?.token) { await _?.revoke?.(); throw unavailable(); } let v; try { assertCurrent(); const assertSelected = () => { assertCurrent(); _.assertSelected(); }; v = await r({ ..._, host: d, apiBaseUrl: f, signal: c, repository: { id: h.id, owner: a.owner, repo: a.repo }, cacheScope: JSON.stringify([ d, f, h.id, o.authenticatedUserProfile?.profileId, o.authenticatedFactoryGitHubAccountId, p.identity, _.cacheScope ]), assertSelected, revalidate: async () => { assertCurrent(); await _.revalidate(); assertCurrent(); } }); assertSelected(); } finally { await _.revoke?.(); } assertCurrent(); _.assertSelected(); i(v); return v; }); } //#endregion //#region src/gateway/server-methods/control-ui.ts var GitHubReadRequestInactiveError = class extends Error { constructor() { super("GitHub request is no longer active. Try again."); } }; async function prepareControlUiGitHubIdentity({ context: e, client: t, signal: n, hasCurrentClientAuthority: r }, i) { const assertActive = () => { if (n?.aborted || (r ? !r() : t?.connId && !e.getClientConnIds?.((e) => e === t).has(t.connId))) throw new GitHubReadRequestInactiveError(); }; return prepareGitHubReaderIdentity(e, i, assertActive); } function createGitHubReadHandler(e, t, n, r) { return async (i) => { const { params: a, respond: o, context: s } = i; const c = t(a); const l = a.section; if (!c || a.refresh !== void 0 && typeof a.refresh !== "boolean" || l !== void 0 && (e !== "controlUi.githubDetail" || l !== "overview" && l !== "checks" && l !== "files" && l !== "discussion")) { respondError(o, ErrorCodes.INVALID_REQUEST, `invalid ${e} params`); return; } const u = resolveAgentIdOrRespondError({ rawAgentId: a.agentId, respond: o, cfg: s.getRuntimeConfig() }); if (!u) return; const d = performance.now(); let f; try { if (a.sessionKey !== void 0 || a.githubHost !== void 0) { await withControlUiSessionGitHubRead(i, u.agentId, c, (e) => r(c, e, void 0, a.refresh === true, l), (e) => o(true, e, void 0)); return; } const { identity: e, assertSelected: t } = await prepareControlUiGitHubIdentity(i, u.agentId); t(); f = performance.now(); const s = await n(c, e, void 0, a.refresh === true, l); t(); o(true, s, void 0); } catch (e) { const { message: t, ...n } = e instanceof GitHubReadRequestInactiveError ? { message: e.message, retryable: false } : e instanceof GitHubIdentityError ? { message: e.message, retryable: false } : gitHubPublicApi.formatControlUiGitHubPreviewError(e); o(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, t, n)); } finally { const t = performance.now(); if (e === "controlUi.githubPreview" && t - d >= 500) s.logGateway?.info("Slow GitHub preview handler", { identityMs: Math.round((f ?? t) - d), loadMs: f === void 0 ? 0 : Math.round(t - f) }); } }; } const SESSION_PREVIEW_TEXT_MAX_CHARS = 200; function parseSessionPreviewKey(e) { if (!isRecord(e) || Object.keys(e).some((e) => e !== "sessionKey")) return null; const t = typeof e.sessionKey === "string" ? e.sessionKey.trim() : ""; return t && t.length <= 512 ? t : null; } function projectSessionPreview(e) { if (!e) return { status: "unavailable" }; const t = truncateOptionalText(e.lastMessagePreview, SESSION_PREVIEW_TEXT_MAX_CHARS); const n = truncateOptionalText(e.title, SESSION_PREVIEW_TEXT_MAX_CHARS); const r = truncateOptionalText(e.derivedTitle, SESSION_PREVIEW_TEXT_MAX_CHARS); const i = truncateOptionalText(e.kind, 64); const a = truncateOptionalText(e.channel, 80); return { status: "ok", sessionKey: e.sessionKey, agentId: e.agentId, ...n ? { title: n } : {}, ...r ? { derivedTitle: r } : {}, ...i ? { kind: i } : {}, ...a ? { channel: a } : {}, ...typeof e.updatedAt === "number" && Number.isFinite(e.updatedAt) ? { updatedAt: e.updatedAt } : {}, ...t ? { lastMessagePreview: t } : {}, ...typeof e.archived === "boolean" ? { archived: e.archived } : {} }; } async function withControlUiSessionPreview(e, t, n, r) { const i = getSessionRowProjection(t); if (!i) { r(null); return; } const a = t.getRuntimeConfig(); const o = resolveRequestedSessionAgentId(a, e); const s = o.ok ? i.readPreview({ key: e, agentId: o.agentId }) : null; if (s !== void 0 && !(operatorSessionCap(n, a) === "invited" && i.needsMembershipPreparation())) { const t = createSessionListEntryFilter({ client: n, cfg: a, membership: o.ok ? i.readMembership({ key: e, agentId: o.agentId }) : void 0 }); r(s && (!t || t(s.sessionKey, s.entry)) ? s : null); return; } await withReadySessionRows(i, (t) => { const n = resolveRequestedSessionAgentId(t, e); return n.ok ? [{ key: e, agentId: n.agentId }] : []; }, (i) => { const a = t.getRuntimeConfig(); const o = resolveRequestedSessionAgentId(a, e); const s = o.ok ? i.describe({ key: e, agentId: o.agentId }) : void 0; const c = createSessionListEntryFilter({ client: n, cfg: a, membership: s?.membership }); if (!s || c && !c(s.key, s.entry)) { r(null); return; } const l = i.present(s, { includeDerivedTitles: true, includeLastMessage: true }); r({ sessionKey: l.key, agentId: s.agentId, title: l.displayName, derivedTitle: l.derivedTitle, kind: l.kind, channel: l.channel, updatedAt: l.updatedAt, lastMessagePreview: l.lastMessagePreview, archived: l.archived }); }); } function parseCheckDetailsParams(e) { if (Object.keys(e).some((e) => ![ "sessionKey", "owner", "repo", "number", "headSha" ].includes(e))) return null; const t = typeof e.sessionKey === "string" ? e.sessionKey.trim() : ""; const n = typeof e.headSha === "string" ? e.headSha : ""; const r = gitHubPublicApi.parseControlUiGitHubPreviewTarget({ ...e, kind: "pull" }); return r?.kind === "pull" && t && t.length <= 512 && /^[0-9a-f]{40}$/i.test(n) ? { sessionKey: t, owner: r.owner, repo: r.repo, number: r.number, headSha: n.toLowerCase() } : null; } async function prepareCheckDetailsSession(e, t, n) { const r = t.getRuntimeConfig(); const i = resolveRequestedSessionAgentId(r, e); if (!i.ok) return null; const a = [ "repositoryWorkspaceId", "worktree", "spawnedCwd", "spawnedWorkspaceDir", "pendingWorktree", "pendingProjectGitUrl", "deviceFolder" ]; const o = await retainGatewaySessionEntryReadOnly(e, i.agentId, (e, t) => a.every((n) => isDeepStrictEqual(e[n], t[n])), r, { exactRead: true }); let s = false; try { const e = o.entry; if (!e?.sessionId) return null; const r = e.repositoryWorkspaceId; const i = r ? await getSessionRepositoryWorkspaceStore().prepare(r) : void 0; const current = () => { n(); const a = t.getRuntimeConfig(); if (!o.isCurrentAtResponse() || createSessionListEntryFilter({ cfg: a, client: null })?.(o.canonicalKey, e) === false) return; const s = i?.current(); return resolveControlUiSessionPrTarget({ ...o, cfg: a }, s?.workspaceId === r && s?.agentId === o.agentId && s.sessionKey === o.canonicalKey ? s : null); }; const a = current(); if (!a) return null; s = true; return { ...a, release: o.release, assertCurrent() { if (current()?.identity !== a.identity) throw new Error("Session pull-request target changed"); } }; } finally { if (!s) o.release(); } } const controlUiHandlers = { "controlUi.linkPreview": async ({ params: e, client: t, context: n, respond: r, signal: i, hasCurrentClientAuthority: a }) => { const revision = () => JSON.stringify([ getRuntimeConfigSnapshotMetadata()?.revision, t?.authenticatedUserId, t?.authenticatedUserProfile?.profileId ]); const o = { principal: t ?? n, revision: revision() }; const isEnabled = () => !t?.connectionSignal?.aborted && a?.() !== false && revision() === o.revision && n.getRuntimeConfig().gateway?.controlUi?.automaticallyFetchFavicons !== false; if (i?.aborted || !isEnabled()) { r(true, {}, void 0); return; } const { parseControlUiLinkPreviewUrl: s, loadControlUiLinkPreview: c } = await import("./control-ui-link-preview-C5qILQ0S.mjs"); const l = Object.keys(e).every((e) => e === "url") ? s(e.url) : null; if (!l) { respondError(r, ErrorCodes.INVALID_REQUEST, "invalid controlUi.linkPreview params"); return; } const u = await c(l, isEnabled, o); r(true, !i?.aborted && isEnabled() ? u : {}, void 0); }, "controlUi.githubPreview": createGitHubReadHandler("controlUi.githubPreview", (e) => gitHubPublicApi.parseControlUiGitHubPreviewTarget(e), (...e) => gitHubPublicApi.loadControlUiGitHubPreview(...e), (e, t, n) => gitHubPublicApi.loadSessionGitHubPreview(e, t, n)), "controlUi.githubDetail": createGitHubReadHandler("controlUi.githubDetail", (e) => gitHubPublicApi.parseGitHubTarget(e), (e, t, n, r, i) => gitHubPublicApi.loadGitHubDetail(e, t, n, r, void 0, i), (...e) => gitHubPublicApi.loadSessionGitHubDetail(...e)), "controlUi.sessionPreview": async ({ params: e, client: t, context: n, respond: r, signal: i, hasCurrentClientAuthority: a }) => { const o = parseSessionPreviewKey(e); if (!o) { respondError(r, ErrorCodes.INVALID_REQUEST, "invalid controlUi.sessionPreview params"); return; } try { while (!getSubagentSessionListReadSnapshotIdentity()) await prepareSubagentSessionListReadCache(); i?.throwIfAborted(); const consume = (e) => { i?.throwIfAborted(); if (a?.() === false) throw new Error("Session preview request is no longer active"); r(true, projectSessionPreview(e), void 0); }; await withControlUiSessionPreview(o, n, t, consume); } catch { r(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "Session preview unavailable")); } }, "controlUi.sessionPullRequests.checks": async ({ params: e, client: t, context: n, respond: r, signal: i }) => { const a = parseCheckDetailsParams(e); if (!a) { respondError(r, ErrorCodes.INVALID_REQUEST, "invalid controlUi.sessionPullRequests.checks params"); return; } let o = null; try { const e = t ? createControlUiSessionPrRead({ allowOwnImportedPullRequest: true, client: t, sessionKey: a.sessionKey, getRuntimeConfig: n.getRuntimeConfig, getSessionRowProjection: () => getSessionRowProjection(n), isCurrentClient: () => !t.connId || n.getClientConnIds?.((e) => e === t).has(t.connId) === true }) : void 0; const s = t ? await e?.() ?? null : o = await prepareCheckDetailsSession(a.sessionKey, n, () => i?.throwIfAborted()); if (!s) throw new gitHubPublicApi.ControlUiGitHubError(404, "Session CI details unavailable"); let c; let l; const assertCurrent = () => { let e = false; try { s.assertCurrent?.(); c?.(); e = true; } catch {} if (i?.aborted || !e) throw new gitHubPublicApi.ControlUiGitHubError(409, "Session changed; reopen CI details"); }; await withControlUiSessionPrSource(s.readSource, async (e, t) => { const assertReadCurrent = () => { e(); assertCurrent(); }; assertReadCurrent(); const { loadControlUiSessionPullRequestChecks: n } = await import("./control-ui-session-pr-check-details-BYUn7uTM.mjs"); const { loadControlUiSessionPullRequests: i } = await import("./control-ui-session-prs-BmcJuM-k.mjs"); const o = await n({ ...a, agentId: s.params.agentId }, { sessionScope: s.identity, credential: () => l, assertCurrent: assertReadCurrent, loadPullRequests: (e) => i(e, { read: { target: s, sourceIdentity: t, assertCurrent: assertReadCurrent, retainReadAuthority: (e, t) => { c = e; l = t; } } }) }); assertReadCurrent(); r(true, o, void 0); }); } catch (e) { const t = e instanceof gitHubPublicApi.ControlUiGitHubError && (e.statusCode === 404 || e.statusCode === 409) ? e.message : gitHubPublicApi.formatControlUiGitHubPreviewError(e).message; r(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, t)); } finally { o?.release(); } }, "controlUi.sessionPullRequests.subscribe": ({ params: e, client: t, context: n, respond: r }) => { const i = parseControlUiSessionPullRequestsSubscribeParams(e); if (!i) { respondError(r, ErrorCodes.INVALID_REQUEST, "invalid controlUi.sessionPullRequests.subscribe params"); return; } const a = t?.connId?.trim(); const o = n.controlUiSessionPullRequests; if (!a || !o) { respondError(r, ErrorCodes.UNAVAILABLE, "session pull request subscriptions unavailable"); return; } o.replace(a, i.sessionKeys, i.refreshSessionKeys.length > 0 ? new Set(i.refreshSessionKeys) : void 0, i.passiveSessionKeys ? new Set(i.passiveSessionKeys) : void 0).catch((e) => { n.logGateway.warn(`Failed to prepare Control UI pull request subscriptions; retry the subscription: ${String(e)}`); }); r(true, { subscribed: i.sessionKeys.length > 0 || Boolean(i.passiveSessionKeys?.length) }, void 0); } }; //#endregion export { controlUiHandlers };