pi-openai-toolkit 0.7.2 → 0.8.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/README.md +32 -2
- package/README_zh.md +35 -2
- package/extensions/image-generation.ts +1 -0
- package/package.json +20 -4
- package/src/compact-client.ts +4 -51
- package/src/config.ts +31 -1
- package/src/image-generation/artifacts.ts +237 -0
- package/src/image-generation/client.ts +248 -0
- package/src/image-generation/eligibility.ts +18 -0
- package/src/image-generation/extension.ts +160 -0
- package/src/image-generation/protocol.ts +405 -0
- package/src/image-generation/references.ts +194 -0
- package/src/image-generation/render.ts +252 -0
- package/src/image-generation/service.ts +243 -0
- package/src/image-generation/types.ts +184 -0
- package/src/model-scope.ts +17 -0
- package/src/remote-v2-client.ts +7 -51
- package/src/responses-headers.ts +67 -0
- package/src/runtime.ts +43 -4
- package/src/types.ts +14 -0
- package/src/web-search/types.ts +3 -5
- package/tsconfig.check.json +12 -0
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
import {
|
|
2
|
+
IMAGE_GENERATION_MIME_TYPE,
|
|
3
|
+
IMAGE_GENERATION_MODEL,
|
|
4
|
+
IMAGE_GENERATION_QUALITIES,
|
|
5
|
+
IMAGE_GENERATION_SIZES,
|
|
6
|
+
MAX_GENERATED_IMAGE_BYTES,
|
|
7
|
+
MAX_IMAGE_DIAGNOSTIC_CHARS,
|
|
8
|
+
MAX_IMAGE_DIMENSION,
|
|
9
|
+
MAX_IMAGE_IDENTIFIER_CHARS,
|
|
10
|
+
MAX_IMAGE_PATH_CHARS,
|
|
11
|
+
MAX_IMAGE_PROMPT_CHARS,
|
|
12
|
+
MAX_REFERENCE_IMAGE_COUNT,
|
|
13
|
+
ImageGenerationError,
|
|
14
|
+
sanitizeImageDiagnostic,
|
|
15
|
+
type GenerateImageParams,
|
|
16
|
+
type NormalizedGenerateImageParams,
|
|
17
|
+
type ParsedGeneratedImage,
|
|
18
|
+
type PreparedReferenceImage,
|
|
19
|
+
type ReferenceImageMimeType,
|
|
20
|
+
} from "./types";
|
|
21
|
+
|
|
22
|
+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
23
|
+
const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
|
24
|
+
const DATA_URL_PATTERN = /^data:image\/[a-z0-9.+-]+;base64,(.*)$/is;
|
|
25
|
+
|
|
26
|
+
export type ImageGenerationRequestBody = {
|
|
27
|
+
model: string;
|
|
28
|
+
store: false;
|
|
29
|
+
stream: false;
|
|
30
|
+
parallel_tool_calls: false;
|
|
31
|
+
input: Array<{
|
|
32
|
+
role: "user";
|
|
33
|
+
content: Array<
|
|
34
|
+
| { type: "input_text"; text: string }
|
|
35
|
+
| { type: "input_image"; image_url: string; detail: "auto" }
|
|
36
|
+
>;
|
|
37
|
+
}>;
|
|
38
|
+
tools: Array<{
|
|
39
|
+
type: "image_generation";
|
|
40
|
+
model: typeof IMAGE_GENERATION_MODEL;
|
|
41
|
+
action: "generate" | "edit";
|
|
42
|
+
size: NormalizedGenerateImageParams["size"];
|
|
43
|
+
quality: NormalizedGenerateImageParams["quality"];
|
|
44
|
+
output_format: "png";
|
|
45
|
+
}>;
|
|
46
|
+
tool_choice: { type: "image_generation" };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type ParsedImageResponseResult =
|
|
50
|
+
| { ok: true; image: ParsedGeneratedImage }
|
|
51
|
+
| {
|
|
52
|
+
ok: false;
|
|
53
|
+
reason: "malformed-response" | "no-image" | "request-rejected" | "oversized-response";
|
|
54
|
+
errorMessage: string;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
58
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function normalizedOptionalString(value: unknown, maxChars: number): string | undefined {
|
|
62
|
+
if (typeof value !== "string") return undefined;
|
|
63
|
+
const trimmed = value.trim();
|
|
64
|
+
return trimmed ? trimmed.slice(0, maxChars) : undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function normalizePathList(value: unknown): string[] {
|
|
68
|
+
if (value === null || value === undefined) return [];
|
|
69
|
+
if (!Array.isArray(value)) {
|
|
70
|
+
throw new ImageGenerationError(
|
|
71
|
+
"invalid-parameters",
|
|
72
|
+
"referenceImagePaths must be an array of path strings or null.",
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const normalized: string[] = [];
|
|
77
|
+
for (const rawPath of value) {
|
|
78
|
+
if (typeof rawPath !== "string") {
|
|
79
|
+
throw new ImageGenerationError(
|
|
80
|
+
"invalid-parameters",
|
|
81
|
+
"referenceImagePaths must contain only path strings.",
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
const trimmed = rawPath.trim();
|
|
85
|
+
if (!trimmed) continue;
|
|
86
|
+
if (trimmed.length > MAX_IMAGE_PATH_CHARS) {
|
|
87
|
+
throw new ImageGenerationError(
|
|
88
|
+
"invalid-parameters",
|
|
89
|
+
`Each reference image path must be at most ${MAX_IMAGE_PATH_CHARS} characters.`,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
normalized.push(trimmed);
|
|
93
|
+
if (normalized.length > MAX_REFERENCE_IMAGE_COUNT) {
|
|
94
|
+
throw new ImageGenerationError(
|
|
95
|
+
"invalid-parameters",
|
|
96
|
+
`referenceImagePaths must contain at most ${MAX_REFERENCE_IMAGE_COUNT} paths.`,
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return normalized;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function normalizeOutputPath(value: unknown): string | undefined {
|
|
104
|
+
if (value === null || value === undefined) return undefined;
|
|
105
|
+
if (typeof value !== "string") {
|
|
106
|
+
throw new ImageGenerationError(
|
|
107
|
+
"invalid-parameters",
|
|
108
|
+
"outputPath must be a path string or null.",
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
const trimmed = value.trim();
|
|
112
|
+
if (!trimmed) return undefined;
|
|
113
|
+
if (trimmed.length > MAX_IMAGE_PATH_CHARS) {
|
|
114
|
+
throw new ImageGenerationError(
|
|
115
|
+
"invalid-parameters",
|
|
116
|
+
`outputPath must be at most ${MAX_IMAGE_PATH_CHARS} characters when provided.`,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
return trimmed;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function normalizeGenerateImageParams(
|
|
123
|
+
params: GenerateImageParams,
|
|
124
|
+
): NormalizedGenerateImageParams {
|
|
125
|
+
const prompt = typeof params.prompt === "string" ? params.prompt.trim() : "";
|
|
126
|
+
if (!prompt || prompt.length > MAX_IMAGE_PROMPT_CHARS) {
|
|
127
|
+
throw new ImageGenerationError(
|
|
128
|
+
"invalid-parameters",
|
|
129
|
+
`prompt must be 1-${MAX_IMAGE_PROMPT_CHARS} characters.`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const size = params.size ?? "auto";
|
|
134
|
+
if (!(IMAGE_GENERATION_SIZES as readonly string[]).includes(size)) {
|
|
135
|
+
throw new ImageGenerationError(
|
|
136
|
+
"invalid-parameters",
|
|
137
|
+
`Unsupported image size: ${String(size)}.`,
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const quality = params.quality ?? "auto";
|
|
142
|
+
if (!(IMAGE_GENERATION_QUALITIES as readonly string[]).includes(quality)) {
|
|
143
|
+
throw new ImageGenerationError(
|
|
144
|
+
"invalid-parameters",
|
|
145
|
+
`Unsupported image quality: ${String(quality)}.`,
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const referenceImagePaths = normalizePathList(params.referenceImagePaths);
|
|
150
|
+
const outputPath = normalizeOutputPath(params.outputPath);
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
prompt,
|
|
154
|
+
referenceImagePaths,
|
|
155
|
+
outputPath,
|
|
156
|
+
size,
|
|
157
|
+
quality,
|
|
158
|
+
action: referenceImagePaths.length > 0 ? "edit" : "generate",
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function buildImageGenerationRequest(args: {
|
|
163
|
+
routingModel: string;
|
|
164
|
+
params: NormalizedGenerateImageParams;
|
|
165
|
+
references: readonly PreparedReferenceImage[];
|
|
166
|
+
}): ImageGenerationRequestBody {
|
|
167
|
+
const content: ImageGenerationRequestBody["input"][number]["content"] = [
|
|
168
|
+
{ type: "input_text", text: args.params.prompt },
|
|
169
|
+
];
|
|
170
|
+
for (const reference of args.references) {
|
|
171
|
+
content.push({
|
|
172
|
+
type: "input_image",
|
|
173
|
+
image_url: `data:${reference.mimeType};base64,${reference.bytes.toString("base64")}`,
|
|
174
|
+
detail: "auto",
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return {
|
|
179
|
+
model: args.routingModel,
|
|
180
|
+
store: false,
|
|
181
|
+
stream: false,
|
|
182
|
+
parallel_tool_calls: false,
|
|
183
|
+
input: [{ role: "user", content }],
|
|
184
|
+
tools: [
|
|
185
|
+
{
|
|
186
|
+
type: "image_generation",
|
|
187
|
+
model: IMAGE_GENERATION_MODEL,
|
|
188
|
+
action: args.params.action,
|
|
189
|
+
size: args.params.size,
|
|
190
|
+
quality: args.params.quality,
|
|
191
|
+
output_format: "png",
|
|
192
|
+
},
|
|
193
|
+
],
|
|
194
|
+
tool_choice: { type: "image_generation" },
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function hasPngEndChunk(buffer: Buffer): boolean {
|
|
199
|
+
return (
|
|
200
|
+
buffer.length >= 33 &&
|
|
201
|
+
buffer.readUInt32BE(buffer.length - 12) === 0 &&
|
|
202
|
+
buffer.toString("ascii", buffer.length - 8, buffer.length - 4) === "IEND"
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function detectReferenceImageMimeType(bytes: Uint8Array): ReferenceImageMimeType | undefined {
|
|
207
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
208
|
+
if (readPngDimensions(buffer) && hasPngEndChunk(buffer)) return "image/png";
|
|
209
|
+
if (
|
|
210
|
+
buffer.length >= 4 &&
|
|
211
|
+
buffer[0] === 0xff &&
|
|
212
|
+
buffer[1] === 0xd8 &&
|
|
213
|
+
buffer[2] === 0xff &&
|
|
214
|
+
buffer.lastIndexOf(Buffer.from([0xff, 0xd9])) >= 3
|
|
215
|
+
) {
|
|
216
|
+
return "image/jpeg";
|
|
217
|
+
}
|
|
218
|
+
if (
|
|
219
|
+
buffer.length >= 20 &&
|
|
220
|
+
buffer.toString("ascii", 0, 4) === "RIFF" &&
|
|
221
|
+
buffer.toString("ascii", 8, 12) === "WEBP"
|
|
222
|
+
) {
|
|
223
|
+
const declaredSize = buffer.readUInt32LE(4) + 8;
|
|
224
|
+
const chunkType = buffer.toString("ascii", 12, 16);
|
|
225
|
+
const chunkSize = buffer.readUInt32LE(16);
|
|
226
|
+
const paddedChunkSize = chunkSize + (chunkSize % 2);
|
|
227
|
+
if (
|
|
228
|
+
declaredSize === buffer.length &&
|
|
229
|
+
(chunkType === "VP8 " || chunkType === "VP8L" || chunkType === "VP8X") &&
|
|
230
|
+
20 + paddedChunkSize <= buffer.length
|
|
231
|
+
) {
|
|
232
|
+
return "image/webp";
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
export function isValidPng(bytes: Uint8Array): boolean {
|
|
239
|
+
return bytes.byteLength >= PNG_SIGNATURE.length && Buffer.from(bytes).subarray(0, 8).equals(PNG_SIGNATURE);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
export function readPngDimensions(bytes: Uint8Array): { width: number; height: number } | undefined {
|
|
243
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
244
|
+
if (!isValidPng(buffer) || buffer.length < 24) return undefined;
|
|
245
|
+
if (buffer.readUInt32BE(8) !== 13 || buffer.toString("ascii", 12, 16) !== "IHDR") return undefined;
|
|
246
|
+
const width = buffer.readUInt32BE(16);
|
|
247
|
+
const height = buffer.readUInt32BE(20);
|
|
248
|
+
if (
|
|
249
|
+
width <= 0 ||
|
|
250
|
+
height <= 0 ||
|
|
251
|
+
width > MAX_IMAGE_DIMENSION ||
|
|
252
|
+
height > MAX_IMAGE_DIMENSION
|
|
253
|
+
) return undefined;
|
|
254
|
+
return { width, height };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function extractBase64(value: string): string {
|
|
258
|
+
const trimmed = value.trim();
|
|
259
|
+
const dataUrl = DATA_URL_PATTERN.exec(trimmed);
|
|
260
|
+
return (dataUrl?.[1] ?? trimmed).trim();
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function decodeGeneratedPng(value: string):
|
|
264
|
+
| { ok: true; bytes: Buffer; width: number; height: number }
|
|
265
|
+
| { ok: false; reason: "malformed-response" | "oversized-response"; errorMessage: string } {
|
|
266
|
+
const base64 = extractBase64(value);
|
|
267
|
+
const maxBase64Chars = Math.ceil(MAX_GENERATED_IMAGE_BYTES / 3) * 4;
|
|
268
|
+
if (base64.length > maxBase64Chars) {
|
|
269
|
+
return {
|
|
270
|
+
ok: false,
|
|
271
|
+
reason: "oversized-response",
|
|
272
|
+
errorMessage: "Image generation returned an image larger than the 32 MiB limit.",
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
if (!base64 || base64.length % 4 !== 0 || !BASE64_PATTERN.test(base64)) {
|
|
276
|
+
return {
|
|
277
|
+
ok: false,
|
|
278
|
+
reason: "malformed-response",
|
|
279
|
+
errorMessage: "Image generation returned invalid base64 image data.",
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const bytes = Buffer.from(base64, "base64");
|
|
284
|
+
if (
|
|
285
|
+
bytes.length === 0 ||
|
|
286
|
+
bytes.length > MAX_GENERATED_IMAGE_BYTES ||
|
|
287
|
+
bytes.toString("base64") !== base64
|
|
288
|
+
) {
|
|
289
|
+
bytes.fill(0);
|
|
290
|
+
return {
|
|
291
|
+
ok: false,
|
|
292
|
+
reason: bytes.length > MAX_GENERATED_IMAGE_BYTES ? "oversized-response" : "malformed-response",
|
|
293
|
+
errorMessage: "Image generation returned invalid or oversized image data.",
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
const dimensions = readPngDimensions(bytes);
|
|
297
|
+
if (!dimensions) {
|
|
298
|
+
bytes.fill(0);
|
|
299
|
+
return {
|
|
300
|
+
ok: false,
|
|
301
|
+
reason: "malformed-response",
|
|
302
|
+
errorMessage: "Image generation returned data that is not a valid PNG image.",
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
return { ok: true, bytes, ...dimensions };
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function extractProviderErrorMessage(value: unknown, fallback: string): string {
|
|
309
|
+
if (!isRecord(value)) return fallback;
|
|
310
|
+
const direct = normalizedOptionalString(value.message, MAX_IMAGE_DIAGNOSTIC_CHARS);
|
|
311
|
+
if (direct) return sanitizeImageDiagnostic(direct, fallback);
|
|
312
|
+
if (isRecord(value.error)) {
|
|
313
|
+
const nested = normalizedOptionalString(value.error.message, MAX_IMAGE_DIAGNOSTIC_CHARS);
|
|
314
|
+
if (nested) return sanitizeImageDiagnostic(nested, fallback);
|
|
315
|
+
}
|
|
316
|
+
return fallback;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
export function parseImageGenerationResponse(value: unknown): ParsedImageResponseResult {
|
|
320
|
+
if (!isRecord(value)) {
|
|
321
|
+
return {
|
|
322
|
+
ok: false,
|
|
323
|
+
reason: "malformed-response",
|
|
324
|
+
errorMessage: "Image generation returned a non-object response.",
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
if (value.status !== "completed") {
|
|
329
|
+
return {
|
|
330
|
+
ok: false,
|
|
331
|
+
reason: "request-rejected",
|
|
332
|
+
errorMessage: extractProviderErrorMessage(
|
|
333
|
+
value,
|
|
334
|
+
`Image generation did not complete (status: ${String(value.status ?? "unknown")}).`,
|
|
335
|
+
),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
if (!Array.isArray(value.output)) {
|
|
339
|
+
return {
|
|
340
|
+
ok: false,
|
|
341
|
+
reason: "malformed-response",
|
|
342
|
+
errorMessage: "Image generation response did not contain an output array.",
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const calls = new Map<string, { result: string; revisedPrompt?: string }>();
|
|
347
|
+
for (let index = 0; index < value.output.length; index += 1) {
|
|
348
|
+
const item = value.output[index];
|
|
349
|
+
if (!isRecord(item) || item.type !== "image_generation_call") continue;
|
|
350
|
+
if (item.status !== "completed") continue;
|
|
351
|
+
const result = typeof item.result === "string"
|
|
352
|
+
? item.result
|
|
353
|
+
: typeof item.b64_json === "string"
|
|
354
|
+
? item.b64_json
|
|
355
|
+
: undefined;
|
|
356
|
+
if (!result?.trim()) continue;
|
|
357
|
+
const id = normalizedOptionalString(item.id, MAX_IMAGE_IDENTIFIER_CHARS) ?? `image_generation_${index}`;
|
|
358
|
+
const revisedPrompt = normalizedOptionalString(item.revised_prompt, MAX_IMAGE_DIAGNOSTIC_CHARS);
|
|
359
|
+
const existing = calls.get(id);
|
|
360
|
+
if (existing && existing.result !== result) {
|
|
361
|
+
return {
|
|
362
|
+
ok: false,
|
|
363
|
+
reason: "malformed-response",
|
|
364
|
+
errorMessage: "Image generation returned conflicting results for one image call.",
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
calls.set(id, { result, revisedPrompt: revisedPrompt ?? existing?.revisedPrompt });
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (calls.size === 0) {
|
|
371
|
+
return {
|
|
372
|
+
ok: false,
|
|
373
|
+
reason: "no-image",
|
|
374
|
+
errorMessage: "Image generation completed without a usable image result.",
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
if (calls.size !== 1) {
|
|
378
|
+
return {
|
|
379
|
+
ok: false,
|
|
380
|
+
reason: "malformed-response",
|
|
381
|
+
errorMessage: "Image generation returned more than one image result for a single-image request.",
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const [imageCallId, call] = [...calls.entries()][0]!;
|
|
386
|
+
const decoded = decodeGeneratedPng(call.result);
|
|
387
|
+
if (!decoded.ok) return decoded;
|
|
388
|
+
|
|
389
|
+
return {
|
|
390
|
+
ok: true,
|
|
391
|
+
image: {
|
|
392
|
+
bytes: decoded.bytes,
|
|
393
|
+
imageCallId,
|
|
394
|
+
responseId: normalizedOptionalString(value.id, MAX_IMAGE_IDENTIFIER_CHARS),
|
|
395
|
+
revisedPrompt: call.revisedPrompt,
|
|
396
|
+
width: decoded.width,
|
|
397
|
+
height: decoded.height,
|
|
398
|
+
},
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export const _protocolTest = {
|
|
403
|
+
PNG_SIGNATURE,
|
|
404
|
+
IMAGE_GENERATION_MIME_TYPE,
|
|
405
|
+
};
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { open, realpath } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { detectReferenceImageMimeType } from "./protocol";
|
|
5
|
+
import {
|
|
6
|
+
MAX_REFERENCE_IMAGE_BYTES,
|
|
7
|
+
MAX_REFERENCE_IMAGE_COUNT,
|
|
8
|
+
MAX_TOTAL_REFERENCE_IMAGE_BYTES,
|
|
9
|
+
ImageGenerationError,
|
|
10
|
+
type PreparedReferenceImage,
|
|
11
|
+
} from "./types";
|
|
12
|
+
|
|
13
|
+
function throwIfAborted(signal: AbortSignal | undefined): void {
|
|
14
|
+
if (signal?.aborted) {
|
|
15
|
+
throw new ImageGenerationError("aborted", "Image generation was cancelled.");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function displayPath(filePath: string, cwd: string): string {
|
|
20
|
+
const rel = relative(cwd, filePath);
|
|
21
|
+
const value = rel && !rel.startsWith(`..${sep}`) && rel !== ".." ? rel : filePath;
|
|
22
|
+
return value.length > 240 ? `…${value.slice(-239)}` : value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function formatBytes(bytes: number): string {
|
|
26
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
27
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
|
|
28
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function clearPreparedReferences(references: readonly PreparedReferenceImage[]): void {
|
|
32
|
+
for (const reference of references) {
|
|
33
|
+
reference.bytes.fill(0);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function prepareReferenceImages(args: {
|
|
38
|
+
paths: readonly string[];
|
|
39
|
+
ctx: Pick<ExtensionContext, "cwd" | "hasUI" | "ui">;
|
|
40
|
+
signal?: AbortSignal;
|
|
41
|
+
}): Promise<PreparedReferenceImage[]> {
|
|
42
|
+
if (args.paths.length === 0) return [];
|
|
43
|
+
if (args.paths.length > MAX_REFERENCE_IMAGE_COUNT) {
|
|
44
|
+
throw new ImageGenerationError(
|
|
45
|
+
"reference-input-invalid",
|
|
46
|
+
`Too many reference images (maximum ${MAX_REFERENCE_IMAGE_COUNT}).`,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
if (!args.ctx.hasUI) {
|
|
50
|
+
throw new ImageGenerationError(
|
|
51
|
+
"reference-upload-approval-required",
|
|
52
|
+
"Reference-image upload requires interactive approval and is unavailable in headless mode.",
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const prepared: PreparedReferenceImage[] = [];
|
|
57
|
+
const seen = new Set<string>();
|
|
58
|
+
let totalBytes = 0;
|
|
59
|
+
try {
|
|
60
|
+
for (const rawPath of args.paths) {
|
|
61
|
+
throwIfAborted(args.signal);
|
|
62
|
+
const candidate = isAbsolute(rawPath) ? resolve(rawPath) : resolve(args.ctx.cwd, rawPath);
|
|
63
|
+
let resolvedPath: string;
|
|
64
|
+
try {
|
|
65
|
+
resolvedPath = await realpath(candidate);
|
|
66
|
+
} catch {
|
|
67
|
+
throw new ImageGenerationError(
|
|
68
|
+
"reference-input-invalid",
|
|
69
|
+
`Reference image does not exist or is not accessible: ${displayPath(candidate, args.ctx.cwd)}`,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
if (seen.has(resolvedPath)) continue;
|
|
73
|
+
|
|
74
|
+
const handle = await open(resolvedPath, "r").catch(() => undefined);
|
|
75
|
+
if (!handle) {
|
|
76
|
+
throw new ImageGenerationError(
|
|
77
|
+
"reference-input-invalid",
|
|
78
|
+
`Reference image does not exist or is not accessible: ${displayPath(resolvedPath, args.ctx.cwd)}`,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let bytes: Buffer | undefined;
|
|
83
|
+
let readCompleted = false;
|
|
84
|
+
try {
|
|
85
|
+
const info = await handle.stat();
|
|
86
|
+
if (!info.isFile()) {
|
|
87
|
+
throw new ImageGenerationError(
|
|
88
|
+
"reference-input-invalid",
|
|
89
|
+
`Reference image must be a regular file: ${displayPath(resolvedPath, args.ctx.cwd)}`,
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
if (info.size <= 0 || info.size > MAX_REFERENCE_IMAGE_BYTES) {
|
|
93
|
+
throw new ImageGenerationError(
|
|
94
|
+
"reference-input-invalid",
|
|
95
|
+
`Reference image must be between 1 byte and 20 MiB: ${displayPath(resolvedPath, args.ctx.cwd)}`,
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
totalBytes += info.size;
|
|
99
|
+
if (totalBytes > MAX_TOTAL_REFERENCE_IMAGE_BYTES) {
|
|
100
|
+
throw new ImageGenerationError(
|
|
101
|
+
"reference-input-invalid",
|
|
102
|
+
"Reference images exceed the 50 MiB total limit.",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
bytes = Buffer.alloc(info.size);
|
|
107
|
+
let offset = 0;
|
|
108
|
+
while (offset < bytes.length) {
|
|
109
|
+
if (args.signal?.aborted) {
|
|
110
|
+
bytes.fill(0);
|
|
111
|
+
throw new ImageGenerationError("aborted", "Image generation was cancelled.");
|
|
112
|
+
}
|
|
113
|
+
const { bytesRead } = await handle.read(
|
|
114
|
+
bytes,
|
|
115
|
+
offset,
|
|
116
|
+
bytes.length - offset,
|
|
117
|
+
offset,
|
|
118
|
+
);
|
|
119
|
+
if (bytesRead === 0) break;
|
|
120
|
+
offset += bytesRead;
|
|
121
|
+
}
|
|
122
|
+
const extra = Buffer.alloc(1);
|
|
123
|
+
const { bytesRead: extraBytesRead } = await handle.read(extra, 0, 1, info.size);
|
|
124
|
+
extra.fill(0);
|
|
125
|
+
if (offset !== info.size || extraBytesRead !== 0) {
|
|
126
|
+
bytes.fill(0);
|
|
127
|
+
throw new ImageGenerationError(
|
|
128
|
+
"reference-input-invalid",
|
|
129
|
+
`Reference image changed while being read: ${displayPath(resolvedPath, args.ctx.cwd)}`,
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
if (args.signal?.aborted) {
|
|
133
|
+
bytes.fill(0);
|
|
134
|
+
throw new ImageGenerationError("aborted", "Image generation was cancelled.");
|
|
135
|
+
}
|
|
136
|
+
readCompleted = true;
|
|
137
|
+
} finally {
|
|
138
|
+
if (!readCompleted) bytes?.fill(0);
|
|
139
|
+
await handle.close().catch(() => undefined);
|
|
140
|
+
}
|
|
141
|
+
if (!bytes) {
|
|
142
|
+
throw new ImageGenerationError(
|
|
143
|
+
"reference-input-invalid",
|
|
144
|
+
`Reference image could not be read: ${displayPath(resolvedPath, args.ctx.cwd)}`,
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const mimeType = detectReferenceImageMimeType(bytes);
|
|
149
|
+
if (!mimeType) {
|
|
150
|
+
bytes.fill(0);
|
|
151
|
+
throw new ImageGenerationError(
|
|
152
|
+
"reference-input-invalid",
|
|
153
|
+
`Reference image must be PNG, JPEG, or WebP: ${displayPath(resolvedPath, args.ctx.cwd)}`,
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
seen.add(resolvedPath);
|
|
157
|
+
prepared.push({ path: resolvedPath, mimeType, bytes });
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (prepared.length === 0) {
|
|
161
|
+
throw new ImageGenerationError(
|
|
162
|
+
"reference-input-invalid",
|
|
163
|
+
"No unique readable reference images were provided.",
|
|
164
|
+
);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const lines = prepared.map(
|
|
168
|
+
(reference) =>
|
|
169
|
+
`• ${displayPath(reference.path, args.ctx.cwd)} (${formatBytes(reference.bytes.length)})`,
|
|
170
|
+
);
|
|
171
|
+
const approved = await args.ctx.ui.confirm(
|
|
172
|
+
"Upload reference images?",
|
|
173
|
+
[
|
|
174
|
+
"The following local files will be uploaded to the current model's configured gateway for image editing:",
|
|
175
|
+
"",
|
|
176
|
+
...lines,
|
|
177
|
+
"",
|
|
178
|
+
"Continue with this paid image request?",
|
|
179
|
+
].join("\n"),
|
|
180
|
+
{ signal: args.signal },
|
|
181
|
+
);
|
|
182
|
+
throwIfAborted(args.signal);
|
|
183
|
+
if (!approved) {
|
|
184
|
+
throw new ImageGenerationError(
|
|
185
|
+
"reference-upload-declined",
|
|
186
|
+
"Reference-image upload was declined.",
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
return prepared;
|
|
190
|
+
} catch (error) {
|
|
191
|
+
clearPreparedReferences(prepared);
|
|
192
|
+
throw error;
|
|
193
|
+
}
|
|
194
|
+
}
|