codex-copilot-dx 1.3.12 → 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.
- package/README.md +2 -2
- package/bin/cli.mjs +5 -10
- package/docs/ARCHITECTURE.md +11 -6
- package/docs/REFERENCE.md +21 -37
- package/package.json +1 -1
- package/src/access-settings.mjs +2 -1
- package/src/adapter.mjs +14 -4
- package/src/claude-capability-config.mjs +2 -2
- package/src/claude-client-config.mjs +5 -3
- package/src/cli-command-spec.mjs +4 -11
- package/src/cli-image.mjs +24 -180
- package/src/cli-management.mjs +21 -6
- package/src/cli-options.mjs +1 -1
- package/src/cli-secret.mjs +39 -0
- package/src/cli-tools.mjs +1 -1
- package/src/client-integration.mjs +13 -12
- package/src/client-model-plan.mjs +3 -1
- package/src/config.mjs +9 -54
- package/src/connection-runtime.mjs +24 -3
- package/src/copilot-client.mjs +16 -1
- package/src/dashboard/connections.js +41 -10
- package/src/dashboard/console.js +6 -4
- package/src/dashboard/features.js +19 -29
- package/src/dashboard/index.html +3 -3
- package/src/dashboard/language.js +8 -7
- package/src/dashboard/ui.css +6 -0
- package/src/dashboard/ui.js +11 -2
- package/src/dashboard/usage.js +10 -5
- package/src/dashboard-api.mjs +2 -1
- package/src/doctor.mjs +4 -5
- package/src/image-models.mjs +20 -0
- package/src/image-retirement.mjs +33 -0
- package/src/image-setup.mjs +16 -105
- package/src/legacy-image-guidance.mjs +73 -0
- package/src/live-models.mjs +2 -1
- package/src/native-images.mjs +111 -0
- package/src/observability.mjs +2 -0
- package/src/optional-routes.mjs +4 -13
- package/src/privacy-detection.mjs +2 -2
- package/src/privacy-model.mjs +3 -3
- package/src/provider-metadata.mjs +5 -4
- package/src/provider-runtime.mjs +2 -1
- package/src/service-control.mjs +6 -7
- package/src/service-worker.mjs +2 -2
- package/src/image-mcp.mjs +0 -328
- package/src/image-provider-config.mjs +0 -194
- package/src/image-provider.mjs +0 -369
- package/src/image-readiness.mjs +0 -55
- package/src/image-references.mjs +0 -50
- package/src/image-skill/SKILL.md +0 -28
- package/src/image-skill/references/editing.md +0 -15
- package/src/image-skill/references/helper.md +0 -27
- package/src/image-skill.mjs +0 -142
- package/src/image-tool-client.mjs +0 -150
package/src/image-provider.mjs
DELETED
|
@@ -1,369 +0,0 @@
|
|
|
1
|
-
import dns from "node:dns/promises";
|
|
2
|
-
import https from "node:https";
|
|
3
|
-
import net from "node:net";
|
|
4
|
-
|
|
5
|
-
export const IMAGE_MAX_BYTES = 32 * 1024 * 1024;
|
|
6
|
-
export const IMAGE_INPUT_MAX_BYTES = 10 * 1024 * 1024;
|
|
7
|
-
export const IMAGE_GENERATION_TIMEOUT_MS = 180_000;
|
|
8
|
-
export const IMAGE_DOWNLOAD_TIMEOUT_MS = 60_000;
|
|
9
|
-
export const IMAGE_SIZES = new Set(["1024x1024", "1536x1024", "1024x1536"]);
|
|
10
|
-
|
|
11
|
-
function providerError(message, code = "ccdx_image_provider_error") {
|
|
12
|
-
const error = new Error(message);
|
|
13
|
-
error.code = code;
|
|
14
|
-
return error;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function checkedPrompt(value) {
|
|
18
|
-
const prompt = String(value || "").trim();
|
|
19
|
-
if (!prompt) throw providerError("Image prompt is required", "ccdx_image_prompt_required");
|
|
20
|
-
if (prompt.length > 16_000) throw providerError("Image prompt exceeds 16000 characters", "ccdx_image_prompt_too_large");
|
|
21
|
-
return prompt;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function checkedSize(value) {
|
|
25
|
-
const size = String(value || "1024x1024").trim().toLowerCase();
|
|
26
|
-
if (!IMAGE_SIZES.has(size)) {
|
|
27
|
-
throw providerError(`Image size must be one of: ${[...IMAGE_SIZES].join(", ")}`, "ccdx_image_size_invalid");
|
|
28
|
-
}
|
|
29
|
-
return size;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function supportsImageEditing(config) {
|
|
33
|
-
return ["qwen-image-3.0-pro", "qwen-image-3.0"].includes(config?.model)
|
|
34
|
-
&& ["qwen-messages", "openai-images"].includes(config?.protocol);
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function checkedImage(config, value) {
|
|
38
|
-
if (value === undefined) return undefined;
|
|
39
|
-
if (!supportsImageEditing(config)) {
|
|
40
|
-
throw providerError("Image editing is not supported by the configured provider", "ccdx_image_edit_unsupported");
|
|
41
|
-
}
|
|
42
|
-
if (typeof value !== "string") {
|
|
43
|
-
throw providerError("Source image must be a PNG, JPEG, or WebP base64 data URI", "ccdx_image_input_invalid");
|
|
44
|
-
}
|
|
45
|
-
if (value.length > 4 * Math.ceil(IMAGE_INPUT_MAX_BYTES / 3) + 32) {
|
|
46
|
-
throw providerError("Source image exceeds the 10 MiB size limit", "ccdx_image_input_too_large");
|
|
47
|
-
}
|
|
48
|
-
const match = /^data:(image\/(?:png|jpeg|webp));base64,/.exec(value);
|
|
49
|
-
if (!match) {
|
|
50
|
-
throw providerError("Source image must be a PNG, JPEG, or WebP base64 data URI", "ccdx_image_input_invalid");
|
|
51
|
-
}
|
|
52
|
-
const encoded = value.slice(match[0].length);
|
|
53
|
-
if (encoded.length > 4 * Math.ceil(IMAGE_INPUT_MAX_BYTES / 3)) {
|
|
54
|
-
throw providerError("Source image exceeds the 10 MiB size limit", "ccdx_image_input_too_large");
|
|
55
|
-
}
|
|
56
|
-
if (!encoded || encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) {
|
|
57
|
-
throw providerError("Source image contains invalid base64 data", "ccdx_image_input_invalid");
|
|
58
|
-
}
|
|
59
|
-
const bytes = Buffer.from(encoded, "base64");
|
|
60
|
-
if (bytes.length > IMAGE_INPUT_MAX_BYTES) {
|
|
61
|
-
throw providerError("Source image exceeds the 10 MiB size limit", "ccdx_image_input_too_large");
|
|
62
|
-
}
|
|
63
|
-
if (bytes.toString("base64") !== encoded) {
|
|
64
|
-
throw providerError("Source image contains non-canonical base64 data", "ccdx_image_input_invalid");
|
|
65
|
-
}
|
|
66
|
-
let metadata;
|
|
67
|
-
try { metadata = imageMetadata(bytes); } catch {
|
|
68
|
-
throw providerError("Source image has an unsupported image format", "ccdx_image_input_invalid");
|
|
69
|
-
}
|
|
70
|
-
if (metadata.mimeType !== match[1]) {
|
|
71
|
-
throw providerError("Source image format does not match its data URI", "ccdx_image_input_invalid");
|
|
72
|
-
}
|
|
73
|
-
return value;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function decodeGeneratedImageDataUri(value, signal) {
|
|
77
|
-
if (signal?.aborted) throw providerError("Image generation timed out or was cancelled", "ccdx_image_timeout");
|
|
78
|
-
const maxEncodedLength = 4 * Math.ceil(IMAGE_MAX_BYTES / 3);
|
|
79
|
-
if (value.length > maxEncodedLength + 32) {
|
|
80
|
-
throw providerError("Generated image exceeds the size limit", "ccdx_image_too_large");
|
|
81
|
-
}
|
|
82
|
-
const match = /^data:(image\/(?:png|jpeg|webp));base64,/.exec(value);
|
|
83
|
-
if (!match) throw providerError("Image API returned an unsupported image data URI", "ccdx_image_format_unsupported");
|
|
84
|
-
const encoded = value.slice(match[0].length);
|
|
85
|
-
if (!encoded || encoded.length > maxEncodedLength || encoded.length % 4 !== 0
|
|
86
|
-
|| !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) {
|
|
87
|
-
throw providerError("Image API returned invalid image data", "ccdx_image_data_invalid");
|
|
88
|
-
}
|
|
89
|
-
const bytes = Buffer.from(encoded, "base64");
|
|
90
|
-
if (bytes.length > IMAGE_MAX_BYTES) throw providerError("Generated image exceeds the size limit", "ccdx_image_too_large");
|
|
91
|
-
if (bytes.toString("base64") !== encoded) throw providerError("Image API returned invalid image data", "ccdx_image_data_invalid");
|
|
92
|
-
if (imageMetadata(bytes).mimeType !== match[1]) {
|
|
93
|
-
throw providerError("Image API returned image data with a mismatched format", "ccdx_image_format_unsupported");
|
|
94
|
-
}
|
|
95
|
-
if (signal?.aborted) throw providerError("Image generation timed out or was cancelled", "ccdx_image_timeout");
|
|
96
|
-
return bytes;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
function generationBody(config, prompt, size, image) {
|
|
100
|
-
if (config.protocol === "qwen-messages") {
|
|
101
|
-
return {
|
|
102
|
-
model: config.model,
|
|
103
|
-
input: { messages: [{ role: "user", content: [...(image ? [{ image }] : []), { text: prompt }] }] },
|
|
104
|
-
parameters: { n: 1, size: size.replace("x", "*"), watermark: false },
|
|
105
|
-
};
|
|
106
|
-
}
|
|
107
|
-
return { model: config.model, prompt, n: 1, size, ...(image ? { image } : {}) };
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
async function boundedJson(response) {
|
|
111
|
-
const maxBytes = 48 * 1024 * 1024;
|
|
112
|
-
const declared = Number(response.headers?.get?.("content-length"));
|
|
113
|
-
if (Number.isFinite(declared) && declared > maxBytes) throw providerError("Image API response was too large");
|
|
114
|
-
const reader = response.body?.getReader?.();
|
|
115
|
-
let text;
|
|
116
|
-
if (!reader) {
|
|
117
|
-
text = await response.text();
|
|
118
|
-
if (Buffer.byteLength(text) > maxBytes) throw providerError("Image API response was too large");
|
|
119
|
-
} else {
|
|
120
|
-
const chunks = [];
|
|
121
|
-
let total = 0;
|
|
122
|
-
try {
|
|
123
|
-
while (true) {
|
|
124
|
-
const { done, value } = await reader.read();
|
|
125
|
-
if (done) break;
|
|
126
|
-
total += value.byteLength;
|
|
127
|
-
if (total > maxBytes) {
|
|
128
|
-
await reader.cancel().catch(() => {});
|
|
129
|
-
throw providerError("Image API response was too large");
|
|
130
|
-
}
|
|
131
|
-
chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
|
|
132
|
-
}
|
|
133
|
-
} finally {
|
|
134
|
-
reader.releaseLock();
|
|
135
|
-
}
|
|
136
|
-
text = Buffer.concat(chunks, total).toString("utf8");
|
|
137
|
-
}
|
|
138
|
-
try { return JSON.parse(text); } catch { throw providerError("Image API returned invalid JSON"); }
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
function upstreamMessage(body) {
|
|
142
|
-
return String(body?.message || body?.error?.message || body?.error || "")
|
|
143
|
-
.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ")
|
|
144
|
-
.trim()
|
|
145
|
-
.slice(0, 500);
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
function imageSource(body) {
|
|
149
|
-
const standard = body?.data?.[0];
|
|
150
|
-
if (typeof standard?.b64_json === "string" && standard.b64_json) {
|
|
151
|
-
return { type: "base64", value: standard.b64_json };
|
|
152
|
-
}
|
|
153
|
-
if (typeof standard?.url === "string" && standard.url) return { type: "url", value: standard.url };
|
|
154
|
-
const contents = body?.output?.choices?.[0]?.message?.content;
|
|
155
|
-
if (Array.isArray(contents)) {
|
|
156
|
-
const image = contents.find((part) => typeof part?.image === "string" && part.image);
|
|
157
|
-
if (image) return { type: "url", value: image.image };
|
|
158
|
-
}
|
|
159
|
-
return null;
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
function imageMetadata(bytes) {
|
|
163
|
-
if (bytes.length >= 24 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
|
|
164
|
-
return { mimeType: "image/png", width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
|
|
165
|
-
}
|
|
166
|
-
if (bytes.length >= 12 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") {
|
|
167
|
-
return { mimeType: "image/webp" };
|
|
168
|
-
}
|
|
169
|
-
if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
|
|
170
|
-
let offset = 2;
|
|
171
|
-
while (offset + 9 < bytes.length) {
|
|
172
|
-
if (bytes[offset] !== 0xff) { offset += 1; continue; }
|
|
173
|
-
const marker = bytes[offset + 1];
|
|
174
|
-
if (marker === 0xd8 || marker === 0xd9) { offset += 2; continue; }
|
|
175
|
-
const length = bytes.readUInt16BE(offset + 2);
|
|
176
|
-
if (length < 2 || offset + 2 + length > bytes.length) break;
|
|
177
|
-
if ([0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf].includes(marker)) {
|
|
178
|
-
return { mimeType: "image/jpeg", height: bytes.readUInt16BE(offset + 5), width: bytes.readUInt16BE(offset + 7) };
|
|
179
|
-
}
|
|
180
|
-
offset += 2 + length;
|
|
181
|
-
}
|
|
182
|
-
return { mimeType: "image/jpeg" };
|
|
183
|
-
}
|
|
184
|
-
throw providerError("Image API returned an unsupported image format", "ccdx_image_format_unsupported");
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
function ipv4Public(address) {
|
|
188
|
-
const parts = address.split(".").map(Number);
|
|
189
|
-
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return false;
|
|
190
|
-
const [a, b, c] = parts;
|
|
191
|
-
if (a === 0 || a === 10 || a === 127 || a >= 224) return false;
|
|
192
|
-
if (a === 100 && b >= 64 && b <= 127) return false;
|
|
193
|
-
if (a === 169 && b === 254) return false;
|
|
194
|
-
if (a === 172 && b >= 16 && b <= 31) return false;
|
|
195
|
-
if (a === 192 && (b === 168 || (b === 0 && [0, 2].includes(c)))) return false;
|
|
196
|
-
if (a === 198 && (b === 18 || b === 19 || (b === 51 && c === 100))) return false;
|
|
197
|
-
if (a === 203 && b === 0 && c === 113) return false;
|
|
198
|
-
return true;
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function publicAddress(address) {
|
|
202
|
-
const family = net.isIP(address);
|
|
203
|
-
if (family === 4) return ipv4Public(address);
|
|
204
|
-
if (family !== 6) return false;
|
|
205
|
-
let lower;
|
|
206
|
-
try { lower = new URL(`https://[${address}]/`).hostname.slice(1, -1); }
|
|
207
|
-
catch { return false; }
|
|
208
|
-
if (lower === "::" || lower === "::1" || lower.startsWith("fc") || lower.startsWith("fd")
|
|
209
|
-
|| /^fe[89ab]/.test(lower) || lower.startsWith("ff") || lower.startsWith("2001:db8:")) return false;
|
|
210
|
-
const mapped = /^::ffff:([a-f0-9]{1,4}):([a-f0-9]{1,4})$/.exec(lower)
|
|
211
|
-
|| /^64:ff9b::(?:([a-f0-9]{1,4}):)?([a-f0-9]{1,4})?$/.exec(lower);
|
|
212
|
-
if (!mapped) return true;
|
|
213
|
-
const high = Number.parseInt(mapped[1] || "0", 16);
|
|
214
|
-
const low = Number.parseInt(mapped[2] || "0", 16);
|
|
215
|
-
return ipv4Public([high >> 8, high & 255, low >> 8, low & 255].join("."));
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
export async function downloadPublicImage(urlValue, {
|
|
219
|
-
lookup = dns.lookup,
|
|
220
|
-
timeoutMs = IMAGE_DOWNLOAD_TIMEOUT_MS,
|
|
221
|
-
maxBytes = IMAGE_MAX_BYTES,
|
|
222
|
-
signal,
|
|
223
|
-
} = {}) {
|
|
224
|
-
let url;
|
|
225
|
-
try { url = new URL(urlValue); } catch { throw providerError("Image API returned an invalid image URL"); }
|
|
226
|
-
if (url.protocol !== "https:" || url.username || url.password) {
|
|
227
|
-
throw providerError("Image API returned an unsafe image URL", "ccdx_image_url_unsafe");
|
|
228
|
-
}
|
|
229
|
-
return new Promise((resolve, reject) => {
|
|
230
|
-
let settled = false;
|
|
231
|
-
let request;
|
|
232
|
-
const finish = (error, value) => {
|
|
233
|
-
if (settled) return;
|
|
234
|
-
settled = true;
|
|
235
|
-
clearTimeout(timer);
|
|
236
|
-
signal?.removeEventListener("abort", onAbort);
|
|
237
|
-
if (error) {
|
|
238
|
-
request?.destroy(error);
|
|
239
|
-
reject(error);
|
|
240
|
-
}
|
|
241
|
-
else resolve(value);
|
|
242
|
-
};
|
|
243
|
-
const timer = setTimeout(() => finish(providerError("Image download timed out", "ccdx_image_timeout")), timeoutMs);
|
|
244
|
-
timer.unref?.();
|
|
245
|
-
const onAbort = () => finish(signal.reason instanceof Error ? signal.reason : providerError("Image request was cancelled"));
|
|
246
|
-
if (signal?.aborted) { onAbort(); return; }
|
|
247
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
248
|
-
// DNS and transfer share one deadline; a late lookup cannot start a cancelled download.
|
|
249
|
-
const hostname = url.hostname.replace(/^\[|\]$/g, "");
|
|
250
|
-
Promise.resolve().then(() => settled ? undefined : lookup(hostname, { all: true, verbatim: true })).then((addresses) => {
|
|
251
|
-
if (settled) return;
|
|
252
|
-
if (!Array.isArray(addresses) || !addresses.length || addresses.some(({ address }) => !publicAddress(address))) {
|
|
253
|
-
finish(providerError("Image API returned a non-public image URL", "ccdx_image_url_unsafe"));
|
|
254
|
-
return;
|
|
255
|
-
}
|
|
256
|
-
request = https.get(url, {
|
|
257
|
-
headers: { Accept: "image/*,application/octet-stream;q=0.5" },
|
|
258
|
-
lookup: (_hostname, options, callback) => {
|
|
259
|
-
if (options?.all) callback(null, addresses);
|
|
260
|
-
else callback(null, addresses[0].address, addresses[0].family);
|
|
261
|
-
},
|
|
262
|
-
}, (response) => {
|
|
263
|
-
response.on("error", (error) => finish(error));
|
|
264
|
-
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
265
|
-
response.resume();
|
|
266
|
-
finish(providerError(`Image download failed with HTTP ${response.statusCode}`));
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
const declared = Number(response.headers["content-length"]);
|
|
270
|
-
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
271
|
-
response.destroy();
|
|
272
|
-
finish(providerError("Generated image exceeds the size limit", "ccdx_image_too_large"));
|
|
273
|
-
return;
|
|
274
|
-
}
|
|
275
|
-
const chunks = [];
|
|
276
|
-
let total = 0;
|
|
277
|
-
response.on("data", (chunk) => {
|
|
278
|
-
total += chunk.length;
|
|
279
|
-
if (total > maxBytes) {
|
|
280
|
-
response.destroy();
|
|
281
|
-
finish(providerError("Generated image exceeds the size limit", "ccdx_image_too_large"));
|
|
282
|
-
return;
|
|
283
|
-
}
|
|
284
|
-
chunks.push(chunk);
|
|
285
|
-
});
|
|
286
|
-
response.on("end", () => finish(null, Buffer.concat(chunks, total)));
|
|
287
|
-
});
|
|
288
|
-
request.on("error", (error) => finish(error));
|
|
289
|
-
}).catch((error) => finish(error));
|
|
290
|
-
});
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
export async function generateImage(config, {
|
|
294
|
-
prompt,
|
|
295
|
-
size = "1024x1024",
|
|
296
|
-
image,
|
|
297
|
-
} = {}, {
|
|
298
|
-
fetchImpl = fetch,
|
|
299
|
-
downloadImage = downloadPublicImage,
|
|
300
|
-
signal,
|
|
301
|
-
timeoutMs = IMAGE_GENERATION_TIMEOUT_MS,
|
|
302
|
-
} = {}) {
|
|
303
|
-
const normalizedPrompt = checkedPrompt(prompt);
|
|
304
|
-
const normalizedSize = checkedSize(size);
|
|
305
|
-
const normalizedImage = checkedImage(config, image);
|
|
306
|
-
const timeout = AbortSignal.timeout(timeoutMs);
|
|
307
|
-
const requestSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
308
|
-
let response;
|
|
309
|
-
let requestUrl = config.endpoint;
|
|
310
|
-
let method = "POST";
|
|
311
|
-
let requestBody = JSON.stringify(generationBody(config, normalizedPrompt, normalizedSize, normalizedImage));
|
|
312
|
-
let headers = { Authorization: `Bearer ${config.api_key}`, "Content-Type": "application/json", Accept: "application/json" };
|
|
313
|
-
for (let redirects = 0; ; redirects += 1) {
|
|
314
|
-
try {
|
|
315
|
-
if (requestSignal.aborted) throw requestSignal.reason;
|
|
316
|
-
response = await fetchImpl(requestUrl, { method, headers, body: requestBody, signal: requestSignal, redirect: "manual" });
|
|
317
|
-
} catch (error) {
|
|
318
|
-
if (requestSignal.aborted) throw providerError("Image generation timed out or was cancelled", "ccdx_image_timeout");
|
|
319
|
-
throw providerError("Image API could not be reached");
|
|
320
|
-
}
|
|
321
|
-
const location = [301, 302, 303, 307, 308].includes(response.status) ? response.headers?.get?.("location") : null;
|
|
322
|
-
if (location == null) break;
|
|
323
|
-
await response.body?.cancel?.().catch?.(() => {});
|
|
324
|
-
let target;
|
|
325
|
-
try { target = new URL(location, requestUrl); }
|
|
326
|
-
catch { throw providerError("Image API returned an invalid redirect", "ccdx_image_redirect_unsafe"); }
|
|
327
|
-
if (target.protocol !== "https:" || target.username || target.password || target.origin !== new URL(requestUrl).origin) {
|
|
328
|
-
throw providerError("Image API redirect was refused; use a same-origin HTTPS endpoint", "ccdx_image_redirect_unsafe");
|
|
329
|
-
}
|
|
330
|
-
if (redirects >= 20) throw providerError("Image API returned too many redirects", "ccdx_image_redirect_limit");
|
|
331
|
-
// Preserve Fetch's method/body rules for legitimate same-origin redirects.
|
|
332
|
-
if (((response.status === 301 || response.status === 302) && method === "POST") || (response.status === 303 && method !== "GET")) {
|
|
333
|
-
method = "GET";
|
|
334
|
-
requestBody = undefined;
|
|
335
|
-
headers = { ...headers };
|
|
336
|
-
delete headers["Content-Type"];
|
|
337
|
-
}
|
|
338
|
-
requestUrl = target.href;
|
|
339
|
-
}
|
|
340
|
-
const body = await boundedJson(response);
|
|
341
|
-
if (!response.ok) {
|
|
342
|
-
const detail = upstreamMessage(body);
|
|
343
|
-
throw providerError(`Image API failed with HTTP ${response.status}${detail ? `: ${detail}` : ""}`);
|
|
344
|
-
}
|
|
345
|
-
const source = imageSource(body);
|
|
346
|
-
if (!source) throw providerError("Image API response did not contain an image");
|
|
347
|
-
let bytes;
|
|
348
|
-
try {
|
|
349
|
-
if (source.type === "base64") bytes = Buffer.from(source.value, "base64");
|
|
350
|
-
else if (source.value.startsWith("data:")) bytes = decodeGeneratedImageDataUri(source.value, requestSignal);
|
|
351
|
-
else bytes = await downloadImage(source.value, { signal: requestSignal, maxBytes: IMAGE_MAX_BYTES });
|
|
352
|
-
} catch (error) {
|
|
353
|
-
if (error?.code?.startsWith?.("ccdx_")) throw error;
|
|
354
|
-
const code = String(error?.cause?.code || error?.code || "").replace(/[^A-Z0-9_-]/gi, "").slice(0, 64);
|
|
355
|
-
throw providerError(`Generated image could not be downloaded${code ? ` (${code})` : ""}`);
|
|
356
|
-
}
|
|
357
|
-
if (!bytes.length || bytes.length > IMAGE_MAX_BYTES) {
|
|
358
|
-
throw providerError("Generated image is empty or exceeds the size limit", "ccdx_image_too_large");
|
|
359
|
-
}
|
|
360
|
-
const metadata = imageMetadata(bytes);
|
|
361
|
-
return {
|
|
362
|
-
data: bytes.toString("base64"),
|
|
363
|
-
mimeType: metadata.mimeType,
|
|
364
|
-
width: metadata.width,
|
|
365
|
-
height: metadata.height,
|
|
366
|
-
model: config.model,
|
|
367
|
-
size: normalizedSize,
|
|
368
|
-
};
|
|
369
|
-
}
|
package/src/image-readiness.mjs
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import os from "node:os";
|
|
2
|
-
import { parse } from "smol-toml";
|
|
3
|
-
import { readBoundedResponseText } from "./http-transport.mjs";
|
|
4
|
-
|
|
5
|
-
export async function probeImageTool(codexContent, { fetchImpl = fetch, timeoutMs = 1500 } = {}) {
|
|
6
|
-
let server;
|
|
7
|
-
let url;
|
|
8
|
-
try {
|
|
9
|
-
server = parse(codexContent).mcp_servers?.ccdx_image;
|
|
10
|
-
if (!server || server.enabled === false) return { ready: false, reason: "not_configured" };
|
|
11
|
-
url = new URL(server.url);
|
|
12
|
-
const host = url.hostname.replace(/^\[|\]$/g, "");
|
|
13
|
-
const local = ["localhost", "127.0.0.1", "::1", ...Object.values(os.networkInterfaces())
|
|
14
|
-
.flat().filter(Boolean).map((entry) => entry.address)];
|
|
15
|
-
if (url.protocol !== "http:" || !local.includes(host) || url.username || url.password
|
|
16
|
-
|| url.pathname !== "/mcp/image" || url.search || url.hash) {
|
|
17
|
-
return { ready: false, reason: "invalid_local_endpoint" };
|
|
18
|
-
}
|
|
19
|
-
} catch {
|
|
20
|
-
return { ready: false, reason: "invalid_config" };
|
|
21
|
-
}
|
|
22
|
-
const signal = AbortSignal.timeout(timeoutMs);
|
|
23
|
-
const headers = { "Content-Type": "application/json", Accept: "application/json, text/event-stream" };
|
|
24
|
-
async function rpc(id, method, params) {
|
|
25
|
-
const response = await fetchImpl(url.href, {
|
|
26
|
-
method: "POST", headers, signal, redirect: "error",
|
|
27
|
-
body: JSON.stringify({ jsonrpc: "2.0", ...(id === undefined ? {} : { id }), method, params }),
|
|
28
|
-
});
|
|
29
|
-
if (!response.ok) {
|
|
30
|
-
await response.body?.cancel?.().catch(() => {});
|
|
31
|
-
throw new Error(`HTTP ${response.status}`);
|
|
32
|
-
}
|
|
33
|
-
if (id === undefined) {
|
|
34
|
-
await response.body?.cancel?.().catch(() => {});
|
|
35
|
-
return;
|
|
36
|
-
}
|
|
37
|
-
const text = await readBoundedResponseText(response, { maxBytes: 64 * 1024, signal, label: "Image tool catalog" });
|
|
38
|
-
const message = JSON.parse(text);
|
|
39
|
-
if (message.jsonrpc !== "2.0" || message.id !== id || message.error) throw new Error("invalid MCP response");
|
|
40
|
-
return message.result;
|
|
41
|
-
}
|
|
42
|
-
try {
|
|
43
|
-
const initialized = await rpc(1, "initialize", {
|
|
44
|
-
protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "ccdx-image-status", version: "1" },
|
|
45
|
-
});
|
|
46
|
-
if (initialized?.serverInfo?.name !== "ccdx-image") return { ready: false, reason: "unexpected_server" };
|
|
47
|
-
await rpc(undefined, "notifications/initialized", {});
|
|
48
|
-
const result = await rpc(2, "tools/list", {});
|
|
49
|
-
return result?.tools?.some((tool) => tool.name === "generate_image")
|
|
50
|
-
? { ready: true, generation: true, editing: result.tools.some(tool => tool.name === "edit_image") }
|
|
51
|
-
: { ready: false, reason: "tool_unavailable" };
|
|
52
|
-
} catch (error) {
|
|
53
|
-
return { ready: false, reason: signal.aborted ? "timeout" : /^HTTP \d+$/.test(error.message) ? error.message : "unreachable" };
|
|
54
|
-
}
|
|
55
|
-
}
|
package/src/image-references.mjs
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
-
import { createByteLruCache } from "./bounded-result-cache.mjs";
|
|
3
|
-
import { IMAGE_INPUT_MAX_BYTES } from "./image-provider.mjs";
|
|
4
|
-
|
|
5
|
-
const IMAGE_ID = /^ccdx_img_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
6
|
-
|
|
7
|
-
function providerScope(config) {
|
|
8
|
-
return createHash("sha256").update(JSON.stringify([
|
|
9
|
-
config.endpoint, config.model, config.protocol, config.api_key,
|
|
10
|
-
])).digest("hex");
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export function createImageReferenceStore({ maxBytes = 64 * 1024 * 1024 } = {}) {
|
|
14
|
-
const cache = createByteLruCache({ maxBytes });
|
|
15
|
-
return {
|
|
16
|
-
remember(config, image) {
|
|
17
|
-
if (!["image/png", "image/jpeg", "image/webp"].includes(image?.mimeType)
|
|
18
|
-
|| typeof image?.data !== "string" || !image.data
|
|
19
|
-
|| image.data.length > Math.ceil(IMAGE_INPUT_MAX_BYTES / 3) * 4
|
|
20
|
-
|| Buffer.byteLength(image.data, "base64") > IMAGE_INPUT_MAX_BYTES) return null;
|
|
21
|
-
const imageId = `ccdx_img_${randomUUID()}`;
|
|
22
|
-
const retained = cache.set(`${providerScope(config)}:${imageId}`, JSON.stringify({
|
|
23
|
-
image: `data:${image.mimeType};base64,${image.data}`,
|
|
24
|
-
size: image.size,
|
|
25
|
-
}));
|
|
26
|
-
return retained ? imageId : null;
|
|
27
|
-
},
|
|
28
|
-
resolve(config, imageId) {
|
|
29
|
-
if (typeof imageId !== "string" || !IMAGE_ID.test(imageId)) {
|
|
30
|
-
throw new Error("Provide the exact image_id returned by CCDX for the image to edit.");
|
|
31
|
-
}
|
|
32
|
-
const value = cache.get(`${providerScope(config)}:${imageId}`);
|
|
33
|
-
if (value === undefined) {
|
|
34
|
-
throw new Error("This image reference is unavailable: the adapter restarted, the image was evicted, or the provider changed. No edit was submitted.");
|
|
35
|
-
}
|
|
36
|
-
return JSON.parse(value);
|
|
37
|
-
},
|
|
38
|
-
clear() { cache.clear(); },
|
|
39
|
-
exportState() { return cache.exportEntries(); },
|
|
40
|
-
importState(values) {
|
|
41
|
-
if (!Array.isArray(values) || values.some(pair => !Array.isArray(pair) || !/^[a-f0-9]{64}:ccdx_img_[0-9a-f-]{36}$/.test(pair[0]) || typeof pair[1] !== "string")) throw new Error("Invalid image-reference handoff");
|
|
42
|
-
for (const [, value] of values) {
|
|
43
|
-
const item = JSON.parse(value);
|
|
44
|
-
if (typeof item.image !== "string" || !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(item.image)) throw new Error("Invalid image-reference handoff");
|
|
45
|
-
}
|
|
46
|
-
cache.importEntries(values);
|
|
47
|
-
},
|
|
48
|
-
stats() { return cache.stats(); },
|
|
49
|
-
};
|
|
50
|
-
}
|
package/src/image-skill/SKILL.md
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: ccdx-image
|
|
3
|
-
description: Generate raster images with the user's enabled CCDX provider, edit earlier CCDX results, or redisplay their saved images. Not for arbitrary uploaded-image edits, masks, transparent output, or code-native SVG/HTML assets.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# CCDX image generation
|
|
7
|
-
|
|
8
|
-
Use the user's enabled CCDX provider for supported image requests. Respect an explicitly requested different provider. CCDX supplies credentials and execution; no additional API key, Python, or SDK setup is needed.
|
|
9
|
-
|
|
10
|
-
## Select the operation
|
|
11
|
-
|
|
12
|
-
- **Generate:** Call `ccdx_image.generate_image` with a complete prompt. Supported sizes are `1024x1024`, `1536x1024`, and `1024x1536`; the default is square.
|
|
13
|
-
- **Edit:** Read [editing.md](references/editing.md) before calling `ccdx_image.edit_image`. Use the exact source `image_id` from this conversation; never substitute a different image or a fresh generation.
|
|
14
|
-
- **Redisplay:** Reuse the requested image's existing Markdown. Do not call generation or editing tools.
|
|
15
|
-
|
|
16
|
-
Use the MCP tool directly when callable. Otherwise, if tool search is available, make one targeted search for the relevant `ccdx_image` tool. Only if the MCP tool remains unavailable, read [helper.md](references/helper.md) for the bundled fallback. An explicitly unsupported edit or a failed tool call is not a reason to use the fallback.
|
|
17
|
-
|
|
18
|
-
## Deliver the result
|
|
19
|
-
|
|
20
|
-
Embed the returned saved-image Markdown unchanged in the final chat reply to display a clickable thumbnail. Image content in a tool result or a viewer call alone is not final delivery. Do not use a code block or replace the image with a download-only link.
|
|
21
|
-
|
|
22
|
-
Retain the image's Markdown/path together with its returned `image_id`, when present. Reuse that artifact for later redisplay. If saving failed, distinguish generation success from delivery failure: do not invent a path, claim display succeeded, or generate/edit again to repair delivery.
|
|
23
|
-
|
|
24
|
-
## Execution boundaries
|
|
25
|
-
|
|
26
|
-
- Do not automatically retry a failed or timed-out image request, switch providers, or run the helper afterward; the request may already have been processed.
|
|
27
|
-
- Preserve the host's approval policy. A user request to generate an image does not bypass execution permissions.
|
|
28
|
-
- Arbitrary uploaded-image edits, masks, reference-image inputs, and transparent output are outside this integration. Explain the limitation without substituting a different operation. Use another available workflow only when consistent with the user's request.
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
# Edit a CCDX result
|
|
2
|
-
|
|
3
|
-
## Select the source
|
|
4
|
-
|
|
5
|
-
Use the specific image's returned `image_id` from this conversation, not a global last image. Resolve an ambiguous source before submitting the edit.
|
|
6
|
-
|
|
7
|
-
A file path is not an edit ID. Handles can expire after cache eviction, provider changes, or adapter restart while saved files remain viewable. For missing or expired handles, explain that this source is unavailable for editing; do not replace it.
|
|
8
|
-
|
|
9
|
-
## Submit and deliver
|
|
10
|
-
|
|
11
|
-
Call `ccdx_image.edit_image` with the exact ID and a prompt specifying changes and what to preserve. Omit `size` to preserve source dimensions unless another supported size was requested.
|
|
12
|
-
|
|
13
|
-
An explicitly unsupported edit must stop. Only an unavailable MCP tool may use [helper.md](helper.md), not a failed or timed-out edit.
|
|
14
|
-
|
|
15
|
-
Each edit preserves the source. Keep the new image/ID mapping alongside the original, and apply `SKILL.md`'s final-image delivery rules.
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
# MCP-unavailable fallback
|
|
2
|
-
|
|
3
|
-
Use only when MCP is unavailable, never after a failed, timed-out, or unsupported image operation. The helper calls the same local CCDX service at most once per execution.
|
|
4
|
-
|
|
5
|
-
## Invoke
|
|
6
|
-
|
|
7
|
-
Generate:
|
|
8
|
-
|
|
9
|
-
```sh
|
|
10
|
-
{{NODE}} {{HELPER}} --prompt 'A complete image prompt' --size 1024x1024
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
Edit an identified CCDX result:
|
|
14
|
-
|
|
15
|
-
```sh
|
|
16
|
-
{{NODE}} {{HELPER}} --image-id 'EXACT_SOURCE_IMAGE_ID' --prompt 'Requested changes and what to preserve'
|
|
17
|
-
```
|
|
18
|
-
|
|
19
|
-
For edits, follow [editing.md](editing.md); omitting `--size` preserves source dimensions. Replace the examples and quote actual arguments safely. Optional `--out` selects a new file; existing files are never overwritten.
|
|
20
|
-
|
|
21
|
-
Loopback HTTP can be restricted. If networking is restricted, request normal execution permission for this exact command before running it. Keep the host's approval policy unchanged.
|
|
22
|
-
|
|
23
|
-
## Interpret the result
|
|
24
|
-
|
|
25
|
-
- **Success:** stdout is the saved absolute path; stderr includes `CCDX image_id` when retained. Embed an absolute-path Markdown image in the final reply and retain its ID.
|
|
26
|
-
- **Explicitly not started:** No image operation was submitted. Resolve the reported connection/permission issue before another attempt.
|
|
27
|
-
- **Other failure or timeout:** Dispatch may have completed. Report without retrying, switching providers, or installing dependencies. Saving/display failure must not trigger regeneration.
|