@ai-agent-forge/plugin-image-generation 0.88.28 → 0.88.29
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/PLUGIN.md +20 -0
- package/README.md +29 -23
- package/agent-forge.json +1 -1
- package/dist/capability.d.ts +4 -4
- package/dist/capability.d.ts.map +1 -1
- package/dist/capability.js +127 -180
- package/dist/capability.js.map +1 -1
- package/dist/images-client.d.ts.map +1 -1
- package/dist/images-client.js +3 -1
- package/dist/images-client.js.map +1 -1
- package/dist/types.d.ts +14 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +4 -4
- package/plugin.json +2 -3
- package/MANUAL.md +0 -15
package/dist/capability.js
CHANGED
|
@@ -3,7 +3,7 @@ import { join, sep } from "node:path";
|
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
import { wrapFetchWithEnvProxyV1 } from "./env-proxy-fetch.js";
|
|
5
5
|
import { createImagesClientV1 } from "./images-client.js";
|
|
6
|
-
import { boundedImageMessageV1, detectImageFormatV1, IMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1, IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1, } from "./types.js";
|
|
6
|
+
import { boundedImageMessageV1, detectImageFormatV1, IMAGE_GENERATION_DOWNLOAD_TIMEOUT_MS_V1, IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1, IMAGE_GENERATION_MAX_MESSAGE_CHARS_V1, } from "./types.js";
|
|
7
7
|
const IMAGE_GENERATE_PARAMETERS = Type.Object({
|
|
8
8
|
prompt: Type.String({ minLength: 1, maxLength: 4000 }),
|
|
9
9
|
size: Type.Optional(Type.String({ minLength: 1, maxLength: 32 })),
|
|
@@ -16,6 +16,7 @@ const IMAGE_EDIT_PARAMETERS = Type.Object({
|
|
|
16
16
|
}, { additionalProperties: false });
|
|
17
17
|
const IMAGE_PATH_PATTERN_V1 = /^[A-Za-z0-9_][A-Za-z0-9._/-]*$/u;
|
|
18
18
|
const GENERATED_IMAGES_DIRECTORY = "generated-images";
|
|
19
|
+
const UNRECOGNIZED_IMAGE_REASON = "Provider response entries did not contain a recognized image payload or URL.";
|
|
19
20
|
function objectInput(first, second) {
|
|
20
21
|
// Shape-based dual-convention read (aligned with subagent-delegate): the
|
|
21
22
|
// runtime invoke face passes the input object first and the host
|
|
@@ -46,6 +47,17 @@ function failed(model, code, message) {
|
|
|
46
47
|
error: { code, message: boundedImageMessageV1(message) },
|
|
47
48
|
};
|
|
48
49
|
}
|
|
50
|
+
function emptyImageResponse(model, message = "Image provider returned no usable images", unrecognizedItems = 0) {
|
|
51
|
+
const reason = unrecognizedItems > 0
|
|
52
|
+
? `${message}; ${unrecognizedItems} unrecognized response item(s). ${UNRECOGNIZED_IMAGE_REASON}`
|
|
53
|
+
: message;
|
|
54
|
+
const result = failed(model, "image_response_empty", reason);
|
|
55
|
+
return {
|
|
56
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
57
|
+
details: result,
|
|
58
|
+
isError: true,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
49
61
|
function cancelled(model) {
|
|
50
62
|
return {
|
|
51
63
|
version: 1,
|
|
@@ -55,131 +67,9 @@ function cancelled(model) {
|
|
|
55
67
|
error: { code: "cancelled", message: "Image generation was cancelled" },
|
|
56
68
|
};
|
|
57
69
|
}
|
|
58
|
-
/** `param` (non-empty string), a non-empty env value, or undefined. */
|
|
59
|
-
function nonEmptyEnvValue(name) {
|
|
60
|
-
const value = process.env[name];
|
|
61
|
-
return typeof value === "string" && value.trim() !== "" ? value : undefined;
|
|
62
|
-
}
|
|
63
70
|
function boundedString(value, maxLength) {
|
|
64
71
|
return typeof value === "string" && value !== "" && value.length <= maxLength ? value : undefined;
|
|
65
72
|
}
|
|
66
|
-
function readInjectedSlot(config) {
|
|
67
|
-
const raw = config.imageGeneration;
|
|
68
|
-
if (raw === undefined)
|
|
69
|
-
return {};
|
|
70
|
-
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
|
71
|
-
return { error: "injected config imageGeneration must be an object" };
|
|
72
|
-
const record = raw;
|
|
73
|
-
if (typeof record.provider !== "string" || record.provider.trim() === "")
|
|
74
|
-
return {
|
|
75
|
-
error: `injected config imageGeneration.provider must be a non-empty string (got ${typeof record.provider})`,
|
|
76
|
-
};
|
|
77
|
-
if (record.model !== undefined && (typeof record.model !== "string" || record.model.trim() === ""))
|
|
78
|
-
return { error: "injected config imageGeneration.model must be a non-empty string when present" };
|
|
79
|
-
return { slot: { provider: record.provider, ...(record.model === undefined ? {} : { model: record.model }) } };
|
|
80
|
-
}
|
|
81
|
-
function readInjectedCatalog(config) {
|
|
82
|
-
const raw = config.imageModelCatalog;
|
|
83
|
-
if (raw === undefined)
|
|
84
|
-
return { catalog: {} };
|
|
85
|
-
if (typeof raw !== "object" || raw === null || Array.isArray(raw))
|
|
86
|
-
return {
|
|
87
|
-
catalog: {},
|
|
88
|
-
error: "injected config imageModelCatalog must be an object mapping providers to image models",
|
|
89
|
-
};
|
|
90
|
-
const catalog = {};
|
|
91
|
-
for (const [providerId, entries] of Object.entries(raw)) {
|
|
92
|
-
if (!Array.isArray(entries))
|
|
93
|
-
return { catalog: {}, error: `injected config imageModelCatalog["${providerId}"] must be an array` };
|
|
94
|
-
const models = [];
|
|
95
|
-
for (const entry of entries) {
|
|
96
|
-
if (typeof entry !== "object" || entry === null)
|
|
97
|
-
return { catalog: {}, error: `injected config imageModelCatalog["${providerId}"] entries must be objects` };
|
|
98
|
-
const record = entry;
|
|
99
|
-
if (typeof record.id !== "string" || record.id === "")
|
|
100
|
-
return {
|
|
101
|
-
catalog: {},
|
|
102
|
-
error: `injected config imageModelCatalog["${providerId}"] entries need a non-empty string id`,
|
|
103
|
-
};
|
|
104
|
-
models.push({ id: record.id, ...(typeof record.name === "string" ? { name: record.name } : {}) });
|
|
105
|
-
}
|
|
106
|
-
if (models.length > 0)
|
|
107
|
-
catalog[providerId] = models;
|
|
108
|
-
}
|
|
109
|
-
return { catalog };
|
|
110
|
-
}
|
|
111
|
-
/** 确定性排序键:name 优先(缺省回退 id),同键按 id;码点序,与宿主快照顺序无关。 */
|
|
112
|
-
function compareCatalogModels(left, right) {
|
|
113
|
-
const leftKey = left.name ?? left.id;
|
|
114
|
-
const rightKey = right.name ?? right.id;
|
|
115
|
-
if (leftKey !== rightKey)
|
|
116
|
-
return leftKey < rightKey ? -1 : 1;
|
|
117
|
-
return left.id < right.id ? -1 : left.id > right.id ? 1 : 0;
|
|
118
|
-
}
|
|
119
|
-
const IMAGE_GENERATION_CONFIG_EXAMPLE = 'Example settings.json: { "capabilities": { "imageGeneration": { "provider": "myimg", "model": "gpt-image-1" } } }';
|
|
120
|
-
/**
|
|
121
|
-
* 六层取值链(供应商能力槽位设计 §3.2):
|
|
122
|
-
* 1. 工具参数 provider/model;
|
|
123
|
-
* 2. settings 槽位(宿主注入的 config.imageGeneration,model 可省);
|
|
124
|
-
* 3. env AGENT_FORGE_IMAGEGEN_PROVIDER/MODEL(存量兼容);
|
|
125
|
-
* 4. 主供应商推断——会话当前 provider 在目录快照中登记过生图模型时取用;
|
|
126
|
-
* 5. 唯一候选推断——全配置域恰好一个 provider 登记过生图模型(且非当前主)时取用;
|
|
127
|
-
* 6. fail-closed——config_missing,多候选时列出候选清单。
|
|
128
|
-
* model 在 1-3 层均未命中时按已解析 provider 的登记生图模型推断(唯一命中直接
|
|
129
|
-
* 用;多命中确定性排序取第一个并注明来源)。
|
|
130
|
-
*/
|
|
131
|
-
function resolveImageTarget(input, slot, catalog, sessionProvider) {
|
|
132
|
-
const paramProvider = boundedString(input.provider, 64);
|
|
133
|
-
const paramModel = boundedString(input.model, 128);
|
|
134
|
-
const envProvider = nonEmptyEnvValue("AGENT_FORGE_IMAGEGEN_PROVIDER");
|
|
135
|
-
const envModel = nonEmptyEnvValue("AGENT_FORGE_IMAGEGEN_MODEL");
|
|
136
|
-
let provider = paramProvider ?? slot?.provider ?? envProvider;
|
|
137
|
-
if (provider === undefined) {
|
|
138
|
-
if (sessionProvider !== undefined && (catalog[sessionProvider]?.length ?? 0) > 0)
|
|
139
|
-
provider = sessionProvider;
|
|
140
|
-
else {
|
|
141
|
-
const candidates = Object.keys(catalog)
|
|
142
|
-
.filter((providerId) => catalog[providerId].length > 0)
|
|
143
|
-
.sort();
|
|
144
|
-
if (candidates.length === 1)
|
|
145
|
-
provider = candidates[0];
|
|
146
|
-
else if (candidates.length > 1)
|
|
147
|
-
return {
|
|
148
|
-
ok: false,
|
|
149
|
-
message: `Multiple image-generation providers are registered in models.json (${candidates.join(", ")}); image generation fails closed instead of guessing. ` +
|
|
150
|
-
`Configure capabilities.imageGeneration in settings.json or pass the provider parameter. ${IMAGE_GENERATION_CONFIG_EXAMPLE}`,
|
|
151
|
-
};
|
|
152
|
-
else
|
|
153
|
-
return {
|
|
154
|
-
ok: false,
|
|
155
|
-
message: "Image generation is not configured: pass provider and model via the tool parameters, set capabilities.imageGeneration in settings.json, " +
|
|
156
|
-
'set AGENT_FORGE_IMAGEGEN_PROVIDER and AGENT_FORGE_IMAGEGEN_MODEL, or register a model with "capabilities": ["generate_image"] for a provider in models.json. ' +
|
|
157
|
-
IMAGE_GENERATION_CONFIG_EXAMPLE,
|
|
158
|
-
};
|
|
159
|
-
}
|
|
160
|
-
}
|
|
161
|
-
let model = paramModel ?? slot?.model ?? envModel;
|
|
162
|
-
let modelSourceNote;
|
|
163
|
-
if (model === undefined) {
|
|
164
|
-
const registered = catalog[provider] ?? [];
|
|
165
|
-
if (registered.length === 1)
|
|
166
|
-
model = registered[0].id;
|
|
167
|
-
else if (registered.length > 1) {
|
|
168
|
-
const first = [...registered].sort(compareCatalogModels)[0];
|
|
169
|
-
model = first.id;
|
|
170
|
-
modelSourceNote =
|
|
171
|
-
`model ${first.id} was picked deterministically (first by name) from ${registered.length} image models registered for provider ${provider} in models.json; ` +
|
|
172
|
-
"pass an explicit model to choose another";
|
|
173
|
-
}
|
|
174
|
-
else
|
|
175
|
-
return {
|
|
176
|
-
ok: false,
|
|
177
|
-
message: `No image model is configured for provider ${provider}: no model came from the tool parameters, settings, or env, ` +
|
|
178
|
-
`and provider ${provider} has no models.json model with "capabilities": ["generate_image"]. Register one or pass an explicit model. ${IMAGE_GENERATION_CONFIG_EXAMPLE}`,
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
return { ok: true, provider, model, ...(modelSourceNote === undefined ? {} : { modelSourceNote }) };
|
|
182
|
-
}
|
|
183
73
|
function promptFrom(value) {
|
|
184
74
|
return boundedString(value, 4000);
|
|
185
75
|
}
|
|
@@ -226,8 +116,8 @@ function localStampV1(date) {
|
|
|
226
116
|
const pad = (value) => String(value).padStart(2, "0");
|
|
227
117
|
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
|
|
228
118
|
}
|
|
229
|
-
function successResult(result, images
|
|
230
|
-
if (result.status !== "succeeded")
|
|
119
|
+
function successResult(result, images) {
|
|
120
|
+
if (result.status !== "succeeded" && result.status !== "partial")
|
|
231
121
|
return result;
|
|
232
122
|
// Zero inlining (user decision, 2026-09-30): image payloads never ride
|
|
233
123
|
// the conversation — they would cost context on every later turn. The
|
|
@@ -240,9 +130,9 @@ function successResult(result, images, modelSourceNote) {
|
|
|
240
130
|
{
|
|
241
131
|
type: "text",
|
|
242
132
|
text: JSON.stringify({
|
|
133
|
+
...(result.status === "partial" ? { status: result.status, omitted: result.omitted } : {}),
|
|
243
134
|
files: result.files,
|
|
244
135
|
model: result.model,
|
|
245
|
-
...(modelSourceNote === undefined ? {} : { modelSource: modelSourceNote }),
|
|
246
136
|
...(result.usage === undefined ? {} : { usage: result.usage }),
|
|
247
137
|
note: "images are saved to disk only; read a file to view it",
|
|
248
138
|
}, null, 1),
|
|
@@ -254,7 +144,12 @@ function successResult(result, images, modelSourceNote) {
|
|
|
254
144
|
/** Write one image; the exclusive-create retry makes concurrent invocations (parallel tool groups) safe. */
|
|
255
145
|
async function writeImage(workspace, stamp, startSequence, produced) {
|
|
256
146
|
const directory = join(workspace, GENERATED_IMAGES_DIRECTORY);
|
|
257
|
-
|
|
147
|
+
try {
|
|
148
|
+
await mkdir(directory, { recursive: true });
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
return { ok: false, error };
|
|
152
|
+
}
|
|
258
153
|
// flag "wx" fails atomically when the name is taken (same-second stamp or
|
|
259
154
|
// a concurrent tool group) instead of racing existsSync-then-write, which
|
|
260
155
|
// silently overwrote one image with another under parallel execution.
|
|
@@ -263,14 +158,14 @@ async function writeImage(workspace, stamp, startSequence, produced) {
|
|
|
263
158
|
const name = `img-${stamp}-${sequence}.${produced.format.extension}`;
|
|
264
159
|
try {
|
|
265
160
|
await writeFile(join(directory, name), produced.bytes, { flag: "wx" });
|
|
266
|
-
return { relativePath: `${GENERATED_IMAGES_DIRECTORY}/${name}`, sequence };
|
|
161
|
+
return { ok: true, relativePath: `${GENERATED_IMAGES_DIRECTORY}/${name}`, sequence };
|
|
267
162
|
}
|
|
268
163
|
catch (error) {
|
|
269
|
-
if (error.code === "EEXIST") {
|
|
164
|
+
if (typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST") {
|
|
270
165
|
sequence += 1;
|
|
271
166
|
continue;
|
|
272
167
|
}
|
|
273
|
-
|
|
168
|
+
return { ok: false, error, attemptedPath: `${GENERATED_IMAGES_DIRECTORY}/${name}` };
|
|
274
169
|
}
|
|
275
170
|
}
|
|
276
171
|
}
|
|
@@ -282,11 +177,13 @@ async function persistImages(workspace, produced) {
|
|
|
282
177
|
let sequence = 1;
|
|
283
178
|
for (const image of produced) {
|
|
284
179
|
const written = await writeImage(workspace, stamp, sequence, image);
|
|
180
|
+
if (!written.ok)
|
|
181
|
+
return { ...written, files };
|
|
285
182
|
files.push(written.relativePath);
|
|
286
183
|
images.push(image);
|
|
287
184
|
sequence = written.sequence + 1;
|
|
288
185
|
}
|
|
289
|
-
return { files, images };
|
|
186
|
+
return { ok: true, files, images };
|
|
290
187
|
}
|
|
291
188
|
/** Inline b64 items pass through; url items are downloaded with the same fetch injection. */
|
|
292
189
|
async function collectImages(response, fetchImpl, signal) {
|
|
@@ -294,6 +191,8 @@ async function collectImages(response, fetchImpl, signal) {
|
|
|
294
191
|
for (const item of response.data) {
|
|
295
192
|
if (item.b64 !== undefined) {
|
|
296
193
|
const bytes = Buffer.from(item.b64, "base64");
|
|
194
|
+
if (bytes.length === 0)
|
|
195
|
+
return { code: "image_response_empty", message: "Image provider returned an empty image" };
|
|
297
196
|
images.push({ bytes, format: detectImageFormatV1(bytes) });
|
|
298
197
|
continue;
|
|
299
198
|
}
|
|
@@ -331,6 +230,8 @@ async function collectImages(response, fetchImpl, signal) {
|
|
|
331
230
|
message: `image download from the provider url failed with status ${download.status} (if this machine reaches the internet through a proxy, set HTTPS_PROXY/HTTP_PROXY — see the image-generation plugin README)`,
|
|
332
231
|
};
|
|
333
232
|
const bytes = Buffer.from(await download.arrayBuffer());
|
|
233
|
+
if (bytes.length === 0)
|
|
234
|
+
return { code: "image_response_empty", message: "Image provider returned an empty image" };
|
|
334
235
|
if (bytes.byteLength > IMAGE_GENERATION_MAX_DOWNLOAD_BYTES_V1)
|
|
335
236
|
return { code: "response_too_large", message: "downloaded image exceeds the 20 MiB response limit" };
|
|
336
237
|
images.push({ bytes, format: detectImageFormatV1(bytes) });
|
|
@@ -340,6 +241,46 @@ async function collectImages(response, fetchImpl, signal) {
|
|
|
340
241
|
function usageOf(response) {
|
|
341
242
|
return response.usage === undefined ? {} : { usage: response.usage };
|
|
342
243
|
}
|
|
244
|
+
function producedImageResult(files, model, response) {
|
|
245
|
+
const count = response.unrecognizedItems ?? 0;
|
|
246
|
+
return {
|
|
247
|
+
version: 1,
|
|
248
|
+
status: count > 0 ? "partial" : "succeeded",
|
|
249
|
+
files,
|
|
250
|
+
model,
|
|
251
|
+
...usageOf(response),
|
|
252
|
+
...(count > 0 ? { omitted: { count, reason: UNRECOGNIZED_IMAGE_REASON } } : {}),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function imageWriteFailure(model, response, result, signal) {
|
|
256
|
+
const message = result.error instanceof Error ? result.error.message : String(result.error);
|
|
257
|
+
const causeCode = typeof result.error === "object" &&
|
|
258
|
+
result.error !== null &&
|
|
259
|
+
"code" in result.error &&
|
|
260
|
+
typeof result.error.code === "string"
|
|
261
|
+
? result.error.code
|
|
262
|
+
: undefined;
|
|
263
|
+
const details = {
|
|
264
|
+
...producedImageResult(result.files, model, response),
|
|
265
|
+
status: signal?.aborted ? "cancelled" : result.files.length > 0 ? "partial" : "failed",
|
|
266
|
+
error: {
|
|
267
|
+
code: "image_write_failed",
|
|
268
|
+
message: boundedImageMessageV1(message),
|
|
269
|
+
...(causeCode === undefined ? {} : { causeCode }),
|
|
270
|
+
...(message.length > IMAGE_GENERATION_MAX_MESSAGE_CHARS_V1 ? { messageTruncated: true } : {}),
|
|
271
|
+
},
|
|
272
|
+
...(result.attemptedPath === undefined
|
|
273
|
+
? {}
|
|
274
|
+
: { attemptedFile: { path: result.attemptedPath, status: "unknown" } }),
|
|
275
|
+
};
|
|
276
|
+
const output = result.attemptedPath === undefined
|
|
277
|
+
? details
|
|
278
|
+
: {
|
|
279
|
+
...details,
|
|
280
|
+
note: "The attempted file may not exist, may be incomplete, or may have changed concurrently.",
|
|
281
|
+
};
|
|
282
|
+
return { content: [{ type: "text", text: JSON.stringify(output, null, 2) }], details, isError: true };
|
|
283
|
+
}
|
|
343
284
|
/** Resolve provider config/credentials/workspace; a miss returns the failed result directly. */
|
|
344
285
|
async function resolveInvocation(api, providerId, fetchImpl, model, baseUrlOverride) {
|
|
345
286
|
const workspace = api.host.workspaceDirectory;
|
|
@@ -366,10 +307,10 @@ function credentialsFailure(model, providerId) {
|
|
|
366
307
|
return failed(model, "credentials_unavailable", `Image generation credentials are unavailable for provider ${providerId}: the host must resolve apiKey and baseUrl for this provider (auth.json; store the key via /login)`);
|
|
367
308
|
}
|
|
368
309
|
/**
|
|
369
|
-
* Registers the
|
|
370
|
-
*
|
|
371
|
-
*
|
|
372
|
-
*
|
|
310
|
+
* Registers the `image_generate` and `image_edit` tools. The factory takes no
|
|
311
|
+
* credentials: provider auth (`apiKey` + `baseUrl`) is resolved at call time
|
|
312
|
+
* through the host's public `CredentialAPI`. The optional `fetchImpl` is a
|
|
313
|
+
* test seam only; production hosts use global fetch.
|
|
373
314
|
*/
|
|
374
315
|
export function createImageGenerationCapabilityFactoryV1(options) {
|
|
375
316
|
// Every outbound request (generation and url download alike) rides the
|
|
@@ -379,48 +320,40 @@ export function createImageGenerationCapabilityFactoryV1(options) {
|
|
|
379
320
|
// undici version and rejects this package's dispatchers.
|
|
380
321
|
const fetchImpl = wrapFetchWithEnvProxyV1(options?.fetchImpl);
|
|
381
322
|
return (api) => {
|
|
382
|
-
|
|
323
|
+
// The session selection is the only target source (D-134). Hosts without
|
|
324
|
+
// the capability-selection service cannot run image generation; keep the
|
|
325
|
+
// tools unregistered instead of shipping an unreachable fallback.
|
|
326
|
+
if (api.selection === undefined) {
|
|
327
|
+
api.logger?.debug("image-generation: host provides no capability-selection service; tools stay unregistered");
|
|
383
328
|
return;
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
return { ok: false, message: "No image-generation target is selected; use /model to choose one" };
|
|
396
|
-
}
|
|
397
|
-
if (!selected.available) {
|
|
398
|
-
return { ok: false, message: selected.error ?? "The selected image-generation target is unavailable" };
|
|
399
|
-
}
|
|
400
|
-
if (selected.adapter !== "openai-images") {
|
|
401
|
-
return {
|
|
402
|
-
ok: false,
|
|
403
|
-
message: `Image-generation adapter "${selected.adapter ?? "none"}" is not supported`,
|
|
404
|
-
};
|
|
405
|
-
}
|
|
329
|
+
}
|
|
330
|
+
const selection = api.selection;
|
|
331
|
+
const resolveTarget = () => {
|
|
332
|
+
const selected = selection.get("generate_image");
|
|
333
|
+
if (selected === undefined) {
|
|
334
|
+
return { ok: false, message: "No image-generation target is selected; use /model to choose one" };
|
|
335
|
+
}
|
|
336
|
+
if (!selected.available) {
|
|
337
|
+
return { ok: false, message: selected.error ?? "The selected image-generation target is unavailable" };
|
|
338
|
+
}
|
|
339
|
+
if (selected.adapter !== "openai-images") {
|
|
406
340
|
return {
|
|
407
|
-
ok:
|
|
408
|
-
|
|
409
|
-
model: selected.id,
|
|
410
|
-
...(selected.baseUrl === undefined ? {} : { baseUrl: selected.baseUrl }),
|
|
411
|
-
...(selected.options === undefined ? {} : { options: selected.options }),
|
|
341
|
+
ok: false,
|
|
342
|
+
message: `Image-generation adapter "${selected.adapter ?? "none"}" is not supported`,
|
|
412
343
|
};
|
|
413
344
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
345
|
+
return {
|
|
346
|
+
ok: true,
|
|
347
|
+
provider: selected.provider,
|
|
348
|
+
model: selected.id,
|
|
349
|
+
...(selected.baseUrl === undefined ? {} : { baseUrl: selected.baseUrl }),
|
|
350
|
+
...(selected.options === undefined ? {} : { options: selected.options }),
|
|
351
|
+
};
|
|
419
352
|
};
|
|
420
353
|
api.registerTool({
|
|
421
354
|
name: "image_generate",
|
|
422
355
|
label: "Image generate",
|
|
423
|
-
|
|
356
|
+
capability: { key: "generate_image", requiresSelection: true },
|
|
424
357
|
description: "Generate images from a prompt via the host-configured provider's OpenAI-compatible images API; saves image files (png/jpg/webp/gif as produced) under generated-images/ and returns their workspace-relative paths — images are never inlined into the conversation, read a returned file to view it",
|
|
425
358
|
parameters: IMAGE_GENERATE_PARAMETERS,
|
|
426
359
|
execute: async (first, second, third) => {
|
|
@@ -438,19 +371,19 @@ export function createImageGenerationCapabilityFactoryV1(options) {
|
|
|
438
371
|
const quality = boundedString(input.quality, 32);
|
|
439
372
|
if (input.n !== undefined && countFrom(input.n) === undefined)
|
|
440
373
|
return failed("", "invalid_input", "n must be an integer between 1 and 4");
|
|
441
|
-
const n = countFrom(input.n)
|
|
374
|
+
const n = countFrom(input.n);
|
|
442
375
|
const sessionSignal = api.sessionAbortSignal?.();
|
|
443
376
|
const invocationSignal = signalFrom(third);
|
|
444
377
|
const clientSignal = combineSignals([invocationSignal, sessionSignal]);
|
|
445
378
|
if (clientSignal?.aborted)
|
|
446
379
|
return cancelled("");
|
|
447
|
-
const target = resolveTarget(
|
|
380
|
+
const target = resolveTarget();
|
|
448
381
|
if (!target.ok)
|
|
449
382
|
return failed("", "config_missing", boundedImageMessageV1(target.message));
|
|
450
|
-
const { provider, model,
|
|
383
|
+
const { provider, model, baseUrl, options } = target;
|
|
451
384
|
const resolvedSize = size ?? boundedString(options?.size, 32);
|
|
452
385
|
const resolvedQuality = quality ?? boundedString(options?.quality, 32);
|
|
453
|
-
const resolvedCount = countFrom(options?.n) ??
|
|
386
|
+
const resolvedCount = n ?? countFrom(options?.n) ?? 1;
|
|
454
387
|
try {
|
|
455
388
|
const resolved = await resolveInvocation(api, provider, fetchImpl, model, baseUrl);
|
|
456
389
|
if (resolved.status === "failed")
|
|
@@ -463,10 +396,17 @@ export function createImageGenerationCapabilityFactoryV1(options) {
|
|
|
463
396
|
...(resolvedQuality === undefined ? {} : { quality: resolvedQuality }),
|
|
464
397
|
}, clientSignal);
|
|
465
398
|
const collected = await collectImages(response, fetchImpl, clientSignal);
|
|
466
|
-
if (!Array.isArray(collected))
|
|
399
|
+
if (!Array.isArray(collected)) {
|
|
400
|
+
if (collected.code === "image_response_empty")
|
|
401
|
+
return emptyImageResponse(model, collected.message, response.unrecognizedItems);
|
|
467
402
|
return failed(model, collected.code, collected.message);
|
|
403
|
+
}
|
|
404
|
+
if (collected.length === 0)
|
|
405
|
+
return emptyImageResponse(model, undefined, response.unrecognizedItems);
|
|
468
406
|
const persisted = await persistImages(resolved.workspace, collected);
|
|
469
|
-
|
|
407
|
+
if (!persisted.ok)
|
|
408
|
+
return imageWriteFailure(model, response, persisted, clientSignal);
|
|
409
|
+
return successResult(producedImageResult(persisted.files, model, response), persisted.images);
|
|
470
410
|
}
|
|
471
411
|
catch (error) {
|
|
472
412
|
return failureFrom(error, clientSignal, model, "Image generation request failed");
|
|
@@ -476,7 +416,7 @@ export function createImageGenerationCapabilityFactoryV1(options) {
|
|
|
476
416
|
api.registerTool({
|
|
477
417
|
name: "image_edit",
|
|
478
418
|
label: "Image edit",
|
|
479
|
-
|
|
419
|
+
capability: { key: "generate_image", requiresSelection: true },
|
|
480
420
|
description: "Edit a previously generated image (workspace-relative path under generated-images/) with a revision prompt; returns the new file path",
|
|
481
421
|
parameters: IMAGE_EDIT_PARAMETERS,
|
|
482
422
|
execute: async (first, second, third) => {
|
|
@@ -498,10 +438,10 @@ export function createImageGenerationCapabilityFactoryV1(options) {
|
|
|
498
438
|
const clientSignal = combineSignals([invocationSignal, sessionSignal]);
|
|
499
439
|
if (clientSignal?.aborted)
|
|
500
440
|
return cancelled("");
|
|
501
|
-
const target = resolveTarget(
|
|
441
|
+
const target = resolveTarget();
|
|
502
442
|
if (!target.ok)
|
|
503
443
|
return failed("", "config_missing", boundedImageMessageV1(target.message));
|
|
504
|
-
const { provider, model,
|
|
444
|
+
const { provider, model, baseUrl } = target;
|
|
505
445
|
try {
|
|
506
446
|
const resolved = await resolveInvocation(api, provider, fetchImpl, model, baseUrl);
|
|
507
447
|
if (resolved.status === "failed")
|
|
@@ -536,10 +476,17 @@ export function createImageGenerationCapabilityFactoryV1(options) {
|
|
|
536
476
|
model,
|
|
537
477
|
}, clientSignal);
|
|
538
478
|
const collected = await collectImages(response, fetchImpl, clientSignal);
|
|
539
|
-
if (!Array.isArray(collected))
|
|
479
|
+
if (!Array.isArray(collected)) {
|
|
480
|
+
if (collected.code === "image_response_empty")
|
|
481
|
+
return emptyImageResponse(model, collected.message, response.unrecognizedItems);
|
|
540
482
|
return failed(model, collected.code, collected.message);
|
|
483
|
+
}
|
|
484
|
+
if (collected.length === 0)
|
|
485
|
+
return emptyImageResponse(model, undefined, response.unrecognizedItems);
|
|
541
486
|
const persisted = await persistImages(resolved.workspace, collected);
|
|
542
|
-
|
|
487
|
+
if (!persisted.ok)
|
|
488
|
+
return imageWriteFailure(model, response, persisted, clientSignal);
|
|
489
|
+
return successResult(producedImageResult(persisted.files, model, response), persisted.images);
|
|
543
490
|
}
|
|
544
491
|
catch (error) {
|
|
545
492
|
return failureFrom(error, clientSignal, model, "Image edit request failed");
|