openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
303 lines (302 loc) • 11.7 kB
JavaScript
import { c as isPathInside } from "./fs-safe-BbWvmdVn.mjs";
import { c as writeFileWindowFully } from "./file-descriptor-DQ-v5bLt.mjs";
import { a as WorkerTaskError } from "./src-Dkfkl2Oz.mjs";
import "./worker-task-pool-BshJjv1P.mjs";
import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import "./exec-aRIvS9s4.mjs";
import { o as WorkerWorkspaceGitHistorySchema } from "./workspace-result-inventory-D0Vsi3cF.mjs";
import { t as MAX_WORKSPACE_RESULT_GIT_PACK_BYTES } from "./node-workspace-transfer-protocol-CTDuSXSy.mjs";
import { i as captureWorkspaceSnapshot, s as decodeWorkspaceManifest } from "./workspace-manifest-worker-CfX0osDw.mjs";
import { b as workspacePathAncestors, i as MAX_RECONCILIATION_TOTAL_BYTES } from "./workspace-manifest-C118sSRH.mjs";
import { a as MAX_WORKSPACE_MANIFEST_BYTES, n as MAX_WORKSPACE_INVENTORY_ENTRIES } from "./workspace-inventory-limits-DfDQlGHa.mjs";
import { o as probeWorkspaceGitMode } from "./workspace-sync-helpers-BhfVF4W_.mjs";
import { i as readWorkspaceTransferPaths, t as createWorkspaceGitTransferList } from "./workspace-sync-inventory-COAk-OVx.mjs";
import { o as parseChangedWorkspaceResult } from "./workspace-manifest-comparison-BpzYeKoQ.mjs";
import { a as assertWorkspaceMatchesManifest } from "./workspace-reconcile-DsKvx4sc.mjs";
import path from "node:path";
import { createHash } from "node:crypto";
import fs from "node:fs/promises";
//#region 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;
}
//#endregion
//#region 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");
}
/** The upload owns both the manifest tree and its optional sibling Git pack. */
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 });
}
}
/** Stages one bounded upload before its context owner publishes the authenticated result. */
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 = Number(e.request.headers["content-length"]);
if (!Number.isSafeInteger(a) || a < 8 || a > r) throw new NodeWorkspaceTransferLimitError("Workspace transfer upload exceeds its byte limit");
const o = new RequestByteReader(e.request, e.signal, t, r);
const readManifest = async (t) => {
const n = (await o.readExactly(4)).readUInt32BE();
if (n < 2 || n > 67108864) throw new NodeWorkspaceTransferLimitError("Workspace transfer manifest exceeds its byte limit");
const r = (await o.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 s = await readManifest(e.baseManifestRef);
t();
const c = await readManifest();
t();
let l;
try {
e.signal.throwIfAborted();
l = parseChangedWorkspaceResult(s.manifest, c.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 l) 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: o,
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 u;
let d;
if (e.resultVersion === 2) {
const e = (await o.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 o.readExactly(e)).toString("utf8"));
u = t === null ? void 0 : WorkerWorkspaceGitHistorySchema.parse(t);
if (u && u.baseCommit !== s.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 o.readExactly(8)).readBigUInt64BE();
if (r > BigInt(268435456)) throw new NodeWorkspaceTransferLimitError("Workspace Git pack exceeds its byte limit");
const i = u?.descendsFromBase && !u.unavailableReason && u.headCommit !== u.baseCommit;
if (Boolean(i) !== r > 0n) throw new NodeWorkspaceTransferInvalidError("payload", "Workspace Git pack does not match its history");
if (r > 0n) {
d = path.join(n, "../", `${path.basename(n)}.pack`);
const e = await fs.open(d, "wx", 384);
try {
let n = 0;
while (n < Number(r)) {
const i = await o.readExactly(Math.min(65536, Number(r) - n));
await writeFileWindowFully(e, i, n, { assertBeforeMutation: t });
t();
n += i.length;
}
} finally {
await e.close();
}
}
}
await o.assertEnd();
t();
if (o.bytesRead !== a) throw new NodeWorkspaceTransferInvalidError("content_length", "Workspace transfer upload length is inconsistent");
try {
await assertWorkspaceMatchesManifest({
root: n,
manifest: c.manifest,
entries: l
});
} catch (e) {
throw wrapValidationError(e, "staging", "Workspace transfer payload did not match its staged result");
}
t();
return {
base: s.manifest,
baseManifestRef: e.baseManifestRef,
baseRaw: s.raw,
current: c.manifest,
currentManifestRef: c.ref,
currentRaw: c.raw,
stagingRoot: n,
...u ? { gitHistory: u } : {},
...d ? { gitPackPath: d } : {}
};
} catch (e) {
if (n) await removeNodeWorkspaceUpload({
stagingRoot: n,
gitPackPath: `${n}.pack`
});
throw e;
}
}
//#endregion
export { nodeWorkspaceTransferEntryPath as a, removeNodeWorkspaceUpload as i, nodeWorkspaceTransferInvalidReason as n, prepareNodeWorkspaceTransferSnapshot as o, readNodeWorkspaceUpload as r, NodeWorkspaceTransferLimitError as t };