UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

5 lines • 9.96 kB
import{o as isPathInside}from"./fs-safe-Bxzu1j4h.mjs";import{s as writeFileWindowFully}from"./file-descriptor-CRkf5tcV.mjs";import{a as WorkerTaskError}from"./src-D4Y-r8_m.mjs";import"./worker-task-pool-Bg54sSAN.mjs";import{n as runCommandWithTimeout}from"./exec-runner-BiCq-T1F.mjs";import"./exec-c5tqm8tb.mjs";import{o as WorkerWorkspaceGitHistorySchema}from"./workspace-result-inventory-Cl0lnMl9.mjs";import{t as MAX_WORKSPACE_RESULT_GIT_PACK_BYTES}from"./node-workspace-transfer-protocol-BFfyPciA.mjs";import{a as MAX_WORKSPACE_MANIFEST_BYTES,n as MAX_WORKSPACE_INVENTORY_ENTRIES}from"./workspace-inventory-limits-BmPI7yuU.mjs";import{l as decodeWorkspaceManifest,o as captureWorkspaceSnapshot}from"./workspace-manifest-worker-C4V2H1Gh.mjs";import{t as workspacePathAncestors}from"./workspace-path-ancestors-BgOePO1n.mjs";import{i as MAX_RECONCILIATION_TOTAL_BYTES}from"./workspace-manifest-BE9NudAI.mjs";import{o as probeWorkspaceGitMode}from"./workspace-sync-helpers-D1bfuj9L.mjs";import{i as readWorkspaceTransferPaths,t as createWorkspaceGitTransferList}from"./workspace-sync-inventory-DffIee16.mjs";import{o as parseChangedWorkspaceResult}from"./workspace-manifest-comparison-DFPdvJq-.mjs";import{i as assertWorkspaceMatchesManifest}from"./workspace-reconcile-core-gXIQUawP.mjs";import"./workspace-reconcile-B9s9mGfp.mjs";import path from"node:path";import{createHash}from"node:crypto";import fs from"node:fs/promises"; //!src/gateway/worker-environments/node-workspace-transfer-snapshot.ts const TRANSFER_TIMEOUT_MS=6e5;async function prepareNodeWorkspaceTransferSnapshot(e){const t=await fs.realpath(e.localPath);const n=await probeWorkspaceGitMode({localPath:t,commandOptions:{timeoutMs:TRANSFER_TIMEOUT_MS,maxOutputBytes:262144,maxCombinedOutputBytes:524288,baseEnv:{...process.env,GIT_TERMINAL_PROMPT:`0`,GIT_ASKPASS:``},signal:e.signal},runTask:runCommandWithTimeout});let r=null;let i;if(n.mode===`git`){if(await fs.realpath(n.gitRoot)!==t)throw new Error(`Worker git workspace sync requires the managed worktree root`);r=n.baseCommit;if(!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(r))throw new Error(`Worker workspace Git base is not a commit id`);const a=await createWorkspaceGitTransferList({gitRoot:t,temporaryDirectory:path.join(e.temporaryRoot,`inventory`),signal:e.signal??AbortSignal.timeout(TRANSFER_TIMEOUT_MS),timeoutMs:TRANSFER_TIMEOUT_MS});const o=await readWorkspaceTransferPaths(a,e.signal);const s=new Set(o);for(const e of o)for(const t of workspacePathAncestors(e))s.add(t);i=s}return{...await captureWorkspaceSnapshot({root:t,baseCommit:r,includePaths:i,signal:e.signal}),root:t}}function nodeWorkspaceTransferEntryPath(e,t){const n=path.join(e,...t.split(`/`));if(n!==e&&!isPathInside(e,n))throw new Error(`Workspace transfer entry escaped its staging root`);return n} //!src/gateway/worker-environments/node-workspace-upload-reader.ts const MAX_UPLOAD_BYTES=MAX_WORKSPACE_MANIFEST_BYTES*2+MAX_RECONCILIATION_TOTAL_BYTES+MAX_WORKSPACE_INVENTORY_ENTRIES*8+8;const MAX_GIT_HISTORY_BYTES=1024;const MAX_V2_UPLOAD_BYTES=MAX_UPLOAD_BYTES+MAX_GIT_HISTORY_BYTES+12+MAX_WORKSPACE_RESULT_GIT_PACK_BYTES;var NodeWorkspaceTransferLimitError=class extends Error{constructor(...e){super(...e);this.code=`workspace-transfer-limit`}};var NodeWorkspaceTransferInvalidError=class extends Error{constructor(e,t,n){super(t,n);this.reason=e;this.code=`workspace-transfer-invalid`}};function nodeWorkspaceTransferInvalidReason(e){return e instanceof NodeWorkspaceTransferInvalidError?e.reason:void 0}var RequestByteReader=class{#e;#t;#n;#r;#i;#a;constructor(e,t,n,r){this.#i=Buffer.alloc(0);this.#a=false;this.bytesRead=0;this.#r=r;this.#e=e[Symbol.asyncIterator]();this.#t=t;this.#n=n}async take(e){this.#t.throwIfAborted();if(this.#i.length===0&&!this.#a){const e=await this.#e.next();this.#n();this.#t.throwIfAborted();this.#a=Boolean(e.done);if(!e.done){if(!Buffer.isBuffer(e.value))throw new NodeWorkspaceTransferInvalidError(`payload`,`Workspace transfer upload must contain binary data`);this.#i=e.value}}if(this.#i.length===0)return Buffer.alloc(0);const t=Math.min(e,this.#i.length);const n=this.#i.subarray(0,t);this.#i=t===this.#i.length?Buffer.alloc(0):this.#i.subarray(t);this.bytesRead+=n.byteLength;if(this.bytesRead>this.#r)throw new NodeWorkspaceTransferLimitError(`Workspace transfer upload exceeds its byte limit`);return n}async readExactly(e){const t=[];let n=e;while(n>0){const e=await this.take(n);if(e.length===0)throw new NodeWorkspaceTransferInvalidError(`premature_eof`,`Workspace transfer upload ended before its declared payload`);t.push(e);n-=e.length}return Buffer.concat(t,e)}async assertEnd(){if((await this.take(1)).length!==0)throw new NodeWorkspaceTransferInvalidError(`trailing_bytes`,`Workspace transfer upload contains trailing bytes`)}};async function streamUploadFile(e){if((await e.reader.readExactly(8)).readBigUInt64BE()!==BigInt(e.entry.size))throw new NodeWorkspaceTransferInvalidError(`file_size`,`Workspace transfer file size differs from its manifest`);const t=createHash(`sha256`);let n=0;while(n<e.entry.size){const r=await e.reader.take(Math.min(65536,e.entry.size-n));if(r.length===0)throw new NodeWorkspaceTransferInvalidError(`premature_eof`,`Workspace transfer upload ended mid-file`);t.update(r);await writeFileWindowFully(e.handle,r,n,{assertBeforeMutation:e.assertCurrent});e.assertCurrent();n+=r.length}if(t.digest(`hex`)!==e.entry.sha256)throw new NodeWorkspaceTransferInvalidError(`file_digest`,`Workspace transfer file digest differs from its manifest`)}async function removeNodeWorkspaceUpload(e){try{await fs.rm(e.stagingRoot,{recursive:true,force:true})}finally{if(e.gitPackPath)await fs.rm(e.gitPackPath,{force:true})}}async function readNodeWorkspaceUpload(e){const{assertCurrent:t}=e;const wrapValidationError=(t,n,r)=>t instanceof WorkerTaskError||e.signal.aborted&&t===e.signal.reason?t:new NodeWorkspaceTransferInvalidError(n,r,{cause:t});let n;try{t();const r=e.resultVersion===2?MAX_V2_UPLOAD_BYTES:MAX_UPLOAD_BYTES;const i=e.request.headers[`content-type`];if(i!==void 0&&i!==`application/vnd.openclaw.worker-workspace-reconcile-v${e.resultVersion??1}`)throw new NodeWorkspaceTransferInvalidError(`payload`,`Workspace result version was not negotiated`);const a=e.request.headers[`content-length`];const o=Number(a);if(a!==void 0&&(!Number.isSafeInteger(o)||o<8||o>r))throw new NodeWorkspaceTransferLimitError(`Workspace transfer upload exceeds its byte limit`);const s=new RequestByteReader(e.request,e.signal,t,r);const readManifest=async t=>{const n=(await s.readExactly(4)).readUInt32BE();if(n<2||n>67108864)throw new NodeWorkspaceTransferLimitError(`Workspace transfer manifest exceeds its byte limit`);const r=(await s.readExactly(n)).toString(`utf8`);try{const n=await decodeWorkspaceManifest(r,t,e.signal);return{raw:r,ref:n.manifestRef,manifest:n.manifest}}catch(e){throw wrapValidationError(e,`manifest`,`Workspace transfer manifest is invalid`)}};const c=await readManifest(e.baseManifestRef);t();const l=await readManifest();t();let u;try{e.signal.throwIfAborted();u=parseChangedWorkspaceResult(c.manifest,l.manifest).entries}catch(t){if(e.signal.aborted&&t===e.signal.reason)throw t;throw new NodeWorkspaceTransferInvalidError(`manifest`,`Workspace transfer manifests cannot be reconciled`,{cause:t})}n=await fs.mkdtemp(path.join(e.temporaryRoot,`upload-`));for(const r of u)try{const e=nodeWorkspaceTransferEntryPath(n,r.path);await fs.mkdir(path.dirname(e),{recursive:true,mode:448});t();if(r.type===`symlink`){await fs.symlink(r.target,e);t()}else{const n=await fs.open(e,`wx`,r.mode);try{await streamUploadFile({reader:s,handle:n,entry:r,assertCurrent:t})}finally{await n.close()}t()}}catch(t){if(t instanceof NodeWorkspaceTransferInvalidError)throw t;if(e.signal.aborted||!e.isAuthorized())throw t;throw new NodeWorkspaceTransferInvalidError(`staging`,`Workspace transfer payload could not be staged`,{cause:t})}let d;let f;if(e.resultVersion===2){const e=(await s.readExactly(4)).readUInt32BE();if(e>MAX_GIT_HISTORY_BYTES)throw new NodeWorkspaceTransferLimitError(`Workspace Git history metadata exceeds its byte limit`);try{const t=JSON.parse((await s.readExactly(e)).toString(`utf8`));d=t===null?void 0:WorkerWorkspaceGitHistorySchema.parse(t);if(d&&d.baseCommit!==c.manifest.baseCommit)throw new Error(`Git history does not match dispatch base`)}catch(e){throw wrapValidationError(e,`payload`,`Workspace Git history is invalid`)}const r=(await s.readExactly(8)).readBigUInt64BE();if(r>BigInt(268435456))throw new NodeWorkspaceTransferLimitError(`Workspace Git pack exceeds its byte limit`);const i=d?.descendsFromBase&&!d.unavailableReason&&d.headCommit!==d.baseCommit;if(Boolean(i)!==r>0n)throw new NodeWorkspaceTransferInvalidError(`payload`,`Workspace Git pack does not match its history`);if(r>0n){f=path.join(n,`../`,`${path.basename(n)}.pack`);const e=await fs.open(f,`wx`,384);try{let n=0;while(n<Number(r)){const i=await s.readExactly(Math.min(65536,Number(r)-n));await writeFileWindowFully(e,i,n,{assertBeforeMutation:t});t();n+=i.length}}finally{await e.close()}}}await s.assertEnd();t();if(a!==void 0&&s.bytesRead!==o)throw new NodeWorkspaceTransferInvalidError(`content_length`,`Workspace transfer upload length is inconsistent`);try{await assertWorkspaceMatchesManifest({root:n,manifest:l.manifest,entries:u})}catch(e){throw wrapValidationError(e,`staging`,`Workspace transfer payload did not match its staged result`)}t();return{base:c.manifest,baseManifestRef:e.baseManifestRef,baseRaw:c.raw,current:l.manifest,currentManifestRef:l.ref,currentRaw:l.raw,stagingRoot:n,...d?{gitHistory:d}:{},...f?{gitPackPath:f}:{}}}catch(e){if(n)await removeNodeWorkspaceUpload({stagingRoot:n,gitPackPath:`${n}.pack`});throw e}}export{nodeWorkspaceTransferEntryPath as a,removeNodeWorkspaceUpload as i,nodeWorkspaceTransferInvalidReason as n,prepareNodeWorkspaceTransferSnapshot as o,readNodeWorkspaceUpload as r,NodeWorkspaceTransferLimitError as t};