openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
340 lines (339 loc) • 13 kB
JavaScript
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { t as isAbortError } from "./abort-signal-D4Q6SEw7.mjs";
import "./paths-DAcAg5aV.mjs";
import { t as FsSafeError, u as openLocalFileSafely } from "./fs-safe-BbWvmdVn.mjs";
import { n as normalizeMediaReferenceSource } from "./inbound-media-uri-DpK4_BLW.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { i as shouldLogVerbose, r as logVerbose } from "./globals-CgepmiqE.mjs";
import { t as buildRandomTempFilePath$1 } from "./temp-download-BCncM5Fr.mjs";
import { r as mergeInboundPathRoots, t as isInboundPathAllowed } from "./inbound-path-policy-BMtpIEux.mjs";
import { a as getSessionSafeDefaultMediaLocalRoots } from "./local-roots-BTz6ULME.mjs";
import { n as resolveInboundMediaReference, t as classifyMediaReferenceSource } from "./media-reference-DDon-yG0.mjs";
import { r as normalizeAttachmentPath } from "./attachments.normalize-_9E9xPsg.mjs";
import { n as classifyAttachmentBytes } from "./attachment-classify-DFSZjMac.mjs";
import { i as readRemoteMediaBufferWithHeaders, t as MediaFetchError } from "./fetch-CpjnlJme.mjs";
import { realpathSync, statSync } from "node:fs";
import path from "node:path";
import fs$1 from "node:fs/promises";
import { readFileHandleBounded } from "@openclaw/fs-safe/advanced";
//#region packages/media-understanding-common/src/errors.ts
/** Error used when a media attachment should be skipped without failing the whole request. */
var MediaUnderstandingSkipError = class extends Error {
constructor(e, t) {
super(t);
this.reason = e;
this.name = "MediaUnderstandingSkipError";
}
};
function isMediaUnderstandingSkipError(e) {
return e instanceof MediaUnderstandingSkipError;
}
//#endregion
//#region src/media-understanding/attachments.cache.ts
const REMOTE_MEDIA_FETCH_RETRY = {
attempts: 3,
minDelayMs: 500,
maxDelayMs: 3e3,
jitter: .2
};
function maxBytesError(e) {
return new MediaUnderstandingSkipError("maxBytes", `Attachment ${e.attachmentIndex + 1} exceeds maxBytes ${e.maxBytes}`);
}
let defaultLocalPathRoots;
function inboundStoreRef(e) {
const t = normalizeMediaReferenceSource(e ?? "");
return t && classifyMediaReferenceSource(t).isMediaStoreUrl ? t : void 0;
}
/** Returns the attachment URL only when it is an HTTP(S) remote source. */
function remoteFetchUrl(e) {
const t = normalizeMediaReferenceSource(e ?? "");
return t && classifyMediaReferenceSource(t).isHttpUrl ? t : void 0;
}
function concreteMime(e) {
const t = e?.trim();
if (!t || t.endsWith("/*") || t === "application/octet-stream") return;
return t;
}
function getDefaultLocalPathRoots() {
defaultLocalPathRoots ??= mergeInboundPathRoots(getSessionSafeDefaultMediaLocalRoots());
return defaultLocalPathRoots;
}
function resolveUsableLocalCandidate(e, t) {
try {
const n = realpathSync(e);
const r = t.map((e) => {
if (e.includes("*")) return e;
try {
return realpathSync(e);
} catch {
return e;
}
});
return statSync(n).isFile() && isInboundPathAllowed({
filePath: n,
roots: r
}) ? e : void 0;
} catch {
return;
}
}
/**
* Lazy resolver for media-understanding attachments.
*
* The cache prefers allowed local paths, falls back to remote URLs when a local path is blocked
* or missing, and owns any temporary files created for providers that require a filesystem path.
*/
var MediaAttachmentCache = class {
constructor(e, t) {
this.entries = /* @__PURE__ */ new Map();
this.stagedPaths = /* @__PURE__ */ new Set();
this.ssrfPolicy = t?.ssrfPolicy;
this.localPathRoots = t?.includeDefaultLocalPathRoots === false ? mergeInboundPathRoots(t.localPathRoots) : mergeInboundPathRoots(t?.localPathRoots, getDefaultLocalPathRoots());
this.fallbackWorkspaceDir = t?.workspaceDir;
for (const t of e) this.entries.set(t.index, { attachment: t });
}
/** Returns attachment bytes, MIME hint, filename, and size within the requested byte limit. */
async getBuffer(e) {
const t = await this.ensureEntry(e.attachmentIndex);
e.signal?.throwIfAborted();
const n = remoteFetchUrl(t.attachment.url);
if (t.bufferResult) {
if (t.bufferResult.size > e.maxBytes) throw maxBytesError(e);
return t.bufferResult;
}
const r = await this.withLocalFile(t, () => this.readEntryLocalBuffer(t, e));
e.signal?.throwIfAborted();
if (r) return r;
if (!n) throw t.lastLocalError ?? new MediaUnderstandingSkipError("empty", `Attachment ${e.attachmentIndex + 1} has no path or URL.`);
try {
const r = await readRemoteMediaBufferWithHeaders({
url: n,
timeoutMs: e.timeoutMs,
maxBytes: e.maxBytes,
ssrfPolicy: this.ssrfPolicy,
retry: REMOTE_MEDIA_FETCH_RETRY,
...e.signal ? { requestInit: { signal: e.signal } } : {}
});
const i = await classifyAttachmentBytes({
buffer: r.buffer,
name: r.fileName ?? n,
declaredMime: concreteMime(t.attachment.mime),
additionalMimeHints: [r.contentType, r.headerContentType]
});
e.signal?.throwIfAborted();
t.bufferResult = {
buffer: r.buffer,
classification: i,
mime: i.mime,
fileName: r.fileName ?? `media-${e.attachmentIndex + 1}`,
size: r.buffer.length
};
return t.bufferResult;
} catch (t) {
e.signal?.throwIfAborted();
if (t instanceof MediaFetchError && t.code === "max_bytes") throw maxBytesError(e);
if (isAbortError(t)) throw new MediaUnderstandingSkipError("timeout", `Attachment ${e.attachmentIndex + 1} timed out while fetching.`);
throw t;
}
}
/** Reads the entry's currently resolved local file, or undefined once it is ruled out. */
async readEntryLocalBuffer(e, t) {
let n = await this.prepareLocalFile(e);
let r;
try {
if (!e.resolvedPath) return;
if (e.statSize !== void 0 && e.statSize > t.maxBytes) throw maxBytesError(t);
n ??= await openLocalFileSafely({ filePath: e.resolvedPath });
if (n.stat.size > t.maxBytes) throw maxBytesError(t);
const i = await this.getCanonicalLocalPathRoots();
if (!isInboundPathAllowed({
filePath: n.realPath,
roots: i
})) throw new MediaUnderstandingSkipError("blocked", `Attachment ${t.attachmentIndex + 1} path is outside allowed roots.`);
r = await readFileHandleBounded(n.handle, t.maxBytes);
} catch (e) {
if (e instanceof FsSafeError) {
if (e.code === "too-large") throw maxBytesError(t);
if (e.code === "not-file" || e.code === "not-found") throw new MediaUnderstandingSkipError("empty", `Attachment ${t.attachmentIndex + 1} path is not a regular file.`);
throw new MediaUnderstandingSkipError("blocked", `Attachment ${t.attachmentIndex + 1} path is outside allowed roots.`);
}
throw e;
} finally {
await n?.handle.close().catch(() => {});
}
const i = n.realPath;
e.resolvedPath = i;
const a = await classifyAttachmentBytes({
buffer: r,
name: i,
declaredMime: concreteMime(e.attachment.mime)
});
e.bufferResult = {
buffer: r,
classification: a,
mime: a.mime,
fileName: path.basename(i) || `media-${t.attachmentIndex + 1}`,
size: r.length,
localPath: i
};
return e.bufferResult;
}
async withLocalFile(e, t) {
do {
if (!e.resolvedPath) continue;
try {
const e = await t();
if (e !== void 0) return e;
} catch (t) {
if (!(t instanceof MediaUnderstandingSkipError) || t.reason !== "blocked" && t.reason !== "empty") throw t;
e.lastLocalError = t;
}
} while (await this.activateStoreAlias(e));
}
async activateStoreAlias(e) {
if (e.storeAliasAttempted) return false;
e.storeAliasAttempted = true;
const t = inboundStoreRef(e.attachment.url);
if (!t) return false;
const n = await resolveInboundMediaReference(t).catch(() => null);
if (!n || n.physicalPath === e.resolvedPath) return false;
e.resolvedPath = n.physicalPath;
e.statSize = void 0;
return true;
}
/** Returns a local path for providers that cannot accept buffers, creating a temp file if needed. */
async getPath(e) {
const t = await this.ensureEntry(e.attachmentIndex);
e.signal?.throwIfAborted();
const n = await this.withLocalFile(t, async () => {
await (await this.prepareLocalFile(t))?.handle.close().catch(() => {});
const n = t.statSize;
if (t.resolvedPath) {
if (n !== void 0 && n > e.maxBytes) throw maxBytesError(e);
return t.resolvedPath;
}
});
e.signal?.throwIfAborted();
if (n) return n;
if (t.tempPath) {
if (t.bufferResult && t.bufferResult.size > e.maxBytes) throw maxBytesError(e);
return t.tempPath;
}
const r = await this.getBuffer(e);
const i = path.extname(r.fileName || "") || "";
const a = buildRandomTempFilePath$1({
prefix: "openclaw-media",
extension: i
});
this.stagedPaths.add(a);
await fs$1.writeFile(a, r.buffer, { signal: e.signal }).catch(async (e) => {
await this.removeStagedPath(a);
throw e;
});
t.tempPath = a;
return a;
}
/** Removes temporary files created by `getPath`; callers should run this after provider use. */
async cleanup() {
const e = [...this.stagedPaths];
for (const e of this.entries.values()) e.tempPath = void 0;
await Promise.all(e.map((e) => this.removeStagedPath(e)));
}
async removeStagedPath(e) {
try {
await fs$1.unlink(e);
} catch (t) {
if (!hasErrnoCode(t, "ENOENT")) {
logWarn(`media-understanding: could not remove staged attachment ${e}; remove it manually if it remains: ${String(t)}`);
return;
}
}
this.stagedPaths.delete(e);
}
/** Drops this cache's bytes after terminal file processing; earlier borrowers keep ownership. */
releaseBuffer(e) {
const t = this.entries.get(e);
if (t) t.bufferResult = void 0;
}
async ensureEntry(e) {
const t = this.entries.get(e) ?? { attachment: { index: e } };
if (!t.localResolutionAttempted) {
t.resolvedPath = await this.resolveLocalPath(t.attachment);
t.localResolutionAttempted = true;
}
this.entries.set(e, t);
return t;
}
async resolveLocalPath(e) {
const t = normalizeAttachmentPath(e.path);
if (!t) return;
const n = await resolveInboundMediaReference(t).catch(() => null);
if (n) return n.physicalPath;
const r = e.workspaceDir ?? this.fallbackWorkspaceDir;
if (r) return path.resolve(r, t);
if (!path.isAbsolute(t)) {
const e = resolveUsableLocalCandidate(path.resolve(t), this.localPathRoots);
if (e) return e;
const n = resolveUsableLocalCandidate(path.resolve(resolveStateDir(), t), this.localPathRoots);
if (n) return n;
}
return path.resolve(t);
}
/** Transfers a newly validated handle to the caller; cached path metadata needs no open. */
async prepareLocalFile(e) {
if (!e.resolvedPath) return;
if (!isInboundPathAllowed({
filePath: e.resolvedPath,
roots: this.localPathRoots
})) {
const t = await this.getCanonicalLocalPathRoots();
const n = e.resolvedPath;
const r = await fs$1.realpath(n).catch(() => n);
if (!isInboundPathAllowed({
filePath: r,
roots: t
})) {
e.resolvedPath = void 0;
if (shouldLogVerbose()) logVerbose(`Blocked attachment path outside allowed roots: ${e.attachment.path ?? e.attachment.url ?? "(unknown)"}`);
throw new MediaUnderstandingSkipError("blocked", `Attachment ${e.attachment.index + 1} path is outside allowed roots.`);
}
}
if (e.statSize !== void 0) return;
let t;
try {
t = await openLocalFileSafely({ filePath: e.resolvedPath });
const n = await this.getCanonicalLocalPathRoots();
if (!isInboundPathAllowed({
filePath: t.realPath,
roots: n
})) {
e.resolvedPath = void 0;
if (shouldLogVerbose()) logVerbose(`Blocked canonicalized attachment path outside allowed roots: ${t.realPath}`);
throw new MediaUnderstandingSkipError("blocked", `Attachment ${e.attachment.index + 1} path is outside allowed roots.`);
}
e.resolvedPath = t.realPath;
e.statSize = t.stat.size;
return t;
} catch (n) {
await t?.handle.close().catch(() => {});
if (n instanceof MediaUnderstandingSkipError) throw n;
if (n instanceof FsSafeError) {
e.resolvedPath = void 0;
if (n.code === "not-file") throw new MediaUnderstandingSkipError("empty", `Attachment ${e.attachment.index + 1} path is not a regular file.`);
if (n.code !== "not-found") throw new MediaUnderstandingSkipError("blocked", `Attachment ${e.attachment.index + 1} path is outside allowed roots.`);
} else throw new MediaUnderstandingSkipError("blocked", `Attachment ${e.attachment.index + 1} could not be canonicalized.`);
e.resolvedPath = void 0;
if (shouldLogVerbose()) logVerbose(`Failed to read attachment ${e.attachment.index + 1}: ${String(n)}`);
return;
}
}
async getCanonicalLocalPathRoots() {
return await (this.canonicalLocalPathRoots ??= (async () => mergeInboundPathRoots(this.localPathRoots, await Promise.all(this.localPathRoots.map(async (e) => {
if (e.includes("*")) return e;
return await fs$1.realpath(e).catch(() => e);
}))))());
}
};
//#endregion
export { MediaUnderstandingSkipError as n, isMediaUnderstandingSkipError as r, MediaAttachmentCache as t };