UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

70 lines • 15 kB
import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{i as gitMaintenanceEnvironmentExpression,r as gitMaintenanceEnvironment}from"./git-maintenance-env-CIA5le3f.mjs";import{l as decodeWorkspaceManifest}from"./workspace-manifest-worker-C4V2H1Gh.mjs";import{t as boundedWorkerError}from"./worker-error-CF2Y40UT.mjs";import{n as REMOTE_WORKSPACE_MANIFEST_JS}from"./workspace-sync-scripts-ChwHuTBs.mjs";import{h as workerWorkspaceCommandSucceeded,v as workspaceSyncError}from"./workspace-sync-helpers-D1bfuj9L.mjs";import{r as NODE_WORKER_WORKSPACE_STDIN_MAX_BYTES}from"./node-workspace-protocol-B16XmC4W.mjs";import{h as workerWorkspaceTransferPaths}from"./workspace-result-staging-BsmW1zVW.mjs";import{t as GITHUB_PUBLICATION_CONFIG_GUARD}from"./github-publication-base-BoRNavWF.mjs";import{r as readGitHubRepositoryPublicationMetadata}from"./github-repository-publication-snapshot-BUhOuBqT.mjs";import{g as readGitHubPublicationTree,s as createGitHubPublicationCommandRunner}from"./github-publication-git-transport-yn7Q8C9o.mjs";import{createHash}from"node:crypto"; //!src/gateway/github-repository-publication-restore.ts const RESTORE_PUBLICATION_INDEX_JS=String.raw` const fs = require("node:fs"); const gitNullPath = process.platform === "win32" ? "NUL" : "/dev/null"; const { spawnSync } = require("node:child_process"); const paths = JSON.parse(fs.readFileSync(0, "utf8")); const cwd = process.cwd(); const env = { ...process.env }; for (const key of Object.keys(env)) if (/^GIT_/i.test(key)) delete env[key]; Object.assign(env, { GIT_CONFIG_GLOBAL: gitNullPath, GIT_CONFIG_SYSTEM: gitNullPath, ${JSON.stringify(gitMaintenanceEnvironment()).slice(1,-1)}, GIT_ATTR_NOSYSTEM: "1", GIT_NO_REPLACE_OBJECTS: "1" }); ${GITHUB_PUBLICATION_CONFIG_GUARD.script} const action = process.argv[1]; if (action !== "add" && action !== "remove") throw new Error("Invalid publication restore operation"); const operation = action === "remove" ? ["update-index", "--force-remove", "-z", "--stdin"] : ["add", "--intent-to-add", "--force", "--pathspec-from-file=-", "--pathspec-file-nul"]; const result = spawnSync("git", ["--literal-pathspecs", "-c", "core.hooksPath=" + gitNullPath, "-c", "core.fsmonitor=false", "-c", "core.attributesFile=" + gitNullPath, ...operation], { env, input: paths.join("\0") + "\0", timeout: 60000, maxBuffer: 128 * 1024, }); if (result.error || result.status !== 0) { throw new Error("Repository publication paths could not be restored; retry workspace preparation"); } `;async function prepareRepositoryPublicationRestore(e){if(!e.publicationStagingRoot||!e.publicationDigest)return[];const{snapshot:t}=await readGitHubRepositoryPublicationMetadata(e.publicationStagingRoot,e.publicationDigest);if(t.baseCommit!==e.current.baseCommit)throw new Error(`Repository publication paths differ from the restored source baseline`);const n=new Map(e.current.entries.map(e=>[e.path,e]));const r=new Map(t.entries.map(e=>[e.path,e]));const i=new Map(r);const a=new Set(t.entries.filter(e=>e.sha===null&&e.mode!==`160000`).map(e=>e.path));let o;if(e.indexBase){const{root:n,commit:s,assertCurrent:c}=e.indexBase;const{run:l}=createGitHubPublicationCommandRunner(c);const readTree=async e=>{const t=await readGitHubPublicationTree(n,e,l);const r=t.toString(`utf8`);if(!Buffer.from(r).equals(t))throw new Error(`Repository publication paths are not valid UTF-8`);return r.split(`\0`).filter(Boolean).map(e=>{const t=e.indexOf(` `);const[n,,r]=e.slice(0,t).split(` `);if(t<0||!n||!r)throw new Error(`Repository publication tree inventory is invalid`);return{path:e.slice(t+1),mode:n,sha:r}})};const[u,d]=await Promise.all([readTree(t.baseTree),readTree(s)]);o=new Set(d.map(e=>e.path));for(const e of u)if(!r.has(e.path)&&(e.mode===`100644`||e.mode===`100755`||e.mode===`120000`))i.set(e.path,{...e,mode:e.mode,sha:e.sha});for(const e of d)if(e.mode!==`160000`&&!i.get(e.path)?.sha)a.add(e.path)}const s=[...i.values()].flatMap(e=>{const t=n.get(e.path);const i=(e.mode===`100644`||e.mode===`100755`)&&t?.type===`file`;const a=e.mode===`120000`&&t?.type===`symlink`;return e.sha&&!o?.has(e.path)&&(i||a||!r.has(e.path))?[e.path]:[]});const c=[];for(const[e,t]of[[`remove`,[...a]],[`add`,s]]){let n=[];let r=2;const flush=()=>{if(n.length){c.push({action:e,input:JSON.stringify(n)});n=[];r=2}};const i=NODE_WORKER_WORKSPACE_STDIN_MAX_BYTES/2;for(const e of t){const t=Buffer.byteLength(JSON.stringify(e))+1;if(t+2>i)throw new Error(`Repository publication path exceeds the restore command limit`);if(r+t>i)flush();n.push(e);r+=t}flush()}return c} //!src/gateway/worker-environments/node-worker-repository-preparation.ts const GIT_TIMEOUT_MS=6e4;const MANIFEST_REF_PATTERN=/^sha256:[a-f0-9]{64}$/u;const WORKER_REPOSITORY_GIT_ARGS=[`-c`,`credential.helper=`,`-c`,`core.askPass=`];const workspaceSyncLog=createSubsystemLogger(`gateway/worker-workspace`);const AUTHENTICATED_GIT_JS=String.raw`const fs = require("node:fs"); const { spawnSync } = require("node:child_process"); const { origin, token, disableLazyFetch } = JSON.parse(fs.readFileSync(0, "utf8")); const env = { ...process.env }; for (const key of Object.keys(env)) if (/^(GIT_|GH_TOKEN$|GITHUB_TOKEN$)/i.test(key)) delete env[key]; Object.assign(env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: process.platform === "win32" ? "NUL" : "/dev/null", GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", SSH_ASKPASS: "" }); if (disableLazyFetch) env.GIT_NO_LAZY_FETCH = "1"; Object.assign(env, token ? ${gitMaintenanceEnvironmentExpression([[`"http." + origin + ".extraheader"`,`"Authorization: Basic " + Buffer.from("x-access-token:" + token).toString("base64")`]])} : ${JSON.stringify(gitMaintenanceEnvironment())}); const args = process.argv.slice(1); // Identity-scoped workspaces can put partial-clone .promisor files at MAX_PATH. if (process.platform === "win32") args.unshift("-c", "core.longpaths=true"); const result = spawnSync("git", args, { env, stdio: ["ignore", "inherit", "inherit"] }); if (result.error) console.error((result.error.code ? result.error.code + ": " : "") + result.error.message); process.exitCode = result.status ?? 1;`;const BIND_PREPARED_REPOSITORY_JS=String.raw`const fs = require("node:fs"); const { spawnSync } = require("node:child_process"); const { origin, commit, branch, workspaceDir, author } = JSON.parse(fs.readFileSync(0, "utf8")); if (fs.realpathSync(process.cwd()) !== fs.realpathSync(workspaceDir)) throw Error("Prepared repository workspace changed"); const env = { ...process.env }; for (const key of Object.keys(env)) if (/^(GIT_|GH_TOKEN$|GITHUB_TOKEN$)/i.test(key)) delete env[key]; const nil = process.platform === "win32" ? "NUL" : "/dev/null"; Object.assign(env, { GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: nil, GIT_TERMINAL_PROMPT: "0", GIT_NO_LAZY_FETCH: "1", GIT_NO_REPLACE_OBJECTS: "1" }); Object.assign(env, ${JSON.stringify(gitMaintenanceEnvironment())}); const git = (args, allowDetached = false) => { const result = spawnSync("git", ["-c", "core.hooksPath=" + nil, "-c", "core.fsmonitor=false", ...args], { env, encoding: "utf8", timeout: 30000, maxBuffer: 262144, }); if (allowDetached && result.status === 1) return undefined; if (result.error || result.status !== 0) throw Error("Prepared repository Git verification failed"); return result.stdout.trim(); }; if (git(["rev-parse", "--verify", "HEAD^{commit}"]) !== commit || git(["remote", "get-url", "origin"]) !== origin) throw Error("Prepared repository differs from its admitted source"); git(["check-ref-format", "--branch", branch]); const current = git(["symbolic-ref", "--quiet", "--short", "HEAD"], true); if (current !== branch) { if (current !== undefined) throw Error("Prepared repository already belongs to another session branch"); git(["checkout", "-b", branch, commit]); } for (const [key, value] of Object.entries(author ?? {})) { if (value) git(["config", "--local", "user." + key, value]); } `;function gitFailure(e,t,n,r){return{kind:`failed`,reason:e,detail:boundedWorkerError(`${t}: ${n.termination} (exit code ${n.code}, signal ${n.signal}): ${r??(n.stderr.trim()||`no stderr output`)}`)}}function createNodeWorkerRepositoryPreparation(e,t){const exec=async n=>{t?.();const assertCurrent=()=>{n.assertCurrent?.();t?.()};const r=await e({...n,...t?{assertCurrent}:{}});t?.();return r};let n=false;const git=(e,t,n)=>exec({argv:[`node`,`-e`,AUTHENTICATED_GIT_JS,`--`,...WORKER_REPOSITORY_GIT_ARGS,...t],input:JSON.stringify({origin:e?.origin,token:e?.gitToken,disableLazyFetch:t[0]===`fetch`}),...n?{resetWorkspace:true}:{},timeoutMs:GIT_TIMEOUT_MS,transportRetry:`never`});const capture=async(e,t,n)=>await exec({argv:[`node`,`-e`,REMOTE_WORKSPACE_MANIFEST_JS,e,...t?[t,`eligible`]:[``,`all`],...n?[n.slice(7)]:[]],timeoutMs:GIT_TIMEOUT_MS,transportRetry:`idempotent`});const checkoutAndCapture=async(e,t,n,r)=>{const i=await git(e,[`fetch`,`--no-tags`,`--`,`origin`,e.commit??e.ref??`HEAD`]);if(!workerWorkspaceCommandSucceeded(i))return gitFailure(`checkout-failed`,`git fetch`,i);const a=await git(e,[`rev-parse`,`--verify`,`FETCH_HEAD^{commit}`]);const o=a.stdout.trim();if(!workerWorkspaceCommandSucceeded(a))return gitFailure(`checkout-failed`,`git rev-parse`,a);if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(o))return gitFailure(`checkout-failed`,`git rev-parse`,a,`invalid commit revision`);if(e.commit!==void 0&&o!==e.commit)return gitFailure(`checkout-failed`,`git rev-parse`,a,`requested commit mismatch`);const s=await git(e,[`checkout`,`--detach`,`--force`,o]);if(!workerWorkspaceCommandSucceeded(s))return gitFailure(`checkout-failed`,`git checkout --detach`,s);if(s.workspaceDir!==t)return gitFailure(`checkout-failed`,`git checkout --detach`,s,`workspace directory changed during checkout`);const c=await capture(s.workspaceDir,o);const l=c.stdout.trim();if(!workerWorkspaceCommandSucceeded(c)||!MANIFEST_REF_PATTERN.test(l))return{kind:`failed`,reason:`manifest-capture-failed`};if(n!==void 0&&l!==n)return{kind:`failed`,reason:`manifest-mismatch`};return{kind:`prepared`,seeded:r,result:{mode:`git`,remoteWorkspaceDir:s.workspaceDir,manifestRef:l,baseCommit:o}}};return{bindPreparedRepository:async(e,t,n)=>{if(e.commit!==t.baseCommit)throw new Error(`Prepared repository does not match the pinned session commit`);const r=await exec({argv:[`node`,`-e`,BIND_PREPARED_REPOSITORY_JS],input:JSON.stringify({origin:e.origin,commit:e.commit,branch:e.branch,workspaceDir:t.workspaceDir,author:n}),timeoutMs:GIT_TIMEOUT_MS,transportRetry:`never`});if(!workerWorkspaceCommandSucceeded(r)||r.workspaceDir!==t.workspaceDir)throw new Error(`Prepared repository session binding failed`);return{mode:`repository`,remoteWorkspaceDir:t.workspaceDir,manifestRef:t.preparedManifestRef,baseManifestRef:t.sourceManifestRef,baseCommit:t.baseCommit}},configureCheckout:async(e,t,n)=>{const r={"user.name":t.name,"user.email":t.email};if(n){const t=await git(void 0,[`-C`,e,`remote`]);if(!workerWorkspaceCommandSucceeded(t))throw workspaceSyncError(t);if(!t.stdout.split(/\r?\n/u).includes(`origin`)){r[`remote.origin.url`]=n;r[`remote.origin.fetch`]=`+refs/heads/*:refs/remotes/origin/*`}}for(const[t,n]of Object.entries(r)){if(!n)continue;const r=await git(void 0,[`-C`,e,`config`,`--local`,t,n]);if(!workerWorkspaceCommandSucceeded(r))throw workspaceSyncError(r)}},captureManifest:async(e,t,n)=>{const r=await capture(e,t,n);const i=r.stdout.trim();if(!workerWorkspaceCommandSucceeded(r)||!MANIFEST_REF_PATTERN.test(i)){const e=boundedWorkerError(r.stderr.trim()||(!workerWorkspaceCommandSucceeded(r)?`${r.termination} (exit code ${r.code}, signal ${r.signal})`:`invalid manifest reference`));throw new Error(`Node workspace manifest capture failed: ${e}`)}return i},async prepareRepository(e,r){const i=createHash(`sha256`).update(e.origin).digest(`hex`);let a;try{const t=await exec({argv:[`openclaw-internal-workspace-seed`],seed:{action:`apply`,key:i},timeoutMs:GIT_TIMEOUT_MS,transportRetry:`never`});if(workerWorkspaceCommandSucceeded(t)&&t.stdout.trim()===`applied`){const n=await git(e,[`remote`,`get-url`,`origin`]);if(!workerWorkspaceCommandSucceeded(n)||n.stdout.trim()!==e.origin)throw new Error(`Node workspace seed origin mismatch`);a=await checkoutAndCapture(e,t.workspaceDir,r,true)}}catch(e){t?.();if(e instanceof Error&&e.message.includes(`INVALID_REQUEST`))throw e;workspaceSyncLog.info(`node worker workspace seeded sync failed; cloning`,{error:boundedWorkerError(e)})}if(a?.kind!==`prepared`){const t=await git(e,[`-c`,`init.templateDir=`,`clone`,`--filter=blob:none`,`--no-checkout`,`--`,e.origin,`.`],true);if(!workerWorkspaceCommandSucceeded(t))return gitFailure(`clone-failed`,`git clone`,t);a=await checkoutAndCapture(e,t.workspaceDir,r,false)}if(a.kind===`prepared`)try{const e=await exec({argv:[`openclaw-internal-workspace-seed`],seed:{action:`store`,key:i,maxAgeMs:216e5},timeoutMs:18e4,transportRetry:`never`});if(!workerWorkspaceCommandSucceeded(e))throw workspaceSyncError(e)}catch(e){t?.();if(e instanceof Error&&e.message.includes(`INVALID_REQUEST`))throw e;if(!n){n=true;workspaceSyncLog.warn(`node worker workspace seed store failed`,{error:boundedWorkerError(e)})}}if(a.kind===`prepared`&&e.branch){const t=await git(e,[`checkout`,`-B`,e.branch,a.result.baseCommit]);if(!workerWorkspaceCommandSucceeded(t))return gitFailure(`checkout-failed`,`git checkout -B`,t)}return a}}}async function restoreNodeWorkerRepositoryCheckpoint(e){const{checkpoint:t,baseManifestRef:n,environmentId:r,workspaceTransfer:i,signal:a,authorize:o,exec:s,transfer:c}=e;const l=await decodeWorkspaceManifest(t.baseManifestRaw,void 0,a);if(l.manifestRef!==n)throw new Error(`Repository checkpoint baseline differs from its cloned commit`);const u=await decodeWorkspaceManifest(t.currentManifestRaw,void 0,a);const d=u.manifestRef;const f=u.manifest;const p=l.manifest;const m=i.publishSnapshot(r,{manifest:f,manifestRef:d,rawManifest:t.currentManifestRaw,root:t.stagingRoot,blobPaths:new Set(workerWorkspaceTransferPaths(f,p,a)),gitPackPath:t.gitPackPath},o);try{const e=await c({direction:`download`,token:m,manifestRef:d,checkpointBaseManifestRef:n,...t.gitPackPath&&t.gitHistory?{checkpointGitHistory:t.gitHistory}:{}},`Repository checkpoint restore failed`,{assertCurrent:o});const r=t.gitHistoryNote??(t.gitHistory&&t.gitPackPath?JSON.parse(e.stdout).gitHistoryNote:void 0);if(r)workspaceSyncLog.info(r);for(const e of await prepareRepositoryPublicationRestore({...t,current:f})){const t=await s({argv:[`node`,`-e`,RESTORE_PUBLICATION_INDEX_JS,e.action],input:e.input,timeoutMs:6e4,transportRetry:`never`,assertCurrent:o});if(t.code!==0||t.termination!==`exit`)throw new Error(`Repository publication paths could not be restored; retry workspace preparation`)}}finally{await i.revoke(r,m)}return d}export{prepareRepositoryPublicationRestore as a,restoreNodeWorkerRepositoryCheckpoint as i,WORKER_REPOSITORY_GIT_ARGS as n,createNodeWorkerRepositoryPreparation as r,AUTHENTICATED_GIT_JS as t};