UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

292 lines (291 loc) • 10.1 kB
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as gitHubPublicApi } from "./github-public-api-C47tI7vQ.mjs"; import { t as recordSessionPrDiagnostic } from "./control-ui-session-pr-diagnostics-WC-f6nil.mjs"; //#region src/gateway/control-ui-session-pr-request.ts /** Shared I/O survives one reader's retirement while each reader owns its delivery. */ function createGitHubReadGroup() { const e = /* @__PURE__ */ new Set(); const t = new AbortController(); const assertCurrent = () => { t.signal.throwIfAborted(); let n = new gitHubPublicApi.ControlUiGitHubError(409, "GitHub read has no active reader"); for (const t of e) try { t(); return; } catch (e) { n = e; } t.abort(n); throw n; }; return { signal: t.signal, assertCurrent, add(t, n) { const reader = () => { n?.throwIfAborted(); t(); }; reader(); e.add(reader); const release = () => { e.delete(reader); n?.removeEventListener("abort", onAbort); }; const onAbort = () => { release(); try { assertCurrent(); } catch {} }; n?.addEventListener("abort", onAbort, { once: true }); return release; } }; } /** Session reads pin the admitted host, endpoint and credential across every auxiliary request. */ function prepareSessionPullRequestGitHubRead(e, t, n = {}) { const r = fetch; const i = n.credential; const a = !i && n.optionalAuth !== false; const o = i ? { token: i.token, apiBaseUrl: i.apiBaseUrl, cacheScope: `${e}:${i.apiBaseUrl}:${gitHubPublicApi.githubApiCredentialCacheScope(i.token)}` } : gitHubPublicApi.resolveGitHubApiCredentialScope(void 0, e); const assertCurrent = () => { t(); i?.assertCurrent(); if (!i && gitHubPublicApi.resolveGitHubApiCredentialScope(void 0, e).cacheScope !== o.cacheScope) throw new gitHubPublicApi.ControlUiGitHubError(409, "GitHub identity changed; reopen the session pull request"); }; const s = { assertSelected: assertCurrent, revalidate: async () => assertCurrent() }; return { ...o, host: e, credential: i, assertCurrent, async request(e, t, i, c) { assertCurrent(); const l = [i, n.signal].filter((e) => Boolean(e)); const u = l.length > 1 ? AbortSignal.any(l) : l[0]; const readJson = async (n) => { recordSessionPrDiagnostic("github-fetch-started"); const { value: i } = await gitHubPublicApi.fetchGitHubJsonPage(e, r, n, { beforeRedirect: c, identity: s, signal: u, apiBaseUrl: o.apiBaseUrl, maxBytes: t }); recordSessionPrDiagnostic("github-fetch-returned"); recordSessionPrDiagnostic("github-json-returned"); return i; }; const d = a ? await gitHubPublicApi.withOptionalGitHubAuth(o.token, readJson) : await readJson(o.token); assertCurrent(); recordSessionPrDiagnostic("github-request-returned"); return d; } }; } //#endregion //#region src/gateway/control-ui-session-prs-checks.ts const FAILING_CHECK_CONCLUSIONS = /* @__PURE__ */ new Set([ "failure", "timed_out", "cancelled", "action_required", "startup_failure" ]); const PAGE_SIZE = 100; const MAX_PAGES = 10; const PAGE_BYTES = 1048576; const MAX_ACTIONS_SUITES = 20; const MAX_STEPS = 200; function sessionPullRequestCheckState(e, t) { if (typeof t === "string" && FAILING_CHECK_CONCLUSIONS.has(t)) return "failed"; if (e !== "completed" || t === "stale") return "running"; return t === "skipped" ? "skipped" : "passed"; } function sessionPullRequestRepositoryApiUrl(e) { return `${e.apiBaseUrl}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`; } function incomplete() { return new gitHubPublicApi.ControlUiGitHubError(502, "GitHub CI details were incomplete or changed while loading"); } /** One bounded pagination owner serves both the compact rollup and on-demand detail. */ async function fetchSessionPullRequestCheckRuns(e, t) { return fetchPages(`${sessionPullRequestRepositoryApiUrl(e)}/commits/${e.headSha}/check-runs?filter=latest`, "check_runs", t); } async function fetchPages(e, t, n) { const r = []; let i; for (let a = 1; a <= MAX_PAGES; a += 1) { const o = await n(`${e}&per_page=${PAGE_SIZE}&page=${a}`, PAGE_BYTES); if (!isRecord(o)) throw incomplete(); const s = o[t]; const c = o.total_count; if (!Array.isArray(s) || s.length > PAGE_SIZE || typeof c !== "number" || !Number.isSafeInteger(c) || c < 0 || c > 1e3 || i !== void 0 && i !== c) throw incomplete(); i = c; for (const e of s) { if (!isRecord(e)) throw incomplete(); r.push(e); } if (r.length === c) return r; if (r.length > c || s.length < PAGE_SIZE) throw incomplete(); } throw incomplete(); } async function fetchSessionPullRequestCheckRollup(e, t) { if (!e.headSha || !/^[0-9a-f]{40}$/i.test(e.headSha)) return; const n = await fetchSessionPullRequestCheckRuns({ ...e, headSha: e.headSha }, t); if (n.length === 0) return; const r = { passed: 0, failed: 0, skipped: 0, running: 0 }; for (const e of n) r[sessionPullRequestCheckState(e.status, e.conclusion)] += 1; return { state: r.failed > 0 ? "failing" : r.running > 0 ? "pending" : "passing", ...r }; } function positiveId(e) { if (typeof e !== "number" || !Number.isSafeInteger(e) || e <= 0) throw incomplete(); return e; } function text(e, t = 512) { const n = readNonBlankString(e); if (!n || n.length > t) throw incomplete(); return n; } function timing(e) { const timestamp = (e) => { if (e === null || e === void 0) return; const t = text(e, 40); if (!Number.isFinite(Date.parse(t))) throw incomplete(); return t; }; return { startedAt: timestamp(e.started_at), completedAt: timestamp(e.completed_at) }; } function readConclusion(e) { return e === null || e === void 0 ? void 0 : text(e, 64); } function safeCheckLink(e) { if (typeof e !== "string" || e.length > 2048) return; const t = URL.parse(e); return t?.protocol === "https:" && !t.username && !t.password ? t.href : void 0; } function parseChecks(e, t) { const n = /* @__PURE__ */ new Set(); return e.map((e) => { const r = positiveId(e.id); if (n.has(r) || e.head_sha !== t.headSha) throw incomplete(); n.add(r); const i = isRecord(e.app) && e.app.slug === "github-actions" ? "actions" : "check"; const a = text(e.status, 64); const o = readConclusion(e.conclusion); return { check: { id: r, name: text(e.name), status: a, conclusion: o, state: sessionPullRequestCheckState(a, o), source: i, detailsUrl: safeCheckLink(e.details_url ?? e.html_url), ...timing(e) }, ...i === "actions" && isRecord(e.check_suite) ? { suiteId: positiveId(e.check_suite.id) } : {} }; }); } function parseSteps(e) { if (!Array.isArray(e) || e.length > MAX_STEPS) throw incomplete(); const t = /* @__PURE__ */ new Set(); return e.map((e) => { if (!isRecord(e)) throw incomplete(); const n = positiveId(e.number); if (t.has(n)) throw incomplete(); t.add(n); return { number: n, name: text(e.name), status: text(e.status, 64), conclusion: readConclusion(e.conclusion), ...timing(e) }; }).toSorted((e, t) => e.number - t.number); } async function loadSuiteJobs(e, t, n, r) { const i = sessionPullRequestRepositoryApiUrl(e); const a = await fetchPages(`${i}/actions/runs?head_sha=${e.headSha}&check_suite_id=${t}`, "workflow_runs", r); if (a.length !== 1 || a[0]?.check_suite_id !== t || a[0]?.head_sha !== e.headSha) throw incomplete(); const o = positiveId(a[0].id); const s = a[0].run_attempt === void 0 ? void 0 : positiveId(a[0].run_attempt); const c = await fetchPages(`${i}/actions/runs/${o}/jobs?filter=all`, "jobs", r); const l = new Map(n.filter((e) => e.suiteId === t).map(({ check: e }) => [`${i}/check-runs/${e.id}`.toLowerCase(), e])); const u = /* @__PURE__ */ new Map(); for (const t of c) { if (t.run_id !== o || t.head_sha !== e.headSha || t.run_attempt !== void 0 && s !== void 0 && positiveId(t.run_attempt) > s) throw incomplete(); const n = typeof t.check_run_url === "string" ? l.get(t.check_run_url.toLowerCase()) : void 0; if (!n) continue; if (u.has(n.id)) throw incomplete(); const r = positiveId(t.id); const i = text(t.status, 64); const a = readConclusion(t.conclusion); u.set(n.id, { ...n, status: i, conclusion: a, state: sessionPullRequestCheckState(i, a), ...timing(t), detailsUrl: `https://${e.host}/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}/actions/runs/${o}/job/${r}`, steps: parseSteps(t.steps ?? []) }); } if ([...l.values()].some((e) => e.state !== "skipped" && !u.has(e.id))) throw incomplete(); return u; } /** Checks remain useful when Actions permissions, history, or the bounded detail budget fail. */ async function fetchSessionPullRequestCheckDetails(e, t) { const n = parseChecks(await fetchSessionPullRequestCheckRuns(e, t), e); const r = { failed: 0, running: 1, passed: 2, skipped: 3 }; const compareChecks = (e, t) => r[e.state] - r[t.state] || e.name.localeCompare(t.name) || e.id - t.id; const i = n.toSorted((e, t) => compareChecks(e.check, t.check)); const a = [...new Set(i.filter(({ check: e }) => e.source === "actions" && e.state !== "skipped").map(({ suiteId: e }) => e))]; let o; const s = /* @__PURE__ */ new Map(); for (const r of a.slice(0, MAX_ACTIONS_SUITES)) try { if (r === void 0) throw incomplete(); const i = await loadSuiteJobs(e, r, n, t); for (const [e, t] of i) s.set(e, t); } catch (e) { o = e; if (e instanceof gitHubPublicApi.ControlUiGitHubError && e.statusCode === 429) break; } if (a.length > MAX_ACTIONS_SUITES && !o) o = new gitHubPublicApi.ControlUiGitHubError(502, "Some Actions steps exceeded the CI detail limit; open the job on GitHub"); return { checks: i.map(({ check: e }) => s.get(e.id) ?? e).toSorted(compareChecks), error: o }; } //#endregion export { prepareSessionPullRequestGitHubRead as a, createGitHubReadGroup as i, fetchSessionPullRequestCheckRollup as n, sessionPullRequestRepositoryApiUrl as r, fetchSessionPullRequestCheckDetails as t };