UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

189 lines • 52.3 kB
import{r as e,t}from"./openclaw-state-read-semver-CqfGj9gv.mjs";import{C as n,a as r,ft as i,ht as a,it as o,mt as s,x as c}from"./openclaw-state-read-map-size-DJbMcZYM.mjs";import{g as l,l as u,v as d}from"./openclaw-state-read-home-dir-BQZX1pD2.mjs";import{a as f}from"./openclaw-state-read-src-BpoB6DKe.mjs";import{C as p,E as m,G as h,P as g,Q as _,S as v,W as y,Z as b,a as ee,g as te,h as x,v as ne,w as re}from"./openclaw-state-read-logger-Ix7jXPG1.mjs";import{t as ie}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{a as ae,r as oe}from"./openclaw-state-read-record-coerce-D1s3ReAs.mjs";import{_ as S,a as se,f as C,l as ce,p as w,v as le}from"./openclaw-state-read-schemas-CLrAtqTl.mjs";import{n as ue,r as T,t as de}from"./openclaw-state-read-process-env-DgVwfN3Y.mjs";import"./openclaw-state-read-runtime-process-entrypoints-ItwYqjQs.mjs";import"./openclaw-state-read-runtime-worker-url-ClM3d-g2.mjs";import{t as E}from"./openclaw-state-read-subsystem-DSi0tJn8.mjs";import{t as fe}from"./openclaw-state-read-errors-D_saNBXy.mjs";import{n as D}from"./openclaw-state-read-spawn-diagnostics-CpCgfk1o.mjs";import{a as pe,l as me}from"./openclaw-state-read-errors-BhOrSl8J.mjs";import"./openclaw-state-read-workspace-state-identity-CGvxbhyj.mjs";import"./openclaw-state-read-worker-task-pool-BbckrCtm.mjs";import"./openclaw-state-read-openclaw-state-db-readonly-CDG18cNK.mjs";import"./openclaw-state-read-sqlite-handle-lifecycle-DQ13SM2U.mjs";import{t as he}from"./openclaw-state-read-windows-appcontainer-spawn-B9xODvkk.mjs";import{qt as ge}from"./openclaw-state-read.worker.js";import"./openclaw-state-read-agent-scope-config-DBTVDK8I.mjs";import{r as _e}from"./openclaw-state-read-workspace-state-guard-lmfygG7O.mjs";import"./openclaw-state-read-backoff-DDprjZZH.mjs";import{t as ve}from"./openclaw-state-read-keyed-async-queue-DZZQbGP9.mjs";import"./openclaw-state-read-agent-deletion-journal-recovery.kernel-DxhVBGkd.mjs";import{n as ye}from"./openclaw-state-read-session-source-authority-B_K2ljxL.mjs";import{t as be}from"./openclaw-state-read-windows-install-roots-nshDFN0K.mjs";import O from"node:path";import{isMainThread as xe,threadId as Se}from"node:worker_threads";import{spawnSync as Ce}from"node:child_process";import we from"node:fs/promises";import Te from"node:os";import{createHash as Ee}from"node:crypto";import{AsyncLocalStorage as k}from"node:async_hooks";import{getSystemErrorMap as De}from"node:util";import{performance as A}from"node:perf_hooks";import{compileFunction as j}from"node:vm";const M=Symbol.for(`openclaw.command-cleanup-uncertain`),Oe=`Command cleanup could not confirm that owned work stopped`;function isCanonicalCommandProcessCleanupError(e){try{return Object.getOwnPropertyDescriptor(e,M)?.value===!0}catch{return!1}}var CommandProcessCleanupError=class extends Error{constructor(e){let t=Oe;for(let n of i(e?.cause))if(isCanonicalCommandProcessCleanupError(n))try{let e=Object.getOwnPropertyDescriptor(n,`message`)?.value;if(typeof e==`string`&&e.trim()&&e!==Oe){t=e;break}}catch{}super(t,e),this.code=`ERR_COMMAND_PROCESS_CLEANUP_UNCERTAIN`,this.cleanup=`uncertain`,this.name=`CommandProcessCleanupError`,Object.defineProperty(this,M,{value:!0})}};function hasCommandProcessCleanupError(e){return i(e).some(isCanonicalCommandProcessCleanupError)}const N=Symbol.for(`openclaw.command-process-cleanup`);function recordCommandProcessCleanup(e,t){return t?Object.defineProperty(e,N,{value:t}):e}function readCommandProcessCleanup(e){return Object.getOwnPropertyDescriptor(e,N)?.value}const P=Symbol.for(`openclaw.command-process-outcome`);function recordCommandProcessFailure(e,t){let n=a(e,`Command failed`),r=Object.isExtensible(n)?n:Error(n.message,{cause:n});return Object.defineProperty(r,P,{value:Object.freeze({...t}),configurable:!0})}function readCommandProcessFailure(e){for(let t of i(e))try{let e=ae(t)?Object.getOwnPropertyDescriptor(t,P):void 0;if(e?.value)return e.value}catch{return}}function createInterruptedCommandOutcome(e){let{reason:t,pid:n,killed:r}=e;return{pid:n,code:t===`timeout`||t===`no-output-timeout`?124:null,signal:null,killed:r,killIssuedByAbort:t===`signal`||t===`output-limit`||void 0,cleanup:`uncertain`,termination:t===`output-limit`?`signal`:t,noOutputTimedOut:t===`no-output-timeout`,outputLimitExceeded:t===`output-limit`||void 0}}function createSanitizedCommandError(e){let t=typeof e.code==`string`?e.code:void 0,n=typeof e.exitCode==`number`?e.exitCode:void 0,r=typeof e.signal==`string`?e.signal:void 0,i=e.timedOut?`Command timed out`:e.isMaxBuffer?`Command output exceeded its capture limit`:e.isCanceled?`Command was canceled`:e.isTerminated?`Command was terminated${r?` by ${r}`:``}`:n!==void 0&&n!==0?`Command exited with code ${n}`:`Command failed during launch or output capture${t?` (${t})`:``}`;return Object.assign(Error(i),{...t?{code:t}:{},...n===void 0?{}:{exitCode:n},...r?{signal:r}:{}})}function isPlainCommandExitFailure(e){return e.failed&&typeof e.exitCode==`number`&&e.exitCode!==0&&e.signal===void 0&&e.cause===void 0&&!e.timedOut&&!e.isCanceled&&!e.isMaxBuffer&&!e.isTerminated}function isPlainCommandSignalFailure(e){return e.failed&&e.exitCode===void 0&&typeof e.signal==`string`&&e.cause===void 0&&!e.timedOut&&!e.isCanceled&&!e.isMaxBuffer&&e.isTerminated===!0}function resolveProcessExitCode(e){return e.explicitCode??e.childExitCode??(e.usesWindowsExitCodeShim&&e.resolvedSignal==null&&!e.timedOut&&!e.noOutputTimedOut&&!e.killIssuedByTimeout&&!e.killIssuedByAbort?0:null)}t();function monotonicNow(){return performance.now()}var ke=/* @__PURE__ */ e({STAGED_INPUT_GITIGNORE:()=>F,STAGED_INPUT_GIT_PATHSPEC:()=>STAGED_INPUT_GIT_PATHSPEC,STAGED_INPUT_MAX_BYTES:()=>STAGED_INPUT_MAX_BYTES,STAGED_INPUT_PATHS_JS:()=>I,createStagedInputPathMatcher:()=>createStagedInputPathMatcher,isStagedInputPath:()=>je,stagedInputDirectoriesFromEntries:()=>R,stagedInputPathDirectory:()=>L});const F=`# Raw task inputs remain private; copy outputs into the project to publish.
*
`,Ae=Ee(`sha256`).update(F).digest(`hex`),I=String.raw`
const STAGED_INPUT_DIRECTORY_PREFIX = ${JSON.stringify(`media/inbound/openclaw-staged-`)};
const STAGED_INPUT_GITIGNORE = ${JSON.stringify(F)};
const STAGED_INPUT_GITIGNORE_SHA256 = ${JSON.stringify(Ae)};
// A producer-shaped name is only a candidate; the marker establishes ownership.
function stagedInputPathDirectory(relativePath) {
  if (!relativePath.startsWith(STAGED_INPUT_DIRECTORY_PREFIX)) {
    return undefined;
  }
  const identity = relativePath.slice(STAGED_INPUT_DIRECTORY_PREFIX.length).split("/")[0];
  const match =
    /^(?:[a-f0-9]{64}|[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12})$/u.exec(
      identity,
    );
  return match?.[0] === identity ? STAGED_INPUT_DIRECTORY_PREFIX + identity : undefined;
}

function isStagedInputPath(relativePath, directories) {
  const directory = stagedInputPathDirectory(relativePath);
  return directory !== undefined && directories.has(directory);
}

// Complete manifests bind the regular marker's exact bytes through their file digest.
function stagedInputDirectoriesFromEntries(entries) {
  const directories = new Set();
  for (const entry of entries) {
    const directory = stagedInputPathDirectory(entry.path);
    if (
      directory &&
      entry.path === directory + "/.gitignore" &&
      entry.type === "file" &&
      entry.size === STAGED_INPUT_GITIGNORE.length &&
      entry.sha256 === STAGED_INPUT_GITIGNORE_SHA256
    ) {
      directories.add(directory);
    }
  }
  return directories;
}`,{stagedInputPathDirectory:L,isStagedInputPath:je,stagedInputDirectoriesFromEntries:R}=j(`${I}\nreturn { stagedInputPathDirectory, isStagedInputPath, stagedInputDirectoriesFromEntries };`)();function createStagedInputPathMatcher(e){let t=/* @__PURE__ */ new Map;return async n=>{let r=L(n);if(!r)return!1;let i=t.get(r);return i||(i=e.readText(`${r}/.gitignore`,{maxBytes:78}).then(e=>e===F,()=>!1),t.set(r,i)),await i}}w({version:ce(1),manifestRef:S().regex(/^sha256:[a-f0-9]{64}$/u),memo:se(le([S().regex(/^worker:\d+:\d+:\d+:\d+:\d+$/u),S().regex(/^[a-f0-9]{64}$/u)])).max(25e3),metrics:w({contentHashCount:C().finite().nonnegative(),memoHitCount:C().finite().nonnegative(),memoTruncatedCount:C().finite().nonnegative()}).strict()}).strict();const z=new k;function activeWorkspaceHashContext(){return z.getStore()}async function withWorkspaceHashMemo(e,t,n){let r=z.getStore(),i=n??r?.metrics;return r?.memo===e&&r.metrics===i?await t():await z.run({memo:e,metrics:i,owner:r?.owner??`gateway`},t)}async function withWorkerWorkspaceHashMemo(e,t,n){return await z.run({memo:e,owner:`worker`,metrics:n},t)}async function withoutWorkspaceHashContext(e){return await z.exit(e)}function pruneWorkspaceHashMemo(e){let t=0;e.forEach((e,n)=>{t+=n.length+e.length});for(let[n,r]of e){if(t<=8388608)break;e.delete(n),t-=n.length+r.length}}const Me=String.raw`
const WORKSPACE_CTIME_SAFETY_MARGIN_MS = 2000;
function workspaceCtimeIsReusable(ctimeNs, startedAtMs) {
  // Recent files cost another hash; a backwards clock keeps them outside the reuse window.
  return ctimeNs >= 0n && ctimeNs < BigInt(startedAtMs - WORKSPACE_CTIME_SAFETY_MARGIN_MS) * 1000000n;
}
function workspaceStatIdentity(owner, stats) {
  return [owner, stats.dev, stats.ino, stats.size, stats.mtimeNs, stats.ctimeNs].join(":");
}
function selectWorkerWorkspaceHashMemoEntries(memo, maxEntries, maxBytes) {
  const compareIdentity = ([left], [right]) =>
    left < right ? -1 : left > right ? 1 : 0;
  const candidates = [...memo]
    .filter(([identity]) => identity.startsWith("worker:"))
    .map((entry) => ({ entry, size: Number(entry[0].split(":")[3]) }))
    .toSorted((left, right) => right.size - left.size || compareIdentity(left.entry, right.entry));
  const selected = [];
  let bytes = 2;
  for (const { entry } of candidates) {
    if (selected.length === maxEntries) {
      break;
    }
    const entryBytes = Buffer.byteLength(JSON.stringify(entry)) + (selected.length > 0 ? 1 : 0);
    if (bytes + entryBytes <= maxBytes) {
      selected.push(entry);
      bytes += entryBytes;
    }
  }
  return selected.toSorted(compareIdentity);
}`,{workspaceCtimeIsReusable:Ne,workspaceStatIdentity:Pe,selectWorkerWorkspaceHashMemoEntries:Fe}=j(`${Me}\nreturn { workspaceCtimeIsReusable, workspaceStatIdentity, selectWorkerWorkspaceHashMemoEntries };`)();function formatCommandOutput(e,t=800){let n=h(e.toString()).replace(/(^|[^\r])\r+(?=\n|$)/g,`$1`).replace(/(^|\n)[^\n]*\r/g,`$1`).trim().split(`
`),r=n.slice(-12).map(g).join(`
`);return`${n.length>12||r.length>t?`…
`:``}${b(r,Math.max(0,r.length-t))}`}function createCommandError(e,t,n){let r=formatCommandOutput(t.stderr,2e3),i=formatCommandOutput(t.stdout,2e3),a=r||i;if(r&&i){let e=1983,t=Math.min(r.length,Math.max(992,e-i.length)),tail=(e,t)=>e.length<=t?e:`…\n${b(e,2-t)}`;a=`stderr: ${tail(r,t)}\nstdout: ${tail(i,e-t)}`}if(t.error){let e=formatCommandOutput(s(t.error,{includeCode:!0}),2e3);a=[a,e].filter(Boolean).join(`
`)}let o=t.signal?`signal ${t.signal}`:``,c=`outputLimitExceeded`in t&&t.outputLimitExceeded?`output limit exceeded`:``,l=c||(!o&&t.code!==null?`exit code ${t.code}`:``),u=[{timeout:`timed out after ${n.timeoutMs/1e3} seconds`,"no-output-timeout":`timed out waiting for output`,"output-limit":`output limit exceeded`,exit:l,error:l,signal:c||(o?``:`terminated`)}[t.termination],o].filter(Boolean).join(`; `),d=_(h(e).replace(/[\r\n]+/g,` `),256),f=Error(`${d} failed${u?` (${u})`:``}${a?`:\n${a}`:``}`,t.error?{cause:t.error}:void 0);return f.name=`CommandExecutionError`,f}const Ie=E(`git/network`),Le=[1e3];function gitCommandName(e){for(let t=0;t<e.length;t+=1){let n=e[t];if([`-c`,`-C`,`--git-dir`,`--work-tree`,`--namespace`,`--config-env`].includes(n))t+=1;else if(/^(?:-c.+|-C.+|--(?:git-dir|work-tree|namespace|config-env|attr-source)=.+)$/u.test(n)||[`--no-optional-locks`,`--no-lazy-fetch`,`--no-replace-objects`,`--bare`,`--literal-pathspecs`,`--no-pager`].includes(n))continue;else return n}}function retryableGitNetworkOperation(e){let t=gitCommandName(e);return t===`fetch`||t===`ls-remote`?t:void 0}function isTransientGitFailure(e){if(e.termination!==`exit`||e.code===null||e.code===0||e.killed||e.signal||e.outputLimitExceeded||e.outputErrorStream||e.cleanup===`uncertain`)return!1;let t=typeof e.stderr==`string`?e.stderr:Buffer.from(e.stderr).toString(`utf8`);return!/authentication failed|permission denied|access denied|repository not found|could not read username|couldn't find remote ref|not our ref|certificate|host key verification failed|no space left|disk quota|cannot lock ref|bad object|checksum|corrupt|inflate:|hash mismatch|SHA(?:1|256) mismatch|CRC mismatch|returned error: (?:401|403|404)\b/iu.test(t)&&/did not send all necessary objects|could not resolve (?:host|proxy)|temporary failure in name resolution|failed to connect|connection (?:reset|timed out|refused|closed)|transfer closed with \d+ bytes remaining to read|remote end hung up unexpectedly|unexpected disconnect|\bEOF\b|ECONNRESET|ETIMEDOUT|empty reply from server|TLS connection was non-properly terminated|SSL_ERROR_SYSCALL|HTTP\/2.*(?:stream|internal_error)|RPC failed; curl (?:5|6|7|18|28|35|52|55|56|92)\b|returned error: (?:408|429|5\d\d)\b/iu.test(t)}async function withGitNetworkRetry(e,t,n){let r=A.now()+(t.timeoutMs??1/0),attempt=e=>{let start=()=>(t.beforeRun?.(),n(e));return t.startRun?t.startRun(start):start()},i=await attempt(t.timeoutMs),a=t.retryDelaysMs??Le,cancelled=()=>({...i,code:null,signal:null,termination:`signal`});for(let[n,o]of a.entries()){if(!e||!isTransientGitFailure(i))break;if(t.signal?.aborted)return cancelled();if(r-A.now()<=o)break;Ie.warn(`Git ${e} hit a transient failure; retrying`,{operation:e,attempt:n+1,maxAttempts:a.length+1,delayMs:o,exitCode:i.code});try{await f(o,t.signal)}catch(e){if(t.signal?.aborted)return cancelled();throw e}if(t.signal?.aborted)return cancelled();let s=Math.floor(r-A.now());if(s<=0)break;i=await attempt(t.timeoutMs===void 0?void 0:s)}return i}const Re=RegExp(`\\(reason=(?:source-disappeared|source-identity-changed|journal-state-changed|journal-mode-changed|wal-copy-unstable|wal-changed-during-copy|main-changed-during-copy|rollback-journal-changed-during-copy|recovery-data-appeared|retained-snapshot-changed), attempts=[1-9][0-9]{0,2}\\)`,`u`);function readPublicSupportCauses(e){return(e.match(/\b(?:GLIBC_\d{1,3}(?:\.\d{1,3}){1,2} not found|[Cc]onnection (?:refused|closed|timed out|reset by peer)|[Pp]ermission denied(?: \((?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic|gssapi-keyex)(?:,(?:publickey|password|keyboard-interactive|hostbased|gssapi-with-mic|gssapi-keyex)){0,5}\))?|[Nn]o space left on device|MCP error -?\d{1,5}|HTTP [1-5]\d{2}|Invalid package dist content inventory(?: entry)?(?:: (?:malformed metadata|content mismatch|executable permission mismatch))?|SQLite (?:snapshot (?:hash|size) mismatch|file generation (?:changed while reading|did not stabilize)|source did not stabilize|WAL commit (?:header is unavailable or changing|publication could not be verified))|Package rollback (?:launcher backup changed|verification (?:timed out|failed))|attempt state write refused|sentinel transaction (?:refused|unavailable)|pipe closed|managed update handoff (?:exited before (?:responding|signaling readiness)|did not (?:respond|signal readiness))|Could not resolve host(?:name)?|Temporary failure in name resolution|Name or service not known|[Nn]etwork is unreachable|Failed to connect|Couldn't connect to server|[Oo]peration timed out|SSL certificate problem|server certificate verification failed|gnutls_handshake\(\) failed|[Uu]nable to access|Authentication failed|terminal prompts disabled|[Rr]epository not found|The requested URL returned error: [1-5]\d{2}|Could not read from remote repository|remote end hung up unexpectedly|RPC failed|early EOF|unexpected disconnect while reading sideband packet|index-pack failed|not a git repository|already exists and is not an empty directory|would be overwritten by (?:merge|checkout)|CONFLICT \((?:content|add\/add|modify\/delete|delete\/modify|rename\/delete|rename\/rename|rename\/add|file\/directory|directory\/file|distinct types|submodule)\))(?!\w)/gu)??[]).map(e=>e.replace(/^permission denied$/u,`Permission denied`)).concat(e.match(Re)??[]).concat(e.match(/^Update database (?:backup|rollback|capture) volume: needs \d{1,8}(?:\.\d)? (?:MiB|GiB); available \d{1,8}(?:\.\d)? (?:MiB|GiB)$/gmu)??[])}const ze=/\bBasic\s+[A-Za-z0-9+/]+={0,2}/giu,Be=/\b(Cookie|Set-Cookie)\s*:\s*[^\r\n]+/giu,Ve=/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/gu,He=ne({patterns:p}).patterns.filter(e=>e!==v),Ue=/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/gu,We=/\b([a-z][a-z0-9+.-]*:\/\/)([^/@\s:?#]+)(?::([^/@\s?#]+))?@/giu,Ge=/([?&])([^=&\s]+)=([^&#\s]+)/giu,Ke=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu,qe=/@[A-Za-z0-9._=-]+:[A-Za-z0-9.-]+/gu,Je=/![A-Za-z0-9._=-]+:[A-Za-z0-9.-]+/gu,Ye=/\$[A-Za-z0-9_-]{16,}/gu,Xe=/(^|[^\w:/])@(?!openclaw\/[a-z0-9])[A-Za-z0-9_]{5,}\b(?!\.)/gu,Ze=/\b\d{9,}\b/gu;function isWindowsAbsolutePath(e){return/^(?:[A-Za-z]:[\\/]|\\\\)/u.test(e)}let B;function pathRedactionPrefixes(e){let t=[e.stateDir,e.env.HOME,e.env.USERPROFILE];if(t.some(e=>e&&!O.isAbsolute(e)&&!isWindowsAbsolutePath(e)))return buildPathRedactionPrefixes(e);let n=B;if(n&&t.every((e,t)=>e===n.inputs[t]))return n.prefixes;let r=buildPathRedactionPrefixes(e);return B={inputs:t,prefixes:r},r}function buildPathRedactionPrefixes(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of[[e.stateDir,`$OPENCLAW_STATE_DIR`],[e.env.HOME,`~`],[e.env.USERPROFILE,`~`]]){if(!n)continue;let e=isWindowsAbsolutePath(n)?O.win32.resolve(n):O.resolve(n),i=isWindowsAbsolutePath(e);for(let n of i?[e,e.replaceAll(`\\`,`/`)]:[e])t.has(n)||t.set(n,{prefix:n,label:r,caseInsensitive:i})}return[...t.values()].toSorted((e,t)=>t.prefix.length-e.prefix.length)}function pathCandidates(e){if(!isWindowsAbsolutePath(e))return[O.resolve(e)];let t=O.win32.resolve(e),n=[t,t.replaceAll(`\\`,`/`)],r=V.exec(e);if(r){let t=e.slice(r[0].length),i;/^UNC[\\/]/iu.test(t)?i=O.win32.resolve(`\\\\${t.slice(4)}`):/^[A-Za-z]:[\\/]/u.test(t)&&(i=O.win32.resolve(t)),i!==void 0&&n.push(i,i.replaceAll(`\\`,`/`))}return n}function hasPathPrefix(e,t){return t.caseInsensitive?e.toLowerCase().startsWith(t.prefix.toLowerCase()):e.startsWith(t.prefix)}function matchPathPrefix(e,t){if(e.length===t.prefix.length&&hasPathPrefix(e,t))return``;if(!hasPathPrefix(e,t))return;let n=e[t.prefix.length];return n===`/`||n===`\\`?e.slice(t.prefix.length):void 0}function isSupportAbsolutePath(e){return O.isAbsolute(e)||isWindowsAbsolutePath(e)}function redactPathForSupport(e,t){if(e==null||typeof e!=`string`)return``;if(e.startsWith(`$`))return e;let n=pathCandidates(e),r=pathRedactionPrefixes(t);for(let e of n)for(let t of r){let n=matchPathPrefix(e,t);if(n!==void 0)return`${t.label}${n}`}return x(n[0]??e,{mode:`tools`})}const V=/^\\\\[?.][\\/]/u;function namespaceMarkerLengthBefore(e,t){let n=t-4;return V.test(e.slice(n,t))?4:0}function replaceKnownPathPrefix(e,t){let n=t.caseInsensitive?t.prefix.toLowerCase():t.prefix,r=t.caseInsensitive?e.toLowerCase():e,i=0,a=``;for(;i<e.length;){let o=r.indexOf(n,i);if(o===-1){a+=e.slice(i);break}a+=e.slice(i,o-namespaceMarkerLengthBefore(e,o)),a+=t.label,i=o+t.prefix.length}return a}function redactKnownPathPrefixesForSupport(e,t){let n=e;for(let e of pathRedactionPrefixes(t))n=replaceKnownPathPrefix(n,e);return n}function redactTextForSupport(e){let t=e.replace(ze,`Basic <redacted>`).replace(Be,`$1: <redacted>`).replace(Ve,`<redacted-aws-key>`).replace(Ue,`<redacted-jwt>`),n=re(te(t,He,{fullContext:!0}),v,()=>`<redacted-aws-secret-key>`);return x(n,{mode:`tools`}).replace(We,(e,t,n,r)=>r?`${t}<redacted>:<redacted>@`:`${t}<redacted>@`).replace(Ge,(e,t,n)=>m(n)?`${t}${n}=<redacted>`:e).replace(qe,`<redacted-matrix-user>`).replace(Je,`<redacted-matrix-room>`).replace(Ye,e=>e===`$OPENCLAW_STATE_DIR`?e:`<redacted-matrix-event>`).replace(Ke,`<redacted-email>`).replace(Xe,`$1<redacted-handle>`).replace(Ze,`<redacted-id>`)}function redactSupportString(e,t,n={}){let r=n.maxLength??2e3,i=n.truncationSuffix??`...<truncated>`,a=redactTextForSupport(e),o=isSupportAbsolutePath(a)?redactPathForSupport(a,t):redactKnownPathPrefixesForSupport(a,t);return o.length<=r?o:`${_(o,r)}${i}`}function redactSupportDiagnosticLine(e,t,n=200){let r=redactSupportString(y(h(e).split(/[\r\n\u2028\u2029]/u).find(e=>e.trim())??``),t,{maxLength:2**53-1}).replace(t.redactRelativePaths?/^.*[\\/].*/u:/["'`]?(?:file:\/\/|\$OPENCLAW_STATE_DIR|(?:^|(?<=[\s=(:["'`]))(?:~[\\/]|[A-Za-z]:[\\/]|\/+|\\+)).*/gu,`[redacted-path]`).replace(/\b(?:Command failed:|command (?:sh|cmd|powershell|bash)\b).*/giu,`[redacted-command]`),i=/\bversion [`'"](GLIBC_\d{1,3}(?:\.\d{1,3}){1,2})['"] not found\b/u.exec(e)?.[1],a=r.trim(),o=[...i?[`${i} not found`]:[],...readPublicSupportCauses(h(e))].filter((e,t,n)=>n.indexOf(e)===t&&!a.toLowerCase().includes(e.toLowerCase()));return _([...o,a].filter(Boolean).join(`; `),n)}[...Array.from(De().values(),([e])=>e)];const H=`string|number|boolean|object|array|null|undefined|bigint|symbol|function|date|nan|int`;RegExp(`^(?:Invalid input: )?expected (${H}), (?:received|got) (${H})$`,`u`);function createFixedWindowBudget(e){let t=o(e.maxRequests,1,{min:1}),n=o(e.windowMs,1,{min:1}),r=e.now??monotonicNow,i=0,a;return{consume(){let e=r();return(a===void 0||e-a>=n)&&(a=e,i=0),i>=t?{allowed:!1,retryAfterMs:Math.max(0,a+n-e)}:(i+=1,{allowed:!0,retryAfterMs:0})}}}const diagnosticNow=()=>A.now(),Qe={"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`]}},$e=[[`preparation`,`preparationMs`],[`snapshot`,`snapshotMs`],[`checkoutRemoval`,`checkoutRemovalMs`],[`finalization`,`bodyFinalizeMs`]];function startGitOperationTiming(e,t,i){try{if(e!==`worktree-removal`&&(!r()||!t.isEnabled(`info`)))return;let a=A.now(),o=c(),s=Qe[e],l,u,f,p,m=0,h,g,_;return{recordRecovery(e){_=e?.startsWith(`refs/openclaw/snapshots/clean-v1/`)?`head`:e?`capture`:`none`},recordInventory(e){g=e},removalProgress(){return{stage:p??f??`preparation`,elapsedMs:Math.round(A.now()-a)}},markRemovalFailure(){p??=f},markPhase(){l===void 0?l=A.now():u=A.now()},markRemovalStage(t){if(e!==`worktree-removal`)return;let n=A.now();f!==void 0&&(h??={},h[f]=(h[f]??0)+n-m),f=t,m=n},finish(c,f){try{let p=A.now(),m=p-a;if(m<1e3||!r()||!t.isEnabled(`info`))return;let v=d(Symbol.for(s.stateKey),()=>({budget:createFixedWindowBudget({maxRequests:60,windowMs:6e4,now:diagnosticNow}),omitted:0}));if(!v.budget.consume().allowed){v.omitted=Math.min(2**53-1,v.omitted+1);return}let y={pid:process.pid,threadId:Se,isMainThread:xe,durationMs:Math.round(m),[s.phases[0]]:Math.round((l??p)-a),...l!==void 0&&u!==void 0?{[s.phases[1]]:Math.round(u-l),[s.phases[2]]:Math.round(p-u)}:{},...Object.fromEntries($e.flatMap(([e,t])=>{let n=h?.[e];return n===void 0?[]:[[t,Math.round(n)]]})),callbackEntered:(e===`ref-mutation`?u:l)!==void 0,outcome:c,...e===`worktree-removal`&&c===`threw`?{errorType:(f instanceof Error?f.constructor.name:typeof f).slice(0,80),error:redactSupportDiagnosticLine(fe(f),{env:{},stateDir:``,redactRelativePaths:!0},500)}:{},omittedObservations:v.omitted,...i?.(),...e===`worktree-removal`?{tracked:g?.tracked??null,untracked:g?.untracked??null,..._?{recovery:_}:{}}:{}};n(o,()=>t.info(e===`ref-mutation`?s.message:`${s.message} ${JSON.stringify(y)}`,y)),v.omitted=0}catch{}}}}catch{return}}const et={65001:`utf-8`,54936:`gb18030`,874:`windows-874`,936:`gbk`,950:`big5`,932:`shift_jis`,949:`euc-kr`,1250:`windows-1250`,1251:`windows-1251`,1252:`windows-1252`,1253:`windows-1253`,1254:`windows-1254`,1255:`windows-1255`,1256:`windows-1256`,1257:`windows-1257`,1258:`windows-1258`};new Map(Object.entries({65001:`utf-8`,874:`windows-874`,932:`shift_jis`,936:`gbk`,949:`euc-kr`,950:`big5`,1258:`windows-1258`,437:`cp437`,720:`cp720`,737:`cp737`,775:`cp775`,850:`cp850`,852:`cp852`,855:`cp855`,857:`cp857`,858:`cp858`,860:`cp860`,861:`cp861`,862:`cp862`,863:`cp863`,865:`cp865`,866:`cp866`,869:`cp869`}).map(([e,t])=>[t,Number.parseInt(e,10)]));let U;function parseWindowsCodePage(e){let t=Number(e.match(/\b(\d{3,5})\b/)?.[1]);return t>0?t:null}function resolveWindowsConsoleEncoding(){return process.platform===`win32`?(U===void 0&&(U=probeWindowsEncoding(be,[`/d`,`/s`,`/c`,`chcp`])),U):null}function probeWindowsEncoding(e,t){he();try{let n=Ce(e(),t,{env:ue(),windowsHide:!0,encoding:`utf8`,killSignal:`SIGKILL`,stdio:[`ignore`,`pipe`,`pipe`],timeout:5e3}),r=parseWindowsCodePage(`${n.stdout??``}\n${n.stderr??``}`);return r===null?null:et[r]??null}catch{return null}}function decodeWindowsOutputBuffer(e){return decodeWindowsBufferWithFallback({...e,resolveFallbackEncoding:()=>e.windowsEncoding??resolveWindowsConsoleEncoding()})}function decodeUtf16BomBuffer(e){let[t,n]=e;return t===255&&n===254||t===254&&n===255?new TextDecoder(t===255?`utf-16le`:`utf-16be`).decode(e):void 0}function decodeWindowsBufferWithFallback(e){if((e.platform??process.platform)!==`win32`)return e.buffer.toString(`utf8`);let t=decodeUtf16BomBuffer(e.buffer);if(t!==void 0)return t;let n=decodeStrictUtf8(e.buffer);if(n!==null)return n;let r=e.resolveFallbackEncoding();if(!r||u(r)===`utf-8`)return e.buffer.toString(`utf8`);try{return new TextDecoder(r).decode(e.buffer)}catch{return e.buffer.toString(`utf8`)}}function decodeStrictUtf8(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return null}}function gitReadOnlyEnvironment(e,t=process.env){let 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 tt=d(Symbol.for(`openclaw.gitRefMutations`),()=>new ve),nt=E(`git/ref-mutation`);async function enqueueGitRefMutation(e,t,n,r){let i=startGitOperationTiming(`ref-mutation`,nt),a=`threw`,o={run:n,signal:r,timing:i,completion:ie()},s=o,abort=()=>{let e=s;s=void 0,e?.completion.reject(e.signal?.reason)};try{r?.throwIfAborted();let n=normalizeGitPathForFilesystem(t),c=await we.realpath(O.resolve(e,n));r?.throwIfAborted();let l=process.platform===`win32`?c.toLowerCase():c;i?.markPhase(),r?.addEventListener(`abort`,abort,{once:!0}),tt.enqueue(l,async()=>{let e=s;if(s=void 0,e)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));let u=await o.completion.promise;return a=`returned`,u}finally{r?.removeEventListener(`abort`,abort),i?.finish(a)}}function normalizeGitPathForFilesystem(e,t=process.platform){if(t!==`win32`)return e;let n=/^\/([a-zA-Z])(?:\/(.*))?$/.exec(e),r=n?.[1];return r?O.win32.normalize(`${r.toUpperCase()}:/${n[2]??``}`):e}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){let 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={}){let{runCommandWithTimeout:r}=await import(`./openclaw-state-read-exec-CJ1WsfoH.mjs`).then(e=>e.t);return D(n.operation,()=>executeGitCommandWithOutput(r,(e,t)=>({...e,stdout:decodeWindowsOutputBuffer({buffer:t})}),e,t,n))}async function executeGitCommandBytes(e,t,n={}){let{runCommandBuffersWithTimeout:r}=await import(`./openclaw-state-read-exec-runner-Cq9LBDUs.mjs`).then(e=>e.t);return D(n.operation,()=>executeGitCommandWithOutput(r,(e,t)=>({...e,stdout:t}),e,t,n))}function createGitPatchCapture(e){let t=Buffer.from(`
diff --git `),n=[],r=Buffer.alloc(0),i=0,a,append=t=>{let r=t.subarray(0,Math.max(0,e+1-i));r.length>0&&(n.push(Buffer.from(r)),i+=r.length,a=r[r.length-1])},finishPatch=()=>{i>e&&a!==10&&n.push(Buffer.from(`
`)),i=0,a=void 0};return{append(e){let n=r.length>0?Buffer.concat([r,e]):e,i=0,a=n.indexOf(t);for(;a!==-1;)append(n.subarray(i,a+1)),finishPatch(),i=a+1,a=n.indexOf(t,i);let o=Math.max(i,n.length-t.length+1);append(n.subarray(i,o)),r=Buffer.from(n.subarray(o))},finish(){return append(r),finishPatch(),Buffer.concat(n)}}}async function executeGitCommandWithOutput(e,t,n,r,i){let a=gitReadOnlyEnvironment(r,i.env??{}),o=i.timeoutMs??12e4,s=gitExecutionArgv(n,r,i),runAttempt=n=>withGitAttemptSource(i,async()=>{let r=i.maxPatchBytes===void 0?void 0:createGitPatchCapture(i.maxPatchBytes),a=await e(s,r?{...n,outputCapture:`discard`,tolerateOutputError:{stderr:!0},onOutputChunk:(e,t)=>{t===`stdout`&&r.append(e)}}:n),o=readCommandProcessCleanup(a);return o&&(a={...a,cleanup:await o.catch(e=>{throw new CommandProcessCleanupError({cause:e})})}),r?t({...a,stdoutTruncatedBytes:void 0},r.finish()):a});if(i.waitForExit===!0){let start=()=>(i.beforeRun?.(),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={}){let{runCommandBuffered:r}=await import(`./openclaw-state-read-exec-CJ1WsfoH.mjs`).then(e=>e.t),i=gitReadOnlyEnvironment(t,n.env??{}),a=gitExecutionArgv(e,t,{...n,killProcessTree:n.killProcessTree!==!1});return await D(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){let n=e.beforeRun?.prepareSessionSourceEffect?await ye(e.beforeRun):void 0;try{for(let e of n?.workspaceEvidence??[])await _e(e);return e.stateOwnerPath&&await me(e.stateOwnerPath),(n||e.stateOwnerPath)&&(n?.assertCurrent??e.beforeRun)?.(),await t()}finally{await n?.release?.()}}function createGitCommandError(e,t){let n=t.timeoutMs??12e4,r=createCommandError(e,t,{timeoutMs:n});return t.termination===`timeout`?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).`):r}function requireGitCommandOutput(e,t,n=createGitCommandError){let r;if(t.termination!==`exit`||t.code!==0?r=t:t.stdoutTruncatedBytes&&(r={...t,code:null,outputLimitExceeded:!0}),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`}const W=[[`maintenance.auto`,`false`],[`gc.auto`,`0`]];W.map(([e,t])=>`'${e}=${t}'`).join(` `);const gitMaintenanceEnvironment=(e={})=>appendGitConfig(e,W);function appendGitConfig(e,t){let n={...e},r=Number(e.GIT_CONFIG_COUNT??0);for(let[e,i]of t)n[`GIT_CONFIG_KEY_${r}`]=e,n[`GIT_CONFIG_VALUE_${r++}`]=i;return n.GIT_CONFIG_COUNT=String(r),n}const G=E(`git/repair`),K=5e4,q=4096,J=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;async function withGitRepositoryRepair(e){let{result:t}=e;if(t.termination!==`exit`||t.code!==128||t.cleanup===`uncertain`||t.outputLimitExceeded)return t;let n=typeof t.stderr==`string`?t.stderr:Buffer.from(t.stderr).toString(`utf8`);if(!/which is in the commit graph file but not in the object database|trying to write ref '[^']+' with nonexistent object/iu.test(n))return t;let assertCurrent=()=>{e.signal?.throwIfAborted(),e.assertCurrent?.()};G.warn(`Git repository has missing ref tips; attempting repair for ${e.cwd}`);try{let t=A.now(),remainingBudget=()=>{assertCurrent();let e=3e5-(A.now()-t);if(e<=0)throw Error(`repair exceeded its five-minute budget`);return Math.ceil(e)},run=async(t,n,r=!1)=>{let i=await e.run([`-c`,`core.commitGraph=false`,`-c`,`maintenance.auto=false`,`-c`,`fetch.writeCommitGraph=false`,...t],{input:n,signal:e.signal,beforeRun:assertCurrent,timeoutMs:remainingBudget(),maxOutputBytes:8388608,env:{GIT_NO_LAZY_FETCH:`1`,GIT_NO_REPLACE_OBJECTS:`1`},killProcessTree:!0});if(i.cleanup===`uncertain`)throw new CommandProcessCleanupError;if(assertCurrent(),i.termination!==`exit`||i.code!==0&&(!r||i.code!==1&&i.code!==128)||i.stdoutTruncatedBytes||i.outputLimitExceeded)throw Error(`repair ${t[0]} failed (${i.termination}, exit ${i.code})`);return i.stdout},n=(await run([`for-each-ref`,`--format=%(refname) %(objectname) %(symref)`])).trim().split(`
`).filter(Boolean);if(n.length>K)throw Error(`repair inventory exceeds ${K} refs`);let r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;for(let e of n){let[t,n,a]=e.trim().split(` `);if(!t?.startsWith(`refs/`)||!n||!J.test(n))throw Error(`repair received an invalid ref inventory`);a?i.set(t,a):r.set(t,n)}let a=(await run([`worktree`,`list`,`--porcelain`,`-z`])).split(`\0`),o=/* @__PURE__ */ new Set,protect=e=>{let t=e;for(;!o.has(t);){o.add(t);let e=i.get(t);if(!e)break;t=e}};for(let e of i.keys())e.startsWith(`refs/remotes/origin/`)||protect(e);for(let e of a)e.startsWith(`branch `)&&protect(e.slice(7));let s=/* @__PURE__ */ new Set;for(let t of(await run([`ls-remote`,`--heads`,`--`,e.remote])).trim().split(`
`).filter(Boolean)){let[e,n]=t.split(`	`);if(!e||!J.test(e)||!n?.startsWith(`refs/heads/`))throw Error(`repair received an invalid remote inventory`);s.add(`refs/remotes/origin/${n.slice(11)}`)}if(s.size>K)throw Error(`repair inventory exceeds ${K} remote refs`);let c=[...r.keys()].filter(e=>e.startsWith(`refs/remotes/origin/`)),l=(e.canonicalTracking||(await run([`config`,`--get-all`,`remote.origin.fetch`])).trim()===`+refs/heads/*:refs/remotes/origin/*`)&&e.pruneTracking!==!1?c.filter(e=>!s.has(e)&&!o.has(e)):[];if(l.length){await run([`update-ref`,`--no-deref`,`--stdin`],`${l.map(e=>`delete ${e} ${r.get(e)}`).join(`
`)}\n`);for(let e of l)r.delete(e)}let u=new Set(r.values());for(let e of a)e.startsWith(`HEAD `)&&J.test(e.slice(5))&&!/^0+$/u.test(e.slice(5))&&u.add(e.slice(5));let d=u.size?await run([`cat-file`,`--batch-check=%(objectname) %(objecttype)`],`${[...u].join(`
`)}\n`):``,f=d.trim().split(`
`).filter(e=>e.endsWith(` missing`)).map(e=>e.split(` `)[0]);if(f.length>q)throw Error(`repair exceeds ${q} missing ref tips`);if(f.length){let t=/^([a-f0-9]+) commit$/m.exec(d)?.[1],n=[`--no-auto-maintenance`,`--no-tags`,`--no-prune`,`--no-prune-tags`,`--no-write-fetch-head`,`--no-recurse-submodules`,...(await run([`config`,`--type=bool`,`--default=false`,`--get`,`remote.origin.promisor`])).trim()===`true`?[`--filter=blob:none`]:[],`--stdin`,`--`,e.remote],r=`${f.join(`
`)}\n`;await run([`fetch`,...t?[`--negotiation-tip=${t}`]:[],...n],r,!0),(await run([`cat-file`,`--batch-check=%(objectname) %(objecttype)`],r)).includes(` missing`)&&await run([`-c`,`fetch.negotiationAlgorithm=noop`,`fetch`,...n],r)}assertCurrent();let p=await e.retry();if(p.cleanup===`uncertain`)throw new CommandProcessCleanupError;if(assertCurrent(),p.termination!==`exit`||p.code!==0)throw Error(`fetch still fails after ref-tip repair`);return e.onRepaired?.(o),G.warn(`Git repository repaired for ${e.cwd}: fetched ${f.length} missing tips, pruned ${l.length} obsolete tracking refs`),p}catch(n){if(hasCommandProcessCleanupError(n))throw n;if(readCommandProcessFailure(n)?.cleanup===`uncertain`)throw new CommandProcessCleanupError({cause:n});return assertCurrent(),G.warn(`Git repository repair failed for ${e.cwd}: ${n instanceof Error?n.message:`repair unavailable`}. Local branches and worktree HEADs were preserved; repair the clone's missing objects or ref locks, then retry.`),t}}const Y=new k,X=/* @__PURE__ */ new WeakMap;function serializeGitWorkerFailure(e){let t=oe(e)?.code;return{name:e instanceof Error?e.name:`Error`,message:e instanceof Error?e.message:String(e),...typeof t==`string`||typeof t==`number`?{code:t}:{},...e instanceof Error&&X.has(e)?{origin:X.get(e)}:{}}}function restoreGitWorkerFailure(e){let t=e.name===`WorktreeRepositoryError`?new pe(e.message):e.name===`GitCommandTimeoutError`?new GitCommandTimeoutError(e.message):Error(e.message);return t.name=e.name,e.code!==void 0&&Object.assign(t,{code:e.code}),e.origin!==void 0&&X.set(t,e.origin),t}function hasGitWorkerContext(){return Y.getStore()!==void 0}async function requestHost(e){let t=Y.getStore();if(!t||t.closed)throw Error(`Git operation requires its worker host`);let n=[];if(e.type===`workspace.inventory.write`){let t=ge(e.input.bytes);e.input.bytes=t,n.push(t.buffer)}if((e.type===`git.text`||e.type===`git.buffer`)&&e.input.options.input instanceof Uint8Array){let t=Uint8Array.from(e.input.options.input);e.input.options.input=t,n.push(t.buffer)}return await new Promise((r,i)=>{t.pending.push({request:e,transfers:n,resolve:r,reject:i}),t.drain??=Promise.resolve().then(()=>drainHostRequests(t))})}async function drainHostRequests(e){try{for(;e.pending.length>0;){let t=e.pending.splice(0,16);try{if(e.closed)throw Error(`Git operation closed before host execution`);let n={type:`git.batch`,input:{requests:t.map(e=>e.request)}},r=await e.channel.request(n,t.flatMap(e=>e.transfers));try{let e=r.input;if(!Array.isArray(e)||e.length!==t.length)throw Error(`Git host returned an incomplete batch`);for(let[n,r]of t.entries()){let t=e[n];t.ok?r.resolve(t.value):r.reject(restoreGitWorkerFailure(t.error))}}finally{r.consumed()}}catch(e){for(let n of t)n.reject(e)}}}finally{e.drain=void 0}}async function requestGitWorkerCommand(e){return await requestHost(e)}async function requestGitWorkerEffect(e){return await requestHost(e)}l(Symbol.for(`openclaw.workspaceCheckouts`),e=>{for(let t of e.values())t.watches.forEach(e=>e.close());e.clear()},`shared-state`),ee(async()=>{try{let{runCommandWithTimeout:e}=await import(`./openclaw-state-read-exec-CJ1WsfoH.mjs`).then(e=>e.t);return(await e([`git`,`--version`],{timeoutMs:2e3})).code===0}catch{return!1}});const rt=/* @__PURE__ */ new Set([`--quiet`,`--no-auto-maintenance`,`--refetch`,`--no-tags`,`--no-write-fetch-head`,`--no-recurse-submodules`,`--recurse-submodules=no`,`--stdin`,`--prune`,`--no-prune`]);function withNoGlob(e){return e?.trim().split(/\s+/).at(-1)===`noglob`?e:e?`${e} noglob`:`noglob`}function gitEnvironment(e,t=[],n=process.platform,r=process.env){let i=e??r,a=n===`win32`&&t.some(e=>e.endsWith(`^{commit}`))?de([r,e],n):void 0,o=a?{MSYS:withNoGlob(T(a,`MSYS`,n)),CYGWIN:withNoGlob(T(a,`CYGWIN`,n))}:{};return appendGitConfig(gitMaintenanceEnvironment({...i,...o}),[[`core.hooksPath`,Te.devNull],[`core.fsmonitor`,`false`]])}async function runGit(e,t,n={}){if(hasGitWorkerContext()){let{signal:r,beforeRun:i,...a}=n,{stdout:o,stderr:s,windowsEncoding:c,...l}=await requestGitWorkerCommand({type:`git.text`,input:{cwd:e,args:t,options:a}});return{...l,stdout:decodeWindowsOutputBuffer({buffer:Buffer.from(o.buffer,o.byteOffset,o.byteLength),windowsEncoding:c}),stderr:decodeWindowsOutputBuffer({buffer:Buffer.from(s.buffer,s.byteOffset,s.byteLength),windowsEncoding:c})}}return await runOwnedGitCommand(e,t,n,executeGitCommand)}async function runGitBytes(e,t,n={}){return await runOwnedGitCommand(e,t,n,executeGitCommandBytes)}async function runOwnedGitCommand(e,t,n,r){let i=n.baseEnv??{...process.env},a=gitEnvironment(n.env,t,process.platform,i);return await withGitRefAdmission(e,t,async o=>{let run=()=>r(e,o,{...n,beforeRun:o===t?n.beforeRun:void 0,baseEnv:i,env:a,input:o===t?n.input:void 0,killProcessTree:n.killProcessTree??(t[0]===`fetch`&&o===t)}),s=await run();if(o!==t||t[0]!==`fetch`||s.code!==128)return s;let[c,l,...u]=t.slice(1).filter(e=>!rt.has(e)&&!e.startsWith(`--negotiation-tip=`));return c!==`origin`||u.length>0||l!==void 0&&!/^\+refs\/heads\/(.+):refs\/remotes\/origin\/\1$/u.test(l)?s:await withGitRepositoryRepair({cwd:e,result:s,remote:`origin`,pruneTracking:!t.includes(`--no-prune`),signal:n.signal,assertCurrent:n.beforeRun,retry:run,run:(t,r)=>executeGitCommand(e,t,{...n,...r,baseEnv:i,env:{...a,...r.env}})})},n.signal,n.refMutationDirectory)}async function withGitRefAdmission(e,t,n,r,i){let a=t[0]===`worktree`&&t[1]===`add`&&!t.includes(`--detach`);if(!(t[0]===`fetch`||t[0]===`update-ref`||t[0]===`merge`||a||t[0]===`symbolic-ref`&&t.length===3&&!t[1]?.startsWith(`-`)||t[0]===`branch`&&t.some(e=>e===`-d`||e===`-D`||e===`--delete`)))return await n(t);let o=i;if(!o){let e=await n([`rev-parse`,`--git-common-dir`]);if(e.termination!==`exit`||e.code!==0)return e;o=typeof e.stdout==`string`?e.stdout:decodeWindowsOutputBuffer({buffer:Buffer.from(e.stdout.buffer,e.stdout.byteOffset,e.stdout.byteLength),windowsEncoding:resolveWindowsConsoleEncoding()}),o=gitPathOutput(o)}let s=!1,c=a?new AbortController:void 0,l=c?setTimeout(()=>{E(`agents/worktrees`).warn(`Managed worktree registration is waiting for repository repair or another Git operation (30-second wait limit).`)},1e3):void 0,u=c?setTimeout(()=>c.abort(new GitCommandTimeoutError(`Managed worktree registration timed out waiting for repository repair or another Git operation. Retry creating the workspace after that operation finishes.`)),3e4):void 0,endWait=()=>{clearTimeout(l),clearTimeout(u)};try{return await enqueueGitRefMutation(e,o,()=>(s=!0,endWait(),n(t)),c?r?AbortSignal.any([r,c.signal]):c.signal:r)}catch(e){if(!s&&r?.aborted&&e===r.reason)return await n(t);throw e}finally{endWait()}}async function runGitBuffered(e,t,n={}){if(hasGitWorkerContext()){let{signal:r,beforeRun:i,...a}=n,o=await requestGitWorkerCommand({type:`git.buffer`,input:{cwd:e,args:t,options:a}});return{...o,stdout:Buffer.from(o.stdout.buffer,o.stdout.byteOffset,o.stdout.byteLength),stderr:Buffer.from(o.stderr.buffer,o.stderr.byteOffset,o.stderr.byteLength)}}let r=n.baseEnv??{...process.env},i=gitEnvironment(n.env,t,process.platform,r);return await withGitRefAdmission(e,t,a=>executeGitCommandBuffered(e,a,{...n,beforeRun:a===t?n.beforeRun:void 0,input:a===t?n.input:void 0,baseEnv:r,env:i}),n.signal,n.refMutationDirectory)}async function requireGit(e,t,n={}){let r=await runGit(e,t,n);return requireGitCommandOutput(`git ${t.join(` `)}`,r).trim()}function gitPathOutput(e){return e.endsWith(`
`)?e.slice(0,e.endsWith(`\r
`)?-2:-1):e}async function requireGitPath(e,t,n={}){let r=await runGit(e,t,n);return normalizeGitPathForFilesystem(gitPathOutput(requireGitCommandOutput(`git ${t.join(` `)}`,r)))}async function requireGitBuffer(e,t,n={}){let r=await runGitBuffered(e,t,n);if(r.termination!==`exit`||r.code!==0)throw createGitCommandError(`git ${t.join(` `)}`,r);return r.stdout}function*workspacePathAncestors(e){for(let t=e.indexOf(`/`);t>=0;t=e.indexOf(`/`,t+1))yield e.slice(0,t)}const it=`
const MATERIALIZED_SANDBOX_SKILLS_WORKSPACE = ${JSON.stringify(`.openclaw/sandbox-skills`)};
function isManagedSandboxSkillsPath(relativePath) {
  return (
    relativePath === MATERIALIZED_SANDBOX_SKILLS_WORKSPACE ||
    relativePath.startsWith(MATERIALIZED_SANDBOX_SKILLS_WORKSPACE + "/")
  );
}`,Z=[`build/intermediates`,`build/outputs/apk`,`build/outputs/bundle`],Q=[`bin/Debug`,`bin/Release`,`obj/Debug`,`obj/Release`],at=[`pnpm`,`agp`,`dotnet`].reduce((e,t)=>e.concat(e.map(e=>[...e,t])),[[]]).toSorted((e,t)=>e.length-t.length),ot=[`__pycache__`,`.pytest_cache`,`.mypy_cache`,`.ruff_cache`,`node_modules`,...Z,...Q],st=[`.artifacts/build-all-cache`,`.artifacts/build-cache-inputs`],ct=`.openclaw/.pnpm-store`,lt=[[`.npm/_cacache`,`npm cache`,`npm_config_cache`],[`.npm/_logs`,`npm logs`,`npm_config_cache`],[`.cache/pip`,`pip cache`,`PIP_CACHE_DIR`],[`.cache/uv`,`uv cache`,`UV_CACHE_DIR`],[`.pnpm-store`,`pnpm store`,`PNPM_CONFIG_STORE_DIR`],[`.bun/install/cache`,`Bun cache`,`BUN_INSTALL_CACHE_DIR`],[`.cargo/registry`,`Cargo registry cache`,`CARGO_HOME`],[`.cargo/git`,`Cargo Git cache`,`CARGO_HOME`],[`.gradle/caches`,`Gradle cache`,`GRADLE_USER_HOME`],[`.local/share/NuGet/http-cache`,`NuGet HTTP cache`,`NUGET_HTTP_CACHE_PATH`],[`.local/share/NuGet/v3-cache`,`NuGet HTTP cache`,`NUGET_HTTP_CACHE_PATH`],[`.nuget/packages`,`NuGet global packages`,`NUGET_PACKAGES`]];function workspaceToolCacheHint(e){let t=lt.find(([t])=>`/${e}/`.includes(`/${t}/`));return t?`\nCache guidance: Directory class: ${t[1]}. Set ${t[2]} to a writable path outside the workspace, move the cache there, and retry recovery.`:``}const ut=[...lt.map(([e])=>e),`.cache/vitest`,`.cache/bun-transpiler`,`.cache/openclaw/bun`,`.cache/ms-playwright`,`.cache/convex/binaries`,`.local/share/pnpm/store`,`artifacts/task-environment/local/share/pnpm/store`,ct,`.openclaw/tools`,`.artifacts/vitest-workers`,`.artifacts/vitest-worker-cache`,`.artifacts/vitest-shard-timings.json`],dt=[`.artifacts/dist-artifacts.lock`,`.openclaw/tmp`],ft=[`.DS_Store`],pt=[`.pyc`,`.pyo`],$=`[0-9a-f]`,mt=`openclaw-inbound-`+[$.repeat(8),$.repeat(4),`4${$.repeat(3)}`,`[89ab]${$.repeat(3)}`,$.repeat(12)].join(`-`);function derivedWorkspaceSegmentPattern(e,t){return`(?:^|/)(?:${[...ot.filter(n=>(!e||!Z.some(e=>e===n))&&(!t||!Q.some(e=>e===n))).map(e=>e.replaceAll(`.`,`\\.`)),...ft.map(e=>e.replaceAll(`.`,`\\.`)),...pt.map(e=>`[^/]*${e.replaceAll(`.`,`\\.`)}`),mt].join(`|`)})(?![^/])`}function isIgnoredWorkspaceBuildOutput(e,t){if(![`dist`,`.cache/openclaw-bun`].some(t=>e===t||e.startsWith(t+`/`)))return!1;let n=e;for(;n;){if(t.has(n)||t.has(n+`/`))return!0;n=n.slice(0,Math.max(0,n.lastIndexOf(`/`)))}return!1}const ht=`
${I}
${it}
const DERIVED_WORKSPACE_ROOT_PATHS = ${JSON.stringify(ut)};
const PNPM_FALLBACK_STORE_ROOT_PATH = ${JSON.stringify(ct)};
const BUILD_CACHE_ROOT_PATHS = ${JSON.stringify(st)};
function isBuildCacheWorkspacePath(relativePath) {
  return BUILD_CACHE_ROOT_PATHS.some((root) => relativePath === root || relativePath.startsWith(root + "/"));
}
function buildCacheInputPaths(paths = []) {
  const retained = new Set();
  for (const entryPath of paths) {
    if (!isBuildCacheWorkspacePath(entryPath)) continue;
    const segments = entryPath.split("/");
    for (let index = 1; index <= segments.length; index++) retained.add(segments.slice(0, index).join("/"));
  }
  return retained;
}
const RUNTIME_WORKSPACE_ROOT_PATHS = ${JSON.stringify(dt)};
const DERIVED_WORKSPACE_SEGMENT_RES = ${JSON.stringify([!1,!0].flatMap(e=>[!1,!0].map(t=>derivedWorkspaceSegmentPattern(e,t))))}.map((pattern) => new RegExp(pattern));
function isRuntimeOwnedWorkspacePath(relativePath) {
  return relativePath === ".git" || relativePath.startsWith(".git/") ||
    relativePath.endsWith("/.git") || relativePath.includes("/.git/") ||
    isManagedSandboxSkillsPath(relativePath) || RUNTIME_WORKSPACE_ROOT_PATHS.some(
    (root) => relativePath === root || relativePath.startsWith(root + "/"),
  );
}
function isDerivedWorkspacePath(relativePath, retainedInput, excludeBuildCaches, legacyDerivedEligibilitySubset) {
  if (isRuntimeOwnedWorkspacePath(relativePath)) {
    return true;
  }
  if (retainedInput) {
    return false;
  }
  if (excludeBuildCaches && isBuildCacheWorkspacePath(relativePath)) return true;
  if (DERIVED_WORKSPACE_ROOT_PATHS.some(
    (root) => (root !== PNPM_FALLBACK_STORE_ROOT_PATH || !legacyDerivedEligibilitySubset?.includes("pnpm")) &&
      (relativePath === root || relativePath.startsWith(root + "/")),
  )) {
    return true;
  }
  const legacySegments = (legacyDerivedEligibilitySubset?.includes("agp") ? 2 : 0) +
    (legacyDerivedEligibilitySubset?.includes("dotnet") ? 1 : 0);
  return DERIVED_WORKSPACE_SEGMENT_RES[legacySegments].test(relativePath);
}
function projectWorkspaceEntries(entries, isRetainedInput, excludeBuildCaches = false) {
  const nonemptyDirectories = new Set();
  const retainedParents = new Set();
  const parent = (entryPath) => entryPath.slice(0, Math.max(0, entryPath.lastIndexOf("/")));
  for (const entry of entries) nonemptyDirectories.add(parent(entry.path));
  const eligible = [];
  // Children precede parents in this reverse walk of the sorted inventory.
  // Prune ancestry created only by excluded contents, but retain original empty directories.
  for (let index = entries.length - 1; index >= 0; index -= 1) {
    const entry = entries[index];
    if (
      isDerivedWorkspacePath(entry.path, isRetainedInput(entry.path), excludeBuildCaches) ||
      (entry.type === "directory" && nonemptyDirectories.has(entry.path) && !retainedParents.has(entry.path))
    ) continue;
    eligible.push(entry);
    retainedParents.add(parent(entry.path));
  }
  return eligible.toReversed();
}`,{isDerivedWorkspacePath:gt,isRuntimeOwnedWorkspacePath:_t,projectWorkspaceEntries:vt,buildCacheInputPaths:yt}=j(`${ht}\nreturn { isDerivedWorkspacePath, isRuntimeOwnedWorkspacePath, projectWorkspaceEntries, buildCacheInputPaths };`)();[...ut.map(e=>`/${e}`),...dt.map(e=>`/${e}`),...ot,...ft,...pt.map(e=>`*${e}`)],String.raw`
const stagedInputOwnership = new Map();
function isStagedInput(relativePath) {
  const directory = stagedInputPathDirectory(relativePath);
  if (!directory) return false;
  if (stagedInputOwnership.has(directory)) return stagedInputOwnership.get(directory);
  let owned = false;
  let descriptor;
  try {
    let parent = root;
    for (const segment of directory.split("/")) {
      parent = path.join(parent, segment);
      const stats = fs.lstatSync(parent);
      if (!stats.isDirectory() || stats.isSymbolicLink()) return false;
    }
    const marker = path.join(parent, ".gitignore");
    const before = fs.lstatSync(marker);
    if (!before.isFile() || before.nlink !== 1 || before.size !== STAGED_INPUT_GITIGNORE.length) return false;
    descriptor = fs.openSync(marker, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
    const opened = fs.fstatSync(descriptor);
    if (!opened.isFile() || opened.nlink !== 1 || opened.dev !== before.dev || opened.ino !== before.ino) return false;
    const bytes = Buffer.alloc(STAGED_INPUT_GITIGNORE.length + 1);
    const length = fs.readSync(descriptor, bytes, 0, bytes.length, 0);
    const after = fs.lstatSync(marker);
    owned = after.isFile() && after.nlink === 1 && after.dev === opened.dev && after.ino === opened.ino &&
      after.mtimeMs === opened.mtimeMs && after.ctimeMs === opened.ctimeMs &&
      fs.realpathSync(marker) === marker && length === STAGED_INPUT_GITIGNORE.length &&
      bytes.subarray(0, length).toString("utf8") === STAGED_INPUT_GITIGNORE;
  } catch {
    // An ignored project directory with an absent or unsafe marker is not an input.
  } finally {
    if (descriptor !== undefined) fs.closeSync(descriptor);
    stagedInputOwnership.set(directory, owned);
  }
  return owned;
}`;export{Pe as A,isPlainCommandExitFailure as B,startGitOperationTiming as C,withWorkspaceHashMemo as D,withWorkerWorkspaceHashMemo as E,ke as F,recordCommandProcessFailure as G,readCommandProcessCleanup as H,CommandProcessCleanupError as I,resolveProcessExitCode as K,createInterruptedCommandOutcome as L,je as M,R as N,withoutWorkspaceHashContext as O,L as P,createSanitizedCommandError as R,resolveWindowsConsoleEncoding as S,pruneWorkspaceHashMemo as T,readCommandProcessFailure as U,isPlainCommandSignalFailure as V,recordCommandProcessCleanup as W,restoreGitWorkerFailure as _,_t as a,gitNullConfigPath as b,workspacePathAncestors as c,requireGitPath as d,runGitBuffered as f,requestGitWorkerEffect as g,requestGitWorkerCommand as h,isIgnoredWorkspaceBuildOutput as i,createStagedInputPathMatcher as j,Ne as k,requireGit as l,hasGitWorkerContext as m,yt as n,vt as o,runGitBytes as p,gt as r,workspaceToolCacheHint as s,at as t,requireGitBuffer as u,serializeGitWorkerFailure as v,activeWorkspaceHashContext as w,decodeWindowsOutputBuffer as x,gitMaintenanceEnvironment as y,hasCommandProcessCleanupError as z};