openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
507 lines (506 loc) • 16.3 kB
JavaScript
import { s as formatErrorMessage } from "./error-coercion-hDrHOSGy.mjs";
import { u as redactToolPayloadText } from "./redact-Mj7pppxC.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs";
import { t as truncateUtf8Prefix } from "./utf8-truncate-BH7Ecfuh.mjs";
import { a as withGitProcessOperation } from "./spawn-diagnostics-DBVI9KzR.mjs";
import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs";
import { t as runCommandBuffered } from "./exec-aRIvS9s4.mjs";
import { t as createCommandError } from "./command-error-BbCvU7oG.mjs";
import { r as githubRepositoryUrl } from "./github-host-CjR25cOO.mjs";
import { n as appendGitConfig, r as gitMaintenanceEnvironment } from "./git-maintenance-env-l0LyckfF.mjs";
import { l as gitNullConfigPath, u as gitReadOnlyEnvironment } from "./git-exec-DHBL622T.mjs";
import { i as withGitNetworkRetry, r as retryableGitNetworkOperation } from "./git-network-retry-BHIqo73F.mjs";
import { a as splitNullBuffer } from "./git-path-inventory-3RPYKCuB.mjs";
import { i as parseGitHubPublicationBaseRef, n as githubPublicationUnsafeConfigArgs } from "./github-publication-base-CnZoRiw5.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import os from "node:os";
//#region src/gateway/github-publication-git-transport.ts
function githubPublicationApiArgs(e, t = "GET", n = "github.com") {
return [
"gh",
"api",
"--hostname",
n,
"--method",
t,
e,
...t === "GET" ? [] : ["--input", "-"]
];
}
async function runPublicationCommand(e, t = {}) {
return await withGitProcessOperation(t.operation ?? "publication", () => withGitNetworkRetry(e[0] === "git" ? retryableGitNetworkOperation(e.slice(1)) : void 0, {
timeoutMs: t.timeoutMs ?? 6e4,
beforeRun: t.beforeRun
}, (n) => runCommandBuffered(e, {
...t.cwd ? { cwd: t.cwd } : {},
env: {
...e[0] === "git" ? gitReadOnlyEnvironment(e.slice(1), t.env ?? {}) : t.env ?? {},
GIT_NO_REPLACE_OBJECTS: "1",
...appendGitConfig(gitMaintenanceEnvironment(), [["core.hooksPath", os.devNull]])
},
...t.input !== void 0 ? { input: typeof t.input === "function" ? t.input() : t.input } : {},
timeoutMs: n,
noOutputTimeoutMs: t.noOutputTimeoutMs,
discardOutput: t.discardOutput,
maxOutputBytes: t.maxOutputBytes ?? 262144
})));
}
async function requirePublicationCommand(e, t = {}) {
const n = await runPublicationCommand(e, t);
if (n.code !== 0 || n.error) throw createCommandError(e[0] ?? "command", {
...n,
stdout: Buffer.alloc(0)
}, { timeoutMs: t.timeoutMs ?? 6e4 });
return n.stdout.toString("utf8").trim();
}
function createGitHubPublicationCommandRunner(e, t = "publication") {
const step = async (t) => {
e?.();
const n = await t();
e?.();
return n;
};
const guarded = (n) => async (r, i = {}) => {
const a = await n(r, {
...i,
operation: t,
beforeRun: e
});
e?.();
return a;
};
return {
step,
run: guarded(runPublicationCommand),
require: guarded(requirePublicationCommand)
};
}
async function readGitHubPublicationBaseSha(e, t, n, r, i) {
const a = await e([
"gh",
"api",
"--hostname",
r,
`repos/${t}/git/ref/heads/${n}`,
"--jq",
"{ref: .ref, sha: .object.sha}"
], { env: i });
if (a.code !== 0) throw new Error("GitHub publication workspace base branch could not be verified.");
return parseGitHubPublicationBaseRef(a.stdout.toString("utf8"), n);
}
async function requireGitHubPublicationCommit(e, t, n, r, i, a, o, s = {}) {
const fetch = async (s) => {
const c = await e([
...GITHUB_CREDENTIAL_ARGS,
"-c",
`core.hooksPath=${os.devNull}`,
"-c",
"core.fsmonitor=false",
"fetch",
"--no-auto-maintenance",
"--no-tags",
"--no-write-fetch-head",
"--recurse-submodules=no",
...s ? ["--refetch", "--stdin"] : ["--filter=blob:none"],
"--",
githubRepositoryUrl(t, r),
...s ? [] : [n]
], {
cwd: i,
env: a,
...s ? { input: `${s.join("\n")}\n` } : {}
});
if (c.code !== 0) {
const e = truncateUtf8Prefix(redactToolPayloadText(sanitizeForLog(c.stderr.toString("utf8").replace(/[\r\n\t]+/gu, " ")).replace(/\b[a-z][a-z\d+.-]*:\/\/\S+/giu, "[redacted URL]")).trim(), 1024);
throw new Error(e ? `${o} Git fetch: ${e}` : o);
}
};
if (!s.commitPresent) {
const t = await e([
"git",
"-c",
"core.commitGraph=false",
"rev-list",
"--missing=allow-any",
"--no-walk",
`${n}^{commit}`
], {
cwd: i,
env: a
});
if (t.code !== 0 || !t.stdout.toString("utf8").trim()) await fetch();
}
if (!s.contents) return;
const missingObjects = async () => {
const t = await e([
"git",
"rev-list",
"--objects",
"--missing=print",
"--no-object-names",
"--max-count=1",
n
], {
cwd: i,
env: {
...a,
GIT_NO_LAZY_FETCH: "1"
},
maxOutputBytes: TREE_LISTING_MAX_OUTPUT_BYTES
});
if (t.code !== 0) throw new Error(o);
return t.stdout.toString("utf8").split("\n").filter((e) => e.startsWith("?")).map((e) => e.slice(1));
};
const c = await missingObjects();
if (c.length) {
await fetch(c);
if ((await missingObjects()).length) throw new Error(o);
}
}
const TREE_LISTING_MAX_OUTPUT_BYTES = 67108864;
async function assertSafeGitPublicationWorkspace(e, t) {
const n = {
GIT_CONFIG_GLOBAL: gitNullConfigPath(),
GIT_CONFIG_SYSTEM: gitNullConfigPath()
};
const [r, i] = await Promise.all([t(githubPublicationUnsafeConfigArgs("--local"), {
cwd: e,
env: n
}), t([
"git",
"config",
"--local",
"--includes",
"--bool",
"--get",
"extensions.worktreeConfig"
], {
cwd: e,
env: n
})]);
const a = i.stdout.toString("utf8").trim();
const o = i.code === 0 && (a === "true" || a === "false") || i.code === 1 && i.stdout.length === 0;
if (r.code !== 1 || r.stdout.length > 0 || !o) throw new Error("GitHub publication workspace has unsupported Git transport configuration.");
const s = a === "true" ? await t(githubPublicationUnsafeConfigArgs("--worktree"), {
cwd: e,
env: n
}) : void 0;
if (s && (s.code !== 1 || s.stdout.length > 0)) throw new Error("GitHub publication workspace has unsupported Git transport configuration.");
const [c, l] = await Promise.all([t([
"git",
"for-each-ref",
"--count=1",
"--format=%(refname)",
"refs/replace"
], { cwd: e }), t([
"git",
"rev-parse",
"--git-path",
"info/grafts"
], { cwd: e })]);
if (c.code !== 0 || c.stdout.length > 0 || l.code !== 0) throw new Error("GitHub publication workspace has unsupported Git replacement metadata.");
const u = await readOptionalAttributeFile(path.resolve(e, l.stdout.toString("utf8").trim()));
if (u && u.length > 0) throw new Error("GitHub publication workspace has unsupported Git replacement metadata.");
}
function assertNoGitFilterAttributes(e) {
for (const t of e.toString("latin1").split(/\r?\n/u)) {
const e = t.trimStart().split(/[\t ]+/u);
if (!e[0] || e[0].startsWith("#")) continue;
if (e.slice(1).some((e) => /^(?:-|!)?filter(?:=|$)/u.test(e))) throw new Error("GitHub publication workspace uses an unsupported Git clean filter.");
}
}
async function readOptionalAttributeFile(e) {
try {
return await fs.readFile(e);
} catch (e) {
if (hasErrnoCode(e, "ENOENT")) return;
throw e;
}
}
async function readGitHubPublicationTree(e, t, n) {
const r = await n([
"git",
"ls-tree",
"-r",
"-z",
"--full-tree",
t
], {
cwd: e,
maxOutputBytes: TREE_LISTING_MAX_OUTPUT_BYTES
});
if (r.code !== 0) throw new Error("GitHub publication workspace tree could not be verified.");
return r.stdout;
}
async function assertGitHubPublicationIndexHasNoFilters(e, t) {
const n = await runPublicationCommand([
"git",
"-c",
"core.fsmonitor=false",
"ls-files",
"--cached",
"--format=%(objectname)",
"--",
":(top,icase,glob)**/.gitattributes"
], {
cwd: e,
env: {
GIT_INDEX_FILE: t,
GIT_LITERAL_PATHSPECS: "0"
},
maxOutputBytes: TREE_LISTING_MAX_OUTPUT_BYTES
});
if (n.code !== 0) throw new Error("GitHub publication workspace attributes could not be verified.");
const r = new Set(n.stdout.toString("utf8").trim().split("\n").filter(Boolean));
if (r.size > 1024) throw new Error("GitHub publication workspace has too many Git attribute files.");
for (const t of r) {
const n = await runPublicationCommand([
"git",
"cat-file",
"blob",
t
], { cwd: e });
if (n.code !== 0) throw new Error("GitHub publication workspace attributes could not be verified.");
assertNoGitFilterAttributes(n.stdout);
}
const i = await runPublicationCommand([
"git",
"rev-parse",
"--git-path",
"info/attributes"
], { cwd: e });
if (i.code !== 0) throw new Error("GitHub publication workspace attributes could not be verified.");
const a = await Promise.all(["GIT_ATTR_GLOBAL", "GIT_ATTR_SYSTEM"].map(async (t) => await runPublicationCommand([
"git",
"var",
t
], { cwd: e })));
if (a.some((e) => e.code !== 0)) throw new Error("GitHub publication workspace attributes could not be verified.");
const o = [path.resolve(e, i.stdout.toString("utf8").trim()), ...a.flatMap((e) => e.stdout.length > 0 ? [e.stdout.toString("utf8").trim()] : [])];
for (const e of o) {
const t = await readOptionalAttributeFile(e);
if (t) assertNoGitFilterAttributes(t);
}
}
async function captureGitHubPublicationWorkspaceSnapshot(e) {
const t = await runPublicationCommand([
"git",
"rev-parse",
"--verify",
"--quiet",
"MERGE_HEAD"
], {
cwd: e.cwd,
beforeRun: e.assertCurrent
});
e.assertCurrent?.();
if (t.code === 0) throw new Error("Workspace base integration is pending. Use github_publish refresh_base, resolve its reported conflicts, then repeat refresh_base with conflictsResolved and the returned baseCommit before tests, Auto Review, and publication.");
if (t.code !== 1) throw new Error("Workspace base integration state could not be verified; retry refresh_base.");
const n = captureOpenClawStateWorkerContext();
const { withSettledLocalWorkspacePath: r } = await import("./local-workspace-projection-CNLu-nkr.mjs");
return await r(e, async (t) => {
const r = await t?.canonicalPaths?.();
const i = {
...e,
assertCurrent: () => {
n.admission.assertCurrent();
e.assertCurrent?.();
t?.assertCurrent();
}
};
const [{ readLiveRegistryWorktreeByPath: a }, { withManagedWorktreeGit: o }, { getRuntimeConfig: s }] = await Promise.all([
import("./registry-read-DQN5h41N.mjs"),
import("./checkout-policy-BceLFAQC.mjs"),
import("./config/config.js")
]);
const c = await a(n, e.cwd);
i.assertCurrent();
return c ? await o({
record: c,
env: process.env,
getConfig: s,
beforeRun: i.assertCurrent
}, (e) => captureSettledGitHubPublicationWorkspaceSnapshot(i, e.sourceOnly ? e : void 0, r)) : await captureSettledGitHubPublicationWorkspaceSnapshot(i, void 0, r);
});
}
async function captureSettledGitHubPublicationWorkspaceSnapshot(e, t, n) {
const { step: r, require: i } = createGitHubPublicationCommandRunner(e.assertCurrent);
const git = (n, a, o) => t ? r(() => t.require(e.cwd, n, {
env: a,
input: o,
beforeRun: e.assertCurrent
})) : i([
"git",
"-c",
`core.hooksPath=${os.devNull}`,
"-c",
"core.fsmonitor=false",
...n
], {
cwd: e.cwd,
env: a,
input: o
});
await r(() => assertSafeGitPublicationWorkspace(e.cwd, runPublicationCommand));
const a = await i([
"git",
"rev-parse",
"--verify",
"HEAD^{commit}"
], { cwd: e.cwd });
const o = path.resolve(e.cwd, await git([
"rev-parse",
"--git-path",
"index"
]));
const s = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-github-snapshot-"));
try {
const i = {
GIT_ATTR_NOSYSTEM: "1",
GIT_CONFIG_GLOBAL: gitNullConfigPath(),
GIT_CONFIG_SYSTEM: gitNullConfigPath(),
GIT_INDEX_FILE: path.join(s, "index")
};
const c = await r(() => fs.stat(o, { bigint: true }));
await r(() => fs.copyFile(o, i.GIT_INDEX_FILE));
const l = Number(c.mtimeNs / 1000000000n);
await r(() => fs.utimes(i.GIT_INDEX_FILE, l, l));
const u = await git(["write-tree"], i);
try {
const n = [
"-c",
`core.attributesFile=${os.devNull}`,
"add",
"-A",
"--verbose"
];
const a = {
cwd: e.cwd,
env: i,
timeoutMs: 6e5,
noOutputTimeoutMs: 18e4,
discardOutput: { stdout: true },
beforeRun: e.assertCurrent
};
const o = await r(() => t ? t.worker.buffered(e.cwd, n, a) : runPublicationCommand([
"git",
"-c",
"core.fsmonitor=false",
...n
], a));
if (o.code !== 0 || o.error) throw createCommandError("git add", o, a);
} catch (e) {
throw new Error(`GitHub publication snapshot staging failed before submission: ${formatErrorMessage(e, { includeCode: true })}. The source index is unchanged; inspect Git locks, disk space and host load, then retry publication.`, { cause: e });
}
let d = await git(["write-tree"], i);
if (n) {
const t = await r(() => readGitHubPublicationTree(e.cwd, d, runPublicationCommand));
const a = new Set([...n].map((e) => Buffer.from(e).toString("hex")));
const o = splitNullBuffer(t).map((e) => e.subarray(e.indexOf(9) + 1)).filter((e) => !a.has(e.toString("hex")));
if (o.length) {
await git([
"update-index",
"--force-remove",
"-z",
"--stdin"
], i, Buffer.concat(o.flatMap((e) => [e, Buffer.from([0])])));
d = await git(["write-tree"], i);
}
}
await r(() => assertGitHubPublicationIndexHasNoFilters(e.cwd, i.GIT_INDEX_FILE));
return {
sourceHeadCommit: a,
sourceIndexTree: u,
workspaceTree: d
};
} finally {
await fs.rm(s, {
recursive: true,
force: true
});
}
}
const GITHUB_CREDENTIAL_ARGS = [
"git",
"-c",
"credential.helper=",
"-c",
"credential.helper=!gh auth git-credential"
];
async function readGitHubPublicationCoauthorTrailers(e) {
return (await e.command([
"git",
"-c",
"trailer.separators=:",
"-c",
"trailer.co-authored-by.key=Co-authored-by",
"show",
"-s",
"--format=%(trailers:key=Co-authored-by,only,unfold)",
e.headCommit
], { cwd: e.cwd })).split(/\r?\n/u);
}
function appendGitHubPublicationMessage(e, t) {
const n = [...new Set(t)].join("\n");
return n ? `${e.trimEnd()}\n\n${n}` : e.trimEnd();
}
/** Prepared commits use our terminal credit footer, never matching prose elsewhere in the message. */
function hasGitHubPublicationMessageFooter(e, t, n) {
const r = e.replace(/[\r\n]+$/u, "").split(/\r?\n/u);
const i = r.lastIndexOf("");
if (i < 1 || r.at(-1) !== n) return false;
const a = r.slice(i + 1, -1);
const o = new Set(t);
return a.length === o.size && [...o].every((e) => a.includes(e));
}
async function assertGitHubPublicationBranchRef(e, t) {
const n = await t([
"git",
"symbolic-ref",
"--quiet",
`refs/heads/${e}`
]);
if (n === 0) throw new Error("GitHub publication workspace branch ref became symbolic.");
if (n !== 1) throw new Error("GitHub publication workspace branch ref could not be verified.");
}
function githubPublicationPushArgs(e, t, n, r) {
return [
...GITHUB_CREDENTIAL_ARGS,
"-c",
`core.hooksPath=${os.devNull}`,
"push",
"--porcelain",
`--force-with-lease=refs/heads/${n}:${r}`,
"--no-follow-tags",
"--recurse-submodules=no",
"--",
e,
`${t}:refs/heads/${n}`
];
}
function githubPublicationRemoteHeadArgs(e, t) {
return [
...GITHUB_CREDENTIAL_ARGS,
"ls-remote",
"--refs",
e,
`refs/heads/${t}`
];
}
function githubPublicationUpdateRefArgs(e, t, n) {
return [
"git",
"-c",
`core.hooksPath=${os.devNull}`,
"-c",
"core.fsmonitor=false",
"update-ref",
`refs/heads/${e}`,
t,
n
];
}
//#endregion
export { requirePublicationCommand as _, captureGitHubPublicationWorkspaceSnapshot as a, githubPublicationApiArgs as c, githubPublicationUpdateRefArgs as d, hasGitHubPublicationMessageFooter as f, requireGitHubPublicationCommit as g, readGitHubPublicationTree as h, assertSafeGitPublicationWorkspace as i, githubPublicationPushArgs as l, readGitHubPublicationCoauthorTrailers as m, appendGitHubPublicationMessage as n, captureSettledGitHubPublicationWorkspaceSnapshot as o, readGitHubPublicationBaseSha as p, assertGitHubPublicationBranchRef as r, createGitHubPublicationCommandRunner as s, TREE_LISTING_MAX_OUTPUT_BYTES as t, githubPublicationRemoteHeadArgs as u, runPublicationCommand as v };