UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

383 lines (382 loc) • 15.3 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { n as runtimeProcessEntrypoints } from "./runtime-process-entrypoints-qiyJvDDT.mjs"; import { a as resolveRuntimeWorkerUrl } from "./runtime-worker-url-DRDkoS4J.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { a as WorkerTaskError } from "./src-Dkfkl2Oz.mjs"; import { a as withGitProcessOperation } from "./spawn-diagnostics-DBVI9KzR.mjs"; import { i as hasCommandProcessCleanupError, l as readCommandProcessFailure, t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { n as createOwnedWorkerTaskPool } from "./worker-task-pool-BshJjv1P.mjs"; import { t as ownedWorkerBytes } from "./worker-transfer-bytes-CoxxqDpw.mjs"; import { h as startGitOperationTiming } from "./git-exec-DHBL622T.mjs"; import { d as runGitBuffered, f as runGitBytes } from "./git-BBx5S0aA.mjs"; import { i as serializeGitWorkerFailure, r as restoreGitWorkerFailure } from "./git-worker-context-CKEbyYPR.mjs"; import path from "node:path"; import { createHash } from "node:crypto"; import fs from "node:fs/promises"; import os from "node:os"; import { channel } from "node:diagnostics_channel"; import { performance } from "node:perf_hooks"; //#region src/infra/git-content-budget.ts const budget = resolveGlobalSingleton(Symbol.for("openclaw.gitContentBudget"), () => ({ active: 0, activeInteractive: 0, waiters: /* @__PURE__ */ new Set(), interactiveWaiters: /* @__PURE__ */ new Set() })); async function withContentGitSlot(e, t, n = false) { t?.throwIfAborted(); const r = n ? budget.interactiveWaiters : budget.waiters; await new Promise((e, i) => { const start = () => { r.delete(start); t?.removeEventListener("abort", abort); budget.active++; budget.activeInteractive += Number(n); e(); }; const abort = () => { r.delete(start); i(toErrorObject(t?.reason, "Git operation aborted")); }; if (budget.active < 2) start(); else { r.add(start); t?.addEventListener("abort", abort, { once: true }); } }); try { t?.throwIfAborted(); return await e(); } finally { budget.active--; budget.activeInteractive -= Number(n); (budget.interactiveWaiters.size > 0 && (budget.waiters.size === 0 || budget.activeInteractive === 0) ? budget.interactiveWaiters : budget.waiters).values().next().value?.(); } } //#endregion //#region src/infra/git-worker.ts const POOL_OWNERS = [ "reads", "summary", "content", "workspace", "worktrees", "worktreeMaintenance" ]; const MAX_PENDING_OPERATIONS = 128; const WORKER_PHASE_TIMEOUT_MS = 18e5; const log = createSubsystemLogger("git/worker"); const operationDiagnostics = channel("openclaw.git.operation"); const SPAWN_OPERATIONS = { "repository.identities": "repository.identities", "repository.branches": "repository.branches", "checkout.revision": "checkout.revision", "checkout.context": "checkout.context", "checkout.diff": "checkout.diff", "checkout.baseline": "checkout.baseline", "pull-request.branch-facts": "pull-request.branch-facts", "pull-request.branch-comparison": "pull-request.branch-facts", "worktree.snapshot": "worktree.snapshot", "worktree.snapshot-verify-exact": "worktree.snapshot", "worktree.cleanup-inspection": "worktree.cleanup", "worktree.cleanup-fingerprint": "worktree.cleanup", "worktree.eviction-classify": "worktree.cleanup", "worktree.eviction-source": "worktree.cleanup", "worktree.eviction-repositories": "worktree.cleanup", "worktree.eviction-purge": "worktree.cleanup", "worktree.provisioning-inspection": "worktree.provision", "worktree.git-size": "worktree.inspect", "worktree.checkout-transition-size": "worktree.inspect", "worktree.directory-size": "worktree.inspect", "workspace.artifacts": "workspace.inventory", "workspace.inventory.select": "workspace.inventory", "workspace.inventory.existing": "workspace.inventory", "workspace.inventory.paths": "workspace.inventory", "workspace.inventory.staged-directories": "workspace.inventory", "workspace.manifest.local": "workspace.manifest", "workspace.manifest.capture": "workspace.manifest", "workspace.manifest.base-refresh": "workspace.manifest", "workspace.manifest.equal": "workspace.manifest", "workspace.manifest.snapshot": "workspace.manifest", "workspace.manifest.document": "workspace.manifest", "workspace.manifest.reference": "workspace.manifest", "workspace.manifest.parse": "workspace.manifest", "workspace.manifest.paths": "workspace.manifest", "workspace.manifest.serialize": "workspace.manifest", "workspace.manifest.overlay": "workspace.manifest", "workspace.manifest.pair": "workspace.manifest", "workspace.manifest.staged": "workspace.manifest", "workspace.manifest.entries": "workspace.manifest", "workspace.manifest.file": "workspace.manifest", "workspace.manifest.nodes": "workspace.manifest", "workspace.manifest.stage-input": "workspace.manifest", "workspace.manifest.tree-input": "workspace.manifest", "workspace.manifest.remote-capture": "workspace.manifest", "workspace.reconcile.preflight": "workspace.manifest" }; function trackPending(e, t) { e.add(t); const settled = () => e.delete(t); t.then(settled, settled); } function runtime() { return resolveGlobalSingleton(Symbol.for("openclaw.gitOperations"), () => ({ pending: /* @__PURE__ */ new Set() }), (e) => { e.closing ??= (async () => { await Promise.all(POOL_OWNERS.map((t) => e[t]?.close() ?? Promise.resolve())); await Promise.allSettled(e.pending); for (const t of POOL_OWNERS) e[t] = void 0; })().finally(() => { e.closing = void 0; }); return e.closing; }); } function poolFor(e, t, n, r) { const i = r ? "summary" : t.type === "worktree.snapshot" || t.type === "worktree.cleanup-inspection" || t.type === "worktree.cleanup-fingerprint" || t.type === "worktree.eviction-classify" || t.type === "worktree.eviction-repositories" || t.type === "worktree.eviction-purge" ? "worktreeMaintenance" : t.type.startsWith("worktree.") ? "worktrees" : t.type.startsWith("workspace.") ? "workspace" : n ? "content" : "reads"; return e[i] ??= createOwnedWorkerTaskPool({ workerUrl: resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.gitOperations), workerClass: i === "summary" ? "singleton" : i === "reads" || i === "content" ? "reader" : i === "workspace" ? "compute" : "writer", workerOptions: i === "summary" || i === "workspace" ? { resourceLimits: { maxOldGenerationSizeMb: i === "summary" ? 512 : 1024 } } : void 0, idleTimeoutMs: i === "reads" ? 12e4 : void 0, sharedCompute: i === "workspace" }, i === "content" || i === "workspace" ? { retainOneIdleWorker: true } : void 0); } /** The host retains processes and authority; workers own bounded inventory and projection work. */ async function runGitWorkerOperation(e, t = {}) { const n = runtime(); if (n.closing || n.pending.size >= MAX_PENDING_OPERATIONS) throw new WorkerTaskError("Git operation capacity is unavailable; retry the request.", "unavailable"); t.signal?.throwIfAborted(); t.assertCurrent?.(); const r = t.transferList?.(e); const i = r ? structuredClone(e, { transfer: [...new Set(r)] }) : structuredClone(e); const a = { ...process.env }; i.filesystemRefs = t.git === void 0 && !Object.entries(a).some(([e, t]) => t !== void 0 && (/^(GIT_DIR|GIT_WORK_TREE|GIT_COMMON_DIR|GIT_CEILING_DIRECTORIES|GIT_DISCOVERY_ACROSS_FILESYSTEM|GIT_NAMESPACE|GIT_SHALLOW_FILE|GIT_GRAFT_FILE|GIT_REPLACE_REF_BASE|GIT_NO_REPLACE_OBJECTS|GIT_INDEX_FILE|GIT_OBJECT_DIRECTORY|GIT_ALTERNATE_OBJECT_DIRECTORIES|GIT_CONFIG_PARAMETERS)$/i.test(e) || /^(HOME|XDG_CONFIG_HOME|GIT_CONFIG_GLOBAL|GIT_CONFIG_SYSTEM)$/i.test(e) && /[\r\n]/u.test(t))) ? createHash("sha256").update(JSON.stringify(Object.entries(a).filter(([e]) => /^(GIT_|HOME$|XDG_CONFIG_HOME$|PATH$|SUDO_UID$)/i.test(e)).toSorted(([e], [t]) => e.localeCompare(t)))).digest("hex") : void 0; const o = executeOperation(n, i, a, { ...t, git: t.git ? { text: t.git.text, buffered: t.git.buffered } : void 0 }); trackPending(n.pending, o); return o; } async function executeOperation(e, t, n, r) { const i = operationDiagnostics.hasSubscribers ? performance.now() : void 0; const a = t.type === "checkout.diff" || t.type === "checkout.baseline" ? t.input.cwd : t.type === "pull-request.branch-facts" || t.type === "pull-request.branch-comparison" ? t.input.root : void 0; const o = a !== void 0; const s = t.type === "checkout.diff" && t.input.summaryOnly === true || t.type === "checkout.revision" && t.input.scope === "diff"; const c = t.type === "worktree.snapshot" || t.type === "worktree.snapshot-verify-exact"; const l = o || c; if (c) { n.GIT_NO_LAZY_FETCH = "1"; n.GIT_ALLOW_PROTOCOL = ""; } let u = 0; let d = 0; let f = 0; let p = 0; let m = 0; let h = 0; let g = null; let _; const v = a !== void 0 ? startGitOperationTiming("content-read", log, () => ({ operation: t.type, ...t.type === "checkout.diff" ? { scope: t.input.scope ?? "all", summaryOnly: t.input.summaryOnly === true } : {}, checkoutId: createHash("sha256").update(path.resolve(a)).digest("hex").slice(0, 16), checkoutClass: t.type === "pull-request.branch-facts" && t.input.refreshIndex ? "managed" : "unspecified", gitCommandCount: u, workerQueueWaitMs: g, summedGitWallMs: Math.round(d), summedGitQueueWaitMs: Math.round(f), gitStdoutBytes: p, gitStderrBytes: m, gitTimeoutCount: h, slowestGitCommand: _ })) : void 0; let y = true; const b = v || r.diffTiming; let x = "threw"; const S = /* @__PURE__ */ new Set(); const C = /* @__PURE__ */ new Set(); const w = /* @__PURE__ */ new Map(); let T; let E = 0; const request = async (e, i) => { try { i.throwIfAborted(); const a = e; let o; const c = []; if (a.type === "git.text" || a.type === "git.buffer") { const e = b ? performance.now() : 0; const execute = async () => { const o = b ? performance.now() : 0; let s = "threw"; if (v) { u++; f += o - e; } try { const e = await withGitProcessOperation(SPAWN_OPERATIONS[t.type], async () => { const e = { ...a.input.options, operation: SPAWN_OPERATIONS[t.type], baseEnv: n, signal: i, beforeRun: r.assertCurrent, killProcessTree: true, lowerPriority: l }; if (a.type === "git.text") { const t = await (r.git?.text ?? runGitBytes)(a.input.cwd, a.input.args, e); if (t.cleanup === "uncertain") throw new CommandProcessCleanupError(); return t; } const o = await (r.git?.buffered ?? runGitBuffered)(a.input.cwd, a.input.args, e); if (o.error && (hasCommandProcessCleanupError(o.error) || readCommandProcessFailure(o.error)?.cleanup === "uncertain")) throw o.error; return o; }); if (v) { s = e.termination; p += e.stdout.byteLength; m += e.stderr.byteLength; h += Number(s === "timeout"); } return e; } finally { if (r.diffTiming) { const e = r.diffTiming.durations; e["git-wall"] = (e["git-wall"] ?? 0) + performance.now() - o; } if (v) { const e = Math.round(performance.now() - o); d += e; if (!_ || e > _.durationMs) { const t = a.input.args; let n = 0; while (n < t.length && t[n].startsWith("-")) n += t[n] === "-c" || t[n] === "-C" ? 2 : 1; const r = t[n] ?? ""; _ = { command: /^(diff|ls-files|rev-parse|rev-list|merge-base|cat-file|symbolic-ref|for-each-ref|version|log|show|hash-object)$/.test(r) ? r : "other", ...r === "diff" ? { diffMode: t.includes("--no-index") ? "--no-index" : t.slice(n + 1).find((e) => /^(--shortstat|--raw|--patch|--name-status)$/.test(e)) ?? "other" } : {}, durationMs: e, termination: s }; } } } }; const g = await (l ? withContentGitSlot(execute, i, s) : execute()); const y = ownedWorkerBytes(g.stdout); const x = ownedWorkerBytes(g.stderr); o = { ...g, stdout: y, stderr: x }; c.push(y.buffer, x.buffer); } else if (a.type === "git.temporary-directory") { const e = await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-git-operation-")); C.add(e); o = e; } else if (a.type === "workspace.inventory.write") { if (!r.onInventoryChunk) throw new Error("Workspace inventory has no active output owner"); r.assertCurrent?.(); await r.onInventoryChunk(a.input.bytes, { signal: i }); } else { if (!r.onEffect) throw new Error("Git read operation requested a lifecycle effect"); r.assertCurrent?.(); o = await r.onEffect(a, { signal: i }); } return { input: { ok: true, value: o }, transferList: [...new Set(c)], timeoutMs: WORKER_PHASE_TIMEOUT_MS }; } catch (e) { if (hasCommandProcessCleanupError(e)) T ??= e instanceof Error ? e : new CommandProcessCleanupError({ cause: e }); else if (readCommandProcessFailure(e)?.cleanup === "uncertain") T ??= new CommandProcessCleanupError({ cause: e }); const t = ++E; w.set(t, e); return { input: { ok: false, error: { ...serializeGitWorkerFailure(e), origin: t } }, timeoutMs: WORKER_PHASE_TIMEOUT_MS }; } }; try { const n = b ? performance.now() : 0; const i = b ? () => { const e = performance.now() - n; g = Math.round(e); if (r.diffTiming) r.diffTiming.durations["worker-queue"] = e; return t; } : t; const a = await poolFor(e, t, o, s).run(i, { inputBytes: r.inputBytes, transferList: r.transferList, signal: r.signal, timeoutMs: WORKER_PHASE_TIMEOUT_MS, onRequest: (e, t) => { if (y) { y = false; v?.markPhase(); } if (!isRecord(e) || e.type !== "git.batch" || !isRecord(e.input) || !Array.isArray(e.input.requests) || e.input.requests.length === 0 || e.input.requests.length > 16) throw new Error("Invalid Git worker request batch"); const n = Promise.all(e.input.requests.map((e) => request(e, t.signal))).then((e) => ({ input: e.map((e) => e.input), transferList: [...new Set(e.flatMap((e) => e.transferList ?? []))], timeoutMs: WORKER_PHASE_TIMEOUT_MS })); trackPending(S, n); return n; } }); v?.markPhase(); if (!a.ok) { if (a.error.origin !== void 0 && w.has(a.error.origin)) throw w.get(a.error.origin); throw restoreGitWorkerFailure(a.error); } r.signal?.throwIfAborted(); r.assertCurrent?.(); if (r.diffTiming) r.diffTiming.revisionUnavailableReason = a.revisionUnavailableReason; x = "returned"; return a.value; } finally { let e = false; try { await Promise.allSettled(S).then(() => { if (T) throw T; return Promise.all([...C].map((e) => fs.rm(e, { recursive: true, force: true }))); }); e = true; } finally { v?.finish(e ? x : "threw"); if (i !== void 0) operationDiagnostics.publish({ operation: t.type, outcome: e && x === "returned" ? "ok" : "error", elapsedMs: performance.now() - i }); } } } //#endregion export { withContentGitSlot as n, runGitWorkerOperation as t };