codex-copilot-dx 1.3.13 → 1.3.14

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.
Files changed (52) hide show
  1. package/README.md +2 -2
  2. package/bin/cli.mjs +5 -10
  3. package/docs/ARCHITECTURE.md +9 -6
  4. package/docs/REFERENCE.md +19 -35
  5. package/package.json +1 -1
  6. package/src/access-settings.mjs +2 -1
  7. package/src/adapter.mjs +14 -4
  8. package/src/claude-capability-config.mjs +2 -2
  9. package/src/claude-client-config.mjs +5 -3
  10. package/src/cli-command-spec.mjs +4 -11
  11. package/src/cli-image.mjs +24 -180
  12. package/src/cli-management.mjs +21 -6
  13. package/src/cli-options.mjs +1 -1
  14. package/src/cli-secret.mjs +39 -0
  15. package/src/cli-tools.mjs +1 -1
  16. package/src/client-integration.mjs +13 -12
  17. package/src/client-model-plan.mjs +3 -1
  18. package/src/config.mjs +9 -54
  19. package/src/connection-runtime.mjs +24 -3
  20. package/src/copilot-client.mjs +16 -1
  21. package/src/dashboard/connections.js +41 -10
  22. package/src/dashboard/console.js +6 -4
  23. package/src/dashboard/features.js +19 -29
  24. package/src/dashboard/index.html +3 -3
  25. package/src/dashboard/language.js +8 -7
  26. package/src/dashboard/ui.css +6 -0
  27. package/src/dashboard/ui.js +11 -2
  28. package/src/dashboard/usage.js +10 -5
  29. package/src/dashboard-api.mjs +2 -1
  30. package/src/doctor.mjs +4 -5
  31. package/src/image-models.mjs +20 -0
  32. package/src/image-retirement.mjs +33 -0
  33. package/src/image-setup.mjs +16 -105
  34. package/src/legacy-image-guidance.mjs +73 -0
  35. package/src/live-models.mjs +2 -1
  36. package/src/native-images.mjs +111 -0
  37. package/src/observability.mjs +2 -0
  38. package/src/optional-routes.mjs +4 -13
  39. package/src/provider-metadata.mjs +5 -4
  40. package/src/provider-runtime.mjs +2 -1
  41. package/src/service-control.mjs +6 -7
  42. package/src/service-worker.mjs +2 -2
  43. package/src/image-mcp.mjs +0 -328
  44. package/src/image-provider-config.mjs +0 -194
  45. package/src/image-provider.mjs +0 -369
  46. package/src/image-readiness.mjs +0 -55
  47. package/src/image-references.mjs +0 -50
  48. package/src/image-skill/SKILL.md +0 -28
  49. package/src/image-skill/references/editing.md +0 -15
  50. package/src/image-skill/references/helper.md +0 -27
  51. package/src/image-skill.mjs +0 -142
  52. package/src/image-tool-client.mjs +0 -150
package/src/image-mcp.mjs DELETED
@@ -1,328 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { randomUUID } from "node:crypto";
5
- import { isIP } from "node:net";
6
- import { isLoopbackAddress, isLoopbackHostHeader } from "./security.mjs";
7
- import { generateImage, supportsImageEditing, IMAGE_MAX_BYTES } from "./image-provider.mjs";
8
- import { readImageProviderConfig } from "./image-provider-config.mjs";
9
- import { servicePreferences } from "./user-settings.mjs";
10
- import { createImageReferenceStore } from "./image-references.mjs";
11
-
12
- const MCP_PROTOCOL_VERSION = "2025-06-18";
13
- const MCP_PROTOCOL_VERSIONS = new Set(["2025-06-18", "2025-03-26", "2024-11-05"]);
14
- const MCP_MAX_BODY_BYTES = 256 * 1024;
15
- const IMAGE_TOOL_NAME = "generate_image";
16
- const EDIT_TOOL_NAME = "edit_image";
17
- const IMAGE_EXTENSIONS = new Map([["image/png", ".png"], ["image/jpeg", ".jpg"], ["image/webp", ".webp"]]);
18
-
19
- async function saveChatImage(image, directory, signal) {
20
- const extension = IMAGE_EXTENSIONS.get(image.mimeType);
21
- if (!extension || typeof image.data !== "string" || !image.data
22
- || image.data.length > 4 * Math.ceil(IMAGE_MAX_BYTES / 3)
23
- || !/^[A-Za-z0-9+/]+={0,2}$/.test(image.data)) throw new Error("Invalid image data for chat display");
24
- const bytes = Buffer.from(image.data, "base64");
25
- if (!bytes.length || bytes.length > IMAGE_MAX_BYTES || bytes.toString("base64") !== image.data) {
26
- throw new Error("Invalid image data for chat display");
27
- }
28
- signal.throwIfAborted();
29
- await fs.mkdir(directory, { recursive: true, mode: 0o700 });
30
- if (!(await fs.lstat(directory)).isDirectory()) throw new Error("Image output path is not a regular directory");
31
- const filePath = path.join(await fs.realpath(directory), `image-${randomUUID()}${extension}`);
32
- signal.throwIfAborted();
33
- const file = await fs.open(filePath, "wx", 0o600);
34
- try {
35
- await file.writeFile(bytes, { signal });
36
- signal.throwIfAborted();
37
- await file.close();
38
- } catch (error) {
39
- await file.close().catch(() => {});
40
- await fs.unlink(filePath).catch(() => {});
41
- throw error;
42
- }
43
- const displayPath = encodeURI(filePath.replaceAll("\\", "/"))
44
- .replace(/[?#()[\]]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
45
- return { filePath, markdown: `![Generated image](<${displayPath}>)` };
46
- }
47
-
48
- function sameHostSocket(socket) {
49
- const remote = String(socket?.remoteAddress || "").replace(/^::ffff:/, "");
50
- const local = String(socket?.localAddress || "").replace(/^::ffff:/, "");
51
- return remote && local && remote === local;
52
- }
53
-
54
- function canonicalIpHost(hostname) {
55
- const address = hostname.replace(/^\[|\]$/g, "");
56
- const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(address);
57
- if (!mapped) return address;
58
- const high = Number.parseInt(mapped[1], 16);
59
- const low = Number.parseInt(mapped[2], 16);
60
- return [high >> 8, high & 255, low >> 8, low & 255].join(".");
61
- }
62
-
63
- function ownHostHeader(host, socket, bindHostname) {
64
- if (isLoopbackHostHeader(host)) return true;
65
- if (typeof host !== "string" || !host || host.includes(",")) return false;
66
- try {
67
- const url = new URL(`http://${host}`);
68
- if (url.username || url.password || url.pathname !== "/" || url.search || url.hash) return false;
69
- if (bindHostname && url.hostname === bindHostname) return true;
70
- const local = String(socket?.localAddress || "");
71
- if (!isIP(local)) return false;
72
- return canonicalIpHost(url.hostname) === canonicalIpHost(new URL(`http://${isIP(local) === 6 ? `[${local}]` : local}`).hostname);
73
- } catch { return false; }
74
- }
75
-
76
- function writeJson(res, statusCode, body) {
77
- if (res.destroyed || res.writableEnded) return;
78
- res.writeHead(statusCode, {
79
- "Content-Type": "application/json",
80
- "Cache-Control": "no-store",
81
- });
82
- res.end(body === undefined ? undefined : JSON.stringify(body));
83
- }
84
-
85
- function jsonRpcError(id, code, message) {
86
- return { jsonrpc: "2.0", id: id ?? null, error: { code, message } };
87
- }
88
-
89
- async function readBody(req) {
90
- const chunks = [];
91
- let total = 0;
92
- for await (const chunk of req) {
93
- total += chunk.length;
94
- if (total > MCP_MAX_BODY_BYTES) throw Object.assign(new Error("MCP request body is too large"), { statusCode: 413 });
95
- chunks.push(chunk);
96
- }
97
- try { return JSON.parse(Buffer.concat(chunks, total).toString("utf8")); }
98
- catch { throw Object.assign(new Error("Invalid JSON"), { parseError: true }); }
99
- }
100
-
101
- function imageTool() {
102
- return {
103
- name: IMAGE_TOOL_NAME,
104
- title: "Generate image",
105
- description: "Generate a raster image with the user's enabled CCDX provider. Input: text prompt and optional size; no source images. Returns image content, saved-image Markdown for the final chat reply, and an edit ID when supported. For changes to an earlier CCDX image use edit_image; for redisplay reuse its Markdown without a tool call.",
106
- inputSchema: {
107
- type: "object",
108
- properties: {
109
- prompt: { type: "string", description: "A detailed, standalone description of the image to generate." },
110
- size: {
111
- type: "string",
112
- enum: ["1024x1024", "1536x1024", "1024x1536"],
113
- default: "1024x1024",
114
- description: "Output dimensions: square, landscape, or portrait.",
115
- },
116
- },
117
- required: ["prompt"],
118
- additionalProperties: false,
119
- },
120
- annotations: {
121
- readOnlyHint: false,
122
- destructiveHint: false,
123
- idempotentHint: false,
124
- openWorldHint: true,
125
- },
126
- };
127
- }
128
-
129
- function editTool() {
130
- const tool = imageTool();
131
- return {
132
- ...tool,
133
- name: EDIT_TOOL_NAME,
134
- title: "Edit image",
135
- description: "Edit a retained CCDX image using its exact image_id and a change prompt. Preserves the source and returns a new image, saved-image Markdown for the final chat reply, and a new edit ID when retained. Omit size to preserve source dimensions. Does not accept paths, URLs, masks, or arbitrary uploads. Redisplay requires no tool call.",
136
- inputSchema: {
137
- ...tool.inputSchema,
138
- properties: {
139
- image_id: { type: "string", description: "The image_id returned in the result of the specific CCDX image to edit." },
140
- prompt: { type: "string", description: "Describe the requested changes and what to preserve from the source image." },
141
- size: { type: "string", enum: [...tool.inputSchema.properties.size.enum], description: "Optional output dimensions; defaults to the source image's requested size." },
142
- },
143
- required: ["image_id", "prompt"],
144
- },
145
- };
146
- }
147
-
148
- function safeToolError(error, apiKey) {
149
- if (typeof error?.message === "string" && error.message) {
150
- let message = error.message.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ");
151
- if (apiKey) message = message.split(apiKey).join("[redacted]");
152
- return message.slice(0, 1000);
153
- }
154
- return "Image generation failed";
155
- }
156
-
157
- export function createImageMcpHandler({
158
- configLoader = () => readImageProviderConfig(),
159
- isEnabled = () => servicePreferences().image_enabled,
160
- generateImageFn = generateImage,
161
- maxConcurrent = 2,
162
- localHostname = "",
163
- imageReferences = createImageReferenceStore(),
164
- imageDirectory = path.join(os.homedir(), ".local", "share", "codex-copilot-dx", "images"),
165
- } = {}) {
166
- let bindHostname = "";
167
- if (localHostname && !isIP(localHostname.replace(/^\[|\]$/g, ""))) {
168
- try { bindHostname = new URL(`http://${localHostname}`).hostname; } catch {}
169
- }
170
- let active = 0;
171
- const metrics = { total: 0, succeeded: 0, failed: 0, busy: 0, cancelled: 0, delivery_failures: 0 };
172
- const handler = async function imageMcpHandler(req, res) {
173
- if (!isLoopbackAddress(req.socket?.remoteAddress) && !sameHostSocket(req.socket)) {
174
- writeJson(res, 403, jsonRpcError(null, -32001, "Image MCP is available only on this device"));
175
- return;
176
- }
177
- if (!ownHostHeader(req.headers?.host, req.socket, bindHostname)) {
178
- writeJson(res, 403, jsonRpcError(null, -32001, "Image MCP is available only on this device"));
179
- return;
180
- }
181
- if (req.method !== "POST") {
182
- res.setHeader?.("Allow", "POST");
183
- writeJson(res, 405, jsonRpcError(null, -32600, "Only POST is supported"));
184
- return;
185
- }
186
- // This endpoint serves native Codex/Node clients, not browser pages. A
187
- // loopback socket alone does not make a browser-supplied Origin trusted.
188
- if (Object.hasOwn(req.headers || {}, "origin")) {
189
- writeJson(res, 403, jsonRpcError(null, -32001, "Browser origins are not allowed for Image MCP"));
190
- return;
191
- }
192
- const mediaType = String(req.headers?.["content-type"] || "").split(";", 1)[0].trim().toLowerCase();
193
- if (mediaType !== "application/json") {
194
- writeJson(res, 415, jsonRpcError(null, -32600, "Image MCP requires application/json"));
195
- return;
196
- }
197
-
198
- let request;
199
- try { request = await readBody(req); }
200
- catch (error) {
201
- writeJson(res, error.statusCode || 400, jsonRpcError(null, error.parseError ? -32700 : -32600, error.message));
202
- return;
203
- }
204
- if (!request || typeof request !== "object" || Array.isArray(request) || request.jsonrpc !== "2.0" || typeof request.method !== "string") {
205
- writeJson(res, 400, jsonRpcError(request?.id, -32600, "Invalid JSON-RPC request"));
206
- return;
207
- }
208
- if (request.id === undefined) {
209
- writeJson(res, 202);
210
- return;
211
- }
212
- const reply = (result) => writeJson(res, 200, { jsonrpc: "2.0", id: request.id, result });
213
- if (request.method === "initialize") {
214
- const requestedVersion = String(request.params?.protocolVersion || "");
215
- const config = configLoader();
216
- if (!config) imageReferences.clear();
217
- reply({
218
- protocolVersion: MCP_PROTOCOL_VERSIONS.has(requestedVersion) ? requestedVersion : MCP_PROTOCOL_VERSION,
219
- capabilities: { tools: { listChanged: false } },
220
- serverInfo: { name: "ccdx-image", version: "1" },
221
- instructions: config && isEnabled()
222
- ? `CCDX handles the configured image API and credentials; no Python or SDK setup. Embed returned image Markdown in the final reply. Redisplay reuses it without tool calls. Keep each image_id with its own image. Do not automatically retry failed/timed-out requests or switch providers.${supportsImageEditing(config) ? " Use generate_image for new images; edit_image requires the exact retained source ID." : " Use generate_image for new images. Editing is unsupported; do not substitute generation."}`
223
- : config ? "Image calls are paused. Resume them in the CCDX WebUI; the provider and retained edit handles are preserved."
224
- : "Image generation is disabled. Enable it with ccdx app codex image setup before requesting images.",
225
- });
226
- return;
227
- }
228
- if (request.method === "ping") {
229
- reply({});
230
- return;
231
- }
232
- if (request.method === "tools/list") {
233
- const config = configLoader();
234
- if (!config) imageReferences.clear();
235
- reply({ tools: config && isEnabled() ? [imageTool(), ...(supportsImageEditing(config) ? [editTool()] : [])] : [] });
236
- return;
237
- }
238
- if (request.method !== "tools/call") {
239
- writeJson(res, 200, jsonRpcError(request.id, -32601, "Method not found"));
240
- return;
241
- }
242
- if (![IMAGE_TOOL_NAME, EDIT_TOOL_NAME].includes(request.params?.name)) {
243
- writeJson(res, 200, jsonRpcError(request.id, -32602, "Unknown image tool"));
244
- return;
245
- }
246
- metrics.total += 1;
247
- const config = configLoader();
248
- if (!config || !isEnabled()) {
249
- metrics.failed += 1;
250
- if (!config) imageReferences.clear();
251
- reply({ content: [{ type: "text", text: config ? "Image calls are paused. Resume them in the CCDX WebUI." : "Image generation is disabled. Run ccdx app codex image setup first." }], isError: true });
252
- return;
253
- }
254
- const editing = request.params.name === EDIT_TOOL_NAME;
255
- if (editing && !supportsImageEditing(config)) {
256
- metrics.failed += 1;
257
- reply({ content: [{ type: "text", text: "The configured image provider does not support CCDX editing. No edit was submitted." }], isError: true });
258
- return;
259
- }
260
- if (active >= maxConcurrent) {
261
- metrics.busy += 1;
262
- metrics.failed += 1;
263
- reply({ content: [{ type: "text", text: "Image generation is busy. Try again after the current request finishes." }], isError: true });
264
- return;
265
- }
266
- active += 1;
267
- const abort = new AbortController();
268
- const cancel = () => abort.abort(new Error("Image request was cancelled"));
269
- req.once?.("aborted", cancel);
270
- res.once?.("close", cancel);
271
- try {
272
- const args = request.params?.arguments || {};
273
- // Only an explicit retained handle can add source pixels to a request.
274
- const source = editing ? imageReferences.resolve(config, args.image_id) : null;
275
- const parameters = { prompt: args.prompt, size: args.size ?? source?.size ?? "1024x1024" };
276
- if (source) parameters.image = source.image;
277
- const image = await generateImageFn(config, parameters, { signal: abort.signal });
278
- abort.signal.throwIfAborted();
279
- let imageId = null;
280
- if (supportsImageEditing(config)) {
281
- try { imageId = imageReferences.remember(config, { ...image, size: parameters.size }); } catch {}
282
- }
283
- const note = imageId ? ` Image ID: ${imageId}. Use this ID for further edits while retained by this adapter.`
284
- : supportsImageEditing(config) ? " The image is available, but an editing reference could not be retained." : "";
285
- let saved;
286
- let delivery;
287
- // The bundled helper already saves once at its caller-selected output path.
288
- if (request.params?._meta?.["ccdx/client_saves_image"] === true) {
289
- delivery = "\nThe calling helper will save this image and return its local path. Embed the saved image in the final chat reply; do not generate or edit again just to display it.";
290
- } else {
291
- try {
292
- saved = await saveChatImage(image, imageDirectory, abort.signal);
293
- delivery = `\nInclude this image Markdown in your final chat reply to show its thumbnail:\n${saved.markdown}\nTo display this same image again, reuse this Markdown; do not call generate_image or edit_image.`;
294
- } catch {
295
- if (abort.signal.aborted) throw abort.signal.reason;
296
- metrics.delivery_failures += 1;
297
- delivery = "\nThe image was generated, but its chat-preview file could not be saved. Image content is still returned. Do not claim it was displayed, invent a file path, or generate/edit again to retry delivery.";
298
- }
299
- }
300
- abort.signal.throwIfAborted();
301
- reply({
302
- // Codex prioritizes structuredContent over image blocks. Keep IDs in metadata/text.
303
- ...(imageId || saved ? { _meta: { ...(imageId ? { "ccdx/image_id": imageId } : {}), ...(saved ? { "ccdx/image_path": saved.filePath } : {}) } } : {}),
304
- content: [
305
- { type: "image", data: image.data, mimeType: image.mimeType },
306
- { type: "text", text: `${editing ? "Edited" : "Generated"} ${image.width || ""}${image.width && image.height ? "×" : ""}${image.height || image.size} image with ${image.model}.${note}${delivery}` },
307
- ],
308
- });
309
- metrics.succeeded += 1;
310
- } catch (error) {
311
- if (abort.signal.aborted) metrics.cancelled += 1;
312
- else metrics.failed += 1;
313
- if (!res.destroyed && !res.writableEnded) {
314
- reply({ content: [{ type: "text", text: safeToolError(error, config.api_key) }], isError: true });
315
- }
316
- } finally {
317
- active -= 1;
318
- req.off?.("aborted", cancel);
319
- res.off?.("close", cancel);
320
- }
321
- };
322
- // Status never reads credentials, loads image guidance, or probes a provider.
323
- handler.stats = () => ({ ...metrics, active, max_concurrent: maxConcurrent });
324
- handler.exportState = () => { if (active) throw new Error("Image requests are active");return imageReferences.exportState(); };
325
- handler.importState = state => imageReferences.importState(state);
326
- handler.referenceBytes = () => imageReferences.stats().bytes;
327
- return handler;
328
- }
@@ -1,194 +0,0 @@
1
- import { readBoundedFileSync } from "./bounded-file.mjs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { atomicWriteFileSync } from "./atomic-file.mjs";
5
-
6
- export const IMAGE_PROVIDER_PROTOCOLS = new Set(["openai-images", "qwen-messages"]);
7
- export const IMAGE_PROVIDER_TIMEOUT_MS = 15_000;
8
-
9
- export function imageProviderConfigPath({ env = process.env, home = os.homedir() } = {}) {
10
- const xdgConfigHome = String(env.XDG_CONFIG_HOME || "").trim();
11
- const configRoot = xdgConfigHome || path.join(home, ".config");
12
- return path.join(configRoot, "codex-copilot-dx", "image-provider.json");
13
- }
14
-
15
- function invalidConfig(filePath, reason) {
16
- return new Error(`Invalid ccdx image provider at ${filePath}: ${reason}`);
17
- }
18
-
19
- export function normalizeImageEndpoint(value) {
20
- let url;
21
- try {
22
- url = new URL(String(value || "").trim());
23
- } catch {
24
- throw new Error("Image API base URL or endpoint must be a valid HTTPS URL");
25
- }
26
- if (url.protocol !== "https:"
27
- || !url.hostname
28
- || url.username
29
- || url.password
30
- || url.search
31
- || url.hash) {
32
- throw new Error("Image API base URL or endpoint must be an HTTPS URL without credentials, query, or fragment");
33
- }
34
- const pathname = url.pathname.replace(/\/+$/, "");
35
- if (pathname.endsWith("/images/generations")) return `${url.origin}${pathname}`;
36
- if (/\/(?:images(?:\/(?:edits|variations))?|chat\/completions|completions|responses|embeddings|models)$/i.test(pathname)) {
37
- throw new Error("Image API URL must be a base URL or an endpoint ending with /images/generations");
38
- }
39
- return `${url.origin}${pathname || "/v1"}/images/generations`;
40
- }
41
-
42
- export function imageModelsEndpoint(endpoint) {
43
- const normalized = normalizeImageEndpoint(endpoint);
44
- return normalized.replace(/\/images\/generations$/, "/models");
45
- }
46
-
47
- function checkedApiKey(value) {
48
- const key = String(value || "").trim();
49
- if (!key) throw new Error("Image API key is required");
50
- if (key.length > 8192 || /[\u0000-\u001f\u007f-\u009f]/.test(key)) throw new Error("Image API key is invalid");
51
- return key;
52
- }
53
-
54
- export function validateImageProviderConfig(value, { filePath = "image-provider.json" } = {}) {
55
- if (!value || typeof value !== "object" || Array.isArray(value)) {
56
- throw invalidConfig(filePath, "expected a JSON object");
57
- }
58
- let endpoint;
59
- let apiKey;
60
- try {
61
- endpoint = normalizeImageEndpoint(value.endpoint);
62
- apiKey = checkedApiKey(value.api_key);
63
- } catch (error) {
64
- throw invalidConfig(filePath, error.message);
65
- }
66
- const model = String(value.model || "").trim();
67
- if (!model || model.length > 256 || /[\u0000-\u001f\u007f-\u009f]/.test(model)) {
68
- throw invalidConfig(filePath, "model must be a non-empty string");
69
- }
70
- const protocol = String(value.protocol || "").trim();
71
- if (!IMAGE_PROVIDER_PROTOCOLS.has(protocol)) {
72
- throw invalidConfig(filePath, `protocol must be one of: ${[...IMAGE_PROVIDER_PROTOCOLS].join(", ")}`);
73
- }
74
- return { enabled: true, endpoint, api_key: apiKey, model, protocol };
75
- }
76
-
77
- export function readImageProviderConfig({ env = process.env, home = os.homedir(), strict = false } = {}) {
78
- const filePath = imageProviderConfigPath({ env, home });
79
- try {
80
- return validateImageProviderConfig(JSON.parse(readBoundedFileSync(filePath, { encoding: "utf8" })), { filePath });
81
- } catch (error) {
82
- if (error?.code === "ENOENT") return null;
83
- if (strict) {
84
- if (String(error?.message || "").startsWith("Invalid ccdx image provider")) throw error;
85
- throw invalidConfig(filePath, error?.message || String(error));
86
- }
87
- return null;
88
- }
89
- }
90
-
91
- export function writeImageProviderConfig(config, { env = process.env, home = os.homedir() } = {}) {
92
- const filePath = imageProviderConfigPath({ env, home });
93
- const normalized = validateImageProviderConfig(config, { filePath });
94
- atomicWriteFileSync(filePath, `${JSON.stringify(normalized, null, 2)}\n`, {
95
- mode: 0o600,
96
- preserveMode: false,
97
- });
98
- return { filePath, config: normalized };
99
- }
100
-
101
- async function limitedText(response, maxBytes = 1024 * 1024) {
102
- const declared = Number(response.headers?.get?.("content-length"));
103
- if (Number.isFinite(declared) && declared > maxBytes) throw new Error("Image API response was too large");
104
- if (!response.body?.getReader) {
105
- const text = await response.text();
106
- if (Buffer.byteLength(text) > maxBytes) throw new Error("Image API response was too large");
107
- return text;
108
- }
109
- const reader = response.body.getReader();
110
- const chunks = [];
111
- let total = 0;
112
- try {
113
- while (true) {
114
- const { done, value } = await reader.read();
115
- if (done) break;
116
- total += value.byteLength;
117
- if (total > maxBytes) {
118
- await reader.cancel().catch(() => {});
119
- throw new Error("Image API response was too large");
120
- }
121
- chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
122
- }
123
- } finally {
124
- reader.releaseLock();
125
- }
126
- return Buffer.concat(chunks, total).toString("utf8");
127
- }
128
-
129
- function errorMessage(value) {
130
- if (!value || typeof value !== "object") return "";
131
- return String(value.message || value.error?.message || value.error || value.reason || "");
132
- }
133
-
134
- function imageModelIds(body) {
135
- if (!body || !Array.isArray(body.data)) return [];
136
- const candidates = body.data
137
- .map((model) => ({
138
- id: String(model?.id || "").trim(),
139
- imageCapable: /image|dall[-_.]?e/i.test(String(model?.id || ""))
140
- || [model?.capabilities, model?.supported_generation_methods, model?.output_modalities]
141
- .flatMap((value) => Array.isArray(value) ? value : [])
142
- .some((value) => /image/i.test(String(value))),
143
- }))
144
- .filter(({ id }) => id
145
- && id.length <= 256
146
- && !/[\u0000-\u001f\u007f-\u009f]/.test(id));
147
- const imageIds = candidates.filter(({ imageCapable }) => imageCapable).map(({ id }) => id);
148
- return [...new Set(imageIds.length ? imageIds : candidates.length === 1 ? [candidates[0].id] : [])];
149
- }
150
-
151
- function detectProtocol(statusCode, body) {
152
- if (statusCode < 400) return null;
153
- const text = `${errorMessage(body)} ${JSON.stringify(body)}`.toLowerCase();
154
- if (text.includes("input.messages")) return "qwen-messages";
155
- if (/(?:field|required|missing|provide)[^\n]{0,80}\bprompt\b|\bprompt\b[^\n]{0,80}(?:required|missing)/i.test(text)) {
156
- return "openai-images";
157
- }
158
- return null;
159
- }
160
-
161
- async function fetchJson(url, init, { fetchImpl, timeoutMs }) {
162
- const response = await fetchImpl(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
163
- const text = await limitedText(response);
164
- let body;
165
- try { body = JSON.parse(text); } catch { throw new Error("Image API returned invalid JSON"); }
166
- return { response, body };
167
- }
168
-
169
- export async function inspectImageProvider({
170
- endpoint,
171
- apiKey,
172
- fetchImpl = fetch,
173
- timeoutMs = IMAGE_PROVIDER_TIMEOUT_MS,
174
- selectModel,
175
- } = {}) {
176
- const normalizedEndpoint = normalizeImageEndpoint(endpoint);
177
- const normalizedKey = checkedApiKey(apiKey);
178
- const headers = { Authorization: `Bearer ${normalizedKey}`, Accept: "application/json" };
179
- const models = await fetchJson(imageModelsEndpoint(normalizedEndpoint), { headers }, { fetchImpl, timeoutMs });
180
- if (!models.response.ok) throw new Error(`Image API model lookup failed with HTTP ${models.response.status}`);
181
- const modelIds = imageModelIds(models.body);
182
- if (!modelIds.length) throw new Error("Image API model lookup returned no image models");
183
- const model = selectModel ? await selectModel([...modelIds]) : modelIds[0];
184
- if (!modelIds.includes(model)) throw new Error("Selected image model is not in the provider catalog");
185
-
186
- const probe = await fetchJson(normalizedEndpoint, {
187
- method: "POST",
188
- headers: { ...headers, "Content-Type": "application/json" },
189
- body: JSON.stringify({ model }),
190
- }, { fetchImpl, timeoutMs });
191
- const protocol = detectProtocol(probe.response.status, probe.body);
192
- if (!protocol) throw new Error("Image API protocol is unsupported or could not be detected safely");
193
- return { endpoint: normalizedEndpoint, modelIds, protocol };
194
- }