openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 11.1 kB
JavaScript
import{o as resolveGlobalSingleton}from"./global-singleton-DolL9xGt.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as areDiagnosticsEnabledForProcess}from"./diagnostic-events-BYBrlAdF.mjs";import{D as runWithDiagnosticTraceContext,x as getActiveDiagnosticTraceContext}from"./diagnostics-timeline-Wd4cnAkV.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{a as withGitProcessOperation}from"./spawn-diagnostics-C-LTFiNq.mjs";import{r as prepareSandboxStateOwnerPath}from"./state-owner-path-CGpPdjBt.mjs";import{f as recordCommandProcessFailure,l as readCommandProcessCleanup,t as CommandProcessCleanupError}from"./exec-result-TD4w1Z1i.mjs";import{u as prepareSessionSourceEffect}from"./session-source-authority-Cun3s-rH.mjs";import{t as KeyedAsyncQueue}from"./keyed-async-queue-qBcorzrt.mjs";import{l as redactSupportDiagnosticLine}from"./diagnostic-support-redaction-fdb2R4EP.mjs";import{r as decodeWindowsOutputBuffer}from"./windows-encoding-hfsJ5_F8.mjs";import{t as createFixedWindowBudget}from"./fixed-window-rate-limit-Dz32amDt.mjs";import{t as createCommandError}from"./command-error-B187dN8z.mjs";import{o as validateWorkspaceFilesystemEvidence}from"./workspace-state-guard-Bv-hX6Uv.mjs";import{i as withGitNetworkRetry,n as gitCommandName,r as retryableGitNetworkOperation}from"./git-network-retry-Dmgh4hDr.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";
//!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;let p;return{recordRecovery(e){p=e?.startsWith(`refs/openclaw/snapshots/clean-v1/`)?`head`:e?`capture`:`none`},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,l){try{const u=performance.now();const m=u-r;if(m<1e3||!areDiagnosticsEnabledForProcess()||!t.isEnabled(`info`))return;const h=resolveGlobalSingleton(Symbol.for(a.stateKey),()=>({budget:createFixedWindowBudget({maxRequests:60,windowMs:6e4,now:diagnosticNow}),omitted:0}));if(!h.budget.consume().allowed){h.omitted=Math.min(Number.MAX_SAFE_INTEGER,h.omitted+1);return}const g={pid:process.pid,threadId,isMainThread,durationMs:Math.round(m),[a.phases[0]]:Math.round((o??u)-r),...o!==void 0&&s!==void 0?{[a.phases[1]]:Math.round(s-o),[a.phases[2]]:Math.round(u-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,...e===`worktree-removal`&&c===`threw`?{errorType:(l instanceof Error?l.constructor.name:typeof l).slice(0,80),error:redactSupportDiagnosticLine(formatErrorMessage(l),{env:{},stateDir:``,redactRelativePaths:true},500)}:{},omittedObservations:h.omitted,...n?.(),...e===`worktree-removal`?{tracked:f?.tracked??null,untracked:f?.untracked??null,...p?{recovery:p}:{}}:{}};runWithDiagnosticTraceContext(i,()=>t.info(e!==`ref-mutation`?`${a.message} ${JSON.stringify(g)}`:a.message,g));h.omitted=0}catch{}}}}catch{return}}
//!src/infra/git-exec.ts
const GIT_TIMEOUT_MS=12e4;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-Nk4ZKR_f.mjs`);return withGitProcessOperation(n.operation,()=>executeGitCommandWithOutput(r,(e,t)=>({...e,stdout:decodeWindowsOutputBuffer({buffer:t})}),e,t,n))}async function executeGitCommandBytes(e,t,n={}){const{runCommandBuffersWithTimeout:r}=await import(`./exec-runner-ChWrSZBY.mjs`);return withGitProcessOperation(n.operation,()=>executeGitCommandWithOutput(r,(e,t)=>({...e,stdout:t}),e,t,n))}function createGitPatchCapture(e){const t=Buffer.from(`
diff --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(`
`));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=n=>withGitAttemptSource(i,async()=>{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,executionIntent:i.executionIntent??`gateway-internal`,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,executionIntent:i.executionIntent??`gateway-internal`,env:a,timeoutMs:e})),timeoutMs:o}}async function executeGitCommandBuffered(e,t,n={}){const{runCommandBuffered:r}=await import(`./exec-Nk4ZKR_f.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=>withGitAttemptSource(n,()=>r(a,{...n,executionIntent:n.executionIntent??`gateway-internal`,env:i,timeoutMs:e}))))}async function withGitAttemptSource(e,t){const n=e.beforeRun?.prepareSessionSourceEffect?await prepareSessionSourceEffect(e.beforeRun):void 0;try{for(const e of n?.workspaceEvidence??[])await validateWorkspaceFilesystemEvidence(e);if(e.stateOwnerPath)await prepareSandboxStateOwnerPath(e.stateOwnerPath);if(n||e.stateOwnerPath)(n?.assertCurrent??e.beforeRun)?.();return await t()}finally{await n?.release?.()}}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`}function quoteGitConfig(e){return`"${e.replace(/\\/gu,`\\\\`).replace(/"/gu,`\\"`).replace(/\n/gu,`\\n`).replace(/\t/gu,`\\t`).replaceAll(`\b`,`\\b`)}"`}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};