openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
211 lines (210 loc) • 7.26 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { i as shouldLogVerbose, r as logVerbose } from "./globals-CgepmiqE.mjs";
import { n as resolveConcurrency } from "./resolve-Qea3Nian.mjs";
import { t as finalizeInboundContext } from "./inbound-context-0zDtB0Zn.mjs";
import { n as formatMediaUnderstandingBody, t as formatAudioTranscripts } from "./format-DRIP403s.mjs";
import { a as resolveAttachmentKind } from "./attachments.normalize-_9E9xPsg.mjs";
import { n as runCapability, r as selectAttachments } from "./runner-owrA54Pb.mjs";
import { r as sendTranscriptEcho, t as DEFAULT_ECHO_TRANSCRIPT_FORMAT } from "./echo-transcript-C-BDqHL2.mjs";
import { t as resolveFileExtractionLimits } from "./file-extraction-limits-Dz8UGxWS.mjs";
import { a as renderMediaAttachmentDisposition, i as applyAttachmentMarkerBudget, t as extractFileContext } from "./file-context-BCvJjAv9.mjs";
import { n as createScopedMediaAttachmentCache, r as normalizeMediaAttachments } from "./runner.attachments-Dzrzdim3.mjs";
import { t as buildMediaUnderstandingRegistry } from "./provider-registry-KU-YX8vG.mjs";
import { t as assertMediaExecutionCurrent } from "./provider-execution-4fHifSsm.mjs";
import pMap from "p-map";
//#region src/media-understanding/apply.ts
const CAPABILITY_ORDER = [
"image",
"audio",
"video"
];
const AUDIO_ONLY_CAPABILITY_ORDER = ["audio"];
const EMPTY_VOICE_NOTE_PLACEHOLDER = "[Voice note could not be transcribed because the audio attachment was too small]";
const SELF_SERVE_CONTEXT_FIELDS = [
"Body",
"BodyForAgent",
"agentText"
];
async function applyMediaUnderstanding(e) {
const { ctx: t, cfg: n } = e;
const r = [
t.CommandBody,
t.RawBody,
t.Body
].map((e) => normalizeOptionalString(e)).find(Boolean);
const i = normalizeMediaAttachments(t);
let a;
let o;
const providerRegistry = () => {
if (o) throw o.error;
try {
return a ??= buildMediaUnderstandingRegistry(e.providers, n);
} catch (e) {
o = { error: e };
throw e;
}
};
const s = createScopedMediaAttachmentCache(i, e);
try {
const a = await pMap(e.processingMode === "files-only" ? [] : e.processingMode === "audio-only" || e.processingMode === "audio-and-files" ? AUDIO_ONLY_CAPABILITY_ORDER : CAPABILITY_ORDER, async (r) => {
const a = {
capability: r,
cfg: n,
ctx: t,
attachments: s,
media: i,
agentId: e.agentId,
agentDir: e.agentDir,
workspaceDir: e.workspaceDir,
providerRegistry,
config: n.tools?.media?.[r],
activeModel: e.activeModel,
execution: e.execution
};
try {
return await runCapability(a);
} catch (e) {
if (shouldLogVerbose()) logVerbose(`Media understanding task failed: ${String(e)}`);
const t = selectAttachments({
capability: r,
attachments: i,
policy: a.config?.attachments
});
return {
outputs: [],
decision: {
capability: r,
outcome: "failed",
attachments: [],
attachmentDispositions: Object.fromEntries([...t.selected.map(({ index: e }) => [e, { kind: "failed" }]), ...t.droppedAttachmentIndexes.map((e) => [e, { kind: "not-selected" }])]),
...r === "image" ? { nativeVisionActive: false } : {}
}
};
}
}, {
concurrency: resolveConcurrency(n),
stopOnError: false
});
if (o) throw o.error;
const c = [];
const l = [];
const u = /* @__PURE__ */ new Set();
for (const e of a) {
l.push(e.decision);
if (e.decision.capability !== "audio") {
for (const t of e.outputs) c.push(t);
continue;
}
const t = /* @__PURE__ */ new Map();
for (const n of e.outputs) {
t.set(n.attachmentIndex, n);
u.add(n.attachmentIndex);
}
for (const n of e.decision.attachments) {
const e = t.get(n.attachmentIndex);
if (e) c.push(e);
else if (n.attempts.some((e) => e.reason?.trim().startsWith("tooSmall"))) c.push({
kind: "audio.transcription",
attachmentIndex: n.attachmentIndex,
text: EMPTY_VOICE_NOTE_PLACEHOLDER,
provider: "openclaw",
model: "synthetic-empty-audio"
});
}
}
if (l.length > 0) t.MediaUnderstandingDecisions = [...t.MediaUnderstandingDecisions ?? [], ...l];
if (c.length > 0) {
const e = c.filter((e) => e.kind === "audio.transcription");
if (e.length > 0) {
const i = formatAudioTranscripts(e);
t.Transcript = i;
if (r) {
t.CommandBody = r;
t.RawBody = r;
} else {
t.CommandBody = i;
t.RawBody = i;
}
const a = n.tools?.media?.audio;
if (a?.echoTranscript && i) await sendTranscriptEcho({
ctx: t,
cfg: n,
transcript: i,
format: a.echoFormat ?? "📝 \"{transcript}\""
});
} else if (r) {
t.CommandBody = r;
t.RawBody = r;
}
t.MediaUnderstanding = [...t.MediaUnderstanding ?? [], ...c];
}
const d = e.processingMode === "audio-only" ? {
blocks: [],
images: [],
localPathSelfServeUpgrades: []
} : await extractFileContext({
attachments: i,
cache: s,
cfg: n,
limits: resolveFileExtractionLimits(n),
skipAttachmentIndexes: u.size > 0 ? u : void 0,
selfServePathsEnabled: e.selfServeLocalPaths === true,
signal: e.execution?.signal,
assertCurrent: e.execution ? () => assertMediaExecutionCurrent(e.execution) : void 0
});
const f = new Set(l.map((e) => e.capability));
const p = t.MediaUnderstandingDecisions ?? [];
const m = e.deliveredImageIndexes;
const h = new Set(c.map((e) => e.attachmentIndex));
const g = i.flatMap((e) => {
const t = resolveAttachmentKind(e);
if (t !== "image" && t !== "audio" && t !== "video" || !f.has(t)) return [];
if (t === "image" && m?.has(e.index)) return [];
const n = p.findLast((n) => n.capability === t && n.attachmentDispositions?.[e.index] !== void 0);
if (!n || h.has(e.index)) return [];
const r = n.attachmentDispositions?.[e.index];
if (t === "image" && n.nativeVisionActive !== false && r?.kind !== "failed") return [];
const i = r ? renderMediaAttachmentDisposition(t, r) : null;
return i ? [{
text: i,
consumesMarkerBudget: true
}] : [];
});
const _ = applyAttachmentMarkerBudget([...d.blocks, ...g]);
if (c.length > 0 || _.length > 0) {
const e = _.length > 0 ? _.join("\n\n").trim() : void 0;
const enrich = (t) => {
const n = formatMediaUnderstandingBody({
body: t,
outputs: c
});
if (e === void 0) return n;
const r = typeof n === "string" ? n.trim() : "";
return r ? `${r}\n\n${e}`.trim() : e;
};
t.agentText = enrich(t.agentText ?? t.BodyForAgent ?? t.Body);
t.Body = enrich(t.Body);
finalizeInboundContext(t, { forceBodyForCommands: true });
}
return {
extractedFileImages: d.images,
...d.localPathSelfServeUpgrades.length > 0 ? { enableLocalPathSelfServe: (e, t) => {
const n = d.localPathSelfServeUpgrades;
for (const r of e) for (const e of n) {
const n = t?.get(e.attachmentIndex);
if (t && !n) continue;
const i = e.render(n);
if (!i) continue;
for (const t of SELF_SERVE_CONTEXT_FIELDS) {
const n = r[t];
if (typeof n === "string") r[t] = n.replace(e.fallback, i);
}
}
} } : {}
};
} finally {
await s.cleanup();
}
}
//#endregion
export { applyMediaUnderstanding as t };