UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

391 lines (390 loc) • 12.1 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { t as areDiagnosticsEnabledForProcess } from "./diagnostic-events-BjAH1Kbx.mjs"; import { T as runWithDiagnosticTraceContext, b as getActiveDiagnosticTraceContext } from "./diagnostics-timeline-CSwiG24r.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { a as withGitProcessOperation } from "./spawn-diagnostics-DBVI9KzR.mjs"; import { c as readCommandProcessCleanup, d as recordCommandProcessFailure, t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs"; import { r as decodeWindowsOutputBuffer } from "./windows-encoding-BGmFeZe1.mjs"; import { t as createCommandError } from "./command-error-BbCvU7oG.mjs"; import { t as createFixedWindowBudget } from "./fixed-window-rate-limit-BNX1HlV6.mjs"; import { i as withGitNetworkRetry, n as gitCommandName, r as retryableGitNetworkOperation } from "./git-network-retry-BHIqo73F.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { isMainThread, threadId } from "node:worker_threads"; import { performance } from "node:perf_hooks"; //#region src/infra/git-operation-timing.ts const diagnosticNow = () => performance.now(); const operations = { "ref-mutation": { stateKey: "openclaw.gitRefMutationDiagnostics", message: "slow Git ref mutation", phases: [ "resolveMs", "queueWaitMs", "queuedOperationMs" ] }, "worktree-removal": { stateKey: "openclaw.worktreeRemovalDiagnostics", message: "slow managed worktree removal", phases: [ "admissionMs", "bodyMs", "finalizeMs" ] }, "content-read": { stateKey: "openclaw.gitContentReadDiagnostics", message: "slow Git content read", phases: [ "firstHostRequestMs", "workerMs", "settlementMs" ] } }; const removalStages = [ ["preparation", "preparationMs"], ["snapshot", "snapshotMs"], ["checkoutRemoval", "checkoutRemovalMs"], ["finalization", "bodyFinalizeMs"] ]; function startGitOperationTiming(e, t, n) { try { if (e !== "worktree-removal" && (!areDiagnosticsEnabledForProcess() || !t.isEnabled("info"))) return; const r = performance.now(); const i = getActiveDiagnosticTraceContext(); const a = operations[e]; let o; let s; let c; let l; let u = 0; let d; let f; return { recordInventory(e) { f = e; }, removalProgress() { return { stage: l ?? c ?? "preparation", elapsedMs: Math.round(performance.now() - r) }; }, markRemovalFailure() { l ??= c; }, markPhase() { if (o === void 0) o = performance.now(); else s = performance.now(); }, markRemovalStage(t) { if (e !== "worktree-removal") return; const n = performance.now(); if (c !== void 0) { d ??= {}; d[c] = (d[c] ?? 0) + n - u; } c = t; u = n; }, finish(c) { try { const l = performance.now(); const u = l - r; if (u < 1e3 || !areDiagnosticsEnabledForProcess() || !t.isEnabled("info")) return; const p = resolveGlobalSingleton(Symbol.for(a.stateKey), () => ({ budget: createFixedWindowBudget({ maxRequests: 60, windowMs: 6e4, now: diagnosticNow }), omitted: 0 })); if (!p.budget.consume().allowed) { p.omitted = Math.min(Number.MAX_SAFE_INTEGER, p.omitted + 1); return; } const m = { pid: process.pid, threadId, isMainThread, durationMs: Math.round(u), [a.phases[0]]: Math.round((o ?? l) - r), ...o !== void 0 && s !== void 0 ? { [a.phases[1]]: Math.round(s - o), [a.phases[2]]: Math.round(l - s) } : {}, ...Object.fromEntries(removalStages.flatMap(([e, t]) => { const n = d?.[e]; return n === void 0 ? [] : [[t, Math.round(n)]]; })), callbackEntered: (e === "ref-mutation" ? s : o) !== void 0, outcome: c, omittedObservations: p.omitted, ...n?.(), ...e === "worktree-removal" ? { tracked: f?.tracked ?? null, untracked: f?.untracked ?? null } : {} }; runWithDiagnosticTraceContext(i, () => t.info(e !== "ref-mutation" ? `${a.message} ${JSON.stringify(m)}` : a.message, m)); p.omitted = 0; } catch {} } }; } catch { return; } } //#endregion //#region src/infra/git-exec.ts const GIT_TIMEOUT_MS = 12e4; /** Inspection consumes local objects; only explicit transfers may hydrate a partial clone. */ function gitReadOnlyEnvironment(e, t = process.env) { const n = gitCommandName(e); return n && (/^(?:cat-file|check-attr|check-ignore|config|describe|diff|diff-files|diff-index|diff-tree|for-each-ref|log|ls-files|ls-tree|merge-base|name-rev|rev-list|rev-parse|show|show-ref|status)$/.test(n) || n === "worktree" && e[e.indexOf(n) + 1] === "list" || n === "branch" && e.includes("--list")) ? { ...t, GIT_NO_LAZY_FETCH: "1" } : t; } var GitCommandTimeoutError = class extends Error { constructor(...e) { super(...e); this.name = "GitCommandTimeoutError"; } }; const gitRefMutations = resolveGlobalSingleton(Symbol.for("openclaw.gitRefMutations"), () => new KeyedAsyncQueue()); const refMutationLog = createSubsystemLogger("git/ref-mutation"); async function enqueueGitRefMutation(e, t, n, r) { const i = startGitOperationTiming("ref-mutation", refMutationLog); let a = "threw"; const o = { run: n, signal: r, timing: i, completion: createDeferredCore() }; let s = o; const abort = () => { const e = s; s = void 0; e?.completion.reject(e.signal?.reason); }; try { r?.throwIfAborted(); const n = normalizeGitPathForFilesystem(t); const c = await fs.realpath(path.resolve(e, n)); r?.throwIfAborted(); const l = process.platform === "win32" ? c.toLowerCase() : c; i?.markPhase(); r?.addEventListener("abort", abort, { once: true }); gitRefMutations.enqueue(l, async () => { const e = s; s = void 0; if (!e) return; try { e.signal?.removeEventListener("abort", abort); e.timing?.markPhase(); e.completion.resolve(await e.run()); } catch (t) { e.completion.reject(t); } }).catch((e) => s?.completion.reject(e)); const u = await o.completion.promise; a = "returned"; return u; } finally { r?.removeEventListener("abort", abort); i?.finish(a); } } function normalizeGitPathForFilesystem(e, t = process.platform) { if (t !== "win32") return e; const n = /^\/([a-zA-Z])(?:\/(.*))?$/.exec(e); const r = n?.[1]; if (!r) return e; return path.win32.normalize(`${r.toUpperCase()}:/${n[2] ?? ""}`); } function gitCommandArgv(e, t, n = []) { return [ "git", ...n.flatMap((e) => ["-c", e]), ...process.platform === "win32" ? ["-c", "core.longpaths=true"] : [], "-C", e, ...t ]; } function gitExecutionArgv(e, t, n) { const r = gitCommandArgv(e, t, n.killProcessTree ? ["maintenance.autoDetach=false", "gc.autoDetach=false"] : []); return n.lowerPriority && process.platform !== "win32" ? [ "nice", "-n", "10", ...r ] : r; } async function executeGitCommand(e, t, n = {}) { const { runCommandWithTimeout: r } = await import("./exec-Df6gUJ1h.mjs"); return withGitProcessOperation(n.operation, () => executeGitCommandWithOutput(r, (e, t) => ({ ...e, stdout: decodeWindowsOutputBuffer({ buffer: t }) }), e, t, n)); } /** The same command/timeout contract, with output bytes owned by a worker consumer. */ async function executeGitCommandBytes(e, t, n = {}) { const { runCommandBuffersWithTimeout: r } = await import("./exec-runner-DEuEb8zx.mjs"); return withGitProcessOperation(n.operation, () => executeGitCommandWithOutput(r, (e, t) => ({ ...e, stdout: t }), e, t, n)); } function createGitPatchCapture(e) { const t = Buffer.from("\ndiff --git "); const n = []; let r = Buffer.alloc(0); let i = 0; let a; const append = (t) => { const r = t.subarray(0, Math.max(0, e + 1 - i)); if (r.length > 0) { n.push(Buffer.from(r)); i += r.length; a = r[r.length - 1]; } }; const finishPatch = () => { if (i > e && a !== 10) n.push(Buffer.from("\n")); i = 0; a = void 0; }; return { append(e) { const n = r.length > 0 ? Buffer.concat([r, e]) : e; let i = 0; let a = n.indexOf(t); while (a !== -1) { append(n.subarray(i, a + 1)); finishPatch(); i = a + 1; a = n.indexOf(t, i); } const o = Math.max(i, n.length - t.length + 1); append(n.subarray(i, o)); r = Buffer.from(n.subarray(o)); }, finish() { append(r); finishPatch(); return Buffer.concat(n); } }; } async function executeGitCommandWithOutput(e, t, n, r, i) { const a = gitReadOnlyEnvironment(r, i.env ?? {}); const o = i.timeoutMs ?? 12e4; const s = gitExecutionArgv(n, r, i); const runAttempt = async (n) => { const r = i.maxPatchBytes === void 0 ? void 0 : createGitPatchCapture(i.maxPatchBytes); let a = await e(s, r ? { ...n, outputCapture: "discard", tolerateOutputError: { stderr: true }, onOutputChunk: (e, t) => { if (t === "stdout") r.append(e); } } : n); const o = readCommandProcessCleanup(a); if (o) a = { ...a, cleanup: await o.catch((e) => { throw new CommandProcessCleanupError({ cause: e }); }) }; return r ? t({ ...a, stdoutTruncatedBytes: void 0 }, r.finish()) : a; }; if (i.waitForExit === true) { const start = () => { i.beforeRun?.(); return runAttempt({ ...i, env: a, timeoutMs: void 0 }); }; return { ...await (i.startRun ? i.startRun(start) : start()), timeoutMs: 0 }; } return { ...await withGitNetworkRetry(retryableGitNetworkOperation(r), { ...i, timeoutMs: o }, (e) => runAttempt({ ...i, env: a, timeoutMs: e })), timeoutMs: o }; } async function executeGitCommandBuffered(e, t, n = {}) { const { runCommandBuffered: r } = await import("./exec-Df6gUJ1h.mjs"); const i = gitReadOnlyEnvironment(t, n.env ?? {}); const a = gitExecutionArgv(e, t, { ...n, killProcessTree: n.killProcessTree !== false }); return await withGitProcessOperation(n.operation, () => withGitNetworkRetry(retryableGitNetworkOperation(t), { ...n, timeoutMs: n.timeoutMs ?? 12e4 }, (e) => r(a, { ...n, env: i, timeoutMs: e }))); } function createGitCommandError(e, t) { const n = t.timeoutMs ?? 12e4; const r = createCommandError(e, t, { timeoutMs: n }); if (t.termination === "timeout") return new GitCommandTimeoutError(`${r.message}\nGit did not finish within its ${n / 1e3}s budget; check remote reachability, repository locks, and clone shape (partial clones fetch missing objects lazily).`); return r; } async function requireGitCommand(e, t, n = {}) { return requireGitCommandOutput(`git ${t.join(" ")}`, await executeGitCommand(e, t, n)).trim(); } function requireGitCommandOutput(e, t, n = createGitCommandError) { let r; if (t.termination !== "exit" || t.code !== 0) r = t; else if (t.stdoutTruncatedBytes) r = { ...t, code: null, outputLimitExceeded: true }; if (r) throw recordCommandProcessFailure(n(e, r), { pid: t.pid, code: t.code, cleanup: t.cleanup, termination: t.termination, killIssuedByAbort: t.killIssuedByAbort, outputLimitExceeded: t.outputLimitExceeded }); return t.stdout; } function gitNullConfigPath() { return process.platform === "win32" ? "NUL" : "/dev/null"; } /** Quote a Git config value without treating its contents as config syntax. */ function quoteGitConfig(e) { return `"${e.replace(/\\/gu, "\\\\").replace(/"/gu, "\\\"").replace(/\n/gu, "\\n").replace(/\t/gu, "\\t").replaceAll("\b", "\\b")}"`; } //#endregion export { executeGitCommand as a, gitCommandArgv as c, normalizeGitPathForFilesystem as d, quoteGitConfig as f, startGitOperationTiming as h, enqueueGitRefMutation as i, gitNullConfigPath as l, requireGitCommandOutput as m, GitCommandTimeoutError as n, executeGitCommandBuffered as o, requireGitCommand as p, createGitCommandError as r, executeGitCommandBytes as s, GIT_TIMEOUT_MS as t, gitReadOnlyEnvironment as u };