UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

417 lines (416 loc) • 15.9 kB
import { a as lstatIfExists } from "./path-existence-Co7-GyVr.mjs"; import { i as resolveEnvironmentValue, n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { i as hasCommandProcessCleanupError, l as readCommandProcessFailure, t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { a as resolveWindowsConsoleEncoding, r as decodeWindowsOutputBuffer } from "./windows-encoding-BGmFeZe1.mjs"; import { n as appendGitConfig, r as gitMaintenanceEnvironment } from "./git-maintenance-env-l0LyckfF.mjs"; import { a as executeGitCommand, d as normalizeGitPathForFilesystem, i as enqueueGitRefMutation, m as requireGitCommandOutput, n as GitCommandTimeoutError, o as executeGitCommandBuffered, r as createGitCommandError, s as executeGitCommandBytes } from "./git-exec-DHBL622T.mjs"; import { n as requestGitWorkerCommand, t as hasGitWorkerContext } from "./git-worker-context-CKEbyYPR.mjs"; import "./workspace-git-C5vMmIXy.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import os from "node:os"; import { performance } from "node:perf_hooks"; //#region src/infra/git-repository-repair.ts const log = createSubsystemLogger("git/repair"); const REPAIR_TIMEOUT_MS = 3e5; const MAX_REFS = 5e4; const MAX_MISSING_TIPS = 4096; const OID = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u; /** The caller keeps its checkout/ref mutation admission through repair and retry. */ async function withGitRepositoryRepair(e) { const { result: t } = e; if (t.termination !== "exit" || t.code !== 128 || t.cleanup === "uncertain" || t.outputLimitExceeded) return t; const n = typeof t.stderr === "string" ? t.stderr : Buffer.from(t.stderr).toString("utf8"); if (!/which is in the commit graph file but not in the object database|trying to write ref '[^']+' with nonexistent object/iu.test(n)) return t; const assertCurrent = () => { e.signal?.throwIfAborted(); e.assertCurrent?.(); }; log.warn(`Git repository has missing ref tips; attempting repair for ${e.cwd}`); try { const t = performance.now(); const remainingBudget = () => { assertCurrent(); const e = REPAIR_TIMEOUT_MS - (performance.now() - t); if (e <= 0) throw new Error("repair exceeded its five-minute budget"); return Math.ceil(e); }; const run = async (t, n, r = false) => { const i = await e.run([ "-c", "core.commitGraph=false", "-c", "maintenance.auto=false", "-c", "fetch.writeCommitGraph=false", ...t ], { input: n, signal: e.signal, beforeRun: assertCurrent, timeoutMs: remainingBudget(), maxOutputBytes: 8388608, env: { GIT_NO_LAZY_FETCH: "1", GIT_NO_REPLACE_OBJECTS: "1" }, killProcessTree: true }); if (i.cleanup === "uncertain") throw new CommandProcessCleanupError(); assertCurrent(); if (i.termination !== "exit" || i.code !== 0 && !(r && (i.code === 1 || i.code === 128)) || i.stdoutTruncatedBytes || i.outputLimitExceeded) throw new Error(`repair ${t[0]} failed (${i.termination}, exit ${i.code})`); return i.stdout; }; const n = (await run(["for-each-ref", "--format=%(refname) %(objectname) %(symref)"])).trim().split("\n").filter(Boolean); if (n.length > MAX_REFS) throw new Error(`repair inventory exceeds ${MAX_REFS} refs`); const r = /* @__PURE__ */ new Map(); const i = /* @__PURE__ */ new Map(); for (const e of n) { const [t, n, a] = e.trim().split(" "); if (!t?.startsWith("refs/") || !n || !OID.test(n)) throw new Error("repair received an invalid ref inventory"); if (a) i.set(t, a); else r.set(t, n); } const a = (await run([ "worktree", "list", "--porcelain", "-z" ])).split("\0"); const o = /* @__PURE__ */ new Set(); const protect = (e) => { let t = e; while (!o.has(t)) { o.add(t); const e = i.get(t); if (!e) break; t = e; } }; for (const e of i.keys()) if (!e.startsWith("refs/remotes/origin/")) protect(e); for (const e of a) if (e.startsWith("branch ")) protect(e.slice(7)); const s = /* @__PURE__ */ new Set(); for (const t of (await run([ "ls-remote", "--heads", "--", e.remote ])).trim().split("\n").filter(Boolean)) { const [e, n] = t.split(" "); if (!e || !OID.test(e) || !n?.startsWith("refs/heads/")) throw new Error("repair received an invalid remote inventory"); s.add(`refs/remotes/origin/${n.slice(11)}`); } if (s.size > MAX_REFS) throw new Error(`repair inventory exceeds ${MAX_REFS} remote refs`); const c = [...r.keys()].filter((e) => e.startsWith("refs/remotes/origin/")); const l = (e.canonicalTracking || (await run([ "config", "--get-all", "remote.origin.fetch" ])).trim() === "+refs/heads/*:refs/remotes/origin/*") && e.pruneTracking !== false ? c.filter((e) => !s.has(e) && !o.has(e)) : []; if (l.length) { await run([ "update-ref", "--no-deref", "--stdin" ], `${l.map((e) => `delete ${e} ${r.get(e)}`).join("\n")}\n`); for (const e of l) r.delete(e); } const u = new Set(r.values()); for (const e of a) if (e.startsWith("HEAD ") && OID.test(e.slice(5)) && !/^0+$/u.test(e.slice(5))) u.add(e.slice(5)); const d = u.size ? await run(["cat-file", "--batch-check=%(objectname) %(objecttype)"], `${[...u].join("\n")}\n`) : ""; const f = d.trim().split("\n").filter((e) => e.endsWith(" missing")).map((e) => e.split(" ")[0]); if (f.length > MAX_MISSING_TIPS) throw new Error(`repair exceeds ${MAX_MISSING_TIPS} missing ref tips`); if (f.length) { const t = /^([a-f0-9]+) commit$/m.exec(d)?.[1]; const n = [ "--no-auto-maintenance", "--no-tags", "--no-prune", "--no-prune-tags", "--no-write-fetch-head", "--no-recurse-submodules", ...(await run([ "config", "--type=bool", "--default=false", "--get", "remote.origin.promisor" ])).trim() === "true" ? ["--filter=blob:none"] : [], "--stdin", "--", e.remote ]; const r = `${f.join("\n")}\n`; await run([ "fetch", ...t ? [`--negotiation-tip=${t}`] : [], ...n ], r, true); if ((await run(["cat-file", "--batch-check=%(objectname) %(objecttype)"], r)).includes(" missing")) await run([ "-c", "fetch.negotiationAlgorithm=noop", "fetch", ...n ], r); } assertCurrent(); const p = await e.retry(); if (p.cleanup === "uncertain") throw new CommandProcessCleanupError(); assertCurrent(); if (p.termination !== "exit" || p.code !== 0) throw new Error("fetch still fails after ref-tip repair"); e.onRepaired?.(o); log.warn(`Git repository repaired for ${e.cwd}: fetched ${f.length} missing tips, pruned ${l.length} obsolete tracking refs`); return p; } catch (n) { if (hasCommandProcessCleanupError(n)) throw n; if (readCommandProcessFailure(n)?.cleanup === "uncertain") throw new CommandProcessCleanupError({ cause: n }); assertCurrent(); log.warn(`Git repository repair failed for ${e.cwd}: ${n instanceof Error ? n.message : "repair unavailable"}. Local branches and worktree HEADs were preserved; repair the clone's missing objects or ref locks, then retry.`); return t; } } //#endregion //#region src/agents/worktrees/git.ts const WORKTREE_CHECKOUT_TIMEOUT_MS = 3e5; const REPAIRABLE_FETCH_FLAGS = /* @__PURE__ */ new Set([ "--no-auto-maintenance", "--refetch", "--no-tags", "--no-write-fetch-head", "--no-recurse-submodules", "--recurse-submodules=no", "--stdin", "--prune", "--no-prune" ]); function withNoGlob(e) { if (e?.trim().split(/\s+/).at(-1) === "noglob") return e; return e ? `${e} noglob` : "noglob"; } /** * Gateway-run Git must never execute repository hooks or filesystem monitors; * the admin-gated setup script is the sole intentional repository-code path. * Exported so other Gateway-owned callers that must bypass the `runGit`/ * `requireGit*` wrappers (e.g. a buffered, non-throwing invocation with a * custom timeout) still pin the same invariant instead of reimplementing it. */ function gitEnvironment(e, t = [], n = process.platform, r = process.env) { const i = e ?? r; const a = n === "win32" && t.some((e) => e.endsWith("^{commit}")) ? mergeProcessEnv([r, e], n) : void 0; const o = a ? { MSYS: withNoGlob(resolveEnvironmentValue(a, "MSYS", n)), CYGWIN: withNoGlob(resolveEnvironmentValue(a, "CYGWIN", n)) } : {}; return { ...i, ...o, ...appendGitConfig(gitMaintenanceEnvironment(), [["core.hooksPath", os.devNull], ["core.fsmonitor", "false"]]) }; } async function runGit(e, t, n = {}) { if (hasGitWorkerContext()) { const { signal: r, beforeRun: i, ...a } = n; const { stdout: o, stderr: s, windowsEncoding: c, ...l } = await requestGitWorkerCommand({ type: "git.text", input: { cwd: e, args: t, options: a } }); return { ...l, stdout: decodeWindowsOutputBuffer({ buffer: Buffer.from(o.buffer, o.byteOffset, o.byteLength), windowsEncoding: c }), stderr: decodeWindowsOutputBuffer({ buffer: Buffer.from(s.buffer, s.byteOffset, s.byteLength), windowsEncoding: c }) }; } return await runOwnedGitCommand(e, t, n, executeGitCommand); } /** Parent-only command execution for text consumers whose decoding runs in a worker. */ async function runGitBytes(e, t, n = {}) { return await runOwnedGitCommand(e, t, n, executeGitCommandBytes); } async function runOwnedGitCommand(e, t, n, r) { const i = n.baseEnv ?? { ...process.env }; const a = gitEnvironment(n.env, t, process.platform, i); return await withGitRefAdmission(e, t, async (o) => { const run = () => r(e, o, { ...n, beforeRun: o === t ? n.beforeRun : void 0, baseEnv: i, env: a, input: o === t ? n.input : void 0, killProcessTree: n.killProcessTree ?? (t[0] === "fetch" && o === t) }); const s = await run(); if (o !== t || t[0] !== "fetch" || s.code !== 128) return s; const [c, l, ...u] = t.slice(1).filter((e) => !REPAIRABLE_FETCH_FLAGS.has(e)); if (c !== "origin" || u.length > 0 || l !== void 0 && !/^\+refs\/heads\/(.+):refs\/remotes\/origin\/\1$/u.test(l)) return s; return await withGitRepositoryRepair({ cwd: e, result: s, remote: "origin", pruneTracking: !t.includes("--no-prune"), signal: n.signal, assertCurrent: n.beforeRun, retry: run, run: (t, r) => executeGitCommand(e, t, { ...n, ...r, baseEnv: i, env: { ...a, ...r.env } }) }); }, n.signal, n.refMutationDirectory); } async function withGitRefAdmission(e, t, n, r, i) { const a = t[0] === "worktree" && t[1] === "add" && !t.includes("--detach"); if (!(t[0] === "fetch" || t[0] === "update-ref" || t[0] === "merge" || a || t[0] === "symbolic-ref" && t.length === 3 && !t[1]?.startsWith("-") || t[0] === "branch" && t.some((e) => e === "-d" || e === "-D" || e === "--delete"))) return await n(t); let o = i; if (!o) { const e = await n(["rev-parse", "--git-common-dir"]); if (e.termination !== "exit" || e.code !== 0) return e; o = typeof e.stdout === "string" ? e.stdout : decodeWindowsOutputBuffer({ buffer: Buffer.from(e.stdout.buffer, e.stdout.byteOffset, e.stdout.byteLength), windowsEncoding: resolveWindowsConsoleEncoding() }); } let s = false; const c = a ? new AbortController() : void 0; const l = c ? setTimeout(() => { createSubsystemLogger("agents/worktrees").warn("Managed worktree registration is waiting for repository repair or another Git operation (30-second wait limit)."); }, 1e3) : void 0; const u = c ? setTimeout(() => c.abort(new GitCommandTimeoutError("Managed worktree registration timed out waiting for repository repair or another Git operation. Retry creating the workspace after that operation finishes.")), 3e4) : void 0; const endWait = () => { clearTimeout(l); clearTimeout(u); }; try { return await enqueueGitRefMutation(e, o.trim(), () => { s = true; endWait(); return n(t); }, c ? r ? AbortSignal.any([r, c.signal]) : c.signal : r); } catch (e) { if (!s && r?.aborted && e === r.reason) return await n(t); throw e; } finally { endWait(); } } /** Byte-preserving Git transport shared by worker inventories and ordinary callers. */ async function runGitBuffered(e, t, n = {}) { if (hasGitWorkerContext()) { const { signal: r, beforeRun: i, ...a } = n; const o = await requestGitWorkerCommand({ type: "git.buffer", input: { cwd: e, args: t, options: a } }); return { ...o, stdout: Buffer.from(o.stdout.buffer, o.stdout.byteOffset, o.stdout.byteLength), stderr: Buffer.from(o.stderr.buffer, o.stderr.byteOffset, o.stderr.byteLength) }; } const r = n.baseEnv ?? { ...process.env }; const i = gitEnvironment(n.env, t, process.platform, r); return await withGitRefAdmission(e, t, (a) => { return executeGitCommandBuffered(e, a, { ...n, beforeRun: a === t ? n.beforeRun : void 0, input: a === t ? n.input : void 0, baseEnv: r, env: i }); }, n.signal, n.refMutationDirectory); } async function requireGit(e, t, n = {}) { const r = await runGit(e, t, n); return requireGitCommandOutput(`git ${t.join(" ")}`, r).trim(); } async function requireGitBuffer(e, t, n = {}) { const r = await runGitBuffered(e, t, n); if (r.termination !== "exit" || r.code !== 0) throw createGitCommandError(`git ${t.join(" ")}`, r); return r.stdout; } /** Git may return relative or Windows-native spellings for its administrative paths. */ async function resolveGitMetadataPath(e, t, n = {}) { return path.resolve(e, normalizeGitPathForFilesystem(await requireGit(e, [ "rev-parse", "--git-path", t ], n))); } function parseWorktreeList(e) { const t = []; let n; for (const r of e.split("\0")) { if (!r) { if (n) { t.push(n); n = void 0; } continue; } if (r.startsWith("worktree ")) { if (n) t.push(n); n = { path: normalizeGitPathForFilesystem(r.slice(9)) }; } else if (n && r.startsWith("HEAD ")) n.head = r.slice(5); else if (n && r === "locked") n.lockedReason = ""; else if (n && r.startsWith("locked ")) n.lockedReason = r.slice(7); else if (n && r.startsWith("branch ")) n.branch = r.slice(7); else if (n && r === "detached") n.branch = null; } if (n) t.push(n); return t; } async function readGitWorktreeList(e, t = {}) { return requireGitCommandOutput("git worktree list", await runGit(e, [ "worktree", "list", "--porcelain", "-z" ], t)); } function* worktreePaths(e) { for (const t of e.matchAll(/(?:^|\0)worktree ([^\0]*)/gu)) yield normalizeGitPathForFilesystem(t[1]); } async function listGitWorktrees(e, t = {}) { return parseWorktreeList(await readGitWorktreeList(e, t)); } /** Native registrations include external checkouts whose directories are currently missing. */ async function readGitWorktreePathInventory(e) { return new Set(Array.from(worktreePaths(await readGitWorktreeList(e)), (e) => path.resolve(e))); } /** Resolve shared storage and its primary root without selecting or validating HEAD. */ async function resolveGitRepositoryPaths(e, t = {}) { const n = normalizeGitPathForFilesystem(await requireGit(e, ["rev-parse", "--git-common-dir"], t)); const r = await fs.realpath(path.resolve(e, n)); const i = worktreePaths(await readGitWorktreeList(e, t)).next().value; return { canonicalRoot: await fs.realpath(i ?? e), commonDir: r }; } async function hasSelfContainedGitMetadata(e) { return (await lstatIfExists(path.join(e, ".git"), "ENOENT"))?.isDirectory() ?? false; } async function worktreePathExists(e) { return await lstatIfExists(e, "ENOENT") !== void 0; } //#endregion export { readGitWorktreePathInventory as a, resolveGitMetadataPath as c, runGitBuffered as d, runGitBytes as f, listGitWorktrees as i, resolveGitRepositoryPaths as l, withGitRepositoryRepair as m, gitEnvironment as n, requireGit as o, worktreePathExists as p, hasSelfContainedGitMetadata as r, requireGitBuffer as s, WORKTREE_CHECKOUT_TIMEOUT_MS as t, runGit as u };