UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

420 lines (419 loc) • 16.7 kB
import { r as isErrno, t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { p as statIfExists } from "./path-existence-Co7-GyVr.mjs"; import { r as GatewayErrorDetailCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { l as gitNullConfigPath } from "./git-exec-DHBL622T.mjs"; import { t as assertionSucceeds } from "./assertion-BVvbcE3a.mjs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; //#region src/gateway/github-publication-failure.ts const identityNextAction = "Reconnect My GitHub or System GitHub in Settings → Profile → GitHub connections (agent overrides: Agents → Tools), then request publication again."; /** An owner observed a definitive outcome; an unavailable probe is not this failure. */ var GitHubPublicationKnownFailure = class extends Error { constructor(e, t, n) { super(e); this.failure = t; this.rejection = n; } }; function rejectGitHubPublicationSelection(e, t) { let n; try { if (t && !t.hasRequest()) n = { code: GatewayErrorDetailCodes.GITHUB_PUBLICATION_SELECTION_REJECTED, idempotencyKey: t.idempotencyKey }; } catch {} throw new GitHubPublicationKnownFailure(e, { code: "identity_changed", nextAction: identityNextAction }, n); } var GitHubPublicationWorkspaceChangedError = class extends GitHubPublicationKnownFailure { constructor(e) { super(e, { code: "workspace_changed", nextAction: "Inspect the reconciled workspace and any recorded GitHub effects, then request a new publication after reviewing the changes." }); } }; /** The session worktree has a branch checked out other than the branch this session publishes. */ var GitHubPublicationSessionBranchMismatchError = class extends GitHubPublicationKnownFailure { constructor(e) { const { session: t, checkedOut: n } = e; super(`The session worktree has branch ${n} checked out, but this session publishes branch ${t}.`, { code: "workspace_changed", nextAction: `In the session worktree, rename the branch back with \`git branch -m ${n} ${t}\`, or switch to it with \`git switch ${t}\` if it still exists, then request publication again. Publication only pushes the session branch.` }); } }; var GitHubPublicationBranchChangedError = class extends GitHubPublicationKnownFailure { constructor(e = {}) { super("GitHub publication cannot safely extend the published branch.", { code: "push_rejected", nextAction: e.originalPullRequest ? "The PR head changed after this workspace last integrated it. Your local work is saved: call prepare_pr with this PR's URL to merge its newer head into that work, resolve any returned conflicts, then publish again. Do not create a replacement PR or redirect publication to another branch." : "Preserve your local work and inspect the published head. If this conversation published the PR from its managed workspace, call prepare_pr with its URL to merge the newer head into the saved work, then publish again; otherwise publish from a new session branch and open a replacement PR. Repository-only checkpoints cannot adopt external branch changes; use a new session branch for those. Do not merge old history merely to make a rebased branch pushable. The broker never rewrites published history." }); } }; /** * Classify a push whose head did not land. Git exiting on its own with a failure while the * remote still holds its pre-push head is a definitive rejection. Anything else (exit 0, a * killed or signalled push, or a moved remote) stays unconfirmed for recovery to settle. */ function gitHubPublicationPushFailure(e, t, { login: n, pushRepository: r }) { if (!t || e.code === 0 || e.signal !== null || e.killed) return /* @__PURE__ */ new Error(e.code === 0 ? "GitHub push verification failed." : "GitHub push was rejected."); return new GitHubPublicationKnownFailure(`GitHub rejected the push to ${r}.`, { code: "push_rejected", nextAction: `Nothing was pushed as @${n}. Give @${n} write access (or point the worktree's origin at a fork it owns) and check the repository's branch rules, then request publication again.` }); } var GitHubPublicationSessionChangedError = class extends GitHubPublicationKnownFailure { constructor() { super("GitHub publication session lifecycle changed.", { code: "session_changed", nextAction: "Review any recorded GitHub effects, then request publication from the current session." }); } }; var GitHubPublicationRequesterUnavailableError = class extends GitHubPublicationKnownFailure { constructor() { super("The original GitHub publication requester is no longer authorized.", { code: "identity_changed", nextAction: "Review any recorded or unconfirmed GitHub effects, then request publication again from an authorized session. Saved work and existing pull requests are retained." }); } }; var GitHubPublicationCreditChangedError = class extends GitHubPublicationKnownFailure { constructor() { super("GitHub publication contributor credit changed.", { code: "identity_changed", nextAction: "Review contributor credit and any recorded GitHub effects, reconcile unpushed prepared commits, then request a new publication. Already published commits and pull requests are retained." }); } }; var GitHubPublicationWorkflowChangesError = class extends GitHubPublicationKnownFailure { constructor() { super("Publishing GitHub workflow changes requires full operator write permission.", { code: "github_rejected", nextAction: "OpenClaw requires the requester's full operator write authority for these workflow changes; this is not a GitHub token scope failure. Your saved changes are intact. Ask a maintainer with full write access to publish, or remove only unintended workflow edits after reviewing the accepted diff." }); } }; /** * Resolve the persisted failure code and guidance. A known failure's message is code-authored, * so it leads the guidance as the specific reason; other errors may carry raw command output * and only select generic guidance. */ function resolveGitHubPublicationFailure(e) { if (e instanceof GitHubPublicationKnownFailure) { const t = /[.!?]$/u.test(e.message) ? e.message : `${e.message}.`; return { code: e.failure.code, nextAction: `${t} ${e.failure.nextAction}` }; } const t = e instanceof Error ? e.message : ""; if (t.includes("publication workspace base")) return { code: "unavailable", nextAction: "The pull request base or its Git history could not be verified. Check repository read access, connectivity, and local Git objects before retrying publication." }; if (t.includes("publication remote branch could not be verified")) return { code: "unavailable", nextAction: "Restore repository read access or connectivity, then verify the published branch before retrying. An unavailable observation does not prove the branch is absent or safe to overwrite." }; if (t.includes("identity")) return { code: t.includes("changed") ? "identity_changed" : "identity_unavailable", nextAction: identityNextAction }; if (t.includes("session") || t.includes("worktree owner")) return { code: "session_changed", nextAction: "Open the current session worktree and request publication again." }; if (t.includes("transport configuration") || t.includes("replacement metadata")) return { code: "workspace_changed", nextAction: "Remove the unsupported Git transport or replacement configuration from the session worktree, then retry." }; if (t.includes("workspace") || t.includes("branch changed")) return { code: "workspace_changed", nextAction: "Inspect the reconciled workspace and any recorded GitHub effects, then request a new publication after reviewing the changes." }; if (t.includes("not a git")) return { code: "not_git", nextAction: "Use a session-owned Git worktree to publish." }; if (t.includes("GitHub remote")) return { code: "not_github", nextAction: "Use a GitHub repository remote to publish." }; if (t.includes("push")) return { code: "push_rejected", nextAction: "Check repository write access and branch drift, then retry without force-pushing." }; if (t.includes("pull request") || t.includes("GitHub")) return { code: "github_rejected", nextAction: "Check pull-request permission for the effective account, then retry." }; return { code: "unavailable", nextAction: "Retry after the Gateway and GitHub are available." }; } //#endregion //#region src/gateway/github-publication-git-index.ts const HARDENED_GIT = [ "git", "-c", `core.hooksPath=${os.devNull}`, "-c", "core.fsmonitor=false" ]; var GitHubPublicationRefCasRejectedError = class extends GitHubPublicationWorkspaceChangedError {}; var GitHubPublicationRecoveryPendingError = class extends Error {}; function assertGitHubPublicationRefCasCompleted(e) { if (e.code === 0) return; if (e.signal === null && !e.killed) throw new GitHubPublicationRefCasRejectedError("GitHub publication workspace branch changed before commit."); throw new Error("GitHub publication workspace branch update outcome is unknown."); } async function syncDirectory(e) { let t; try { t = await fs.open(e, "r"); await t.sync(); } catch (e) { const t = isErrno(e) ? e.code : void 0; if (process.platform !== "win32" || t !== "EINVAL" && t !== "EPERM") throw e; } finally { await t?.close().catch(() => void 0); } } async function sameFile(e, t) { try { const [n, r] = await Promise.all([fs.stat(e), fs.stat(t)]); return n.nlink >= 2 && r.nlink >= 2 && n.dev === r.dev && n.ino === r.ino; } catch (e) { if (hasErrnoCode(e, "ENOENT")) return false; throw e; } } async function writeDurableFile(e, t) { await fs.writeFile(e, t, { flag: "w", mode: 384 }); const n = await fs.open(e, "r+"); try { await n.sync(); } finally { await n.close(); } } function publicationRecoveryPath(e, t) { return `${e}.openclaw-${createHash("sha256").update(t).digest("hex")}`; } async function recoverGitHubPublicationBranchAndIndex(e) { e.assertCustody(); const mutate = async (t) => { e.assertCustody(); return await t(); }; const t = await e.run([ "git", "rev-parse", "--git-path", "index" ], { cwd: e.cwd }); const n = path.resolve(e.cwd, t); const r = `${n}.lock`; const i = publicationRecoveryPath(n, e.requestId); if (await statIfExists(i) === void 0) return; const a = await sameFile(i, r); if (!a && await statIfExists(r) !== void 0) throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace recovery is waiting for another Git operation."); const o = await e.run([ "git", "rev-parse", "--verify", `refs/heads/${e.branch}` ], { cwd: e.cwd }); if (!a) { const t = await e.run([...HARDENED_GIT, "write-tree"], { cwd: e.cwd }); if (o === e.sourceHeadCommit || t === e.workspaceTree && await publicationCommitMatches(e, o)) { await mutate(async () => await fs.rm(i, { force: true })); return; } throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace recovery is pending."); } if (o === e.sourceHeadCommit) { await mutate(async () => await fs.rm(r, { force: true })); await mutate(async () => await fs.rm(i, { force: true })); await mutate(async () => await syncDirectory(path.dirname(n))); return; } if (!await publicationCommitMatches(e, o)) throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace branch recovery is pending."); await mutate(async () => await fs.rename(r, n)); await mutate(async () => await syncDirectory(path.dirname(n))); await mutate(async () => await fs.rm(i, { force: true })); } async function publicationCommitMatches(e, t) { const [n, r, i] = await Promise.all([ e.run([ "git", "show", "-s", "--format=%B", t ], { cwd: e.cwd }), e.run([ "git", "rev-parse", `${t}^` ], { cwd: e.cwd }), e.run([ "git", "rev-parse", `${t}^{tree}` ], { cwd: e.cwd }) ]); return n.split(/\r?\n/u).includes(`OpenClaw-Publication: ${e.requestId}`) && r === e.sourceHeadCommit && i === e.workspaceTree; } /** Moves the branch and accepted index together while honoring Git's standard index lock. */ async function updateGitHubPublicationBranchAndIndex(e) { e.assertCurrent(); const t = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-github-index-")); const n = path.join(t, "replacement-index"); const r = path.join(t, "observed-index"); try { const t = await e.run([ "git", "rev-parse", "--git-path", "index" ], { cwd: e.cwd }); const i = path.resolve(e.cwd, t); const a = `${i}.lock`; const o = publicationRecoveryPath(i, e.requestId); let s = false; let c = false; let l = false; let u = false; const installIndex = async (t) => { t(); await fs.rename(a, i); s = false; u = true; e.assertCustody(); await syncDirectory(path.dirname(i)); e.assertCustody(); await fs.rm(o, { force: true }); }; try { const t = { ...e.env, GIT_CONFIG_GLOBAL: gitNullConfigPath(), GIT_CONFIG_SYSTEM: gitNullConfigPath() }; await e.run([ ...HARDENED_GIT, "read-tree", e.headCommit ], { cwd: e.cwd, env: { ...t, GIT_INDEX_FILE: n } }); const u = await fs.readFile(n); let d; try { d = await fs.readFile(o); } catch (e) { if (!hasErrnoCode(e, "ENOENT")) throw e; } if (d && !d.equals(u)) { const t = await e.run([ "git", "rev-parse", "--verify", `refs/heads/${e.branch}` ], { cwd: e.cwd }); if (await sameFile(o, a) || t !== e.previousHead) throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace recovery data changed."); d = void 0; } if (!d) { e.assertCurrent(); c = true; await writeDurableFile(o, u); await syncDirectory(path.dirname(i)); } if (await sameFile(o, a)) { const t = await e.run([ "git", "rev-parse", "--verify", `refs/heads/${e.branch}` ], { cwd: e.cwd }); if (t === e.headCommit) { l = true; s = true; try { await installIndex(e.assertCustody); return; } catch (e) { throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace index recovery is pending.", { cause: e }); } } if (t !== e.previousHead) throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace branch recovery is pending."); e.assertCustody(); c = true; await fs.rm(a); e.assertCustody(); await syncDirectory(path.dirname(i)); } else if (await statIfExists(a) !== void 0) throw new Error("GitHub publication workspace index is locked by another operation."); e.assertCurrent(); try { await fs.link(o, a); s = true; c = true; } catch (e) { throw new Error("GitHub publication workspace index changed before commit.", { cause: e }); } await fs.copyFile(i, r); const f = await e.run([...HARDENED_GIT, "write-tree"], { cwd: e.cwd, env: { ...t, GIT_INDEX_FILE: r } }); if (f !== e.sourceIndexTree && f !== e.workspaceTree) throw new GitHubPublicationWorkspaceChangedError("GitHub publication workspace index changed after its accepted snapshot."); e.assertCurrent(); await syncDirectory(path.dirname(i)); e.assertCurrent(); if (e.updateRef) { l = true; try { await e.updateRef(); } catch (e) { if (e instanceof GitHubPublicationRefCasRejectedError) l = false; throw e; } } await installIndex(e.updateRef ? e.assertCustody : e.assertCurrent); } catch (e) { if (!u && l && s) throw new GitHubPublicationRecoveryPendingError("GitHub publication workspace recovery is pending.", { cause: e }); throw e; } finally { const hasCustody = () => assertionSucceeds(() => e.assertCustody()); if (!u && !l && s && hasCustody() && await sameFile(o, a) && hasCustody()) await fs.rm(a, { force: true }); if ((u || !l && c) && hasCustody()) await fs.rm(o, { force: true }); } } finally { await fs.rm(t, { recursive: true, force: true }); } } //#endregion export { GitHubPublicationBranchChangedError as a, GitHubPublicationRequesterUnavailableError as c, GitHubPublicationWorkflowChangesError as d, GitHubPublicationWorkspaceChangedError as f, resolveGitHubPublicationFailure as h, updateGitHubPublicationBranchAndIndex as i, GitHubPublicationSessionBranchMismatchError as l, rejectGitHubPublicationSelection as m, assertGitHubPublicationRefCasCompleted as n, GitHubPublicationCreditChangedError as o, gitHubPublicationPushFailure as p, recoverGitHubPublicationBranchAndIndex as r, GitHubPublicationKnownFailure as s, GitHubPublicationRecoveryPendingError as t, GitHubPublicationSessionChangedError as u };