openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 18.9 kB
JavaScript
import{t as e}from"./git-operation.worker-fs-safe-2XqdJR5K.mjs";import{l as t}from"./git-operation.worker-map-size-CypexNQj.mjs";import{n}from"./git-operation.worker-path-existence-Bpkbkop2.mjs";import{u as r}from"./git-operation.worker-home-dir-DUQkhCrS.mjs";import{i}from"./git-operation.worker-record-coerce-BUlpHiHI.mjs";import{l as a,u as o}from"./git-operation.worker-git-TpQcAIgG.mjs";import{Fn as s,Gt as c,In as l,Kt as u,Ln as d,Rt as f,Vt as p,Wt as m,Xn as h,ar as g,dn as _,er as v,gn as y,hn as b,qn as x}from"./git-operation.worker.js";import{o as S}from"./git-operation.worker-runtime-process-bootstrap.generated-NdDxMbTB.mjs";import{Nt as C,kt as w,n as T}from"./git-operation.worker-worker-task-pool-BBrceUCf.mjs";import{n as E,t as D}from"./git-operation.worker-workspace-hash-memo-CMIph4rA.mjs";import{d as O,n as k,p as A}from"./git-operation.worker-workspace-manifest-DsRMcvMP.mjs";import{n as j}from"./git-operation.worker-workspace-result-git-DNTVSnX7.mjs";import M from"node:fs/promises";import N from"node:path";import P from"node:os";import{createHash as F}from"node:crypto";import{performance as I}from"node:perf_hooks";import{channel as L}from"node:diagnostics_channel";import{getFsSafeNativeConfig as R}from"@openclaw/fs-safe/config";function createPendingPromiseTracker(e){return t=>{e.add(t);let settled=()=>e.delete(t);return t.then(settled,settled),t}}const z=r(Symbol.for(`openclaw.gitContentBudget`),()=>({active:0,activeInteractive:0,waiters:/* @__PURE__ */ new Set,interactiveWaiters:/* @__PURE__ */ new Set}));async function withContentGitSlot(e,n,r=!1){n?.throwIfAborted();let i=r?z.interactiveWaiters:z.waiters;await new Promise((e,a)=>{let start=()=>{i.delete(start),n?.removeEventListener(`abort`,abort),z.active++,z.activeInteractive+=Number(r),e()},abort=()=>{i.delete(start),a(t(n?.reason,`Git operation aborted`))};z.active<2?start():(i.add(start),n?.addEventListener(`abort`,abort,{once:!0}))});try{return n?.throwIfAborted(),await e()}finally{z.active--,z.activeInteractive-=Number(r),(z.interactiveWaiters.size>0&&(z.waiters.size===0||z.activeInteractive===0)?z.interactiveWaiters:z.waiters).values().next().value?.()}}const B=[`reads`,`summary`,`content`,`workspace`,`worktrees`,`worktreeMaintenance`],V=18e5,H=y(`git/worker`),U=L(`openclaw.git.operation`),W={"github.profile-token":`github.identity`,"github.profile-stage":`github.identity`,"github.profile-refresh":`github.identity`,"checkout.bootstrap-workspace":`repository.identities`,"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.initial":`workspace.manifest`,"workspace.manifest.template":`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.result":`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`,"workspace.reconcile.patch":`workspace.manifest`,"workspace.reconcile.diff":`workspace.manifest`,"workspace.reconcile.ownership":`workspace.manifest`,"workspace.reconcile.apply":`workspace.manifest`,"workspace.reconcile.recover":`workspace.manifest`,"workspace.reconcile.temporary":`workspace.manifest`};function runtime(){return r(Symbol.for(`openclaw.gitOperations`),()=>({pending:/* @__PURE__ */ new Set}),e=>(e.closing??=(async()=>{await Promise.all(B.map(t=>e[t]?.close()??Promise.resolve())),await Promise.allSettled(e.pending);for(let t of B)e[t]=void 0})().finally(()=>{e.closing=void 0}),e.closing))}function poolFor(e,t,n,r){let 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.`)||t.type===`github.profile-stage`||t.type===`github.profile-refresh`?`worktrees`:t.type.startsWith(`workspace.`)?`workspace`:n?`content`:`reads`;return e[i]??=T({workerUrl:C(S.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:!0}:void 0)}async function runGitWorkerOperation(e,t={}){let n=runtime();if(n.closing||n.pending.size>=128)throw new w(`Git operation capacity is unavailable; retry the request.`,`unavailable`);t.signal?.throwIfAborted(),t.assertCurrent?.();let r=t.transferList?.(e),i=r?structuredClone(e,{transfer:[...new Set(r)]}):structuredClone(e),a=i.type.startsWith(`github.profile-`)||i.type===`checkout.bootstrap-workspace`,o=a?{}:{...process.env};i.filesystemRefs=!a&&t.git===void 0&&!Object.entries(o).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)))?F(`sha256`).update(JSON.stringify(Object.entries(o).filter(([e])=>/^(GIT_|HOME$|XDG_CONFIG_HOME$|PATH$|SUDO_UID$)/i.test(e)).toSorted(([e],[t])=>e.localeCompare(t)))).digest(`hex`):void 0;let s=executeOperation(n,i,o,{...t,git:t.git?{text:t.git.text,buffered:t.git.buffered}:void 0});return createPendingPromiseTracker(n.pending)(s)}async function executeOperation(e,t,n,r){let s=U.hasSubscribers?I.now():void 0,l=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,d=l!==void 0,p=t.type===`checkout.diff`&&t.input.summaryOnly===!0||t.type===`checkout.revision`&&t.input.scope===`diff`,g=t.type===`worktree.snapshot`||t.type===`worktree.snapshot-verify-exact`,y=d||g;g&&(n.GIT_NO_LAZY_FETCH=`1`,n.GIT_ALLOW_PROTOCOL=``);let S=0,C=0,w=0,T=0,E=0,D=0,O=null,k,A=l===void 0?void 0:_(`content-read`,H,()=>({operation:t.type,...t.type===`checkout.diff`?{scope:t.input.scope??`all`,summaryOnly:t.input.summaryOnly===!0}:{},checkoutId:F(`sha256`).update(N.resolve(l)).digest(`hex`).slice(0,16),checkoutClass:t.type===`pull-request.branch-facts`&&t.input.refreshIndex?`managed`:`unspecified`,gitCommandCount:S,workerQueueWaitMs:O,summedGitWallMs:Math.round(C),summedGitQueueWaitMs:Math.round(w),gitStdoutBytes:T,gitStderrBytes:E,gitTimeoutCount:D,slowestGitCommand:k})),j=!0,L=A||r.diffTiming,R=`threw`,z=/* @__PURE__ */ new Set,B=/* @__PURE__ */ new Set,G=/* @__PURE__ */ new Map,K,q=0,request=async(e,i)=>{try{i.throwIfAborted();let s=e,c,l=[];if(s.type===`git.text`||s.type===`git.buffer`){let e=L?I.now():0,execute=async()=>{let c=L?I.now():0,l=`threw`;A&&(S++,w+=c-e);try{let e=await b(W[t.type],async()=>{let e={...s.input.options,operation:W[t.type],baseEnv:n,signal:i,beforeRun:r.assertCurrent,killProcessTree:!0,lowerPriority:y};if(s.type===`git.text`){let t=await(r.git?.text??o)(s.input.cwd,s.input.args,e);if(t.cleanup===`uncertain`)throw new x;return t}let c=await(r.git?.buffered??a)(s.input.cwd,s.input.args,e);if(c.error&&(h(c.error)||v(c.error)?.cleanup===`uncertain`))throw c.error;return c});return A&&(l=e.termination,T+=e.stdout.byteLength,E+=e.stderr.byteLength,D+=Number(l===`timeout`)),e}finally{if(r.diffTiming){let e=r.diffTiming.durations;e[`git-wall`]=(e[`git-wall`]??0)+I.now()-c}if(A){let e=Math.round(I.now()-c);if(C+=e,!k||e>k.durationMs){let t=s.input.args,n=0;for(;n<t.length&&t[n].startsWith(`-`);)n+=t[n]===`-c`||t[n]===`-C`?2:1;let r=t[n]??``;k={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:l}}}}},d=await(y?withContentGitSlot(execute,i,p):execute()),f=u(d.stdout),m=u(d.stderr);c={...d,stdout:f,stderr:m},l.push(f.buffer,m.buffer)}else if(s.type===`git.temporary-directory`){let e=await M.mkdtemp(N.join(P.tmpdir(),`openclaw-git-operation-`));B.add(e),c=e}else if(s.type===`workspace.inventory.write`){if(!r.onInventoryChunk)throw Error(`Workspace inventory has no active output owner`);r.assertCurrent?.(),await r.onInventoryChunk(s.input.bytes,{signal:i})}else if(s.type===`workspace.manifest.read`){if(!r.readWorkspaceManifest)throw Error(`Workspace manifest has no active read owner`);r.assertCurrent?.();let e=await r.readWorkspaceManifest(s.input.knownTreeRoot,{signal:i});c=e,l.push(e.buffer)}else{if(!r.onEffect)throw Error(`Git read operation requested a lifecycle effect`);r.assertCurrent?.(),c=await r.onEffect(s,{signal:i})}return{input:{ok:!0,value:c},transferList:[...new Set(l)],timeoutMs:V}}catch(e){h(e)?K??=e instanceof Error?e:new x({cause:e}):v(e)?.cleanup===`uncertain`&&(K??=new x({cause:e}));let t=++q;return G.set(t,e),{input:{ok:!1,error:{...c(e),origin:t}},timeoutMs:V}}},J=t.type===`github.profile-refresh`?f(()=>r.assertCurrent?.(),r.signal):void 0;t.mutationAuthority=J?.buffer;try{let n=L?I.now():0,a=L?()=>{let e=I.now()-n;return O=Math.round(e),r.diffTiming&&(r.diffTiming.durations[`worker-queue`]=e),t}:t,o=await poolFor(e,t,d,p).run(a,{inputBytes:r.inputBytes,transferList:r.transferList,signal:r.signal,timeoutMs:V,onNotification:J?.onNotification??r.onNotification,onRequest:(e,t)=>{if(j&&(j=!1,A?.markPhase()),!i(e)||e.type!==`git.batch`||!i(e.input)||!Array.isArray(e.input.requests)||e.input.requests.length===0||e.input.requests.length>16)throw Error(`Invalid Git worker request batch`);let 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:V}));return createPendingPromiseTracker(z)(n)}});if(A?.markPhase(),J?.throwIfRefused(),!o.ok)throw o.error.origin!==void 0&&G.has(o.error.origin)?G.get(o.error.origin):m(o.error);return r.signal?.throwIfAborted(),r.assertCurrent?.(),r.diffTiming&&(r.diffTiming.revisionUnavailableReason=o.revisionUnavailableReason),R=`returned`,o.value}catch(e){throw J?.throwIfRefused(),e}finally{J?.dispose();let e=!1;try{await Promise.allSettled(z).then(()=>{if(K)throw K;return Promise.all([...B].map(e=>M.rm(e,{recursive:!0,force:!0})))}),e=!0}finally{A?.finish(e?R:`threw`),s!==void 0&&U.publish({operation:t.type,outcome:e&&R===`returned`?`ok`:`error`,elapsedMs:I.now()-s})}}}function computationInputBytes(e){if(typeof e==`string`)return e.length*2;if(ArrayBuffer.isView(e))return e.byteLength;if(e instanceof Set){let t=64;for(let n of e)t+=computationInputBytes(n);return t}return e&&typeof e==`object`?Object.entries(e).reduce((e,[t,n])=>e+t.length*2+computationInputBytes(n),64):8}function transferableManifestInput(e){if(`payload`in e.input)return[e.input.payload.buffer];switch(e.type){case`workspace.manifest.paths`:case`workspace.manifest.parse`:return[e.input.raw.buffer];case`workspace.manifest.base-refresh`:return[e.input.baseRaw.buffer];case`workspace.manifest.equal`:case`workspace.manifest.pair`:return[e.input.baseRaw.buffer,e.input.currentRaw.buffer];case`workspace.manifest.stage-input`:return`publication`in e.input?[e.input.publication.metadata.buffer]:[e.input.baseManifestRaw.buffer,e.input.currentManifestRaw.buffer];default:return[]}}async function computeWorkspaceManifest(e,t,n){if(p()){let{executeWorkspaceManifestComputation:t}=await import(`./git-operation.worker-workspace-manifest-computation.runtime-DBgiwfnP.mjs`);return await t(e)}return await runGitWorkerOperation(e,{signal:t,git:n,inputBytes:256+computationInputBytes(e.input),transferList:transferableManifestInput})}async function computeValue(e,t,n){return n?.throwIfAborted(),computeWorkspaceManifest({type:e,input:{payload:new TextEncoder().encode(JSON.stringify(t))}},n)}function captureHashes(e=!0){let t=D();return t&&e&&E(t.memo),{hashes:t?{owner:t.owner,entries:e?[...t.memo]:[]}:void 0,accept(e){if(t){for(let[n,r]of e.hashes)t.memo.set(n,r);E(t.memo),t.metrics&&(t.metrics.contentHashCount+=e.metrics.contentHashCount,t.metrics.memoHitCount+=e.metrics.memoHitCount)}return e.value}}}async function computeWorkspaceFileSnapshot(e,t,n){if(p()){let{readWorkspaceFileSnapshotWithLimit:r}=await import(`./git-operation.worker-workspace-actual-manifest-Y3A72WaR.mjs`).then(e=>e.a);return await r(e,t,n)}let r=captureHashes(!1);return r.accept(await computeValue(`workspace.manifest.file`,{path:e,maxBytes:t,root:n,hashes:r.hashes}))}async function readWorkspaceNodes(e,t){let n=captureHashes();return new Map(n.accept(await computeValue(`workspace.manifest.nodes`,{root:e,paths:t,hashes:n.hashes})))}async function prepareWorkspaceTreeInput(e){if(p()){let{buildWorkspaceTreeInput:t}=await import(`./git-operation.worker-workspace-result-preparation.runtime-BYrbIVgd.mjs`);return t(e)}return computeValue(`workspace.manifest.tree-input`,e)}async function prepareWorkspaceTemporaryDirectory(e,t){let n=await runWorkspaceFilesystemComputation({type:`workspace.reconcile.temporary`,input:{prefix:e}},t);return await M.mkdtemp(n)}async function runWorkspaceFilesystemComputation(e,t={}){try{var n=d();let r=await l(s([t.assertCurrent,t.workerAuthority?.assertCurrent]));n.a({[Symbol.asyncDispose]:async()=>await r.release?.()});let i=[.../* @__PURE__ */ new Set([...r.workspaceEvidence??[],...t.workerAuthority?.workspaceEvidence??[]])];if(`root`in e.input){let t=e.input.root,n=i.find(e=>e.workspaceDir===t);n||(n=await g(e.input.root),i.push(n)),e.input.root=n.canonical}let a=r.assertCurrent;a();let o=f(a,t.workerAuthority?.signal);try{let n={...e,mutation:{decision:o.buffer,filesystem:i,stateOwnerPath:t.workerAuthority?.stateOwnerPath,nativeMode:R().mode}},r=await runGitWorkerOperation(n,{assertCurrent:a,signal:t.workerAuthority?.signal,onNotification:o.onNotification,inputBytes:256+computationInputBytes(e.input)+computationInputBytes(n.mutation),transferList:transferableManifestInput});return o.throwIfRefused(),r}catch(e){throw o.throwIfRefused(),e}finally{o.dispose()}}catch(e){n.e=e}finally{await n.d()}}function localPath(e,t){return N.join(e,...t.split(`/`))}async function removeEmptyWorkspaceDirectory(t,n){let r;try{r=await t.list(n)}catch(t){if(t instanceof e&&[`not-found`,`path-alias`].includes(t.code))return;throw t}if(!(r.length>0))try{await t.remove(n)}catch(r){if(r instanceof e&&[`not-found`,`path-alias`].includes(r.code)||(await t.list(n).catch(()=>void 0))?.length)return;throw r}}async function localWorkspaceNode(e,t){let r=localPath(e,t),i=await n(r);if(i)return i.isDirectory()&&!i.isSymbolicLink()?{path:t,type:`directory`}:i.isSymbolicLink()?{path:t,type:`symlink`,mode:511,target:await M.readlink(r)}:i.isFile()?{path:t,...await computeWorkspaceFileSnapshot(r,k,e)}:{path:t,type:`unsupported`}}async function fileEntryMatches(e,t){let n=await computeWorkspaceFileSnapshot(e,k).catch(e=>{if(e instanceof w)throw e});return n?.type===`file`&&n.mode===t.mode&&n.size===t.size&&n.sha256===t.sha256}async function absoluteEntryMatches(e,t){let n=await M.lstat(e).catch(()=>void 0);return n?t.type===`symlink`?n.isSymbolicLink()&&await M.readlink(e)===t.target:!n.isFile()||n.isSymbolicLink()?!1:await fileEntryMatches(e,t):!1}async function readWorkspaceTreeFile(e){let t=await j(e.repositoryRoot,[`--literal-pathspecs`,`ls-tree`,`-z`,`--full-tree`,e.tree,`--`,e.entry.path],{maxOutputBytes:1048576},`git ls-tree failed`),n=t.indexOf(0),r=t.indexOf(9);if(n!==t.byteLength-1||r<0||r>n)throw Error(`Cloud workspace recovery snapshot is missing: ${e.entry.path}`);let i=t.subarray(0,r).toString(`utf8`),a=/^100(?:644|755) blob ([a-f0-9]{40})$/u.exec(i),o=t.subarray(r+1,n);if(!a||!o.equals(Buffer.from(e.entry.path)))throw Error(`Cloud workspace recovery snapshot is invalid: ${e.entry.path}`);let s=await j(e.repositoryRoot,[`cat-file`,`blob`,a[1]],{maxOutputBytes:k+1});if(s.byteLength!==e.entry.size||F(`sha256`).update(s).digest(`hex`)!==e.entry.sha256)throw Error(`Cloud workspace recovery snapshot is invalid: ${e.entry.path}`);return s}async function directoryContainsOnlyWorkspaceEntries(e,t,n,r,i=!1){let a=!1;for(let o of await M.readdir(localPath(e,t))){let s=`${t}/${o}`;if(A(s))return!1;if(!O(s,await n(s),i)){let t=await M.lstat(localPath(e,s));if(t.isDirectory()&&!t.isSymbolicLink()){if(!await directoryContainsOnlyWorkspaceEntries(e,s,n,r?.directories.has(s)?r:void 0,i))return!1}else if(!r?.paths.has(s))return!1}a=!0}return r!==void 0||a}export{runWorkspaceFilesystemComputation as a,absoluteEntryMatches,directoryContainsOnlyWorkspaceEntries,readWorkspaceNodes as i,localPath,localWorkspaceNode,prepareWorkspaceTemporaryDirectory as n,prepareWorkspaceTreeInput as r,readWorkspaceTreeFile,removeEmptyWorkspaceDirectory,computeWorkspaceManifest as t};