openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
230 lines (229 loc) • 9.85 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { n as resolveFilesystemPath } from "./home-dir-EKmgmdPG.mjs";
import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs";
import { n as detectMime } from "./mime-D2wVBzpa.mjs";
import { t as normalizeImageGenerationResolution } from "./resolution-DwXlhOG0.mjs";
import { t as createEnumOptionParser } from "./enum-option-2-tUH_OI.mjs";
import { a as providerSummaryText, i as formatEnvelopeForText, n as runCapabilityCommand, t as registerLocalProvidersCommand } from "./providers-command-D9EdIVJQ.mjs";
import { t as isMissingMediaUnderstandingProvider } from "./media-understanding-result-B9ThU4q5.mjs";
import { t as collectOption } from "./helpers-Cxs4nwgv.mjs";
import { t as parseOptionalPositiveInteger } from "./parse-positive-integer-DrSNo4LV.mjs";
import path from "node:path";
//#region src/cli/capability-cli/image.ts
const IMAGE_OUTPUT_FORMATS = [
"png",
"jpeg",
"webp"
];
const IMAGE_BACKGROUNDS = [
"transparent",
"opaque",
"auto"
];
const IMAGE_QUALITIES = [
"low",
"medium",
"high",
"xhigh",
"max",
"auto"
];
const IMAGE_MODERATIONS = ["low", "auto"];
const parseImageOption = createEnumOptionParser();
function registerImageCapabilityCommands(e) {
const t = e.command("image").description("Image generation and description").option("--agent <id>", "Agent whose model and auth state should be used");
for (const [e, n] of [["generate", "Generate images"], ["edit", "Edit images with one or more input files"]]) {
const r = t.command(e).description(n);
if (e === "edit") r.requiredOption("--file <path>", "Input file", collectOption);
r.requiredOption("--prompt <text>", "Prompt text").option("--model <provider/model>", "Model override").option("--count <n>", "Number of images").option("--size <size>", "Size hint like 1024x1024").option("--aspect-ratio <ratio>", "Aspect ratio hint like 16:9").option("--resolution <value>", "Resolution hint: 1K, 2K, or 4K").option("--output-format <format>", "Output format hint: png, jpeg, or webp").option("--background <value>", "Background hint: transparent, opaque, or auto").option("--openai-background <value>", "OpenAI background hint: transparent, opaque, or auto").option("--openai-moderation <value>", "OpenAI moderation hint: low or auto").option("--quality <value>", "Quality hint: low, medium, high, xhigh, max, or auto").option("--timeout-ms <ms>", "Provider request timeout in milliseconds").option("--output <path>", "Output path").option("--agent <id>", "Agent whose saved provider auth is used (default: agents.defaults.systemAgent.agentId, then the sole agent)").option("--json", "Output JSON", false).action((t, n) => runCapabilityCommand(t.json, formatEnvelopeForText, async () => {
const r = getAsyncWorkSignal();
const i = `image.${e}`;
const a = String(t.prompt);
const o = e === "edit" ? Array.isArray(t.file) ? t.file : [String(t.file)] : void 0;
const { resolveCapabilityAgentOption: s, parseOptionalTimeoutMs: c, requireProviderModelOverride: l, resolveLocalCapabilityAgent: u } = await import("./shared-CwcDzg1K.mjs");
const d = s(n, t.agent);
const f = t.model;
const p = parseOptionalPositiveInteger(t.count, "--count");
const m = t.size;
const h = normalizeOptionalString(t.aspectRatio);
const { parseAspectRatioValue: g } = await import("./runtime-shared-DUK2H2ja.mjs");
if (h && !g(h)) throw new Error("--aspect-ratio must be a W:H ratio of positive numbers, like 16:9");
const _ = normalizeImageGenerationResolution(t.resolution);
const v = parseImageOption(t.outputFormat, IMAGE_OUTPUT_FORMATS, "--output-format");
const y = parseImageOption(t.background, IMAGE_BACKGROUNDS, "--background");
const b = parseImageOption(t.openaiBackground, IMAGE_BACKGROUNDS, "--openai-background");
const x = parseImageOption(t.openaiModeration, IMAGE_MODERATIONS, "--openai-moderation");
const S = parseImageOption(t.quality, IMAGE_QUALITIES, "--quality");
const C = c(t.timeoutMs);
const w = t.output;
const { getModelsCommandSecretTargetIds: T } = await import("./command-secret-targets-CYdGJLhL.mjs");
const { generateImage: E } = await import("./runtime-C3M855am.mjs");
const { getImageMetadata: D } = await import("./media-services-B_q3spOh.mjs");
const { readInputFiles: O, writeOutputAsset: k } = await import("./media-output-DUqxON0M.mjs");
l(f);
const { cfg: A, agentDir: j } = await u({
commandName: `infer ${i}`,
targetIds: T(),
agent: d
});
const M = o && o.length > 0 ? await Promise.all((await O(o)).map(async (e) => ({
buffer: e.buffer,
fileName: path.basename(e.path),
mimeType: await detectMime({
buffer: e.buffer,
filePath: e.path
}) ?? "image/png"
}))) : void 0;
r?.throwIfAborted();
const N = await E({
cfg: A,
agentDir: j,
prompt: a,
modelOverride: f,
count: p,
size: m,
aspectRatio: h,
resolution: _,
quality: S,
outputFormat: v,
background: y,
providerOptions: b || x ? { openai: {
...b ? { background: b } : {},
...x ? { moderation: x } : {}
} } : void 0,
timeoutMs: C,
inputImages: M,
signal: r
});
r?.throwIfAborted();
const P = await Promise.all(N.images.map(async (e, t) => {
const n = await k({
buffer: e.buffer,
mimeType: e.mimeType,
originalFilename: e.fileName,
outputPath: w,
outputIndex: t,
outputCount: N.images.length,
subdir: "generated"
});
const r = await D(e.buffer).catch(() => void 0);
return {
...n,
width: r?.width,
height: r?.height,
revisedPrompt: e.revisedPrompt
};
}));
return {
ok: true,
capability: i,
transport: "local",
provider: N.provider,
model: N.model,
attempts: N.attempts,
outputs: P,
ignoredOverrides: N.ignoredOverrides
};
}));
}
for (const [e, n] of [["describe", "Describe one image file"], ["describe-many", "Describe multiple image files"]]) {
const r = t.command(e).description(n);
const i = e === "describe-many";
if (i) r.requiredOption("--file <path>", "Image file", collectOption);
else r.requiredOption("--file <path>", "Image file");
r.option("--prompt <text>", "Prompt hint").option("--model <provider/model>", "Model override").option("--timeout-ms <ms>", "Provider request timeout in milliseconds").option("--agent <id>", "Agent whose saved provider auth is used (default: agents.defaults.systemAgent.agentId, then the sole agent)").option("--json", "Output JSON", false).action((t, n) => runCapabilityCommand(t.json, formatEnvelopeForText, async () => {
const { parseOptionalTimeoutMs: r, resolveCapabilityAgentOption: a, requireProviderModelOverride: o, resolveLocalCapabilityAgent: s } = await import("./shared-CwcDzg1K.mjs");
const c = getAsyncWorkSignal();
const l = c ? {
signal: c,
assertCurrent: () => c.throwIfAborted()
} : void 0;
const u = `image.${e}`;
const d = i ? t.file : [String(t.file)];
const f = t.model;
const p = t.prompt;
const m = r(t.timeoutMs);
const h = a(n, t.agent);
const { getModelsCommandSecretTargetIds: g } = await import("./command-secret-targets-CYdGJLhL.mjs");
const { runWithImageModelFallback: _ } = await import("./model-fallback-image-DlzcYhEC.mjs");
const { describeImageFile: v, describePreparedImageWithModel: y, prepareImageDescriptionInput: b } = await import("./runtime-B1oFfDL6.mjs");
const { cfg: x, agentId: S, agentDir: C } = await s({
commandName: `infer ${u}`,
targetIds: g(),
agent: h
});
const w = o(f);
const T = normalizeOptionalString(p);
const E = await Promise.all(d.map(async (e) => {
const t = e.trim();
const n = /^https?:\/\//i.test(t) ? t : resolveFilesystemPath(e);
const r = /^https?:\/\//i.test(n);
const i = w ? await b({
filePath: n,
...r ? { mediaUrl: n } : {},
cfg: x,
timeoutMs: m
}, l) : void 0;
const a = w && i ? await _({
cfg: x,
modelOverride: `${w.provider}/${w.model}`,
abortSignal: c,
run: async (e, t) => {
const r = await y({
image: i,
cfg: x,
agentId: S,
agentDir: C,
provider: e,
model: t,
prompt: T ?? "Describe the image.",
timeoutMs: m
}, l);
if (!r.text?.trim()) throw new Error(`No description returned for image: ${n}`);
return r;
}
}) : {
result: await v({
filePath: n,
...r ? { mediaUrl: n } : {},
cfg: x,
agentId: S,
agentDir: C,
prompt: T,
timeoutMs: m
}, l),
provider: void 0,
model: void 0,
attempts: []
};
if (!a.result.text) {
if (isMissingMediaUnderstandingProvider(a.result)) throw new Error("No image understanding provider is configured or ready. Configure an image-capable tools.media.models entry or agents.defaults.imageModel.primary, or pass --model <provider/model> after configuring that provider's auth/API key.");
throw new Error(`No description returned for image: ${n}`);
}
return {
path: n,
text: a.result.text,
provider: a.provider ?? a.result.provider,
model: a.result.model ?? a.model,
attempts: a.attempts,
kind: "image.description"
};
}));
return {
ok: true,
capability: u,
transport: "local",
provider: E[0]?.provider,
model: E[0]?.model,
attempts: E.flatMap((e) => e.attempts),
outputs: E.map(({ attempts: e, ...t }) => t)
};
}));
}
registerLocalProvidersCommand(t, "List image generation providers", async (e, t) => {
const { listGenerationProviders: n } = await import("./media-providers-Duy95i79.mjs");
return n("image", e, t);
}, providerSummaryText);
}
//#endregion
export { registerImageCapabilityCommands };