@qzsy/dsh-image-generation 0.1.3 → 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 CHANGED
@@ -1,12 +1,11 @@
1
- // runtime/index.js
1
+ // src/index.ts
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
2
4
  import z from "@deepseek-ai/schemastery";
3
- import { credentialRef } from "@deepseek-ai/dsh-credentials";
4
5
  import { AttachmentId } from "@deepseek-ai/dsh-attachment";
6
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
5
7
  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"];
8
+ var name = "image-gen";
10
9
  var CATALOG_NS = "image-gen";
11
10
  var RUNTIME_NS = "image-gen-runtime";
12
11
  var RPC_CHANNEL = "/image-gen";
@@ -17,7 +16,8 @@ var API_FORMATS = Object.freeze([
17
16
  "openai-chat-image"
18
17
  ]);
19
18
  var IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
20
- var USER_AGENT = "dsh-image-generation/0.1.1";
19
+ var IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
20
+ var USER_AGENT = "@qzsy/dsh-image-generation/0.2.0";
21
21
  var DEFAULT_SIZE = "1024x1024";
22
22
  var DEFAULT_QUALITY = "auto";
23
23
  var SIZE_TO_ASPECT = {
@@ -85,35 +85,47 @@ function emptyRuntime() {
85
85
  defaultQuality: DEFAULT_QUALITY
86
86
  };
87
87
  }
88
- function slugifyProviderId(name2) {
89
- const slug = String(name2 ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
88
+ function slugifyProviderId(value) {
89
+ const slug = String(value ?? "").trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
90
90
  return slug || "provider";
91
91
  }
92
92
  function apiKeyEnvFor(providerId) {
93
- const body = String(providerId).toUpperCase().replace(/[^A-Z0-9]+/g, "_");
94
- return `IMAGE_GEN_${body}_API_KEY`;
93
+ return `IMAGE_GEN_${String(providerId).toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
95
94
  }
96
95
  function trimSlash(url) {
97
96
  return String(url ?? "").trim().replace(/\/+$/, "");
98
97
  }
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}`;
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}`;
106
118
  }
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;
119
+ function abortError(signal) {
120
+ const error = new Error("image_generate: cancelled");
121
+ error.name = "AbortError";
122
+ error.cause = signal?.reason;
123
+ return error;
112
124
  }
113
125
  function isAbortError(error) {
114
- return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
126
+ return error instanceof Error && error.name === "AbortError";
115
127
  }
116
- function errorOf(payload, status) {
128
+ function responseError(payload, status) {
117
129
  const detail = typeof payload?.error === "string" ? payload.error : payload?.error?.message ?? payload?.message ?? payload?.error?.status;
118
130
  return detail && String(detail).length > 0 ? String(detail) : `image API error (HTTP ${status})`;
119
131
  }
@@ -123,8 +135,8 @@ function sniffImageMediaType(data) {
123
135
  if (data.length >= 12 && data.toString("latin1", 0, 4) === "RIFF" && data.toString("latin1", 8, 12) === "WEBP") {
124
136
  return "image/webp";
125
137
  }
126
- const gifHeader = data.length >= 6 ? data.toString("latin1", 0, 6) : "";
127
- if (gifHeader === "GIF87a" || gifHeader === "GIF89a")
138
+ const gif = data.length >= 6 ? data.toString("latin1", 0, 6) : "";
139
+ if (gif === "GIF87a" || gif === "GIF89a")
128
140
  return "image/gif";
129
141
  return "image/png";
130
142
  }
@@ -136,123 +148,121 @@ var MEDIA_TYPE_EXTENSIONS = {
136
148
  };
137
149
  function imageFileName(index, mediaType) {
138
150
  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}`;
151
+ const extension = MEDIA_TYPE_EXTENSIONS[mediaType] ?? "png";
152
+ return `image-${stamp}-${Math.random().toString(36).slice(2, 8)}-${index}.${extension}`;
141
153
  }
142
- var IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg", ".webp", ".gif"]);
143
154
  function workspaceRoot(cwd) {
144
- return typeof cwd === "string" && cwd.trim() ? cwd.trim() : process.cwd();
155
+ return typeof cwd === "string" && cwd.trim().length > 0 ? cwd.trim() : process.cwd();
145
156
  }
146
157
  function outputDirectory(cwd) {
147
158
  return join(workspaceRoot(cwd), "generate", "image");
148
159
  }
149
- function isGeneratedImagePath(abs) {
150
- const parent = dirname(abs);
151
- return basename(parent) === "image" && basename(dirname(parent)) === "generate" && IMAGE_EXTENSIONS.has(extname(abs).toLowerCase());
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;
152
177
  }
153
178
  function decodeDataUrl(value) {
154
- const match = String(value).match(/^data:([^;,]+);base64,(.+)$/s);
179
+ const match = String(value ?? "").match(/^data:([^;,]+);base64,(.+)$/s);
155
180
  if (!match)
156
181
  return null;
157
- return { mime: match[1], data: Buffer.from(match[2], "base64") };
182
+ return { mediaType: match[1], data: Buffer.from(match[2], "base64") };
158
183
  }
159
- async function fetchToBuffer(url, signal) {
184
+ async function downloadImage(url, signal) {
160
185
  const response = await fetch(url, { redirect: "follow", signal });
161
186
  if (!response.ok)
162
- throw new Error(`image download failed (HTTP ${response.status})`);
187
+ throw new Error(`image_generate: image download failed (HTTP ${response.status})`);
163
188
  return Buffer.from(await response.arrayBuffer());
164
189
  }
165
- function pushImage(out, data, mime) {
190
+ function pushImage(sink, data, mediaType) {
166
191
  if (!data || data.length === 0)
167
192
  return;
168
- out.push({ data, mime: mime && IMAGE_MEDIA_TYPES.includes(mime) ? mime : sniffImageMediaType(data) });
193
+ const type = mediaType && IMAGE_MEDIA_TYPES.includes(mediaType) ? mediaType : sniffImageMediaType(data);
194
+ sink.push({ data, mediaType: type });
169
195
  }
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)
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")
174
208
  continue;
175
209
  if (typeof entry.b64_json === "string" && entry.b64_json.length > 0) {
176
- pushImage(out, Buffer.from(entry.b64_json, "base64"), "image/png");
210
+ pushImage(sink, Buffer.from(entry.b64_json, "base64"), "image/png");
177
211
  continue;
178
212
  }
179
- if (typeof entry.url === "string" && entry.url.length > 0) {
180
- out.push({ url: entry.url, mime: "image/png" });
181
- }
213
+ pushUrl(sink, entry.url, "image/png");
182
214
  }
183
215
  }
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) {
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 : []) {
191
219
  const inline = part?.inlineData ?? part?.inline_data;
192
220
  if (inline && typeof inline.data === "string" && inline.data.length > 0) {
193
- pushImage(out, Buffer.from(inline.data, "base64"), inline.mimeType ?? inline.mime_type);
221
+ pushImage(sink, Buffer.from(inline.data, "base64"), inline.mimeType ?? inline.mime_type);
194
222
  }
195
223
  }
196
224
  }
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);
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);
202
229
  }
203
230
  }
204
231
  }
205
- function collectChatImages(payload, out) {
206
- const choices = Array.isArray(payload?.choices) ? payload.choices : [];
207
- for (const choice of choices) {
232
+ function collectChatImages(payload, sink) {
233
+ for (const choice of Array.isArray(payload?.choices) ? payload.choices : []) {
208
234
  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" });
235
+ for (const image of Array.isArray(message.images) ? message.images : []) {
236
+ pushUrl(sink, image?.image_url?.url ?? image?.url);
219
237
  }
220
238
  const content = message.content;
221
239
  if (Array.isArray(content)) {
222
240
  for (const part of content) {
223
- const url = part?.image_url?.url ?? part?.inline_data?.data;
224
241
  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" });
242
+ pushUrl(sink, part.image_url.url);
230
243
  } else if (part?.inline_data?.data) {
231
- pushImage(out, Buffer.from(part.inline_data.data, "base64"), part.inline_data.mime_type);
244
+ pushImage(sink, Buffer.from(part.inline_data.data, "base64"), part.inline_data.mime_type);
232
245
  }
233
246
  }
234
- } else if (typeof content === "string") {
247
+ continue;
248
+ }
249
+ if (typeof content === "string") {
235
250
  const match = content.match(/data:(image\/[a-zA-Z0-9.+-]+);base64,([A-Za-z0-9+/=\s]+)/);
236
251
  if (match)
237
- pushImage(out, Buffer.from(match[2].replace(/\s+/g, ""), "base64"), match[1]);
252
+ pushImage(sink, Buffer.from(match[2].replace(/\s+/g, ""), "base64"), match[1]);
238
253
  }
239
254
  }
240
255
  }
241
- async function materializeImages(raw, signal) {
256
+ async function materializeImages(sink, signal) {
242
257
  const images = [];
243
- for (const item of raw) {
258
+ for (const item of sink) {
244
259
  if (item.data) {
245
- images.push({ data: item.data, mime: item.mime ?? sniffImageMediaType(item.data) });
260
+ images.push({ data: item.data, mediaType: item.mediaType ?? sniffImageMediaType(item.data) });
246
261
  continue;
247
262
  }
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) });
263
+ if (typeof item.url === "string") {
264
+ const data = await downloadImage(item.url, signal);
265
+ images.push({ data, mediaType: sniffImageMediaType(data) });
256
266
  }
257
267
  }
258
268
  if (images.length === 0)
@@ -264,11 +274,11 @@ async function readJson(response, signal) {
264
274
  return await response.json();
265
275
  } catch (error) {
266
276
  if (signal?.aborted === true || isAbortError(error))
267
- throw abortedError(signal, error);
277
+ throw abortError(signal);
268
278
  throw new Error(`image API returned an unprocessable response (HTTP ${response.status}): ${String(error)}`);
269
279
  }
270
280
  }
271
- async function postJson(url, { apiKey, body, signal, googleHost }) {
281
+ async function postJson(url, { apiKey, body, signal, googleHost = false }) {
272
282
  const headers = {
273
283
  "content-type": "application/json",
274
284
  accept: "application/json",
@@ -289,12 +299,12 @@ async function postJson(url, { apiKey, body, signal, googleHost }) {
289
299
  });
290
300
  } catch (error) {
291
301
  if (signal?.aborted === true || isAbortError(error))
292
- throw abortedError(signal, error);
293
- throw new Error(`image generation request failed: ${String(error)}`);
302
+ throw abortError(signal);
303
+ throw new Error(`image_generate: request failed: ${String(error)}`);
294
304
  }
295
305
  const payload = await readJson(response, signal);
296
306
  if (!response.ok)
297
- throw new Error(errorOf(payload, response.status));
307
+ throw new Error(responseError(payload, response.status));
298
308
  return payload;
299
309
  }
300
310
  function sizeOf(args, runtime) {
@@ -310,10 +320,10 @@ function geminiAspect(size) {
310
320
  function isImagenModel(model) {
311
321
  return /imagen/i.test(model);
312
322
  }
313
- function geminiUrl(baseUrl, model, verb) {
314
- const b = trimSlash(baseUrl);
323
+ function geminiEndpoint(baseUrl, model, verb) {
324
+ const base = trimSlash(baseUrl);
315
325
  const id = model.startsWith("models/") ? model.slice("models/".length) : model;
316
- return `${b}/models/${encodeURIComponent(id)}:${verb}`;
326
+ return `${base}/models/${encodeURIComponent(id)}:${verb}`;
317
327
  }
318
328
  async function generateOpenAiImages({ provider, model, args, runtime, apiKey, signal, references }) {
319
329
  const size = sizeOf(args, runtime);
@@ -335,12 +345,12 @@ async function generateOpenAiImages({ provider, model, args, runtime, apiKey, si
335
345
  } catch (error) {
336
346
  if (!/response_format/i.test(String(error?.message ?? error)))
337
347
  throw error;
338
- const { response_format: _omit, ...rest } = body;
348
+ const { response_format: _ignored, ...rest } = body;
339
349
  payload = await postJson(url, { apiKey, body: rest, signal });
340
350
  }
341
- const raw = [];
342
- collectOpenAiImages(payload, raw);
343
- return materializeImages(raw, signal);
351
+ const sink = [];
352
+ collectOpenAiImages(payload, sink);
353
+ return materializeImages(sink, signal);
344
354
  }
345
355
  async function generateXaiImages({ provider, model, args, runtime, apiKey, signal, references }) {
346
356
  const size = sizeOf(args, runtime);
@@ -353,45 +363,38 @@ async function generateXaiImages({ provider, model, args, runtime, apiKey, signa
353
363
  response_format: "b64_json",
354
364
  ...size === undefined ? {} : { aspect_ratio: SIZE_TO_ASPECT[size] ?? "1:1" },
355
365
  ...quality === undefined ? {} : { quality },
356
- ...editing ? references.length === 1 ? { image: { type: "image_url", url: references[0] } } : { images: references.map((url2) => ({ type: "image_url", url: url2 })) } : {}
366
+ ...editing ? references.length === 1 ? { image: { type: "image_url", url: references[0] } } : { images: references.map((url) => ({ type: "image_url", url })) } : {}
357
367
  };
358
368
  const payload = await postJson(url, { apiKey, body, signal });
359
- const raw = [];
360
- collectOpenAiImages(payload, raw);
361
- return materializeImages(raw, signal);
369
+ const sink = [];
370
+ collectOpenAiImages(payload, sink);
371
+ return materializeImages(sink, signal);
362
372
  }
363
373
  async function generateGeminiImage({ provider, model, args, runtime, apiKey, signal, references }) {
364
374
  const size = sizeOf(args, runtime);
365
375
  const googleHost = /generativelanguage\.googleapis\.com/i.test(provider.baseUrl);
376
+ const prompt = args.prompt.trim();
366
377
  if (isImagenModel(model)) {
367
- const url2 = geminiUrl(provider.baseUrl, model, "predict");
368
- const payload2 = await postJson(url2, {
378
+ const payload = await postJson(geminiEndpoint(provider.baseUrl, model, "predict"), {
369
379
  apiKey,
370
380
  googleHost,
371
381
  signal,
372
382
  body: {
373
- instances: [{ prompt: args.prompt.trim() }],
374
- parameters: {
375
- sampleCount: 1,
376
- aspectRatio: geminiAspect(size)
377
- }
383
+ instances: [{ prompt }],
384
+ parameters: { sampleCount: 1, aspectRatio: geminiAspect(size) }
378
385
  }
379
386
  });
380
- const raw2 = [];
381
- collectGeminiImages(payload2, raw2);
382
- return materializeImages(raw2, signal);
387
+ const sink = [];
388
+ collectGeminiImages(payload, sink);
389
+ return materializeImages(sink, signal);
383
390
  }
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
- }
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") } });
392
396
  }
393
- const url = geminiUrl(provider.baseUrl, model, "generateContent");
394
- const payload = await postJson(url, {
397
+ const payload = await postJson(geminiEndpoint(provider.baseUrl, model, "generateContent"), {
395
398
  apiKey,
396
399
  googleHost,
397
400
  signal,
@@ -403,36 +406,28 @@ async function generateGeminiImage({ provider, model, args, runtime, apiKey, sig
403
406
  }
404
407
  }
405
408
  });
406
- const raw = [];
407
- collectGeminiImages(payload, raw);
408
- if (raw.length === 0)
409
- collectChatImages(payload, raw);
410
- return materializeImages(raw, signal);
409
+ const sink = [];
410
+ collectGeminiImages(payload, sink);
411
+ if (sink.length === 0)
412
+ collectChatImages(payload, sink);
413
+ return materializeImages(sink, signal);
411
414
  }
412
415
  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, {
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"), {
423
422
  apiKey,
424
423
  signal,
425
- body: {
426
- model,
427
- messages: [{ role: "user", content }],
428
- max_tokens: 4096
429
- }
424
+ body: { model, messages: [{ role: "user", content }], max_tokens: 4096 }
430
425
  });
431
- const raw = [];
432
- collectChatImages(payload, raw);
433
- collectOpenAiImages(payload, raw);
434
- collectGeminiImages(payload, raw);
435
- return materializeImages(raw, signal);
426
+ const sink = [];
427
+ collectChatImages(payload, sink);
428
+ collectOpenAiImages(payload, sink);
429
+ collectGeminiImages(payload, sink);
430
+ return materializeImages(sink, signal);
436
431
  }
437
432
  var GENERATORS = {
438
433
  "openai-images": generateOpenAiImages,
@@ -442,23 +437,24 @@ var GENERATORS = {
442
437
  };
443
438
  async function resolveApiKey(ctx, apiKeyEnv, signal) {
444
439
  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 设置 → 生图配置");
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
+ }
448
444
  const credentials = ctx.get("credentials");
449
445
  if (credentials === undefined) {
450
- throw new Error(`image_generate: no credentials service; store the key for "${apiKeyEnv}"`);
446
+ throw new Error(`image_generate: the credentials service is unavailable; cannot read "${apiKeyEnv}"`);
451
447
  }
452
448
  const resolved = await credentials.resolve(credentialRef(apiKeyEnv));
453
449
  if (resolved !== undefined && resolved.value.length > 0)
454
450
  return resolved.value;
455
- throw new Error(`image_generate: no API key for "${apiKeyEnv}"; set it in 设置 → 生图配置`);
451
+ throw new Error(`image_generate: no API key is stored for "${apiKeyEnv}". Open Settings → Image generation and save one.`);
456
452
  }
457
453
  async function resolveReferenceImages(refs, attachments, signal) {
458
454
  if (refs === undefined)
459
455
  return;
460
456
  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");
457
+ throw new Error("image_generate: referenceImages must contain 1–5 complete image references; omit it only for a new image");
462
458
  }
463
459
  if (attachments === undefined)
464
460
  throw new Error("image_generate: editing requires the DSH attachment service");
@@ -470,7 +466,7 @@ async function resolveReferenceImages(refs, attachments, signal) {
470
466
  throw new Error("image_generate: invalid referenceImages entry; copy a complete image reference or call read_image first");
471
467
  }
472
468
  if (seen.has(ref.attachmentId))
473
- throw new Error("image_generate: referenceImages contains duplicate images");
469
+ throw new Error("image_generate: referenceImages contains the same image twice");
474
470
  seen.add(ref.attachmentId);
475
471
  const stored = await attachments.readImage(imageRefFromValue(ref), signal);
476
472
  urls.push(`data:${stored.ref.mediaType};base64,${Buffer.from(stored.data).toString("base64")}`);
@@ -489,12 +485,15 @@ function imageRefFromValue(image) {
489
485
  };
490
486
  }
491
487
  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 };
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
+ `) };
498
497
  }
499
498
  function imageGenerateContent(value) {
500
499
  return [
@@ -514,7 +513,7 @@ function findModel(provider, modelId) {
514
513
  function createImageGenerateTool(ctx, currentCatalog, currentRuntime) {
515
514
  return defineTool({
516
515
  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.",
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.",
518
517
  parameters: {
519
518
  referenceImages: {
520
519
  type: "array",
@@ -582,7 +581,7 @@ function createImageGenerateTool(ctx, currentCatalog, currentRuntime) {
582
581
  },
583
582
  presentCall: (args) => ({
584
583
  card: "generic",
585
- title: `image_generate${args.referenceImages === undefined ? "" : ` (edit, ${args.referenceImages.length} images)`}: ${truncate(args.prompt)}`
584
+ title: `image_generate${args.referenceImages === undefined ? "" : ` (edit, ${args.referenceImages.length} image${args.referenceImages.length === 1 ? "" : "s"})`}: ${truncate(args.prompt)}`
586
585
  }),
587
586
  presentResult: (_args, result) => ({
588
587
  card: "generic",
@@ -594,23 +593,24 @@ function createImageGenerateTool(ctx, currentCatalog, currentRuntime) {
594
593
  throw new Error("image_generate: prompt must be a non-empty string");
595
594
  const runtime = currentRuntime();
596
595
  if (!runtime.enabled) {
597
- throw new Error("image_generate: disabled in 设置 → 插件 → 插件配置 → 图形生成");
596
+ throw new Error("image_generate is turned off. Enable it under Settings → Plugins → Plugin configuration → Image generation.");
598
597
  }
599
598
  if (!runtime.providerId || !runtime.modelId) {
600
- throw new Error("image_generate: 尚未选择生图模型。请先在 设置 → 生图配置 添加供应商,再在 设置 → 插件 → 插件配置 → 图形生成 中选择一个模型");
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.");
601
600
  }
602
601
  const catalog = currentCatalog();
603
602
  const provider = findProvider(catalog, runtime.providerId);
604
603
  if (provider === undefined) {
605
- throw new Error(`image_generate: provider "${runtime.providerId}" is missing; reopen 设置 → 生图配置`);
604
+ throw new Error(`image_generate: provider "${runtime.providerId}" no longer exists. Open Settings → Image generation and pick another one.`);
606
605
  }
607
606
  const model = findModel(provider, runtime.modelId);
608
607
  if (model === undefined) {
609
- throw new Error(`image_generate: model "${runtime.modelId}" is not on provider "${provider.name}"; edit 设置 → 生图配置`);
608
+ throw new Error(`image_generate: model "${runtime.modelId}" is not listed on provider "${provider.name}". Edit Settings → Image generation.`);
610
609
  }
611
610
  if (!API_FORMATS.includes(provider.apiFormat)) {
612
- throw new Error(`image_generate: unknown API format "${provider.apiFormat}"`);
611
+ throw new Error(`image_generate: unsupported API format "${provider.apiFormat}" on provider "${provider.name}".`);
613
612
  }
613
+ assertHttpUrl(provider.baseUrl, `Base URL of provider "${provider.name}"`);
614
614
  const attachments = ctx.get("attachments");
615
615
  const references = await resolveReferenceImages(args.referenceImages, attachments, exec.signal);
616
616
  const apiKey = await resolveApiKey(ctx, provider.apiKeyEnv, exec.signal);
@@ -623,16 +623,15 @@ function createImageGenerateTool(ctx, currentCatalog, currentRuntime) {
623
623
  signal: exec.signal,
624
624
  references
625
625
  });
626
- const cwd = exec.agent?.session.header.cwd;
627
- const directory = outputDirectory(cwd);
626
+ const directory = outputDirectory(exec.agent?.session.header.cwd);
628
627
  await mkdir(directory, { recursive: true });
629
628
  const paths = [];
630
629
  const mediaTypes = [];
631
630
  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));
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));
636
635
  mediaTypes.push(mediaType);
637
636
  }
638
637
  const refs = [];
@@ -694,31 +693,22 @@ function registerRpc(ctx) {
694
693
  return;
695
694
  scoped.effect(() => connection.rpc.handle(RPC_CHANNEL, async (endpoint, payload, signal) => {
696
695
  try {
697
- if (typeof payload !== "object" || payload === null)
696
+ if (payload === null || typeof payload !== "object")
698
697
  throw new BadRequest("payload must be an object");
699
698
  if (endpoint === "image") {
700
699
  const attachments = ctx.get("attachments");
701
700
  if (attachments === undefined)
702
- throw new Error("no attachment service is mounted; generated-image bytes are unavailable");
701
+ throw new Error("the attachment service is not mounted; image bytes are unavailable");
703
702
  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
- });
703
+ return ok({ mediaType: stored.ref.mediaType, dataBase64: Buffer.from(stored.data).toString("base64") });
708
704
  }
709
705
  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
706
  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
- });
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") });
722
712
  }
723
713
  throw new BadRequest(`unknown /image-gen endpoint "${endpoint}"`);
724
714
  } catch (error) {
@@ -728,17 +718,21 @@ function registerRpc(ctx) {
728
718
  });
729
719
  }
730
720
  function apply(ctx, config) {
731
- const read = (key, fallback) => {
721
+ const readProviders = () => {
722
+ const value = unwrapVolatile(config?.providers);
723
+ return Array.isArray(value) ? value : [];
724
+ };
725
+ const readField = (key, fallback) => {
732
726
  const value = unwrapVolatile(config?.[key]);
733
727
  return value === undefined ? fallback : value;
734
728
  };
735
- let currentCatalog = () => ({ providers: Array.isArray(read("providers", [])) ? read("providers", []) : [] });
729
+ let currentCatalog = () => ({ providers: readProviders() });
736
730
  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)
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)
742
736
  });
743
737
  ctx.inject(["settings"], (settingsCtx) => {
744
738
  if (typeof settingsCtx.settings?.installSection !== "function")
@@ -760,7 +754,7 @@ function apply(ctx, config) {
760
754
  promptCtx.systemPrompt.section({
761
755
  name: "tool:image-gen",
762
756
  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."
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."
764
758
  });
765
759
  });
766
760
  ctx.tools.register(createImageGenerateTool(ctx, () => currentCatalog(), () => currentRuntime()));
@@ -778,7 +772,6 @@ export {
778
772
  apply,
779
773
  emptyCatalog,
780
774
  emptyRuntime,
781
- inject,
782
775
  name,
783
776
  slugifyProviderId,
784
777
  sniffImageMediaType