UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

655 lines (654 loc) • 22.5 kB
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { x as registerOpenClawStateDatabaseLifecycleListener } from "./openclaw-state-db-cache-CkwtTqzF.mjs"; import { n as gitHubPublicApi } from "./github-public-api-C47tI7vQ.mjs"; import { t as runGitReadOperation } from "./git-read-cache-DAtcfAms.mjs"; import { t as createRetainedCache } from "./retained-cache-Dwkf3ewM.mjs"; import { n as readTaskPullRequestReceipts } from "./control-ui-session-task-prs-CqXfyl6N.mjs"; import { t as captureOwnGitHubPullRequestReader } from "./github-publication-inspect-reader-B7C2nwns.mjs"; import { t as recordSessionPrDiagnostic } from "./control-ui-session-pr-diagnostics-WC-f6nil.mjs"; import { a as prepareSessionPullRequestGitHubRead, i as createGitHubReadGroup, n as fetchSessionPullRequestCheckRollup, r as sessionPullRequestRepositoryApiUrl } from "./control-ui-session-prs-checks-CRddYp6P.mjs"; import { t as resolveGitHubForkParent } from "./github-repository-target-B4raqX1R.mjs"; //#region src/gateway/control-ui-session-pr-metadata.ts const metadata = createRetainedCache(); registerOpenClawStateDatabaseLifecycleListener((e) => { if (e.kind !== "opened") metadata.clear(); }); /** One GitHub metadata read per credential/repository/number, across task and branch views. */ async function readSessionPullRequestMetadata(e, t, n, r = {}) { t.assertCurrent(); const i = JSON.stringify([ t.host, t.apiBaseUrl, t.cacheScope, e.owner.toLowerCase(), e.repo.toLowerCase(), e.number, r.bindingIdentity ]); let a = metadata.get(i); const o = Date.now(); const s = !r.expected || !a?.lastGood || pullRequestMetadataSignature(a.lastGood) === r.expected; const c = a && !a.access.signal.aborted && a.startedAt <= o && a.expiresAt > o && (a.failed || s) && (a.failed || !r.refresh || a.startedAt + 1e4 > o); if (!a || a.access.signal.aborted) a = { access: createGitHubReadGroup(), expiresAt: 0, startedAt: 0 }; const l = a; const u = l.access.add(t.assertCurrent, r.signal); try { if (!c || !l.promise) { const e = prepareSessionPullRequestGitHubRead(t.host, l.access.assertCurrent, { signal: l.access.signal, credential: t.credential }); l.startedAt = o; l.failed = false; l.expiresAt = o + 9e4; l.promise = n(e).then((e) => { l.lastGood = e; return e; }, (e) => { l.failed = true; l.expiresAt = Date.now() + (e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429 ? 3e5 : 3e4); throw e; }); metadata.set(i, l); } try { return await racePromiseWithAbortSignal(l.promise, r.signal); } catch (e) { t.assertCurrent(); const n = r.retainFailure?.(e); if (n && l.lastGood) { r.onRetainedFailure?.(e); return l.lastGood; } if (n === false) l.lastGood = void 0; throw e; } } finally { u(); t.assertCurrent(); } } function pullRequestMetadataSignature(e) { return JSON.stringify([ e.state, e.title, e.headSha ]); } function derivePullState(e) { if (readNonBlankString(e.merged_at)) return "merged"; if (e.state !== "open") return "closed"; return e.draft === true ? "draft" : "open"; } function parsePullListItem(e) { if (!isRecord(e)) return null; const t = asFiniteNumber(e.number); const n = readNonBlankString(e.title); const r = readNonBlankString(e.html_url); const i = isRecord(e.base) ? e.base : {}; const a = isRecord(i.repo) ? i.repo : {}; const o = isRecord(a.owner) ? a.owner : {}; const s = readNonBlankString(o.login); const c = readNonBlankString(a.name); const l = isRecord(e.head) ? e.head : {}; const u = isRecord(l.repo) ? l.repo : {}; const d = readNonBlankString(u.full_name); if (!t || !Number.isSafeInteger(t) || t < 1 || !n || !r || !s || !c) return null; const f = isRecord(e.user) ? e.user : {}; const p = readNonBlankString(f.login); return { number: t, title: n, url: r, owner: s, repo: c, state: derivePullState(e), ...p ? { author: { login: p } } : {}, branch: readNonBlankString(l.ref), headSha: readNonBlankString(l.sha), ...d ? { headRepository: d } : {}, baseRef: readNonBlankString(i.ref), mergeCommitSha: readNonBlankString(e.merge_commit_sha) }; } function rethrowRateLimit(e) { if (e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429) throw e; } /** * The facts a chip carries without spending quota on per-PR detail calls. The * rate-limited path renders exactly this, so both callers share one shape. */ function stateOnlyPullRequestChip(e, t) { return { number: e.number, owner: e.owner, repo: e.repo, branch: t, title: e.title, url: e.url, state: e.state, ...e.headSha && /^[0-9a-f]{40}$/i.test(e.headSha) ? { headSha: e.headSha.toLowerCase() } : {}, ...e.author ? { author: e.author } : {} }; } async function finishPullRequest(e, t, n, r) { const i = stateOnlyPullRequestChip(e, t); if (e.state !== "open" && e.state !== "draft") return i; const a = `${sessionPullRequestRepositoryApiUrl({ ...e, apiBaseUrl: n.apiBaseUrl })}/pulls/${e.number}`; const [o, s] = await Promise.all([r === void 0 ? n.request(a).catch(rethrowRateLimit) : Promise.resolve(r), fetchSessionPullRequestCheckRollup({ ...e, apiBaseUrl: n.apiBaseUrl }, n.request).catch(rethrowRateLimit)]); return { ...i, ...isRecord(o) ? { additions: asFiniteNumber(o.additions), deletions: asFiniteNumber(o.deletions), changedFiles: asFiniteNumber(o.changed_files) } : {}, ...s ? { checks: s, checksUrl: `${e.url}/checks` } : {} }; } /** Read the accepted original identity, without treating its observed commit as a head lock. */ async function loadBoundSessionPullRequest(e, t, n) { const [r, i] = e.base.repository.split("/"); if (!r || !i || e.url !== `https://${t.host}/${r}/${i}/pull/${e.number}`) throw new Error("The session pull request association changed"); const a = parsePullListItem(n.preparedDetails); return readSessionPullRequestMetadata({ owner: r, repo: i, number: e.number }, t, async (t) => { const a = n.preparedDetails ?? await t.request(`${sessionPullRequestRepositoryApiUrl({ owner: r, repo: i, apiBaseUrl: t.apiBaseUrl })}/pulls/${e.number}`); const o = parsePullListItem(a); const s = isRecord(a) && isRecord(a.base) ? a.base : void 0; const c = isRecord(a) && isRecord(a.head) ? a.head : void 0; if (!o || o.url !== e.url || o.number !== e.number || o.owner.toLowerCase() !== r.toLowerCase() || o.repo.toLowerCase() !== i.toLowerCase() || !s || !isRecord(s.repo) || s.repo.id !== e.base.repositoryId || !c || c.ref !== e.head.branch || c.repo !== null && (!isRecord(c.repo) || c.repo.id !== e.head.repositoryId)) throw new Error("The session pull request association changed"); try { return await finishPullRequest(o, e.head.branch, t, a); } catch (t) { if (t instanceof gitHubPublicApi.ControlUiGitHubError && t.statusCode === 429) { n.onRetainedFailure(t); return stateOnlyPullRequestChip(o, e.head.branch); } throw t; } }, { ...n, ...a ? { expected: pullRequestMetadataSignature(stateOnlyPullRequestChip(a, e.head.branch)) } : {}, retainFailure: (e) => e instanceof gitHubPublicApi.ControlUiGitHubError && (e.retryable || e.statusCode === 502) }); } //#endregion //#region src/gateway/control-ui-session-prs.ts const SUCCESS_CACHE_MS = 9e4; const RATE_LIMIT_CACHE_MS = 3e5; const FAILURE_CACHE_MS = 3e4; const MAX_PULL_REQUESTS = 3; const branchCache = createRetainedCache(); function branchCacheKey(e, t, n) { return JSON.stringify([ t.host, t.apiBaseUrl, e.owner.toLowerCase(), e.repo.toLowerCase(), e.branch, e.forkHeadCandidates?.map(({ owner: e, repo: t }) => [e.toLowerCase(), t.toLowerCase()]) ?? [], n, t.cacheScope ]); } /** Historical landing facts remain scoped to the current session, source, and credential. */ function readKnownSessionBranchMergedHeads(e, t) { t.assertCurrent(); const n = prepareSessionPullRequestGitHubRead(e.host ?? "github.com", t.assertCurrent); const r = branchCache.get(branchCacheKey(e, n, JSON.stringify([t.target.branchIdentity ?? t.target.identity, t.sourceIdentity]))); n.assertCurrent(); return structuredClone(r?.lastGood?.mergedHeads ?? []); } function branchCreateUrl(e, t) { const n = encodeURIComponent(e.owner); const r = encodeURIComponent(e.repo); const i = t.split("/").map(encodeURIComponent).join("/"); return `https://${e.host ?? "github.com"}/${n}/${r}/pull/new/${i}`; } async function resolveSessionBranch(e, t, n, r) { if (!e.branch || e.branch === e.defaultBranch) return; const i = e.root; if (!i) return { owner: e.owner, repo: e.repo, branch: e.branch, createUrl: branchCreateUrl(e, e.branch) }; const a = await runGitReadOperation({ type: "pull-request.branch-facts", input: { root: i, branch: e.branch, defaultBranch: e.defaultBranch, mergedHeads: t, refreshIndex: r } }, { refresh: n }); if (!a) return; return { owner: e.owner, repo: e.repo, branch: e.branch, ...a.creatable ? { createUrl: branchCreateUrl(e, e.branch) } : {}, ...a.stats ? { additions: a.stats.additions, deletions: a.stats.deletions, changedFiles: a.stats.changedFiles } : {} }; } function parsePullList(e, t) { if (!Array.isArray(e)) return []; return e.map(parsePullListItem).filter((e) => { if (!e) return false; const n = URL.parse(e.url); if (n?.protocol !== "https:" || n.username || n.password || n.hostname !== t) throw new gitHubPublicApi.ControlUiGitHubError(502, "GitHub returned a pull request for another host"); return true; }); } function pullsByHeadUrl(e, t, n, r) { const i = encodeURIComponent(n); return `${sessionPullRequestRepositoryApiUrl({ owner: e, repo: t, apiBaseUrl: r })}/pulls?head=${i}&state=all&sort=updated&direction=desc&per_page=5`; } function mergedHeadsOf(e) { const t = []; for (const n of e) if (n.state === "merged" && n.headSha) t.push({ sha: n.headSha.toLowerCase(), ...n.baseRef ? { baseRef: n.baseRef } : {}, ...n.mergeCommitSha ? { mergeCommitSha: n.mergeCommitSha.toLowerCase() } : {} }); return t; } async function fetchBranchPullRequests(e, t, n) { const r = `${e.owner}:${e.branch}`; let i = parsePullList(await t.request(pullsByHeadUrl(e.owner, e.repo, r, t.apiBaseUrl)), t.host).filter((e) => !e.headRepository || e.headRepository.toLowerCase() === `${e.owner}/${e.repo}`.toLowerCase()); for (const n of e.forkHeadCandidates ?? []) { if (i.length > 0) break; const r = `${n.owner}/${n.repo}`.toLowerCase(); i = parsePullList(await t.request(pullsByHeadUrl(e.owner, e.repo, `${n.owner}:${e.branch}`, t.apiBaseUrl)), t.host).filter((e) => e.headRepository?.toLowerCase() === r); } if (i.length === 0) { const n = resolveGitHubForkParent(await t.request(sessionPullRequestRepositoryApiUrl({ ...e, apiBaseUrl: t.apiBaseUrl }))); if (n) i = parsePullList(await t.request(pullsByHeadUrl(n.owner, n.repo, r, t.apiBaseUrl)), t.host); } const a = mergedHeadsOf(i); const isActive = (e) => e.state === "open" || e.state === "draft"; const o = i.some(isActive); const s = i.toSorted((e, t) => Number(isActive(t)) - Number(isActive(e))).slice(0, MAX_PULL_REQUESTS); const branchOf = (t) => t.branch ?? e.branch ?? ""; const c = i.map((e) => stateOnlyPullRequestChip(e, branchOf(e))); let l; let u = false; try { l = await Promise.all(s.map((e) => readSessionPullRequestMetadata(e, t, (t) => finishPullRequest(e, branchOf(e), t), { refresh: n, expected: pullRequestMetadataSignature(stateOnlyPullRequestChip(e, branchOf(e))) }))); } catch (e) { if (!(e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429)) throw e; l = s.map((e) => stateOnlyPullRequestChip(e, branchOf(e))); u = true; } return { pullRequests: l, rateLimited: u, publicationCandidates: c, mergedHeads: a, workingBranchHasLivePullRequest: o }; } async function refreshBranchPullRequests(e, t, n) { const r = { owner: e.owner, repo: e.repo }; try { const i = { ...await fetchBranchPullRequests(e, t, n.refreshMode === "forced"), repository: r }; if (i.rateLimited) { n.expiresAt = Date.now() + RATE_LIMIT_CACHE_MS; if (n.lastGood) { const identity = (e) => `${e.owner}/${e.repo}#${e.number}`.toLowerCase(); const e = new Map(n.lastGood.pullRequests.map((e) => [identity(e), e])); i.pullRequests = [...i.pullRequests.map((t) => { const n = e.get(identity(t)); e.delete(identity(t)); return n && t.state === n.state && t.headSha === n.headSha && (t.state === "open" || t.state === "draft") ? { ...n, ...t } : t; }), ...e.values()].slice(0, MAX_PULL_REQUESTS); } } const { rateLimited: a, ...o } = i; n.lastGood = o; return i; } catch (e) { t.assertCurrent(); const i = e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429; n.expiresAt = Date.now() + (i ? RATE_LIMIT_CACHE_MS : FAILURE_CACHE_MS); if (i) return { pullRequests: [], publicationCandidates: [], mergedHeads: [], workingBranchHasLivePullRequest: false, ...n.lastGood, repository: r, rateLimited: true }; if (n.lastGood) return { ...n.lastGood, rateLimited: false, status: "unavailable" }; throw e; } } async function loadControlUiSessionPullRequests(e, t) { recordSessionPrDiagnostic("load-entered", t.read.target); if (t.read.target.ownGitHubProfileId && t.read.target.taskReceiptsOnly) return { ...t.read.branchSnapshot ?? { pullRequests: [], rateLimited: false }, branchRead: false }; if (t.read.projection === "publication" || !t.read.target.taskReceipts || t.read.target.ownGitHubProfileId) return loadControlUiSessionBranchPullRequests(e, t); recordSessionPrDiagnostic("branch-started", t.read.target); const n = t.read.target.taskReceiptsOnly ? t.read.branchSnapshot ?? { pullRequests: [], rateLimited: false } : await loadControlUiSessionBranchPullRequests(e, t).catch(() => ({ pullRequests: [], rateLimited: false, status: "unavailable" })); recordSessionPrDiagnostic("branch-returned", t.read.target); if (!t.read.target.taskReceiptsOnly) t.read.onBranchRead?.(n); recordSessionPrDiagnostic("receipts-started", t.read.target); const r = await readTaskPullRequestReceipts({ ...t.read.target.taskReceipts, ...n.pullRequests.length ? { branchUrls: [...new Set(n.pullRequests.map((e) => e.url))] } : {} }, t.read.assertCurrent, t.cacheSignal); recordSessionPrDiagnostic("receipts-returned", t.read.target, { count: r.taskPullRequests.length }); if (t.read.target.taskReceiptsOnly) { recordSessionPrDiagnostic("load-returned", t.read.target); return { ...n, taskPullRequests: r.taskPullRequests, taskPullRequestCount: r.taskPullRequestCount, ...t.read.branchSnapshot ? { pullRequestCount: r.pullRequestCount } : {}, branchRead: false }; } const i = []; let a = false; for (const n of r.taskPullRequests) { const r = new URL(n.url); if (r.hostname !== "github.com" && r.hostname !== t.read.target.githubHost) { i.push(n); continue; } let o; try { const s = prepareSessionPullRequestGitHubRead(r.hostname, t.read.assertCurrent, { signal: t.cacheSignal }); recordSessionPrDiagnostic("metadata-started", t.read.target, { count: i.length }); o = await readSessionPullRequestMetadata(n, s, async (e) => { const t = await e.request(sessionPullRequestRepositoryApiUrl({ ...n, apiBaseUrl: e.apiBaseUrl }) + "/pulls/" + n.number); const i = parsePullListItem(t); if (!i || i.number !== n.number || i.owner.toLowerCase() !== n.owner.toLowerCase() || i.repo.toLowerCase() !== n.repo.toLowerCase() || new URL(i.url).hostname !== r.hostname) throw new Error("GitHub returned another task pull request"); return finishPullRequest(i, i.branch ?? n.branch, e, t); }, { refresh: e.refresh, signal: t.cacheSignal, retainFailure: () => true, onRetainedFailure: () => { a = true; } }); } catch { a = true; t.read.assertCurrent(); } recordSessionPrDiagnostic("metadata-returned", t.read.target, { count: i.length, current: Boolean(o) }); i.push({ ...n, ...o ? { pullRequest: o } : {} }); } t.read.assertCurrent(); recordSessionPrDiagnostic("load-returned", t.read.target); return { ...n, taskPullRequests: i, taskPullRequestCount: r.taskPullRequestCount, pullRequestCount: r.pullRequestCount, ...a && !n.rateLimited ? { status: "unavailable" } : {} }; } async function loadControlUiSessionBranchPullRequests(e, t) { const { target: n, assertCurrent: r, projection: i } = t.read; try { r(); const a = { ...e, ...n.params }; const o = n.ownGitHubProfileId; const s = n.githubPullRequest; if (s && i !== "publication") try { if (!s.preparedHeadCommit || s.host !== n.githubHost) throw new Error("The session pull request is not prepared on the current host"); let e; let i; if (o) { const { readOwnGitHubPullRequest: a } = await import("./github-publication-inspect-B7CRL32r.mjs"); const c = await a({ pullRequestUrl: s.url, agentId: n.params.agentId, reader: captureOwnGitHubPullRequestReader(o, () => s.host), assertCurrent: r }); c.assertCurrent(); const l = c.result; if (!c.credential || l.url !== s.url || l.host !== s.host || l.number !== s.number || l.base.repositoryId !== s.base.repositoryId || l.head && (l.head.repositoryId !== s.head.repositoryId || l.head.branch !== s.head.branch)) throw new Error("The session pull request association changed"); e = c.credential; i = c.details; t.read.retainReadAuthority?.(c.assertIdentityCurrent, e); } const c = prepareSessionPullRequestGitHubRead(s.host, r, { signal: t.cacheSignal, credential: e }); let l = false; let u = false; const d = await loadBoundSessionPullRequest(s, c, { bindingIdentity: JSON.stringify([n.identity, t.read.sourceIdentity]), refresh: a.refresh, signal: t.cacheSignal, preparedDetails: i, onRetainedFailure: (e) => { l = true; u = e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429; } }); r(); return { pullRequests: [d], repository: { owner: d.owner, repo: d.repo }, rateLimited: u, ...l && !u ? { status: "unavailable" } : {} }; } catch (e) { r(); return e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429 ? { pullRequests: [], rateLimited: true, status: "rate-limited" } : { pullRequests: [], discardPrevious: true, rateLimited: false, status: "unavailable" }; } const c = n.source; recordSessionPrDiagnostic("context-started", n); const l = typeof c === "string" ? await runGitReadOperation({ type: "checkout.context", input: { root: c, githubHost: t.read.target.githubHost } }, { refresh: a.refresh }) : c; recordSessionPrDiagnostic("context-returned", n); r(); if (!l) { branchCache.release(t.cacheSignal); return { pullRequests: [], rateLimited: false }; } if (!l.branch || l.branch === l.defaultBranch) { branchCache.release(t.cacheSignal); return { pullRequests: [], repository: { owner: l.owner, repo: l.repo }, rateLimited: false }; } recordSessionPrDiagnostic("branch-cache-started", n); const u = await cachedBranchPullRequests(l, t, a.refresh === true, JSON.stringify([n.branchIdentity ?? n.identity, t.read.sourceIdentity])).catch(() => null); recordSessionPrDiagnostic("branch-cache-returned", n); r(); if (!u) return { pullRequests: [], repository: { owner: l.owner, repo: l.repo }, rateLimited: false, status: "unavailable" }; const { publicationCandidates: d, mergedHeads: f, workingBranchHasLivePullRequest: p, ...m } = u; recordSessionPrDiagnostic("branch-facts-started", n); const h = i === "publication" || p ? void 0 : await resolveSessionBranch(l, f, a.refresh === true, n.refreshIndex === true); recordSessionPrDiagnostic("branch-facts-returned", n); r(); return { ...m, pullRequests: i === "publication" ? d : m.pullRequests, ...h ? { branch: h } : {} }; } catch (e) { branchCache.release(t.cacheSignal); throw e; } } function trackBranchRefresh(e, t, n) { e.expiresAt = Date.now() + SUCCESS_CACHE_MS; e.refreshMode = t; const r = n().finally(() => { if (e.promise === r) e.refreshMode = null; }); e.promise = r; return r; } async function cachedBranchPullRequests(e, t, n, r) { let i; try { i = prepareSessionPullRequestGitHubRead(e.host ?? "github.com", t.read.assertCurrent); } catch (e) { branchCache.release(t.cacheSignal); throw e; } const a = branchCacheKey(e, i, r); const o = branchCache.get(a, t.cacheSignal) ?? { access: createGitHubReadGroup(), expiresAt: 0, promise: Promise.resolve({ pullRequests: [], publicationCandidates: [], rateLimited: false, mergedHeads: [], workingBranchHasLivePullRequest: false }), refreshMode: null }; const s = o.expiresAt > Date.now() && !o.access.signal.aborted; if (o.access.signal.aborted) o.access = createGitHubReadGroup(); const c = o.access.add(i.assertCurrent, t.cacheSignal); const l = prepareSessionPullRequestGitHubRead(i.host, o.access.assertCurrent, { signal: o.access.signal }); try { if (s) { branchCache.set(a, o, t.cacheSignal); if (!n || o.refreshMode === "forced") return await racePromiseWithAbortSignal(o.promise, t.cacheSignal); const r = o.promise; const i = o.refreshMode; const s = o.expiresAt; return await racePromiseWithAbortSignal(trackBranchRefresh(o, "forced", async () => { const t = await r; l.assertCurrent(); if (t.rateLimited) { if (i === null) o.expiresAt = s; return t; } return refreshBranchPullRequests(e, l, o); }), t.cacheSignal); } const r = trackBranchRefresh(o, n ? "forced" : "normal", () => refreshBranchPullRequests(e, l, o)); branchCache.set(a, o, t.cacheSignal); return await racePromiseWithAbortSignal(r, t.cacheSignal); } finally { c(); i.assertCurrent(); } } //#endregion export { readKnownSessionBranchMergedHeads as n, loadControlUiSessionPullRequests as t };