openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
144 lines (142 loc) • 14.9 kB
JavaScript
import{xt as e}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import t from"node:path";import{createHash as n}from"node:crypto";import{compileFunction as r}from"node:vm";const i=`# Raw task inputs remain private; copy outputs into the project to publish.
*
`,a=n(`sha256`).update(i).digest(`hex`),o=String.raw`
const STAGED_INPUT_DIRECTORY_PREFIX = ${JSON.stringify(`media/inbound/openclaw-staged-`)};
const STAGED_INPUT_GITIGNORE = ${JSON.stringify(i)};
const STAGED_INPUT_GITIGNORE_SHA256 = ${JSON.stringify(a)};
// 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:s,isStagedInputPath:c,stagedInputDirectoriesFromEntries:l}=r(`${o}\nreturn { stagedInputPathDirectory, isStagedInputPath, stagedInputDirectoriesFromEntries };`)();function createStagedInputPathMatcher(e){let t=/* @__PURE__ */ new Map;return async n=>{let r=s(n);if(!r)return!1;let a=t.get(r);return a||(a=e.readText(`${r}/.gitignore`,{maxBytes:78}).then(e=>e===i,()=>!1),t.set(r,a)),await a}}const u=25e4,d=67108864,f=4294967296;function*workspacePathAncestors(e){for(let t=e.indexOf(`/`);t>=0;t=e.indexOf(`/`,t+1))yield e.slice(0,t)}const p=[`.openclaw`,`sandbox-skills`].join(`/`),m=`
const MATERIALIZED_SANDBOX_SKILLS_WORKSPACE = ${JSON.stringify(p)};
function isManagedSandboxSkillsPath(relativePath) {
return (
relativePath === MATERIALIZED_SANDBOX_SKILLS_WORKSPACE ||
relativePath.startsWith(MATERIALIZED_SANDBOX_SKILLS_WORKSPACE + "/")
);
}`,h=[`__pycache__`,`.pytest_cache`,`.mypy_cache`,`.ruff_cache`,`node_modules`],g=[`.artifacts/build-all-cache`,`.artifacts/build-cache-inputs`],_=`.openclaw/.pnpm-store`,v=[`.cache/vitest`,`.cache/bun-transpiler`,`.cache/openclaw/bun`,`.cache/ms-playwright`,`.cache/convex/binaries`,`.local/share/NuGet/http-cache`,`.local/share/NuGet/v3-cache`,`.nuget/packages`,`.local/share/pnpm/store`,_,`.artifacts/vitest-workers`,`.artifacts/vitest-worker-cache`,`.artifacts/vitest-shard-timings.json`],y=[`.artifacts/dist-artifacts.lock`,`.openclaw/tmp`],b=[`.DS_Store`],x=[`.pyc`,`.pyo`],S=`[0-9a-f]`,C=`openclaw-inbound-`+[S.repeat(8),S.repeat(4),`4${S.repeat(3)}`,`[89ab]${S.repeat(3)}`,S.repeat(12)].join(`-`),w=`(?:^|/)(?:${[...h.map(e=>e.replaceAll(`.`,`\\.`)),...b.map(e=>e.replaceAll(`.`,`\\.`)),...x.map(e=>`[^/]*${e.replaceAll(`.`,`\\.`)}`),C].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 T=`
${o}
${m}
const DERIVED_WORKSPACE_ROOT_PATHS = ${JSON.stringify(v)};
const PNPM_FALLBACK_STORE_ROOT_PATH = ${JSON.stringify(_)};
const BUILD_CACHE_ROOT_PATHS = ${JSON.stringify(g)};
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(y)};
const DERIVED_WORKSPACE_SEGMENT_RE = new RegExp(${JSON.stringify(w)});
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 = false, excludeBuildCaches = false, includeLegacyPnpmStore = false) {
if (isRuntimeOwnedWorkspacePath(relativePath)) {
return true;
}
if (retainedInput) {
return false;
}
if (excludeBuildCaches && isBuildCacheWorkspacePath(relativePath)) return true;
if (DERIVED_WORKSPACE_ROOT_PATHS.some(
(root) => (!includeLegacyPnpmStore || root !== PNPM_FALLBACK_STORE_ROOT_PATH) &&
(relativePath === root || relativePath.startsWith(root + "/")),
)) {
return true;
}
return DERIVED_WORKSPACE_SEGMENT_RE.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:E,isRuntimeOwnedWorkspacePath:D,projectWorkspaceEntries:O,buildCacheInputPaths:k}=r(`${T}\nreturn { isDerivedWorkspacePath, isRuntimeOwnedWorkspacePath, projectWorkspaceEntries, buildCacheInputPaths };`)();[`${p}`,...v.map(e=>`/${e}`),...y.map(e=>`/${e}`),...h,...b,...x.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;
}`;const A=268435456,j=/^sha256:([a-f0-9]{64})$/u,M=/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;function manifestPath(e){if(typeof e!=`string`||!e||e.includes(`\\`)||t.posix.isAbsolute(e)||t.posix.normalize(e)!==e||e===`.`||e===`..`||e.startsWith(`../`))throw Error(`Worker workspace manifest contains an unsafe path`);return e}function manifestMode(e){if(typeof e!=`number`||!Number.isInteger(e)||e<0||e>511)throw Error(`Worker workspace manifest contains an invalid mode`);return e}function gitFileMode(e){return e&73?493:420}function compareManifestPaths(e,t){return e.path<t.path?-1:+(e.path>t.path)}function createManifestBudget(){let e=0,t=0;return n=>{if(e+=Buffer.byteLength(n.path),t+=n.type===`file`?n.size:n.type===`symlink`?Buffer.byteLength(n.target):0,e>67108864)throw Error(`Worker workspace manifest paths exceed their byte limit`);if(t>4294967296)throw Error(`Worker workspace manifest exceeds its eligible byte limit`)}}function parseRawEntry(n){if(!e(n))throw Error(`Worker workspace manifest contains an invalid entry`);let r=manifestPath(n.path),i=manifestMode(n.mode);if(n.type===`directory`)return{path:r,type:`directory`,mode:i};if(n.type===`file`){if(typeof n.size!=`number`||!Number.isSafeInteger(n.size)||n.size<0||typeof n.sha256!=`string`||!/^[a-f0-9]{64}$/u.test(n.sha256))throw Error(`Worker workspace manifest contains invalid file metadata`);return{path:r,type:`file`,mode:gitFileMode(i),size:n.size,sha256:n.sha256}}if(n.type===`symlink`){if(typeof n.target!=`string`||!n.target||n.target.includes(`\\`)||t.posix.isAbsolute(n.target)||t.win32.parse(n.target).root!==``)throw Error(`Worker workspace manifest contains an unsafe symlink`);let e=`/workspace`,i=t.posix.resolve(t.posix.dirname(`${e}/${r}`),n.target);if(i!==e&&!i.startsWith(`${e}/`))throw Error(`Worker workspace manifest symlink escapes its root`);return{path:r,type:`symlink`,mode:511,target:n.target}}throw Error(`Worker workspace manifest contains an unsupported entry type`)}function validateAndProjectEntries(e,t,n=`current`){if(e.length>25e4)throw Error(`Worker workspace manifest has too many entries`);let r=e.map(parseRawEntry),i=``,a=createManifestBudget(),o=/* @__PURE__ */ new Map;for(let e of r){if(i>=e.path)throw Error(`Worker workspace manifest paths are not unique and sorted`);for(let t of workspacePathAncestors(e.path))if(o.get(t)?.type!==`directory`)throw Error(`Worker workspace manifest entry has a non-directory parent`);a(e),o.set(e.path,e),i=e.path}let s=l(r),u=k(t),d=n===`stored`?r:O(r,e=>u.has(e)||c(e,s),t!==void 0);return{entries:d.filter(e=>e.type!==`directory`),directories:d.filter(e=>e.type===`directory`).map(e=>e.path)}}function serializeWorkerWorkspaceManifest(e,t=`current`){let n=[...(e.directories??[]).map(e=>({path:e,type:`directory`,mode:448})),...e.entries].toSorted(compareManifestPaths),r=l(n),i=k(e.buildCacheInputs),a=t===`stored`?n:O(n,e=>i.has(e)||c(e,r),e.buildCacheInputs!==void 0);if(a.length>25e4)throw Error(`Worker workspace manifest has too many entries`);let o=createManifestBudget(),s=0,u=Buffer.byteLength(JSON.stringify({version:e.version,baseCommit:e.baseCommit,entries:[]}));for(let e of a)if(s+=Buffer.byteLength(JSON.stringify(e)),o(e),u+s+Math.max(0,a.length-1)>67108864)throw Error(`Worker workspace manifest exceeds the 64 MiB safety limit`);return JSON.stringify({version:e.version,baseCommit:e.baseCommit,entries:a})}function parseWorkerWorkspaceManifest(t,r,i,a=`current`){if(Buffer.byteLength(t)>67108864)throw Error(`Worker workspace manifest exceeds the 64 MiB safety limit`);let o=j.exec(r);if(!o)throw Error(`Worker workspace manifest reference is invalid`);if(n(`sha256`).update(t).digest(`hex`)!==o[1])throw Error(`Worker workspace manifest digest does not match its reference`);let s=JSON.parse(t);if(!e(s))throw Error(`Worker workspace manifest is invalid`);if(s.version!==1||s.baseCommit!==null&&(typeof s.baseCommit!=`string`||!M.test(s.baseCommit))||!Array.isArray(s.entries))throw Error(`Worker workspace manifest has an unsupported shape`);return{version:1,baseCommit:s.baseCommit,...validateAndProjectEntries(s.entries,i,a),...i===void 0?{}:{buildCacheInputs:i}}}function parseJournalEntry(e){let t=parseRawEntry(e);if(t.type===`directory`)throw Error(`Worker workspace reconciliation journal contains a directory entry`);return t}function parseWorkerWorkspaceReconciliationPlan(t){let n=JSON.parse(t);if(!e(n))throw Error(`Worker workspace reconciliation journal is invalid`);let{baseDirectories:r=[],appliedDirectories:i=[]}=n;if(n.version!==1||typeof n.temporaryNonce!=`string`||!/^[a-f0-9]{32}$/u.test(n.temporaryNonce)||typeof n.baseManifestRef!=`string`||!j.test(n.baseManifestRef)||typeof n.currentManifestRef!=`string`||!j.test(n.currentManifestRef)||typeof n.baseTree!=`string`||!/^[a-f0-9]{40}$/u.test(n.baseTree)||typeof n.basePackSha256!=`string`||!/^[a-f0-9]{64}$/u.test(n.basePackSha256)||!Array.isArray(n.baseEntries)||!Array.isArray(n.appliedEntries)||!Array.isArray(r)||!Array.isArray(i)||n.appliedManifestRef!==void 0&&(typeof n.appliedManifestRef!=`string`||!j.test(n.appliedManifestRef))||n.baseEntries.length+n.appliedEntries.length+r.length+i.length>5e5)throw Error(`Worker workspace reconciliation journal has an unsupported shape`);let a=n.baseEntries.map(parseJournalEntry),o=n.appliedEntries.map(parseJournalEntry),s=r.map(manifestPath),c=i.map(manifestPath);for(let e of[a,o]){let t=e.map(e=>e.path);if(new Set(t).size!==t.length)throw Error(`Worker workspace reconciliation journal has duplicate paths`)}for(let e of[s,c])if(new Set(e).size!==e.length)throw Error(`Worker workspace reconciliation journal has duplicate directories`);return{version:1,temporaryNonce:n.temporaryNonce,baseManifestRef:n.baseManifestRef,currentManifestRef:n.currentManifestRef,baseEntries:a,appliedEntries:o,baseDirectories:s,appliedDirectories:c,appliedManifestRef:n.appliedManifestRef,baseTree:n.baseTree,basePackSha256:n.basePackSha256}}export{serializeWorkerWorkspaceManifest as a,isIgnoredWorkspaceBuildOutput as c,d,f,parseWorkerWorkspaceReconciliationPlan as i,workspacePathAncestors as l,s as m,gitFileMode as n,k as o,createStagedInputPathMatcher as p,parseWorkerWorkspaceManifest as r,E as s,A as t,u};