UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

217 lines (216 loc) • 7.57 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { w as root } from "./fs-safe-BbWvmdVn.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { s as hasWorktreeUnknownOutcome } from "./errors-CJd09ymz.mjs"; import { o as requireGit, u as runGit } from "./git-BBx5S0aA.mjs"; import { d as WORKTREE_SETUP_HEADROOM_BYTES } from "./allocation-DPkHxKtM.mjs"; import { i as timeWorktreePreparationPhase } from "./preparation-timing-YO2wGpby.mjs"; import { t as withWorktreeGitConfig } from "./checkout-git-config-ClOP9WBP.mjs"; import { a as detectWorktreeFilesystemBackend, r as prepareWorktreeTemplate } from "./template-cache-Dc62QDDC.mjs"; import { n as resolveSandboxDependencyTemplateIdentity, t as prepareSandboxDependencyTemplate } from "./dependency-template-CZqXhJMA.mjs"; import { i as prepareLocalWorkspaceCheckout } from "./local-workspace-checkout-D7yp8kUm.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { parse as parse$1 } from "yaml"; //#region src/gateway/worker-environments/local-workspace-template.ts const log = createSubsystemLogger("agents/worktrees"); async function hasContainedVirtualStore(e, t) { try { const { buffer: n } = await (await root(e)).read("node_modules/.modules.yaml", { symlinks: "reject", maxBytes: 1048576 }); const r = parse$1(n.toString("utf8")); if (!isRecord(r) || typeof r.virtualStoreDir !== "string") return false; const i = path.posix.resolve(t, "node_modules"); const a = path.posix.relative(i, path.posix.resolve(i, r.virtualStoreDir)); return a !== ".." && !a.startsWith("../") && !path.posix.isAbsolute(a); } catch { return false; } } /** Only dependencies may survive installation; repository setup outputs remain private. */ async function validateTemplate(e, t, n, r = "validate") { return await withWorktreeGitConfig(e, true, { signal: n.signal, beforeRun: n.commitGuard }, async (i) => { const a = await i.run(e, [ "--no-optional-locks", "status", "--porcelain=v2", "--branch", "-z", "--untracked-files=normal", "--ignored=matching" ], { signal: n.signal, beforeRun: n.commitGuard, killProcessTree: true }); const o = a.stdout.split("\0"); if (a.code !== 0 || a.termination !== "exit" || a.stdoutTruncatedBytes || o.pop() !== "") return false; const s = o.filter((e) => e.startsWith("# branch.oid ")); if (s.length !== 1 || s[0] !== `# branch.oid ${t}`) return false; for (const t of o) { if (t.startsWith("# ")) continue; if (!t.startsWith("! ") && !t.startsWith("? ")) return false; const i = t.slice(2); const a = i.replace(/\/$/u, "").split("/"); if (a.some((e) => !e || e === "." || e === "..") || path.isAbsolute(i)) return false; const o = path.join(e, ...a); const s = a.indexOf("node_modules"); if (s !== -1 && r !== "source-only") { if (!(await fs.lstat(path.join(e, ...a.slice(0, s + 1)))).isDirectory()) return false; continue; } if (r === "validate") return false; n.commitGuard(); await fs.rm(o, { recursive: true, force: true }); } return true; }); } /** The returned template retains its generation until the caller settles its clone. */ async function prepareLocalWorkspaceTemplate(e) { const { guard: t } = e; const n = await detectWorktreeFilesystemBackend(e.temporaryRoot, t); if (!n) return; const r = { signal: t.signal, beforeRun: t.commitGuard, killProcessTree: true }; const i = await runGit(e.source, ["show", `${e.baseCommit}:pnpm-lock.yaml`], r); if (i.code !== 0 || i.stdoutTruncatedBytes) { log.debug("sandbox dependency template skipped: no complete pnpm lockfile at the selected commit"); return; } const a = await resolveSandboxDependencyTemplateIdentity(e.sandbox, { signal: t.signal, assertCurrent: t.commitGuard }); if (!a) { log.debug("sandbox dependency template skipped: local image identity unavailable"); return; } const o = path.resolve(e.source, await requireGit(e.source, ["rev-parse", "--git-common-dir"], r)); const prepareSource = async (r, i) => { await t.requireDiskSpace([{ path: e.templateRoot, bytes: WORKTREE_SETUP_HEADROOM_BYTES }], "sandbox dependency template"); await n.createTemplate(r, i); await timeWorktreePreparationPhase("checkout", () => prepareLocalWorkspaceCheckout({ source: e.source, destination: r, temporaryRoot: e.temporaryRoot, baseCommit: e.baseCommit, branch: "openclaw-template", signal: i.signal, assertCurrent: i.commitGuard })); }; const s = await prepareWorktreeTemplate({ env: e.env, now: Date.now, options: t, cacheKey: sha256Hex(`sandbox-v1\n${o}\n${e.templateRoot}\n${a.key}`), contentKey: sha256Hex(`${e.baseCommit}\n${sha256Hex(i.stdout)}\n${a.key}`), repoRoot: e.repoRoot, commonDir: o, worktreeRoot: e.templateRoot, sourceCommit: e.baseCommit, backend: `sandbox-${n.id}`, requireSpace: () => t.requireDiskSpace([{ path: e.templateRoot, bytes: WORKTREE_SETUP_HEADROOM_BYTES }], "sandbox dependency template"), validate: (t, n) => validateTemplate(t.path, e.baseCommit, n), prepare: async (n, r) => { const i = { ...t, ...r, signal: r.signal ?? t.signal }; await prepareSource(n.path, i); const o = await prepareSandboxDependencyTemplate({ directory: n.path, cfg: e.sandbox, scopeKey: n.id, identity: a, signal: i.signal, assertCurrent: i.commitGuard, rollbackGuard: r.rollbackGuard }); const s = o.installed && await hasContainedVirtualStore(n.path, a.docker.workdir); i.commitGuard(); const c = await validateTemplate(n.path, e.baseCommit, i, s ? "dependencies" : "source-only"); if (s && c) { log.info("sandbox dependency template prepared for the selected commit"); return; } const l = o.installed ? s ? "installation changed tracked source" : "pnpm virtual store is outside node_modules or unavailable" : o.reason; log.warn(`sandbox dependency template using source-only fallback: ${l}`); if (c) return; i.commitGuard(); await fs.rm(n.path, { recursive: true, force: true }); await prepareSource(n.path, i); } }); return s ? { record: s, backend: n } : void 0; } /** The caller holds worktree mutation before projection custody, matching removal's lock order. */ async function cloneLocalWorkspaceTemplate(e) { const t = await timeWorktreePreparationPhase("templatePrepare", () => prepareLocalWorkspaceTemplate(e)); if (!t) return false; const { record: n, backend: r } = t; const { guard: i } = e; let a; try { i.commitGuard(); await i.requireDiskSpace([{ path: e.destination, bytes: r.id === "btrfs" ? r.estimateCloneBytes(0, 0) : WORKTREE_SETUP_HEADROOM_BYTES }], "sandbox workspace clone"); try { await timeWorktreePreparationPhase("templateApply", () => r.cloneTemplate(n.path, e.destination, i)); } catch (t) { if (hasWorktreeUnknownOutcome(t)) throw t; i.commitGuard(); await fs.rm(e.destination, { recursive: true, force: true }); log.warn("sandbox dependency snapshot unavailable; using source-only checkout"); return false; } await requireGit(e.destination, [ "branch", "-m", e.branch ], { signal: i.signal, beforeRun: i.commitGuard, killProcessTree: true }); return true; } catch (e) { a = e; throw e; } finally { await n.release(a); } } //#endregion export { cloneLocalWorkspaceTemplate, prepareLocalWorkspaceTemplate };