@qzsy/dsh-image-generation 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,778 @@
1
+ // src/index.ts
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
4
+ import z from "@deepseek-ai/schemastery";
5
+ import { AttachmentId } from "@deepseek-ai/dsh-attachment";
6
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
7
+ import { defineTool } from "@deepseek-ai/dsh-tools";
8
+ var name = "image-gen";
9
+ var CATALOG_NS = "image-gen";
10
+ var RUNTIME_NS = "image-gen-runtime";
11
+ var RPC_CHANNEL = "/image-gen";
12
+ var API_FORMATS = Object.freeze([
13
+ "openai-images",
14
+ "xai-images",
15
+ "gemini-image",
16
+ "openai-chat-image"
17
+ ]);
18
+ var IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
19
+ var IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
20
+ var USER_AGENT = "@qzsy/dsh-image-generation/0.2.0";
21
+ var DEFAULT_SIZE = "1024x1024";
22
+ var DEFAULT_QUALITY = "auto";
23
+ var SIZE_TO_ASPECT = {
24
+ "1024x1024": "1:1",
25
+ "1024x1536": "2:3",
26
+ "1536x1024": "3:2",
27
+ auto: "auto"
28
+ };
29
+ var GROK_QUALITY = {
30
+ low: "low",
31
+ medium: "medium",
32
+ high: "medium",
33
+ auto: undefined
34
+ };
35
+ var modelSchema = z.object({
36
+ id: z.string(),
37
+ name: z.string()
38
+ });
39
+ var providerSchema = z.object({
40
+ id: z.string(),
41
+ name: z.string(),
42
+ baseUrl: z.string(),
43
+ apiFormat: z.string().default("openai-images"),
44
+ apiKeyEnv: z.string().role("credential-ref"),
45
+ models: z.array(modelSchema).default([])
46
+ });
47
+ var CatalogConfig = z.object({
48
+ providers: z.array(providerSchema).default([])
49
+ });
50
+ var RuntimeConfig = z.object({
51
+ enabled: z.boolean().default(true),
52
+ providerId: z.string().default(""),
53
+ modelId: z.string().default(""),
54
+ defaultSize: z.string().default(DEFAULT_SIZE),
55
+ defaultQuality: z.string().default(DEFAULT_QUALITY)
56
+ });
57
+ var maybeVolatile = (schema) => schema && typeof schema.volatile === "function" ? schema.volatile() : schema;
58
+ var Config = z.object({
59
+ providers: maybeVolatile(z.array(providerSchema).default([])),
60
+ enabled: maybeVolatile(z.boolean().default(true)),
61
+ providerId: maybeVolatile(z.string().default("")),
62
+ modelId: maybeVolatile(z.string().default("")),
63
+ defaultSize: maybeVolatile(z.string().default(DEFAULT_SIZE)),
64
+ defaultQuality: maybeVolatile(z.string().default(DEFAULT_QUALITY))
65
+ });
66
+ function unwrapVolatile(value) {
67
+ if (value && typeof value === "object" && typeof value.get === "function") {
68
+ try {
69
+ return value.get();
70
+ } catch {
71
+ return;
72
+ }
73
+ }
74
+ return value;
75
+ }
76
+ function emptyCatalog() {
77
+ return { providers: [] };
78
+ }
79
+ function emptyRuntime() {
80
+ return {
81
+ enabled: true,
82
+ providerId: "",
83
+ modelId: "",
84
+ defaultSize: DEFAULT_SIZE,
85
+ defaultQuality: DEFAULT_QUALITY
86
+ };
87
+ }
88
+ function slugifyProviderId(value) {
89
+ const slug = String(value ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
90
+ return slug || "provider";
91
+ }
92
+ function apiKeyEnvFor(providerId) {
93
+ return `IMAGE_GEN_${String(providerId).toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
94
+ }
95
+ function trimSlash(url) {
96
+ return String(url ?? "").trim().replace(/\/+$/, "");
97
+ }
98
+ function assertHttpUrl(value, label) {
99
+ const text = trimSlash(value);
100
+ if (text.length === 0)
101
+ throw new Error(`image_generate: ${label} is empty`);
102
+ let parsed;
103
+ try {
104
+ parsed = new URL(text);
105
+ } catch {
106
+ throw new Error(`image_generate: ${label} is not a valid URL: ${text}`);
107
+ }
108
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
109
+ throw new Error(`image_generate: ${label} must start with http:// or https://`);
110
+ }
111
+ return text;
112
+ }
113
+ function joinEndpoint(baseUrl, suffix) {
114
+ const base = trimSlash(baseUrl);
115
+ if (base.length === 0)
116
+ throw new Error("image_generate: the selected provider has no Base URL");
117
+ return base.endsWith(suffix) ? base : `${base}${suffix}`;
118
+ }
119
+ function abortError(signal) {
120
+ const error = new Error("image_generate: cancelled");
121
+ error.name = "AbortError";
122
+ error.cause = signal?.reason;
123
+ return error;
124
+ }
125
+ function isAbortError(error) {
126
+ return error instanceof Error && error.name === "AbortError";
127
+ }
128
+ function responseError(payload, status) {
129
+ const detail = typeof payload?.error === "string" ? payload.error : payload?.error?.message ?? payload?.message ?? payload?.error?.status;
130
+ return detail && String(detail).length > 0 ? String(detail) : `image API error (HTTP ${status})`;
131
+ }
132
+ function sniffImageMediaType(data) {
133
+ if (data.length >= 3 && data[0] === 255 && data[1] === 216 && data[2] === 255)
134
+ return "image/jpeg";
135
+ if (data.length >= 12 && data.toString("latin1", 0, 4) === "RIFF" && data.toString("latin1", 8, 12) === "WEBP") {
136
+ return "image/webp";
137
+ }
138
+ const gif = data.length >= 6 ? data.toString("latin1", 0, 6) : "";
139
+ if (gif === "GIF87a" || gif === "GIF89a")
140
+ return "image/gif";
141
+ return "image/png";
142
+ }
143
+ var MEDIA_TYPE_EXTENSIONS = {
144
+ "image/png": "png",
145
+ "image/jpeg": "jpg",
146
+ "image/webp": "webp",
147
+ "image/gif": "gif"
148
+ };
149
+ function imageFileName(index, mediaType) {
150
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
151
+ const extension = MEDIA_TYPE_EXTENSIONS[mediaType] ?? "png";
152
+ return `image-${stamp}-${Math.random().toString(36).slice(2, 8)}-${index}.${extension}`;
153
+ }
154
+ function workspaceRoot(cwd) {
155
+ return typeof cwd === "string" && cwd.trim().length > 0 ? cwd.trim() : process.cwd();
156
+ }
157
+ function outputDirectory(cwd) {
158
+ return join(workspaceRoot(cwd), "generate", "image");
159
+ }
160
+ function samePath(left, right) {
161
+ return process.platform === "win32" ? left.toLowerCase() === right.toLowerCase() : left === right;
162
+ }
163
+ function resolveGeneratedImage(cwd, value) {
164
+ if (typeof value !== "string" || value.trim().length === 0) {
165
+ throw new BadRequest("payload.path must be a non-empty string");
166
+ }
167
+ const root = workspaceRoot(cwd);
168
+ const directory = outputDirectory(root);
169
+ const absolute = resolve(isAbsolute(value) ? value : join(root, value));
170
+ if (!samePath(dirname(absolute), directory)) {
171
+ throw new BadRequest("path must point at a file directly under generate/image");
172
+ }
173
+ if (!IMAGE_EXTENSIONS.has(extname(absolute).toLowerCase())) {
174
+ throw new BadRequest("path must be a png, jpg, webp or gif file");
175
+ }
176
+ return absolute;
177
+ }
178
+ function decodeDataUrl(value) {
179
+ const match = String(value ?? "").match(/^data:([^;,]+);base64,(.+)$/s);
180
+ if (!match)
181
+ return null;
182
+ return { mediaType: match[1], data: Buffer.from(match[2], "base64") };
183
+ }
184
+ async function downloadImage(url, signal) {
185
+ const response = await fetch(url, { redirect: "follow", signal });
186
+ if (!response.ok)
187
+ throw new Error(`image_generate: image download failed (HTTP ${response.status})`);
188
+ return Buffer.from(await response.arrayBuffer());
189
+ }
190
+ function pushImage(sink, data, mediaType) {
191
+ if (!data || data.length === 0)
192
+ return;
193
+ const type = mediaType && IMAGE_MEDIA_TYPES.includes(mediaType) ? mediaType : sniffImageMediaType(data);
194
+ sink.push({ data, mediaType: type });
195
+ }
196
+ function pushUrl(sink, url, mediaType = "image/png") {
197
+ if (typeof url !== "string" || url.length === 0)
198
+ return;
199
+ const decoded = decodeDataUrl(url);
200
+ if (decoded)
201
+ pushImage(sink, decoded.data, decoded.mediaType);
202
+ else
203
+ sink.push({ url, mediaType });
204
+ }
205
+ function collectOpenAiImages(payload, sink) {
206
+ for (const entry of Array.isArray(payload?.data) ? payload.data : []) {
207
+ if (entry === null || typeof entry !== "object")
208
+ continue;
209
+ if (typeof entry.b64_json === "string" && entry.b64_json.length > 0) {
210
+ pushImage(sink, Buffer.from(entry.b64_json, "base64"), "image/png");
211
+ continue;
212
+ }
213
+ pushUrl(sink, entry.url, "image/png");
214
+ }
215
+ }
216
+ function collectGeminiImages(payload, sink) {
217
+ for (const candidate of Array.isArray(payload?.candidates) ? payload.candidates : []) {
218
+ for (const part of Array.isArray(candidate?.content?.parts) ? candidate.content.parts : []) {
219
+ const inline = part?.inlineData ?? part?.inline_data;
220
+ if (inline && typeof inline.data === "string" && inline.data.length > 0) {
221
+ pushImage(sink, Buffer.from(inline.data, "base64"), inline.mimeType ?? inline.mime_type);
222
+ }
223
+ }
224
+ }
225
+ for (const prediction of Array.isArray(payload?.predictions) ? payload.predictions : []) {
226
+ const base64 = prediction?.bytesBase64Encoded ?? prediction?.bytes_base64_encoded;
227
+ if (typeof base64 === "string" && base64.length > 0) {
228
+ pushImage(sink, Buffer.from(base64, "base64"), prediction?.mimeType);
229
+ }
230
+ }
231
+ }
232
+ function collectChatImages(payload, sink) {
233
+ for (const choice of Array.isArray(payload?.choices) ? payload.choices : []) {
234
+ const message = choice?.message ?? {};
235
+ for (const image of Array.isArray(message.images) ? message.images : []) {
236
+ pushUrl(sink, image?.image_url?.url ?? image?.url);
237
+ }
238
+ const content = message.content;
239
+ if (Array.isArray(content)) {
240
+ for (const part of content) {
241
+ if (part?.type === "image_url" && typeof part?.image_url?.url === "string") {
242
+ pushUrl(sink, part.image_url.url);
243
+ } else if (part?.inline_data?.data) {
244
+ pushImage(sink, Buffer.from(part.inline_data.data, "base64"), part.inline_data.mime_type);
245
+ }
246
+ }
247
+ continue;
248
+ }
249
+ if (typeof content === "string") {
250
+ const match = content.match(/data:(image\/[a-zA-Z0-9.+-]+);base64,([A-Za-z0-9+/=\s]+)/);
251
+ if (match)
252
+ pushImage(sink, Buffer.from(match[2].replace(/\s+/g, ""), "base64"), match[1]);
253
+ }
254
+ }
255
+ }
256
+ async function materializeImages(sink, signal) {
257
+ const images = [];
258
+ for (const item of sink) {
259
+ if (item.data) {
260
+ images.push({ data: item.data, mediaType: item.mediaType ?? sniffImageMediaType(item.data) });
261
+ continue;
262
+ }
263
+ if (typeof item.url === "string") {
264
+ const data = await downloadImage(item.url, signal);
265
+ images.push({ data, mediaType: sniffImageMediaType(data) });
266
+ }
267
+ }
268
+ if (images.length === 0)
269
+ throw new Error("image_generate: the response carried no image data");
270
+ return images;
271
+ }
272
+ async function readJson(response, signal) {
273
+ try {
274
+ return await response.json();
275
+ } catch (error) {
276
+ if (signal?.aborted === true || isAbortError(error))
277
+ throw abortError(signal);
278
+ throw new Error(`image API returned an unprocessable response (HTTP ${response.status}): ${String(error)}`);
279
+ }
280
+ }
281
+ async function postJson(url, { apiKey, body, signal, googleHost = false }) {
282
+ const headers = {
283
+ "content-type": "application/json",
284
+ accept: "application/json",
285
+ "user-agent": USER_AGENT
286
+ };
287
+ if (googleHost)
288
+ headers["x-goog-api-key"] = apiKey;
289
+ else
290
+ headers.authorization = `Bearer ${apiKey}`;
291
+ let response;
292
+ try {
293
+ response = await fetch(url, {
294
+ method: "POST",
295
+ redirect: "error",
296
+ headers,
297
+ body: JSON.stringify(body),
298
+ ...signal !== undefined ? { signal } : {}
299
+ });
300
+ } catch (error) {
301
+ if (signal?.aborted === true || isAbortError(error))
302
+ throw abortError(signal);
303
+ throw new Error(`image_generate: request failed: ${String(error)}`);
304
+ }
305
+ const payload = await readJson(response, signal);
306
+ if (!response.ok)
307
+ throw new Error(responseError(payload, response.status));
308
+ return payload;
309
+ }
310
+ function sizeOf(args, runtime) {
311
+ return args.size ?? runtime.defaultSize ?? DEFAULT_SIZE;
312
+ }
313
+ function qualityOf(args, runtime) {
314
+ return args.quality ?? runtime.defaultQuality ?? DEFAULT_QUALITY;
315
+ }
316
+ function geminiAspect(size) {
317
+ const aspect = SIZE_TO_ASPECT[size] ?? "1:1";
318
+ return aspect === "auto" ? "1:1" : aspect;
319
+ }
320
+ function isImagenModel(model) {
321
+ return /imagen/i.test(model);
322
+ }
323
+ function geminiEndpoint(baseUrl, model, verb) {
324
+ const base = trimSlash(baseUrl);
325
+ const id = model.startsWith("models/") ? model.slice("models/".length) : model;
326
+ return `${base}/models/${encodeURIComponent(id)}:${verb}`;
327
+ }
328
+ async function generateOpenAiImages({ provider, model, args, runtime, apiKey, signal, references }) {
329
+ const size = sizeOf(args, runtime);
330
+ const quality = qualityOf(args, runtime);
331
+ const editing = references !== undefined;
332
+ const url = joinEndpoint(provider.baseUrl, editing ? "/images/edits" : "/images/generations");
333
+ const body = {
334
+ model,
335
+ prompt: args.prompt.trim(),
336
+ n: 1,
337
+ ...size === "auto" ? {} : { size },
338
+ ...quality === "auto" ? {} : { quality },
339
+ response_format: "b64_json",
340
+ ...editing ? { images: references.map((image_url) => ({ image_url })) } : {}
341
+ };
342
+ let payload;
343
+ try {
344
+ payload = await postJson(url, { apiKey, body, signal });
345
+ } catch (error) {
346
+ if (!/response_format/i.test(String(error?.message ?? error)))
347
+ throw error;
348
+ const { response_format: _ignored, ...rest } = body;
349
+ payload = await postJson(url, { apiKey, body: rest, signal });
350
+ }
351
+ const sink = [];
352
+ collectOpenAiImages(payload, sink);
353
+ return materializeImages(sink, signal);
354
+ }
355
+ async function generateXaiImages({ provider, model, args, runtime, apiKey, signal, references }) {
356
+ const size = sizeOf(args, runtime);
357
+ const quality = GROK_QUALITY[qualityOf(args, runtime)];
358
+ const editing = references !== undefined;
359
+ const url = joinEndpoint(provider.baseUrl, editing ? "/images/edits" : "/images/generations");
360
+ const body = {
361
+ model,
362
+ prompt: args.prompt.trim(),
363
+ response_format: "b64_json",
364
+ ...size === undefined ? {} : { aspect_ratio: SIZE_TO_ASPECT[size] ?? "1:1" },
365
+ ...quality === undefined ? {} : { quality },
366
+ ...editing ? references.length === 1 ? { image: { type: "image_url", url: references[0] } } : { images: references.map((url) => ({ type: "image_url", url })) } : {}
367
+ };
368
+ const payload = await postJson(url, { apiKey, body, signal });
369
+ const sink = [];
370
+ collectOpenAiImages(payload, sink);
371
+ return materializeImages(sink, signal);
372
+ }
373
+ async function generateGeminiImage({ provider, model, args, runtime, apiKey, signal, references }) {
374
+ const size = sizeOf(args, runtime);
375
+ const googleHost = /generativelanguage\.googleapis\.com/i.test(provider.baseUrl);
376
+ const prompt = args.prompt.trim();
377
+ if (isImagenModel(model)) {
378
+ const payload = await postJson(geminiEndpoint(provider.baseUrl, model, "predict"), {
379
+ apiKey,
380
+ googleHost,
381
+ signal,
382
+ body: {
383
+ instances: [{ prompt }],
384
+ parameters: { sampleCount: 1, aspectRatio: geminiAspect(size) }
385
+ }
386
+ });
387
+ const sink = [];
388
+ collectGeminiImages(payload, sink);
389
+ return materializeImages(sink, signal);
390
+ }
391
+ const parts = [{ text: prompt }];
392
+ for (const dataUrl of references ?? []) {
393
+ const decoded = decodeDataUrl(dataUrl);
394
+ if (decoded)
395
+ parts.push({ inline_data: { mime_type: decoded.mediaType, data: decoded.data.toString("base64") } });
396
+ }
397
+ const payload = await postJson(geminiEndpoint(provider.baseUrl, model, "generateContent"), {
398
+ apiKey,
399
+ googleHost,
400
+ signal,
401
+ body: {
402
+ contents: [{ role: "user", parts }],
403
+ generationConfig: {
404
+ responseModalities: ["TEXT", "IMAGE"],
405
+ imageConfig: { aspectRatio: geminiAspect(size) }
406
+ }
407
+ }
408
+ });
409
+ const sink = [];
410
+ collectGeminiImages(payload, sink);
411
+ if (sink.length === 0)
412
+ collectChatImages(payload, sink);
413
+ return materializeImages(sink, signal);
414
+ }
415
+ async function generateChatImage({ provider, model, args, runtime, apiKey, signal, references }) {
416
+ const prompt = args.prompt.trim();
417
+ const content = references === undefined ? prompt : [
418
+ { type: "text", text: prompt },
419
+ ...references.map((url) => ({ type: "image_url", image_url: { url } }))
420
+ ];
421
+ const payload = await postJson(joinEndpoint(provider.baseUrl, "/chat/completions"), {
422
+ apiKey,
423
+ signal,
424
+ body: { model, messages: [{ role: "user", content }], max_tokens: 4096 }
425
+ });
426
+ const sink = [];
427
+ collectChatImages(payload, sink);
428
+ collectOpenAiImages(payload, sink);
429
+ collectGeminiImages(payload, sink);
430
+ return materializeImages(sink, signal);
431
+ }
432
+ var GENERATORS = {
433
+ "openai-images": generateOpenAiImages,
434
+ "xai-images": generateXaiImages,
435
+ "gemini-image": generateGeminiImage,
436
+ "openai-chat-image": generateChatImage
437
+ };
438
+ async function resolveApiKey(ctx, apiKeyEnv, signal) {
439
+ if (signal?.aborted === true)
440
+ throw abortError(signal);
441
+ if (typeof apiKeyEnv !== "string" || apiKeyEnv.length === 0) {
442
+ throw new Error("image_generate: the selected provider has no API key reference. Open Settings → Image generation and save one.");
443
+ }
444
+ const credentials = ctx.get("credentials");
445
+ if (credentials === undefined) {
446
+ throw new Error(`image_generate: the credentials service is unavailable; cannot read "${apiKeyEnv}"`);
447
+ }
448
+ const resolved = await credentials.resolve(credentialRef(apiKeyEnv));
449
+ if (resolved !== undefined && resolved.value.length > 0)
450
+ return resolved.value;
451
+ throw new Error(`image_generate: no API key is stored for "${apiKeyEnv}". Open Settings → Image generation and save one.`);
452
+ }
453
+ async function resolveReferenceImages(refs, attachments, signal) {
454
+ if (refs === undefined)
455
+ return;
456
+ if (!Array.isArray(refs) || refs.length < 1 || refs.length > 5) {
457
+ throw new Error("image_generate: referenceImages must contain 1–5 complete image references; omit it only for a new image");
458
+ }
459
+ if (attachments === undefined)
460
+ throw new Error("image_generate: editing requires the DSH attachment service");
461
+ const seen = new Set;
462
+ const urls = [];
463
+ for (const ref of refs) {
464
+ signal?.throwIfAborted?.();
465
+ if (ref === null || typeof ref !== "object" || typeof ref.attachmentId !== "string" || !IMAGE_MEDIA_TYPES.includes(ref.mediaType) || ![ref.bytes, ref.width, ref.height].every((value) => Number.isSafeInteger(value) && value > 0)) {
466
+ throw new Error("image_generate: invalid referenceImages entry; copy a complete image reference or call read_image first");
467
+ }
468
+ if (seen.has(ref.attachmentId))
469
+ throw new Error("image_generate: referenceImages contains the same image twice");
470
+ seen.add(ref.attachmentId);
471
+ const stored = await attachments.readImage(imageRefFromValue(ref), signal);
472
+ urls.push(`data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
473
+ }
474
+ return urls;
475
+ }
476
+ function imageRefFromValue(image) {
477
+ return {
478
+ attachmentId: AttachmentId(image.attachmentId),
479
+ mediaType: image.mediaType,
480
+ bytes: image.bytes,
481
+ width: image.width,
482
+ height: image.height,
483
+ ...image.name === undefined ? {} : { name: image.name },
484
+ ...image.originalDimensions === undefined ? {} : { originalDimensions: image.originalDimensions }
485
+ };
486
+ }
487
+ function imageGenerateText(value) {
488
+ const lines = [
489
+ `Saved ${value.paths.length} image${value.paths.length === 1 ? "" : "s"}:`,
490
+ ...value.paths.map((path) => `- ${path}`)
491
+ ];
492
+ if (value.images?.length) {
493
+ lines.push("", `Image references (for image_generate.referenceImages): ${JSON.stringify(value.images)}`);
494
+ }
495
+ return { type: "text", text: lines.join(`
496
+ `) };
497
+ }
498
+ function imageGenerateContent(value) {
499
+ return [
500
+ imageGenerateText(value),
501
+ ...(value.images ?? []).map((image) => ({ type: "image", attachment: imageRefFromValue(image) }))
502
+ ];
503
+ }
504
+ function truncate(text, max = 60) {
505
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
506
+ }
507
+ function findProvider(catalog, providerId) {
508
+ return (catalog.providers ?? []).find((row) => row.id === providerId);
509
+ }
510
+ function findModel(provider, modelId) {
511
+ return (provider.models ?? []).find((row) => row.id === modelId);
512
+ }
513
+ function createImageGenerateTool(ctx, currentCatalog, currentRuntime) {
514
+ return defineTool({
515
+ name: "image_generate",
516
+ description: "Generate an image with the model selected in Settings → Plugins → Plugin configuration → Image generation, " + "and save it under generate/image in the session workspace. The image is shown inline in the conversation. " + "Returns the saved file paths. To edit or use existing images as references, pass referenceImages copied from " + "the image reference text or structured tool results (read_image.image or image_generate.images). " + "For local files, call read_image first. Omit referenceImages only for a new image.",
517
+ parameters: {
518
+ referenceImages: {
519
+ type: "array",
520
+ description: "Optional 1–5 ordered complete DSH image references to edit or use as source images. Not file paths or URLs. Omit only for new images.",
521
+ items: {
522
+ type: "object",
523
+ additionalProperties: false,
524
+ properties: {
525
+ attachmentId: { type: "string", required: true },
526
+ mediaType: { type: "string", enum: IMAGE_MEDIA_TYPES, required: true },
527
+ bytes: { type: "integer", required: true },
528
+ width: { type: "integer", required: true },
529
+ height: { type: "integer", required: true },
530
+ name: { type: "string" },
531
+ originalDimensions: {
532
+ type: "object",
533
+ additionalProperties: false,
534
+ properties: {
535
+ width: { type: "integer", required: true },
536
+ height: { type: "integer", required: true }
537
+ }
538
+ }
539
+ }
540
+ }
541
+ },
542
+ prompt: { type: "string", required: true, description: "What the image should show." },
543
+ size: {
544
+ type: "string",
545
+ enum: ["1024x1024", "1024x1536", "1536x1024", "auto"],
546
+ description: "Image dimensions; omit for the configured default."
547
+ },
548
+ quality: {
549
+ type: "string",
550
+ enum: ["low", "medium", "high", "auto"],
551
+ description: "Rendering quality; omit for the configured default."
552
+ }
553
+ },
554
+ output: {
555
+ schema: {
556
+ type: "object",
557
+ additionalProperties: false,
558
+ properties: {
559
+ paths: { type: "array", items: { type: "string" }, required: true },
560
+ provider: { type: "string" },
561
+ model: { type: "string" },
562
+ format: { type: "string" },
563
+ images: {
564
+ type: "array",
565
+ items: {
566
+ type: "object",
567
+ additionalProperties: false,
568
+ properties: {
569
+ attachmentId: { type: "string", required: true },
570
+ mediaType: { type: "string", enum: IMAGE_MEDIA_TYPES, required: true },
571
+ bytes: { type: "integer", required: true },
572
+ width: { type: "integer", required: true },
573
+ height: { type: "integer", required: true },
574
+ name: { type: "string" }
575
+ }
576
+ }
577
+ }
578
+ }
579
+ },
580
+ render: (_args, value) => imageGenerateContent(value)
581
+ },
582
+ presentCall: (args) => ({
583
+ card: "generic",
584
+ title: `image_generate${args.referenceImages === undefined ? "" : ` (edit, ${args.referenceImages.length} image${args.referenceImages.length === 1 ? "" : "s"})`}: ${truncate(args.prompt)}`
585
+ }),
586
+ presentResult: (_args, result) => ({
587
+ card: "generic",
588
+ content: result.content.filter((block) => block.type === "text")
589
+ }),
590
+ async execute(args, exec) {
591
+ const prompt = String(args.prompt ?? "").trim();
592
+ if (prompt.length === 0)
593
+ throw new Error("image_generate: prompt must be a non-empty string");
594
+ const runtime = currentRuntime();
595
+ if (!runtime.enabled) {
596
+ throw new Error("image_generate is turned off. Enable it under Settings → Plugins → Plugin configuration → Image generation.");
597
+ }
598
+ if (!runtime.providerId || !runtime.modelId) {
599
+ throw new Error("image_generate: no image model is selected. Add a provider under Settings → Image generation, then choose a model under Settings → Plugins → Plugin configuration → Image generation.");
600
+ }
601
+ const catalog = currentCatalog();
602
+ const provider = findProvider(catalog, runtime.providerId);
603
+ if (provider === undefined) {
604
+ throw new Error(`image_generate: provider "${runtime.providerId}" no longer exists. Open Settings → Image generation and pick another one.`);
605
+ }
606
+ const model = findModel(provider, runtime.modelId);
607
+ if (model === undefined) {
608
+ throw new Error(`image_generate: model "${runtime.modelId}" is not listed on provider "${provider.name}". Edit Settings → Image generation.`);
609
+ }
610
+ if (!API_FORMATS.includes(provider.apiFormat)) {
611
+ throw new Error(`image_generate: unsupported API format "${provider.apiFormat}" on provider "${provider.name}".`);
612
+ }
613
+ assertHttpUrl(provider.baseUrl, `Base URL of provider "${provider.name}"`);
614
+ const attachments = ctx.get("attachments");
615
+ const references = await resolveReferenceImages(args.referenceImages, attachments, exec.signal);
616
+ const apiKey = await resolveApiKey(ctx, provider.apiKeyEnv, exec.signal);
617
+ const images = await GENERATORS[provider.apiFormat]({
618
+ provider,
619
+ model: model.id,
620
+ args: { ...args, prompt },
621
+ runtime,
622
+ apiKey,
623
+ signal: exec.signal,
624
+ references
625
+ });
626
+ const directory = outputDirectory(exec.agent?.session.header.cwd);
627
+ await mkdir(directory, { recursive: true });
628
+ const paths = [];
629
+ const mediaTypes = [];
630
+ for (const [index, image] of images.entries()) {
631
+ const mediaType = image.mediaType ?? sniffImageMediaType(image.data);
632
+ const fileName = imageFileName(index, mediaType);
633
+ await writeFile(join(directory, fileName), image.data);
634
+ paths.push(join("generate", "image", fileName));
635
+ mediaTypes.push(mediaType);
636
+ }
637
+ const refs = [];
638
+ if (attachments !== undefined) {
639
+ for (const [index, image] of images.entries()) {
640
+ try {
641
+ const ref = await attachments.saveImage({
642
+ data: image.data,
643
+ mediaType: mediaTypes[index],
644
+ name: basename(paths[index])
645
+ });
646
+ refs.push({
647
+ attachmentId: ref.attachmentId,
648
+ mediaType: ref.mediaType,
649
+ bytes: ref.bytes,
650
+ width: ref.width,
651
+ height: ref.height,
652
+ ...ref.name === undefined ? {} : { name: ref.name }
653
+ });
654
+ } catch (error) {
655
+ ctx.logger?.warn?.(`dsh-image-generation: could not attach ${paths[index]}: ${error instanceof Error ? error.message : String(error)}`);
656
+ }
657
+ }
658
+ }
659
+ return {
660
+ paths,
661
+ provider: provider.id,
662
+ model: model.id,
663
+ format: provider.apiFormat,
664
+ ...refs.length > 0 ? { images: refs } : {}
665
+ };
666
+ }
667
+ });
668
+ }
669
+ function ok(value) {
670
+ return { ok: true, value };
671
+ }
672
+ function failure(error) {
673
+ return {
674
+ ok: false,
675
+ error: {
676
+ code: error instanceof Error && error.name === "BadRequest" ? "bad-request" : "internal",
677
+ message: error instanceof Error ? error.message : String(error),
678
+ details: {}
679
+ }
680
+ };
681
+ }
682
+
683
+ class BadRequest extends Error {
684
+ constructor(message) {
685
+ super(message);
686
+ this.name = "BadRequest";
687
+ }
688
+ }
689
+ function registerRpc(ctx) {
690
+ ctx.inject(["connection"], (scoped) => {
691
+ const connection = scoped.get("connection");
692
+ if (connection === undefined)
693
+ return;
694
+ scoped.effect(() => connection.rpc.handle(RPC_CHANNEL, async (endpoint, payload, signal) => {
695
+ try {
696
+ if (payload === null || typeof payload !== "object")
697
+ throw new BadRequest("payload must be an object");
698
+ if (endpoint === "image") {
699
+ const attachments = ctx.get("attachments");
700
+ if (attachments === undefined)
701
+ throw new Error("the attachment service is not mounted; image bytes are unavailable");
702
+ const stored = await attachments.readImage(imageRefFromValue(payload), signal);
703
+ return ok({ mediaType: stored.ref.mediaType, dataBase64: Buffer.from(stored.data).toString("base64") });
704
+ }
705
+ if (endpoint === "file") {
706
+ const cwd = typeof payload.cwd === "string" ? payload.cwd : "";
707
+ if (cwd.trim().length === 0)
708
+ throw new BadRequest("payload.cwd is required for a workspace file");
709
+ const absolute = resolveGeneratedImage(cwd, payload.path);
710
+ const data = await readFile(absolute, signal !== undefined ? { signal } : {});
711
+ return ok({ mediaType: sniffImageMediaType(data), dataBase64: data.toString("base64") });
712
+ }
713
+ throw new BadRequest(`unknown /image-gen endpoint "${endpoint}"`);
714
+ } catch (error) {
715
+ return failure(error);
716
+ }
717
+ }, { authority: "loopback" }), "dsh-image-generation: /image-gen rpc channel");
718
+ });
719
+ }
720
+ function apply(ctx, config) {
721
+ const readProviders = () => {
722
+ const value = unwrapVolatile(config?.providers);
723
+ return Array.isArray(value) ? value : [];
724
+ };
725
+ const readField = (key, fallback) => {
726
+ const value = unwrapVolatile(config?.[key]);
727
+ return value === undefined ? fallback : value;
728
+ };
729
+ let currentCatalog = () => ({ providers: readProviders() });
730
+ let currentRuntime = () => ({
731
+ enabled: readField("enabled", true),
732
+ providerId: readField("providerId", ""),
733
+ modelId: readField("modelId", ""),
734
+ defaultSize: readField("defaultSize", DEFAULT_SIZE),
735
+ defaultQuality: readField("defaultQuality", DEFAULT_QUALITY)
736
+ });
737
+ ctx.inject(["settings"], (settingsCtx) => {
738
+ if (typeof settingsCtx.settings?.installSection !== "function")
739
+ return;
740
+ settingsCtx.settings.installSection(ctx, CATALOG_NS, CatalogConfig, emptyCatalog(), {
741
+ setSource: (source) => {
742
+ currentCatalog = source;
743
+ },
744
+ onChange: () => {}
745
+ });
746
+ settingsCtx.settings.installSection(ctx, RUNTIME_NS, RuntimeConfig, emptyRuntime(), {
747
+ setSource: (source) => {
748
+ currentRuntime = source;
749
+ },
750
+ onChange: () => {}
751
+ });
752
+ });
753
+ ctx.inject(["systemPrompt"], (promptCtx) => {
754
+ promptCtx.systemPrompt.section({
755
+ name: "tool:image-gen",
756
+ order: 121,
757
+ text: "To create an image, call image_generate with a prompt and optional size/quality. " + "The model selected in Settings → Plugins → Plugin configuration → Image generation is used. " + "Files are saved under generate/image in the workspace and shown inline in the conversation. " + "Use read_image on a returned path if you need to inspect the file."
758
+ });
759
+ });
760
+ ctx.tools.register(createImageGenerateTool(ctx, () => currentCatalog(), () => currentRuntime()));
761
+ registerRpc(ctx);
762
+ }
763
+ export {
764
+ API_FORMATS,
765
+ CATALOG_NS,
766
+ CatalogConfig,
767
+ Config,
768
+ RPC_CHANNEL,
769
+ RUNTIME_NS,
770
+ RuntimeConfig,
771
+ apiKeyEnvFor,
772
+ apply,
773
+ emptyCatalog,
774
+ emptyRuntime,
775
+ name,
776
+ slugifyProviderId,
777
+ sniffImageMediaType
778
+ };