openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1 lines • 13.4 kB
JavaScript
import{n as e}from"./openclaw-state-read-tmp-openclaw-dir-C3Ynn93H.mjs";import{n as t}from"./openclaw-state-read-fs-safe-CpAHBauR.mjs";import{t as n}from"./openclaw-state-read-usingCtx-03vOGQ3v.mjs";import{a as r,r as i}from"./openclaw-state-read-kysely-sync-DQyYiAw5.mjs";import{a}from"./openclaw-state-read-sqlite-transaction-V1rK3HH2.mjs";import{M as o,N as s,P as c,c as l,j as u,m as d,n as f}from"./openclaw-state-read-workspace-path-exclusions-Cjo9Lmns.mjs";import{n as p}from"./openclaw-state-read-exec-runner-Cq9LBDUs.mjs";import{qt as m}from"./openclaw-state-read.worker.js";import"./openclaw-state-read-session-row-changes-C0Qzq-vO.mjs";import"./openclaw-state-read-workspace-state-guard-lmfygG7O.mjs";import"./openclaw-state-read-session-source-authority-B_K2ljxL.mjs";import{r as h,t as g}from"./openclaw-state-read-placement-row-codec-H0QnPs2g.mjs";import{c as _,i as v,m as y,r as b}from"./openclaw-state-read-workspace-manifest-B5vKGqPY.mjs";import{c as x,d as S,f as C,i as w,l as T,n as E,o as D,r as O,u as k}from"./openclaw-state-read-workspace-reconcile-fs-D0L5ne7X.mjs";import{o as A}from"./openclaw-state-read-workspace-manifest-comparison-BsGOV5Ve.mjs";import{n as j,r as M,t as N}from"./openclaw-state-read-workspace-reconcile-derived-paths-vX7802kb.mjs";import{t as P}from"./openclaw-state-read-workspace-reconcile-core-Cc_tdhvi.mjs";import{n as F,r as I}from"./openclaw-state-read-exec-CJ1WsfoH.mjs";import L from"node:fs";import R from"node:path";import z from"node:fs/promises";import{createHash as B,randomBytes as V}from"node:crypto";import"node:util";const H=6e5;function workspaceRecoveryConflict(e){return/* @__PURE__ */ Error(`Gateway workspace changed while cloud recovery was pending: ${e}`)}async function requireGit(e,t,n,r,i){let a=await p([`git`,`-C`,e,...t],{timeoutMs:H,...n?{input:n}:{},...r?{env:r}:{},...i?{beforeInput:i}:{},maxOutputBytes:1048576});if(a.termination!==`exit`||a.code!==0)throw Error((a.stderr||a.stdout||`git ${t[0]} failed`).trim());return a.stdout.trim()}async function writeRawWorkspaceTree(e){let t=e.repositoryRoot,r=`refs/heads/openclaw-snapshot-${V(16).toString(`hex`)}`,i=R.join(t,`.git`,`snapshot-input`);try{try{var a=n();await k({...e,inputPath:i,ref:r});let o=a.a(await z.open(i,`r`)),{stdout:s}=await I(`git`,[`-C`,t,`fast-import`,`--quiet`],{stdinFileDescriptor:o.fd,timeoutMs:H,maxBuffer:1048576});return s.split(` `)[2].split(` `)[0]}catch(e){a.e=e}finally{await a.d()}}finally{await z.rm(i,{force:!0})}}async function readWorkspacePatch(e,t,n){let r=R.join(e,`.git`,`workspace.patch`),i=await z.open(r,`wx`,384),a=0,o=!1;try{let r=await p([`git`,`-C`,e,`diff`,`--binary`,`--full-index`,`--no-renames`,t,n,`--`],{timeoutMs:H,killProcessTree:!0,outputCapture:{stdout:`discard`,stderr:`head`},maxOutputBytes:{stdout:v,stderr:1048576},terminateOnOutputLimit:!0,onOutputChunk:(e,t)=>{if(t!==`stdout`)return!0;if(a+e.byteLength>805306368)return o=!0,!1;let n=0;for(;n<e.byteLength;){let t=L.writeSync(i.fd,e,n,e.byteLength-n);if(t===0)throw Error(`Cloud workspace patch write made no progress`);n+=t}return a+=e.byteLength,!0}});if(o)throw new y(`Cloud workspace patch exceeds its byte limit`);if(r.termination!==`exit`||r.code!==0)throw Error(r.stderr.trim()||`git diff failed`)}finally{await i.close()}return m(await z.readFile(r))}async function createWorkspacePatch(t){let n=await z.mkdtemp(R.join(e(),`openclaw-workspace-patch-`));try{await requireGit(n,[`init`,`--quiet`,`--object-format=sha1`]);let e=0;for(let n of t.baseEntries){if(n.type===`file`&&n.size>67108864)throw new y(`Cloud workspace rollback file is too large: ${n.path}`);if(e+=n.type===`file`?n.size:Buffer.byteLength(n.target),e>805306368)throw new y(`Cloud workspace rollback exceeds its byte limit`)}let r=await writeRawWorkspaceTree({repositoryRoot:n,entries:t.baseEntries,source:{root:t.root}}),i=await F([`git`,`-C`,n,`pack-objects`,`--stdout`,`--revs`],{input:Buffer.from(`${r}\n`),timeoutMs:H,maxOutputBytes:{stdout:b+1,stderr:1048576}});if(i.stdout.byteLength>268435456)throw new y(`Cloud workspace recovery snapshot exceeds its byte limit`);if(i.termination!==`exit`||i.code!==0)throw Error(i.stderr.toString(`utf8`).trim()||`git pack-objects failed`);let a={baseTree:r,basePack:m(i.stdout),publicationPack:t.publicationCopy?new Uint8Array(i.stdout):void 0,basePackSha256:B(`sha256`).update(i.stdout).digest(`hex`)};if(t.baseEntries.length===0&&t.appliedEntries.length===0)return{...a,patch:/* @__PURE__ */ new Uint8Array};let o=await readWorkspacePatch(n,r,await writeRawWorkspaceTree({repositoryRoot:n,entries:t.appliedEntries,source:{root:t.stagingRoot}}));return{...a,patch:o}}finally{await z.rm(n,{recursive:!0,force:!0})}}async function applyWorkspacePatch(t){if(t.patch.byteLength===0)return;let n=await z.mkdtemp(R.join(e(),`openclaw-no-git-`));try{await requireGit(t.root,[`-c`,`core.autocrlf=false`,`apply`,`--no-index`,`--binary`,`--whitespace=nowarn`],t.patch,{GIT_DIR:R.join(n,`.git`)},t.assertCurrent)}finally{await z.rm(n,{recursive:!0,force:!0})}}function validateJournalSnapshot(e){if(e.basePack.byteLength>268435456||!/^[a-f0-9]{40}$/u.test(e.baseTree)||B(`sha256`).update(e.basePack).digest(`hex`)!==e.basePackSha256)throw Error(`Cloud workspace reconciliation recovery snapshot is invalid`)}async function createWorkspaceRecoveryPatch(t){let n=await z.mkdtemp(R.join(e(),`openclaw-workspace-recovery-`));try{await requireGit(n,[`init`,`--quiet`,`--object-format=sha1`]),await requireGit(n,[`index-pack`,`--stdin`],t.journal.basePack),await requireGit(n,[`cat-file`,`-e`,`${t.journal.baseTree}^{tree}`]);let e=t.journal.baseEntries,r=t.journal.appliedEntries,i=new Map(e.map(e=>[e.path,e])),a=new Map(r.map(e=>[e.path,e])),o=/* @__PURE__ */ new Set([...i.keys(),...a.keys()]),s=/* @__PURE__ */ new Set;for(let e of o)for(let t of l(e))s.add(t);let c=[],u=await S(t.root,[...o]);for(let e of[...o].toSorted()){let n=u.get(e);if(!n){let t=i.get(e),n=a.get(e);if(t&&n)throw workspaceRecoveryConflict(e);continue}let r=i.get(e),l=a.get(e);if(r&&A(n,r))c.push(r);else if(l&&A(n,l))c.push(l);else if(!(n.type===`directory`&&(s.has(e)&&await E(t.root,e,t.isRetainedInput,{paths:o,directories:s},t.excludeBuildCaches)||await E(t.root,e,t.isRetainedInput,void 0,t.excludeBuildCaches))))throw workspaceRecoveryConflict(e)}let d=await writeRawWorkspaceTree({repositoryRoot:n,entries:c,source:{root:t.root}}),f=t.filteredBaseTree?await writeRawWorkspaceTree({repositoryRoot:n,entries:e,source:{root:n,tree:t.journal.baseTree}}):t.journal.baseTree;return await x({type:`workspace.reconcile.diff`,input:{root:n,baseTree:d,currentTree:f}})}finally{await z.rm(n,{recursive:!0,force:!0})}}async function assertWorkspaceRecoveryBase(e){let t=e.journal.baseEntries,n=e.journal.appliedEntries;await P({root:e.root,manifest:{version:1,baseCommit:null,entries:e.journal.baseEntries},entries:t});let r=new Set(e.journal.baseDirectories??[]),i=new Set(e.journal.appliedDirectories??[]);for(let t of r)if((await w(e.root,t))?.type!==`directory`)throw workspaceRecoveryConflict(t);let a=new Set(t.map(e=>e.path)),o=/* @__PURE__ */ new Set;for(let e of a)for(let t of l(e))o.add(t);for(let t of n){if(a.has(t.path))continue;let n=await z.lstat(O(e.root,t.path)).catch(()=>void 0);if(!(n?.isDirectory()&&!n.isSymbolicLink()&&o.has(t.path)&&await E(e.root,t.path,e.isRetainedInput,{paths:a,directories:o},e.excludeBuildCaches))&&n)throw workspaceRecoveryConflict(t.path)}for(let t of i){if(r.has(t)||a.has(t))continue;let n=await w(e.root,t);if(n&&!(n.type===`directory`&&await E(e.root,t,e.isRetainedInput,void 0,e.excludeBuildCaches)))throw workspaceRecoveryConflict(t)}}async function assertWorkspaceRecoveryDirectoriesRecoverable(e){let t=new Set(e.journal.baseDirectories??[]),n=new Set(e.journal.appliedDirectories??[]),r=new Map(e.journal.baseEntries.map(e=>[e.path,e])),i=new Map(e.journal.appliedEntries.map(e=>[e.path,e])),a=new Set(i.keys()),o=/* @__PURE__ */ new Set([...t,...n]);for(let s of o){let o=await w(e.root,s);if(o?.type===`directory`){if(r.has(s)&&n.has(s)&&!await E(e.root,s,e.isRetainedInput,{paths:a,directories:n},e.excludeBuildCaches))throw workspaceRecoveryConflict(s);continue}if(!o){if(t.has(s)&&n.has(s))throw workspaceRecoveryConflict(s);continue}let c=r.get(s),l=i.get(s);if(!(c&&A(o,c)||l&&A(o,l)))throw workspaceRecoveryConflict(s)}}async function restoreWorkspaceJournalDirectories(e){let n=await t(e.root,{mode:448,assertBeforeMutation:e.assertCurrent}),r=e.journal.baseDirectories??[],i=new Set(e.journal.appliedDirectories??[]);for(let e of r.toSorted())await n.mkdir(e);let a=new Set(r),o=new Set(e.journal.baseEntries.map(e=>e.path));for(let e of[...i].toSorted((e,t)=>t.localeCompare(e)))a.has(e)||o.has(e)||await D(n,e)}async function recoverWorkerWorkspaceReconciliation(e){if(e.journal.appliedManifestRef)throw Error(`Cloud workspace result is already applied and awaits fence acceptance`);if(!d()){let t=await T(`openclaw-workspace-recovery-input-`);try{let n=R.join(t,`base.pack`),{basePack:r,...i}=e.journal;return await z.writeFile(n,r),await C({type:`workspace.reconcile.recover`,input:{root:e.root,journal:i,basePackPath:n,buildCacheInputs:e.buildCacheInputs}},e)}finally{await z.rm(t,{recursive:!0,force:!0})}}let n=await z.realpath(e.root);validateJournalSnapshot(e.journal);let r=u(await t(n)),i=f(e.buildCacheInputs),a=[...e.journal.baseEntries,...e.journal.appliedEntries],l=s(a),p=[...a.map(e=>e.path),...e.journal.baseDirectories??[],...e.journal.appliedDirectories??[]];for(let e of p){let t=c(e);t&&!l.has(t)&&await r(e)&&l.add(t)}let m={...e.journal,baseEntries:M(e.journal.baseEntries,l,e.buildCacheInputs),appliedEntries:M(e.journal.appliedEntries,l,e.buildCacheInputs),baseDirectories:j(e.journal.baseDirectories,l,e.buildCacheInputs),appliedDirectories:j(e.journal.appliedDirectories,l,e.buildCacheInputs)},isRetainedInput=async e=>i.has(e)||o(e,l)||await r(e),h={root:n,journal:m,isRetainedInput,filteredBaseTree:m.baseEntries.length!==e.journal.baseEntries.length,excludeBuildCaches:e.buildCacheInputs!==void 0,assertCurrent:e.assertCurrent};try{await assertWorkspaceRecoveryBase(h);return}catch{}await assertWorkspaceRecoveryDirectoriesRecoverable(h);let g=await createWorkspaceRecoveryPatch(h);await N(n,m.baseEntries,isRetainedInput,e.assertCurrent,e.buildCacheInputs!==void 0),await applyWorkspacePatch({root:n,patch:g,assertCurrent:e.assertCurrent}),await restoreWorkspaceJournalDirectories(h),await assertWorkspaceRecoveryBase(h)}const query=e=>r(e);function isCurrentJournalOwner(e,t,n,r){if(t?.state!==`active`&&t?.state!==`draining`||t.environmentId!==n.environmentId||t.activeOwnerEpoch!==n.ownerEpoch)return!1;if(t.generation===n.placementGeneration)return!0;if(t.state!==`draining`||t.generation!==n.placementGeneration+1)return!1;let a=r?r.get(n.sessionId):i(e,query(e).selectFrom(`worker_workspace_pending_results`).select([`environment_id as environmentId`,`owner_epoch as ownerEpoch`,`placement_generation as placementGeneration`]).where(`session_id`,`=`,n.sessionId)).rows[0];return a?.environmentId===n.environmentId&&a.ownerEpoch===n.ownerEpoch&&a.placementGeneration===n.placementGeneration}function assertJournalOwner(e,t,n={}){let r=h(e,t.sessionId),i=isCurrentJournalOwner(e,r,t),a=n.allowFailedOwner===!0&&r.state===`failed`&&r.generation>t.placementGeneration&&r.environmentId===t.environmentId&&r.activeOwnerEpoch===t.ownerEpoch;if(!i&&!a)throw Error(`Cannot reconcile stale worker workspace for session ${t.sessionId}`);return r}function getWorkspaceReconciliationPlacement(e,t){let n=g(e,t.sessionId);return isCurrentJournalOwner(e,n,t)?n:void 0}function listWorkspaceReconciliationOwners(e){return i(e,query(e).selectFrom(`worker_workspace_reconciliations`).select([`session_id`,`environment_id`,`owner_epoch`,`placement_generation`]).orderBy(`session_id`)).rows.map(e=>({sessionId:e.session_id,environmentId:e.environment_id,ownerEpoch:e.owner_epoch,placementGeneration:e.placement_generation}))}function loadWorkspaceReconciliation(e,t,n={}){let r=assertJournalOwner(e,t,n),a=i(e,query(e).selectFrom(`worker_workspace_reconciliations`).selectAll().where(`session_id`,`=`,t.sessionId)).rows[0];if(!a)return;let o=_(a.plan_json);if(a.environment_id!==t.environmentId||a.owner_epoch!==t.ownerEpoch||a.placement_generation!==t.placementGeneration||r.workspaceBaseManifestRef!==a.base_manifest_ref&&r.workspaceBaseManifestRef!==o.appliedManifestRef)throw Error(`Worker workspace journal owner is stale for session ${t.sessionId}`);if(o.baseManifestRef!==a.base_manifest_ref||o.currentManifestRef!==a.current_manifest_ref)throw Error(`Worker workspace journal metadata is inconsistent for ${t.sessionId}`);if(a.base_pack.byteLength>268435456||B(`sha256`).update(a.base_pack).digest(`hex`)!==o.basePackSha256)throw Error(`Worker workspace journal snapshot is invalid for ${t.sessionId}`);return{...o,basePack:a.base_pack}}function readWorkspaceJournalInDatabase(e,t){return t.type===`placementJournals.owners`?{type:t.type,owners:listWorkspaceReconciliationOwners(e)}:a(e,()=>t.type===`placementJournals.placement`?{type:t.type,placement:getWorkspaceReconciliationPlacement(e,t.owner)}:{type:t.type,journal:loadWorkspaceReconciliation(e,t.owner,{allowFailedOwner:t.allowFailedOwner})})}export{recoverWorkerWorkspaceReconciliation as i,isCurrentJournalOwner,createWorkspacePatch as n,readWorkspacePatch as r,readWorkspaceJournalInDatabase,applyWorkspacePatch as t};