openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
464 lines (463 loc) • 22.6 kB
JavaScript
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { n as resolveGitHubHost } from "./github-host-runtime-CMm44VF1.mjs";
import { s as prepareGitHubPublicationRepositoryIdentity, t as assertExpectedSharedGitHubPublisher } from "./github-publication-availability-BPmIEgKL.mjs";
import { a as GitHubPublicationBranchChangedError, c as GitHubPublicationRequesterUnavailableError, f as GitHubPublicationWorkspaceChangedError, l as GitHubPublicationSessionBranchMismatchError, s as GitHubPublicationKnownFailure, t as GitHubPublicationRecoveryPendingError } from "./github-publication-git-index-DZcaQ_xd.mjs";
import { t as parseGitHubRemoteUrl } from "./github-remote-xiDM0pdC.mjs";
import { n as resolveGitHubRepositoryTarget } from "./github-repository-target-B4raqX1R.mjs";
import { r as projectGitHubPublicationResult } from "./github-publication-receipt-CYjil9rT.mjs";
import { r as parseGitHubPublicationBaseBranch } from "./github-publication-base-CnZoRiw5.mjs";
import { _ as requirePublicationCommand, c as githubPublicationApiArgs, v as runPublicationCommand } from "./github-publication-git-transport-eGUYv0Ac.mjs";
import { i as readSharedGitHubPublication, t as inspectOwnGitHubPullRequest } from "./github-publication-inspect-_P_HOxPu.mjs";
//#region src/gateway/github-publication-pr-preflight.ts
/** Recheck eligibility and return the observed PR for the caller's remaining effect preconditions. */
async function assertExistingPullRequestWriteAccess(e) {
const { pullRequest: t, identity: n, assertCurrent: r } = e;
r();
if ((n.host ?? "github.com") !== t.host) throw new Error("The GitHub publisher host changed; inspect the PR again before preparation.");
if (t.state !== "open" && t.state !== "draft") throw new Error("This PR is closed or merged; it cannot be continued as an open PR.");
const i = t.head;
if (!i) throw new Error("The original head repository is unavailable. Restore it before continuing this PR.");
const unavailable = () => /* @__PURE__ */ new Error("The original PR's write eligibility could not be verified. Check the head branch and the publisher's access, then retry preparation.");
const read = async (e) => {
r();
const i = await runPublicationCommand(githubPublicationApiArgs(e, "GET", t.host), {
env: n.env,
beforeRun: r
}).catch(() => {
r();
throw unavailable();
});
r();
if (i.code !== 0) throw unavailable();
try {
return JSON.parse(i.stdout.toString("utf8"));
} catch {
throw unavailable();
}
};
const repository = async (t) => {
const n = await read(`repos/${t.repository}`);
if (!isRecord(n) || n.id !== t.repositoryId || n.full_name !== t.repository || typeof n.archived !== "boolean" || !isRecord(n.owner) || typeof n.owner.type !== "string") throw unavailable();
if (e.requirePublicRepositories && n.private !== false) throw new Error("The recorded PR must remain public to continue without a linked GitHub account.");
const r = isRecord(n.permissions) ? n.permissions : void 0;
return {
archived: n.archived,
ownerType: n.owner.type,
push: typeof r?.push === "boolean" ? r.push : void 0
};
};
const a = await repository(t.base);
const o = i.repositoryId === t.base.repositoryId ? a : await repository(i);
if (a.archived || o.archived) throw new Error("The base or head repository is archived. It must be writable before continuing.");
const s = await read(`repos/${t.base.repository}/pulls/${t.number}`);
if (!isRecord(s) || s.number !== t.number || !isRecord(s.user) || s.user.id !== t.author.accountId || s.state !== "open" || s.merged !== false || typeof s.maintainer_can_modify !== "boolean" || !isRecord(s.base) || !isRecord(s.base.repo) || s.base.repo.id !== t.base.repositoryId || s.base.ref !== t.base.branch || !isRecord(s.head) || !isRecord(s.head.repo) || s.head.repo.id !== i.repositoryId || s.head.ref !== i.branch || s.head.sha !== i.commit) throw new Error("The original PR or head changed. Inspect it again before preparing work.");
const c = await read(`repos/${i.repository}/branches/${encodeURIComponent(i.branch)}`);
if (!isRecord(c) || c.name !== i.branch || !isRecord(c.commit) || c.commit.sha !== i.commit || typeof c.protected !== "boolean") throw new Error("The original head branch changed or is unavailable. Inspect it again before preparing work.");
if (!(o.push === true || s.maintainer_can_modify && a.push === true && o.ownerType === "User" && i.repositoryId !== t.base.repositoryId)) {
if (o.push === void 0 || a.push === void 0) throw new Error("GitHub did not expose enough publisher permission information to prepare this PR.");
throw new Error("The publisher has no observed write permission to the original head. Grant repository access or allow maintainer edits on an eligible fork.");
}
if (c.protected) throw new Error("The head branch is protected. Repository permission alone does not establish that the publisher can append commits.");
r();
return s;
}
//#endregion
//#region src/gateway/github-publication-pull-requests.ts
async function readGitHubPublicationApi(e, t, n = []) {
const r = await e.refreshIdentity();
e.assertCurrent();
return {
identity: r,
raw: await requirePublicationCommand([...githubPublicationApiArgs(t, "GET", r.host ?? e.host ?? resolveGitHubHost()), ...n], { env: r.env })
};
}
/** Read only the receipt-selected PR and verify both repository/branch boundaries. */
async function readPublishedGitHubPullRequest(e) {
const t = e.publishedPullRequest;
const { identity: n, raw: r } = await readGitHubPublicationApi(e, `repos/${e.repository}/pulls/${t.number}`);
e.assertCurrent();
const i = JSON.parse(r);
if (!isRecord(i) || i.html_url !== t.url || i.number !== t.number || !isRecord(i.user) || i.user.id !== (e.publisherAccountId ?? n.account.accountId) || !isRecord(i.head) || !isRecord(i.head.repo) || typeof i.head.repo.full_name !== "string" || i.head.repo.full_name.toLowerCase() !== t.pushRepository.toLowerCase() || i.head.ref !== e.branch || !isRecord(i.base) || !isRecord(i.base.repo) || typeof i.base.repo.full_name !== "string" || i.base.repo.full_name.toLowerCase() !== e.repository.toLowerCase() || e.baseBranch !== void 0 && i.base.ref !== e.baseBranch) throw new Error("The original published pull request target changed.");
const [a] = parseGitHubPublicationPullRequests(JSON.stringify([{
url: i.html_url,
userId: i.user.id,
state: i.state,
body: i.body ?? "",
headSha: i.head.sha,
headRef: i.head.ref,
baseRef: i.base.ref
}]));
return {
identity: n,
candidate: a
};
}
async function loadGitHubPublicationPullRequests(e) {
if (e.pullRequest) {
const t = e.pullRequest;
const { identity: n, raw: r } = await readGitHubPublicationApi(e, `repos/${t.base.repository}/pulls/${t.number}`, ["--jq", "{url: .html_url, userId: .user.id, state: .state, body: \"\", headSha: .head.sha, headRef: .head.ref, baseRef: .base.ref, headRepository: .head.repo.full_name, headRepositoryId: .head.repo.id, baseRepository: .base.repo.full_name, baseRepositoryId: .base.repo.id}"]);
const i = JSON.parse(r);
if (!isRecord(i) || i.url !== t.url || i.headRepository !== t.head.repository || i.headRepositoryId !== t.head.repositoryId || i.baseRepository !== t.base.repository || i.baseRepositoryId !== t.base.repositoryId || i.headRef !== t.head.branch || i.baseRef !== t.base.branch) throw new Error("The original GitHub pull request target changed.");
return {
identity: n,
candidates: parseGitHubPublicationPullRequests(JSON.stringify([i]))
};
}
if (e.publishedPullRequest) {
const { identity: t, candidate: n } = await readPublishedGitHubPullRequest({
...e,
publishedPullRequest: e.publishedPullRequest
});
return {
identity: t,
candidates: [n]
};
}
const t = JSON.stringify(e.marker);
const { identity: n, raw: r } = await readGitHubPublicationApi(e, `repos/${e.repository}/pulls`, [
"-f",
`head=${e.pushOwner}:${e.branch}`,
...e.baseBranch ? ["-f", `base=${e.baseBranch}`] : [],
"-f",
"state=all",
"--paginate",
"--jq",
`map({url: .html_url, userId: .user.id, state: .state, body: (if ((.body // "") | contains(${t})) then ${t} else "" end), headSha: .head.sha, headRef: .head.ref, baseRef: .base.ref}) | tojson`
]);
return {
identity: n,
candidates: parseGitHubPublicationPullRequests(r)
};
}
/** Parses the complete authenticated PR lookup; one malformed candidate invalidates the response. */
function parseGitHubPublicationPullRequests(e) {
let t;
try {
t = e.split(/\r?\n/u).map((e) => JSON.parse(e));
} catch (e) {
throw new Error("GitHub pull request lookup returned invalid JSON.", { cause: e });
}
const n = [];
for (const e of t) {
if (!Array.isArray(e)) throw new Error("GitHub pull request lookup returned an invalid response.");
n.push(...e);
}
return n.map((e) => {
if (!isRecord(e)) throw new Error("GitHub pull request lookup returned an invalid candidate.");
const t = e.userId;
const n = readNonBlankString(e.url);
const r = e.state;
const i = e.body;
const a = readNonBlankString(e.headSha);
const o = readNonBlankString(e.headRef);
const s = readNonBlankString(e.baseRef);
if (!Number.isSafeInteger(t) || Number(t) < 1 || !n || r !== "open" && r !== "closed" || typeof i !== "string" || !a || !o || !s) throw new Error("GitHub pull request lookup returned an invalid candidate.");
return {
userId: Number(t),
url: n,
state: r,
body: i,
headSha: a,
headRef: o,
baseRef: s
};
});
}
function matchingGitHubPublicationHeads(e, t) {
return t.candidates.filter((n) => (e.pullRequest || n.userId === t.identity.account.accountId) && n.headSha === e.headCommit && n.headRef === e.branch && (e.baseBranch === void 0 || n.baseRef === e.baseBranch));
}
async function findGitHubPublicationPullRequest(e) {
const { identity: t, candidates: n } = await loadGitHubPublicationPullRequests(e);
if (e.publishedPullRequest && n.some((e) => e.state === "closed")) throw new GitHubPublicationKnownFailure("The original published pull request was closed.", {
code: "github_rejected",
nextAction: "Inspect the original pull request before requesting another publication."
});
const r = matchingGitHubPublicationHeads(e, {
identity: t,
candidates: n
});
const i = r.find((e) => e.state === "open") ?? r.find((t) => t.state === "closed" && t.body.includes(e.marker));
if (i) {
await e.recordObserved?.(i.url);
if (i.state === "closed" && i.body.includes(e.marker)) {
e.assertCurrent();
throw new GitHubPublicationKnownFailure("GitHub pull request was closed before publication completed.", {
code: "github_rejected",
nextAction: "Reopen the closed pull request or retry to create a new publication request."
});
}
}
const a = n.find((t) => t.state === "open" && t.headRef === e.branch && t.baseRef === e.baseBranch);
if (!e.pullRequest && a && a.userId !== t.account.accountId) throw new GitHubPublicationKnownFailure("GitHub pull request is owned by another account.", {
code: "github_rejected",
nextAction: "Check pull-request permission for the effective account, then retry."
});
if (i) return i.url;
e.assertCurrent();
}
/** Observe only the saved request's commit and PR; an absent response proves no non-execution. */
async function reconcileGitHubPublicationPullRequest(e) {
const t = {
...e,
baseBranch: e.readContinuation ? void 0 : e.baseBranch
};
const n = e.beforeRetry ? await loadGitHubPublicationPullRequests(t) : void 0;
if (n && !matchingGitHubPublicationHeads(t, n).some((t) => t.state === "open" || !t.body.includes(e.marker))) return;
const { raw: r } = await readGitHubPublicationApi(e, `repos/${e.pushRepository}/git/commits/${e.headCommit}`);
e.assertCurrent();
const i = JSON.parse(r);
const a = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/iu;
if (!isRecord(i) || i.sha !== e.headCommit || !isRecord(i.tree) || typeof i.tree.sha !== "string" || !a.test(i.tree.sha) || !Array.isArray(i.parents) || typeof i.message !== "string") throw new Error("GitHub publication commit observation is invalid.");
const o = i.parents.map((e) => {
if (!isRecord(e) || typeof e.sha !== "string" || !a.test(e.sha)) throw new Error("GitHub publication commit observation is invalid.");
return e.sha;
});
if (i.tree.sha !== e.workspaceTree || o.length !== 1 || o[0] !== e.parentCommit || !i.message.split(/\r?\n/u).includes(`OpenClaw-Publication: ${e.requestId}`)) return;
const includesCommit = async (t) => {
if (t === e.headCommit) return true;
if (!a.test(t)) throw new Error("GitHub publication head observation is invalid.");
const { raw: n } = await readGitHubPublicationApi(e, `repos/${e.pushRepository}/compare/${e.headCommit}...${t}?per_page=1`, ["--jq", "{sha: .merge_base_commit.sha}"]);
const r = JSON.parse(n);
if (!isRecord(r) || typeof r.sha !== "string" || !a.test(r.sha)) throw new Error("GitHub publication ancestry observation is invalid.");
return r.sha === e.headCommit;
};
let { identity: s, candidates: c } = n ?? await loadGitHubPublicationPullRequests(t);
let l = e.baseBranch;
let u = e.knownPullRequestUrls;
if (e.readContinuation) {
c = c.filter((t) => t.userId === s.account.accountId && t.headRef === e.branch && t.body.includes(e.marker));
l = void 0;
if (c.length === 0) {
const t = await e.readContinuation();
if (t?.publishedPullRequest) {
({identity: s, candidates: c} = await loadGitHubPublicationPullRequests({
...e,
...t
}));
l = t.baseBranch;
u = [t.publishedPullRequest.url];
}
}
}
let d = false;
for (const t of c) {
if (!e.pullRequest && t.userId !== s.account.accountId || t.headRef !== e.branch || l !== void 0 && t.baseRef !== l || !e.pullRequest && !t.body.includes(e.marker) && !u.includes(t.url) && !(e.pushOnly && t.state === "open")) continue;
if (await includesCommit(t.headSha)) {
await e.recordObserved?.(t.url);
return t.url;
}
d = true;
}
if (!e.pushOnly || d) throw new Error("The original GitHub pull request has not been confirmed.");
if (e.pushOnly === "observed") return;
const { raw: f } = await readGitHubPublicationApi(e, `repos/${e.pushRepository}/git/matching-refs/heads/${encodeURIComponent(e.branch)}`);
const p = JSON.parse(f);
if (!Array.isArray(p)) throw new Error("GitHub publication branch observation is invalid.");
const m = p.find((t) => isRecord(t) && t.ref === `refs/heads/${e.branch}`);
if (!isRecord(m) || !isRecord(m.object) || typeof m.object.sha !== "string" || !await includesCommit(m.object.sha)) throw new Error("The original GitHub push has not been confirmed.");
await e.recordPushObserved?.(e.headCommit);
}
//#endregion
//#region src/gateway/github-publication-target.ts
/** A current workspace receipt selects its own PR without granting arbitrary import authority. */
async function preparePublishedPullRequestTarget(e, t) {
if (!e.session) return t;
const n = await readSharedGitHubPublication(e.session, { status: "published" });
e.assertCurrent();
if (!n) return t;
if (!("worktree_id" in n) || n.repository?.toLowerCase() !== t.repository.toLowerCase() || n.branch !== t.branch) throw new GitHubPublicationWorkspaceChangedError("The original publication's repository or head branch changed; saved work was preserved.");
const r = projectGitHubPublicationResult(n).publisher;
const i = URL.parse(n.pull_request_url ?? "");
const a = Number(i?.pathname.split("/").at(-1));
if (!i || !Number.isSafeInteger(a) || a < 1 || i.href.toLowerCase() !== `https://${t.githubHost}/${n.repository}/pull/${a}`.toLowerCase()) throw new GitHubPublicationWorkspaceChangedError("The original publication's PR is invalid.");
const o = {
url: i.href,
number: a,
pushRepository: t.pushRepository
};
const { candidate: s } = await readPublishedGitHubPullRequest({
publishedPullRequest: o,
repository: t.repository,
branch: t.branch,
host: t.githubHost,
publisherAccountId: r?.accountId,
refreshIdentity: async () => e.identity,
assertCurrent: e.assertCurrent
});
if (!e.reconcile && s.state === "closed") return t;
assertExpectedSharedGitHubPublisher(r, {
source: e.identity.source,
...e.identity.account
});
return {
...t,
baseBranch: s.baseRef,
publishedPullRequest: o
};
}
/** A refreshed observation must still name the bound PR and its original repositories/refs. */
function assertBoundGitHubPullRequest(e, t) {
if (t.url !== e.url || t.host !== e.host || t.number !== e.number || !t.head || t.base.repository !== e.base.repository || t.base.repositoryId !== e.base.repositoryId || t.base.branch !== e.base.branch || t.head.repository !== e.head.repository || t.head.repositoryId !== e.head.repositoryId || t.head.branch !== e.head.branch) throw new GitHubPublicationWorkspaceChangedError("The original PR target changed; saved work was preserved.");
}
/** Resolve the authoritative Git remote and GitHub PR parent with the selected publisher. */
async function prepareGitHubPublicationTarget(e) {
const { worktree: t, assertCurrent: n } = e;
const r = e.identity.host ?? resolveGitHubHost();
const i = await prepareGitHubPublicationRepositoryIdentity(e);
if (e.pullRequest) {
const i = e.pullRequest;
if (i.host !== r || !i.preparedHeadCommit || i.preparedHeadCommit !== i.head.commit) throw new GitHubPublicationWorkspaceChangedError("The original PR preparation is incomplete or its publisher host changed.");
const a = await requirePublicationCommand([
"git",
"symbolic-ref",
"--quiet",
"--short",
"HEAD"
], { cwd: t.path });
n();
if (a !== t.branch) throw new GitHubPublicationSessionBranchMismatchError({
session: t.branch,
checkedOut: a
});
return {
pushRepository: i.head.repository,
repository: i.base.repository,
branch: i.head.branch,
baseBranch: i.base.branch,
pushOwner: i.head.repository.split("/")[0],
githubHost: r
};
}
const a = parseGitHubRemoteUrl(i.originUrl, r);
if (!a || !/^[A-Za-z0-9_.-]+$/u.test(a.owner) || !/^[A-Za-z0-9_.-]+$/u.test(a.repo)) throw new Error("GitHub publication requires a GitHub remote.");
const o = `${a.owner}/${a.repo}`;
const s = await requirePublicationCommand([
"git",
"symbolic-ref",
"--quiet",
"--short",
"HEAD"
], { cwd: t.path });
n();
if (s !== t.branch) throw new GitHubPublicationSessionBranchMismatchError({
session: t.branch,
checkedOut: s
});
const c = await requirePublicationCommand([
"gh",
"api",
"--hostname",
r,
`repos/${o}`,
"--jq",
"{fork, default_branch, parent: {name: .parent.name, default_branch: .parent.default_branch, owner: {login: .parent.owner.login}}}"
], { env: e.identity.env });
n();
const l = JSON.parse(c);
const u = resolveGitHubRepositoryTarget(l, a);
if (!u) throw new Error("GitHub repository response omitted its publication target.");
const d = `${u.pullRequest.owner}/${u.pullRequest.repo}`;
const f = u.fork ? u.pullRequest.defaultBranch : parseGitHubPublicationBaseBranch(t.baseRef, u.pullRequest.defaultBranch);
if (!u.fork && s === f) throw new GitHubPublicationWorkspaceChangedError("GitHub publication branch changed to its pull request base.");
return preparePublishedPullRequestTarget(e, {
pushRepository: o,
repository: d,
branch: s,
baseBranch: f,
pushOwner: u.push.owner,
githubHost: r
});
}
/** Keep a recorded attempt's target fixed until any dispatched effect is reconciled. */
async function prepareGitHubPublicationExecutionTarget(e) {
const { row: t } = e;
const n = await prepareGitHubPublicationTarget({
worktree: e.worktree,
identity: e.identity,
pullRequest: e.pullRequest,
session: t.identity_source === "personal" ? void 0 : {
agentId: t.agent_id,
sessionKey: t.session_key,
sessionId: t.session_id,
lifecycleRevision: e.lifecycleRevision
},
assertCurrent: e.assertCurrent
});
const r = e.expectedTarget;
if (r && (r.pushRepository !== n.pushRepository || r.repository !== n.repository || r.baseBranch !== n.baseBranch)) throw new GitHubPublicationWorkspaceChangedError("GitHub publication accepted repository target changed.");
if (t.head_commit && t.base_branch && t.base_branch !== n.baseBranch) return { status: "reconcile" };
return {
status: "ready",
target: n
};
}
/** Reuse genuine publication receipts for repeats; a remote advance is never an implicit import. */
async function prepareBoundGitHubPublication(e) {
const { pullRequest: t, row: n } = e;
const r = await readSharedGitHubPublication({
agentId: n.agent_id,
sessionKey: n.session_key,
sessionId: n.session_id
}, { status: "published" });
e.assertCurrent();
let i = t.head.commit;
if (r?.head_commit && r.repository === t.base.repository && r.branch === t.head.branch && r.pull_request_url === t.url) {
const t = await runPublicationCommand([
"git",
"merge-base",
"--is-ancestor",
i,
r.head_commit
], {
cwd: e.cwd,
beforeRun: e.assertCurrent
});
e.assertCurrent();
if (t.code === 0) i = r.head_commit;
else if (t.code !== 1) throw new GitHubPublicationRecoveryPendingError("The accepted PR source and previous publication could not be compared; saved work was preserved.");
}
let a;
const assertCurrent = () => {
e.assertCurrent();
try {
a?.();
} catch {
throw new GitHubPublicationRequesterUnavailableError();
}
};
const refresh = async () => {
const r = await inspectOwnGitHubPullRequest({
pullRequestUrl: t.url,
session: {
agentId: n.agent_id,
sessionKey: n.session_key,
sessionId: n.session_id
},
requester: e.requester,
assertCurrent: e.assertCurrent
}).catch(() => {
throw new GitHubPublicationRequesterUnavailableError();
});
assertBoundGitHubPullRequest(t, r.result);
const o = r.result.head.commit;
const s = n.head_commit !== n.source_head_commit && o === n.head_commit;
if (o !== i && !s) throw new GitHubPublicationBranchChangedError({ originalPullRequest: true });
a = r.assertCurrent;
if (!s) await assertExistingPullRequestWriteAccess({
pullRequest: r.result,
identity: await e.refreshIdentity(),
assertCurrent,
requirePublicRepositories: r.requirePublicRepositories
});
assertCurrent();
return s;
};
return {
assertCurrent,
refresh,
observedPublication: await refresh()
};
}
//#endregion
export { findGitHubPublicationPullRequest as a, preparePublishedPullRequestTarget as i, prepareGitHubPublicationExecutionTarget as n, reconcileGitHubPublicationPullRequest as o, prepareGitHubPublicationTarget as r, assertExistingPullRequestWriteAccess as s, prepareBoundGitHubPublication as t };