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