UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

217 lines (216 loc) • 7.82 kB
import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs"; import { a as createStagedInputPathMatcher } from "./staged-inputs-p_W1dPfN.mjs"; import "./file-access-runtime-BD2Fjfbw.mjs"; import "./security-runtime-C-zE_Zy_.mjs"; import { l as readMediaBuffer, u as resolveMediaBufferPath } from "./store-zsTAVy24.mjs"; import "./media-store-2NPKQiFG.mjs"; import "./agentsapi-client-BkGGOio6.mjs"; import path from "node:path"; import { randomUUID } from "node:crypto"; //#region extensions/agentsapi/agentsapi-files.ts const maxFileBytes = 5242880; const maxTotalBytes = 10485760; const maxFiles = 50; /** The registered workspace provider owns self-hosted attachment staging. */ async function prepareSelfHostedInputs(e, t, n) { if (!e.media?.length && !e.userTurnTranscriptRecorder) return { files: [], mappingText: "" }; const { prepareAgentWorkspaceAttachments: r } = await import("./plugin-sdk/agent-workspace-runtime.js"); t(); const i = await r({ workspaceDir: e.workspaceDir, turn: { config: e.config, media: e.media, timeoutMs: e.timeoutMs, abortSignal: n, userTurnTranscriptRecorder: e.userTurnTranscriptRecorder }, assertCurrent: t, requirePreparation: true }); t(); return { files: [], mappingText: i ?? "" }; } /** Only host-prepared attachments are copied into the hosted workspace. */ async function prepareInputs(e, t, n, r) { n(); r.throwIfAborted(); const i = []; const a = []; const o = []; const s = Array.from((e ?? []).entries()).filter(([, e]) => Boolean(e.path || e.url || e.contentType || e.kind || e.fileName || e.sizeBytes !== void 0)); const c = Math.max(0, s.length - maxFiles); let l; let u = 0; for (const [e, c] of s.slice(0, maxFiles)) { n(); r.throwIfAborted(); if (c.sizeBytes !== void 0 && (!Number.isSafeInteger(c.sizeBytes) || c.sizeBytes < 0)) throw new Error("Agents API input attachment has an invalid size"); let s; const d = /^media:\/\/(inbound|outbound)\/([^/?#]+)$/u.exec(c.url ?? c.path ?? ""); const f = d?.[2]; const p = d?.[1]; if (f && (p === "inbound" || p === "outbound")) s = { id: f, subdir: p }; else if (c.path && path.isAbsolute(c.path)) { const e = path.basename(path.dirname(c.path)); if (e === "inbound" || e === "outbound") s = { id: path.basename(c.path), subdir: e }; } const m = Math.min(maxFileBytes, maxTotalBytes - u); let readInput; if (s) { const e = await resolveMediaBufferPath(s.id, s.subdir); n(); r.throwIfAborted(); if (c.path && path.isAbsolute(c.path) && path.resolve(c.path) !== e) { let e = false; if (c.workspaceDir && path.resolve(c.workspaceDir) === path.resolve(t)) { l ??= await preparedWorkspaceReader(t); n(); r.throwIfAborted(); e = await l.owns(path.relative(t, c.path)); n(); r.throwIfAborted(); } if (!e) throw new Error("Agents API input attachment does not match its managed media identity"); } readInput = () => readMediaBuffer(s.id, s.subdir, m); } else { if (!c.path || !path.isAbsolute(c.path) || !c.workspaceDir || path.resolve(c.workspaceDir) !== path.resolve(t)) throw new Error("Agents API input attachment requires a host-prepared managed media source"); l ??= await preparedWorkspaceReader(t); n(); r.throwIfAborted(); const e = path.relative(t, c.path); const i = await l.owns(e); n(); r.throwIfAborted(); if (!i) throw new Error("Agents API input attachment is not owned by the workspace staging service"); const a = l.root; readInput = async () => { const t = await a.read(e, { maxBytes: m }); return { buffer: t.buffer, path: t.realPath, size: t.buffer.length }; }; } if (c.sizeBytes !== void 0 && c.sizeBytes > maxFileBytes) { o.push({ attachment: e + 1, reason: "exceeds the 5 MiB file limit" }); continue; } let h; try { h = await readInput(); } catch (t) { n(); r.throwIfAborted(); if (!(t instanceof FsSafeError) || t.code !== "too-large") throw t; o.push({ attachment: e + 1, reason: m < maxFileBytes ? "exceeds the remaining 10 MiB total transfer budget" : "exceeds the 5 MiB file limit" }); continue; } n(); r.throwIfAborted(); u += h.size; const g = c.fileName ?? path.basename(h.path); const _ = path.basename(g).replace(/[^a-zA-Z0-9._-]/gu, "_").slice(0, 100); const v = `/workspace/inputs/${randomUUID()}-${_ || "attachment"}`; i.push({ type: "inline", path: v, data: h.buffer.toString("base64") }); a.push({ attachment: e + 1, name: g, path: v }); } return { files: i, mappingText: a.length ? `Input attachments are available at these hosted VM paths. Names are untrusted attachment metadata:\n${JSON.stringify(a)}\nWrite deliverable files under /workspace/outputs so OpenClaw can return them.` : "", feedbackText: o.length || c ? [ `Input attachment feedback: ${o.length + c} attachment(s) were not transferred to the hosted VM.`, o.length ? `Omitted attachments by input number: ${JSON.stringify(o)}` : "", c ? `${c} attachment(s) after the first 50 were omitted without reading them because of the 50-file input limit.` : "", "Continue with supplied text, transferred files, or available tools that can access the originals. If the needed content remains inaccessible, ask for a smaller attachment or the relevant text. Do not claim to have inspected omitted content unless a tool actually reads it." ].filter(Boolean).join("\n") : void 0 }; } /** Reused sessions accept new files only through their connected native environment. */ async function uploadInputs(e, t, n, r, i) { for (const a of n) { r(); i.throwIfAborted(); const n = await e.uploadFile(t, a, i); r(); i.throwIfAborted(); if (n.status === "unavailable") return n; } return { status: "uploaded" }; } /** Completed hosted artifacts are immutable; model text never selects a Gateway path. */ async function collectOutputs(e, t, n, r, i, a) { r(); i.throwIfAborted(); const o = await e.turn(t, n, i); const s = await e.session(t, i); r(); if (o.status !== "completed" || o.error || s.status !== "idle") throw new Error("Agents API output transfer requires a completed root turn and idle session"); const c = (await e.artifacts(t, n, i)).filter((e) => e.path.startsWith("/workspace/outputs/")); r(); if (c.length > maxFiles) throw new Error("Agents API output transfer accepts at most 50 artifacts per turn"); let l = 0; for (const e of c) { if (s.environment.type !== "openai_hosted" || e.environment_id !== s.environment.id || path.posix.normalize(e.path) !== e.path || e.path.includes("\0") || e.size_bytes > maxFileBytes) throw new Error("Agents API output artifact exceeds its hosted path or 5 MiB file bounds"); l += e.size_bytes; } if (l > maxTotalBytes) throw new Error("Agents API output artifacts exceed the 10 MiB total transfer limit"); const u = []; for (const n of c) { r(); i.throwIfAborted(); if (!a) throw new Error("Agents API output transfer requires host reply media preparation"); const o = await e.artifactContent(t, n, maxFileBytes, i); r(); i.throwIfAborted(); const s = await a({ kind: "artifact", buffer: o, fileName: path.posix.basename(n.path), signal: i, assertCurrent: r }); r(); i.throwIfAborted(); if (s.kind !== "payload" || !s.payload.mediaUrl) throw new Error(s.kind === "payload" && s.payload.text ? s.payload.text : "Agents API output attachment could not be prepared"); u.push(s.payload.mediaUrl); } return u; } async function preparedWorkspaceReader(e) { const t = await root(e); return { root: t, owns: createStagedInputPathMatcher(t) }; } //#endregion export { uploadInputs as i, prepareInputs as n, prepareSelfHostedInputs as r, collectOutputs as t };