openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
396 lines (395 loc) • 14 kB
JavaScript
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs";
import { i as generateSecureToken } from "./secure-random-CW5OZnK1.mjs";
import { a as computeWorkspaceFileSnapshot, i as captureWorkspaceSnapshot } from "./workspace-manifest-worker-CfX0osDw.mjs";
import { i as MAX_WORKSPACE_INVENTORY_TOTAL_BYTES } from "./workspace-inventory-limits-DfDQlGHa.mjs";
import { a as nodeWorkspaceTransferEntryPath, i as removeNodeWorkspaceUpload, o as prepareNodeWorkspaceTransferSnapshot, r as readNodeWorkspaceUpload } from "./node-workspace-upload-reader-3Kkh_MRA.mjs";
import { n as prepareWorkerWorkspaceGitPack } from "./workspace-git-base-DmGgNjwY.mjs";
import path from "node:path";
import fs from "node:fs/promises";
//#region src/gateway/worker-environments/node-workspace-transfer-owner.ts
function isNodeWorkspaceTransferOwnerCurrent(e, t) {
const n = t?.environment;
const r = t?.credential;
return Boolean(n && r && n.state === "attached" && n.destroyRequestedAtMs === null && n.ownerEpoch === e.ownerEpoch && n.attachedSessionIds.length === 1 && n.attachedSessionIds[0] === e.sessionId && r.ownerEpoch === e.ownerEpoch && r.sessionId === e.sessionId);
}
//#endregion
//#region src/gateway/worker-environments/node-workspace-transfer-service.ts
const TRANSFER_TIMEOUT_MS = 6e5;
const MANIFEST_REF_PATTERN = /^sha256:[a-f0-9]{64}$/u;
function isOperationAuthorized(e) {
try {
e?.();
return true;
} catch {
return false;
}
}
function createNodeWorkspaceTransferService(e) {
const t = /* @__PURE__ */ new Map();
const n = new KeyedAsyncQueue();
const r = e.now ?? Date.now;
const i = e.temporaryRoot ?? path.join(resolveStateDir(), "tmp", "node-workspace-transfer");
let a;
const ensureTemporaryRoot = () => {
a ??= (async () => {
await fs.rm(i, {
recursive: true,
force: true
});
await fs.mkdir(i, {
recursive: true,
mode: 448
});
})();
return a;
};
const isCurrentContext = (n) => t.get(n.environmentId) === n && !n.signal.aborted && n.isAuthorized() && isNodeWorkspaceTransferOwnerCurrent(n, e.getOwner(n.environmentId));
const discardUpload = (e, t) => {
if (!t.disposal) {
t.abortController.abort(/* @__PURE__ */ new Error("Node workspace upload discarded"));
t.disposal = (async () => {
const n = t.receiving;
try {
await n?.result.catch((e) => {
if (!n.signal.aborted || e !== n.signal.reason) throw e;
});
} finally {
try {
if (t.uploaded) await removeNodeWorkspaceUpload(t.uploaded);
} finally {
if (e.upload === t) e.upload = void 0;
}
}
})();
}
return t.disposal;
};
const closeContext = async (e) => {
e.abortController.abort(/* @__PURE__ */ new Error("Node workspace transfer context closed"));
const n = await Promise.allSettled([e.pack?.catch(() => void 0), e.upload ? discardUpload(e, e.upload) : void 0]);
await fs.rm(e.temporaryRoot, {
recursive: true,
force: true
});
if (t.get(e.environmentId) === e) t.delete(e.environmentId);
const r = n.find((e) => e.status === "rejected");
if (r) throw r.reason;
};
const closeEnvironment = (e) => n.enqueue(e, async () => {
const n = t.get(e);
if (n) await closeContext(n);
});
const mintDownload = (e, t, n, i) => {
i?.throwIfAborted();
if (!isCurrentContext(e) || !n()) throw new Error("Node workspace transfer owner is no longer current");
const a = generateSecureToken({
bytes: 32,
redact: true
});
e.downloads.set(a, {
direction: "download",
token: a,
manifestRef: t,
expiresAtMs: r() + TRANSFER_TIMEOUT_MS,
isAuthorized: n,
...i ? { signal: i } : {}
});
return a;
};
const pruneSnapshots = (e) => {
const t = /* @__PURE__ */ new Set([e.currentManifestRef, ...[...e.downloads.values()].map((e) => e.manifestRef)]);
for (const n of e.snapshots.keys()) if (!t.has(n)) e.snapshots.delete(n);
};
const authorizationCurrent = (e) => {
const { capability: t, context: n } = e;
if (!isCurrentContext(n) || t.expiresAtMs <= r()) return false;
return t.direction === "download" ? n.downloads.get(t.token) === t && !t.signal?.aborted && t.isAuthorized() : n.upload === t && t.isAuthorized() && !t.abortController.signal.aborted && (t.state === "receiving" || t.state === "completed");
};
const assertAuthorizationCurrent = (e) => {
if (!authorizationCurrent(e)) throw new Error("Workspace transfer authority closed");
};
const routeMatchesDownload = (e, t, n) => {
if (n.direction !== "download" || n.environmentId !== e.environmentId) return false;
return n.kind === "blob" ? Boolean(e.snapshots.get(t.manifestRef)?.manifest.entries.some((e) => e.type === "file" && e.sha256 === n.sha256)) : n.manifestRef === t.manifestRef;
};
async function replaceContext(r) {
const { authorize: a, ...o } = r;
const s = e.getOwner;
const assertCurrent = () => {
o.signal?.throwIfAborted();
a?.();
if (!o.isAuthorized() || !isNodeWorkspaceTransferOwnerCurrent(o, s(o.environmentId))) throw new Error("Node workspace transfer owner is no longer current");
};
return await n.enqueue(r.environmentId, async () => {
assertCurrent();
const e = t.get(r.environmentId);
if (e) {
await closeContext(e);
assertCurrent();
}
await ensureTemporaryRoot();
assertCurrent();
const n = new AbortController();
const s = {
...o,
temporaryRoot: await fs.mkdtemp(path.join(i, "context-")),
currentManifestRef: r.kind === "repository" ? r.baseManifestRef : "",
baseCommit: r.kind === "repository" ? r.baseCommit : null,
snapshots: /* @__PURE__ */ new Map(),
downloads: /* @__PURE__ */ new Map(),
abortController: n,
signal: r.signal ? AbortSignal.any([r.signal, n.signal]) : n.signal
};
try {
assertCurrent();
let e;
if (r.kind === "sync") {
e = await prepareNodeWorkspaceTransferSnapshot({
localPath: r.localPath,
temporaryRoot: s.temporaryRoot,
signal: AbortSignal.any([s.signal, AbortSignal.timeout(TRANSFER_TIMEOUT_MS)])
});
assertCurrent();
s.snapshots.set(e.manifestRef, e);
s.localPath = e.root;
s.baseCommit = e.manifest.baseCommit;
s.currentManifestRef = e.manifestRef;
}
t.set(s.environmentId, s);
return e ? {
snapshot: e,
token: mintDownload(s, e.manifestRef, () => isOperationAuthorized(a))
} : void 0;
} catch (e) {
await closeContext(s);
throw e;
}
});
}
return {
initialize: ensureTemporaryRoot,
async prepareAttachments(e) {
e.signal.throwIfAborted();
const n = t.get(e.environmentId);
if (!n || !isCurrentContext(n) || !e.isAuthorized()) throw new Error("Worker attachment transfer authority closed");
const r = await fs.realpath(e.localPath);
e.signal.throwIfAborted();
const i = await captureWorkspaceSnapshot({
root: r,
baseCommit: null,
signal: e.signal
});
e.signal.throwIfAborted();
if (!isCurrentContext(n) || !e.isAuthorized()) throw new Error("Worker attachment transfer authority closed");
const a = {
...i,
root: r
};
n.snapshots.set(a.manifestRef, a);
return {
snapshot: a,
token: mintDownload(n, a.manifestRef, e.isAuthorized, e.signal)
};
},
prepareRepository: (e) => replaceContext({
...e,
kind: "repository"
}),
prepareSync: (e) => replaceContext({
...e,
kind: "sync"
}),
prepareUpload(e, n, i, a) {
i?.();
const o = t.get(e);
if (!o || !MANIFEST_REF_PATTERN.test(n) || !isCurrentContext(o)) throw new Error("Node workspace transfer context is unavailable");
if (o.upload) throw new Error("Node workspace transfer upload is already active");
const s = generateSecureToken({
bytes: 32,
redact: true
});
o.upload = {
direction: "upload",
token: s,
baseManifestRef: n,
...a ? { resultVersion: a } : {},
expiresAtMs: r() + TRANSFER_TIMEOUT_MS,
state: "ready",
isAuthorized: () => isOperationAuthorized(i),
abortController: new AbortController()
};
return s;
},
takeUpload(e, n) {
const r = t.get(e);
const i = r?.upload;
if (!r || !i || i.state !== "completed" || !i.isAuthorized() || i.abortController.signal.aborted || i.baseManifestRef !== n || !i.uploaded || !isCurrentContext(r)) throw new Error("Node workspace transfer upload did not complete");
r.upload = void 0;
return i.uploaded;
},
async discardUpload(e, n) {
const r = t.get(e);
const i = r?.upload;
if (r && i?.token === n) await discardUpload(r, i);
},
getSnapshot(e, n) {
return t.get(e)?.snapshots.get(n);
},
publishSnapshot(e, n, r) {
r?.();
const i = t.get(e);
if (!i || !isCurrentContext(i)) throw new Error("Node workspace transfer context is unavailable");
i.snapshots.set(n.manifestRef, n);
i.currentManifestRef = n.manifestRef;
pruneSnapshots(i);
return mintDownload(i, n.manifestRef, () => isOperationAuthorized(r));
},
async revoke(e, n) {
const r = t.get(e);
r?.downloads.delete(n);
if (r) pruneSnapshots(r);
const i = r?.upload;
if (r && i?.token === n) await discardUpload(r, i);
},
authorize(e) {
const n = t.get(e.route.environmentId);
if (!n) return;
const i = n.downloads.get(e.token);
if (i) {
const t = {
context: n,
capability: i,
route: e.route
};
if (!authorizationCurrent(t) || !routeMatchesDownload(n, i, e.route)) return;
return t;
}
const a = n.upload;
if (!a || !isCurrentContext(n) || a.token !== e.token || a.state !== "ready" || !a.isAuthorized() || a.expiresAtMs <= r() || e.route.kind !== "reconcile" || e.route.environmentId !== n.environmentId || e.route.baseManifestRef !== a.baseManifestRef) return;
a.state = "receiving";
return {
context: n,
capability: a,
route: e.route
};
},
isAuthorizationCurrent: authorizationCurrent,
authorizationSignal(e) {
const t = e.context.signal;
const n = e.capability;
return n.direction === "download" && n.signal ? AbortSignal.any([t, n.signal]) : n.direction === "upload" ? AbortSignal.any([t, n.abortController.signal]) : t;
},
snapshot(e) {
if (e.capability.direction !== "download" || e.route.kind !== "manifest" && e.route.kind !== "pack" || !authorizationCurrent(e)) return;
return e.context.snapshots.get(e.capability.manifestRef);
},
async pack(e) {
if (e.route.kind !== "pack" || !authorizationCurrent(e)) return;
const { context: t, route: n } = e;
const r = t.snapshots.get(n.manifestRef);
if (r?.gitPackPath) return r.gitPackPath;
const { baseCommit: i } = t;
if (!t.localPath || !i || r?.manifest.baseCommit !== i) return;
if (!t.pack) t.pack = prepareWorkerWorkspaceGitPack({
root: t.localPath,
baseCommit: i,
temporaryRoot: t.temporaryRoot,
signal: AbortSignal.any([t.signal, AbortSignal.timeout(TRANSFER_TIMEOUT_MS)])
}).catch((e) => {
t.pack = void 0;
throw e;
});
const a = await t.pack;
return authorizationCurrent(e) ? a : void 0;
},
blob(e) {
if (e.capability.direction !== "download" || e.route.kind !== "blob" || !authorizationCurrent(e)) return;
const t = e.context.snapshots.get(e.capability.manifestRef);
const n = e.route.sha256;
const r = t?.manifest.entries.find((e) => e.type === "file" && e.sha256 === n && (!t.blobPaths || t.blobPaths.has(e.path)));
return t && r?.type === "file" ? {
path: nodeWorkspaceTransferEntryPath(t.root, r.path),
size: r.size,
sha256: r.sha256
} : void 0;
},
async receiveUpload(e) {
const { authorization: t } = e;
const n = t.capability;
if (n.direction !== "upload" || t.route.kind !== "reconcile" || n.state !== "receiving") throw new Error("Workspace transfer upload owner is unavailable");
const r = AbortSignal.any([e.signal, n.abortController.signal]);
const i = (async () => {
const assertCurrent = () => {
r.throwIfAborted();
assertAuthorizationCurrent(t);
};
let i;
try {
r.throwIfAborted();
i = await readNodeWorkspaceUpload({
request: e.request,
baseManifestRef: n.baseManifestRef,
resultVersion: n.resultVersion,
temporaryRoot: t.context.temporaryRoot,
signal: r,
assertCurrent,
isAuthorized: () => authorizationCurrent(t)
});
assertCurrent();
const a = t.context;
if (a.localPath && !a.snapshots.has(i.baseManifestRef)) {
if (a.baseCommit !== i.base.baseCommit) {
await a.pack?.catch(() => void 0);
assertCurrent();
a.pack = void 0;
a.baseCommit = i.base.baseCommit;
}
a.snapshots.set(i.baseManifestRef, {
manifest: i.base,
manifestRef: i.baseManifestRef,
rawManifest: i.baseRaw,
root: a.localPath
});
a.currentManifestRef = i.baseManifestRef;
}
n.uploaded = i;
n.state = "completed";
return { manifestRef: i.currentManifestRef };
} catch (e) {
if (i) await removeNodeWorkspaceUpload(i);
if (t.context.upload === n && !n.disposal) t.context.upload = void 0;
throw e;
}
})();
n.receiving = {
result: i,
signal: r
};
return await i;
},
async verifyBlob(e) {
const t = await computeWorkspaceFileSnapshot(e.path, Math.min(e.size, MAX_WORKSPACE_INVENTORY_TOTAL_BYTES));
return t.type === "file" && t.size === e.size && t.sha256 === e.sha256;
},
fenceEnvironment(e, n) {
const r = t.get(e);
if (r) r.abortController.abort(n ?? /* @__PURE__ */ new Error("Worker environment credential revoked"));
closeEnvironment(e).catch(() => void 0);
},
close: closeEnvironment,
async closeAll() {
await a;
const e = await Promise.allSettled([...t.keys()].map(closeEnvironment));
e.push(...await Promise.allSettled([fs.rm(i, {
recursive: true,
force: true
})]));
const n = e.find((e) => e.status === "rejected");
if (n) throw n.reason;
}
};
}
//#endregion
export { createNodeWorkspaceTransferService };