zapagent 1.14.22 → 1.14.24

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.
@@ -0,0 +1,186 @@
1
+ import { inflateSync } from "node:zlib";
2
+ import { CODEX_RESPONSES_BASE_URL } from "./openai-responses.js";
3
+ import { parseImageDimensions } from "../../utils/image-dimensions.js";
4
+
5
+ export const IMAGE_MAX_BYTES = 8 * 1024 * 1024;
6
+ export const IMAGE_RESPONSE_MAX_BYTES = 32 * 1024 * 1024;
7
+ export const IMAGE_TIMEOUT_MS = 300_000;
8
+ export interface ImageGenerationRequest {
9
+ prompt: string;
10
+ quality?: "auto" | "low" | "medium" | "high";
11
+ size?: "auto" | "1024x1024" | "1536x1024" | "1024x1536";
12
+ background?: "auto" | "opaque" | "transparent";
13
+ }
14
+ export interface GeneratedImage {
15
+ bytes: Buffer;
16
+ width: number;
17
+ height: number;
18
+ requestBytes: number;
19
+ responseBytes: number;
20
+ }
21
+ export interface CodexImageOptions {
22
+ model: string;
23
+ getCredentials: (signal?: AbortSignal) => Promise<{ accessToken: string; accountId?: string }>;
24
+ fetch?: typeof globalThis.fetch;
25
+ timeoutMs?: number;
26
+ idleMs?: number;
27
+ maxResponseBytes?: number;
28
+ }
29
+
30
+
31
+ const crcTable = Uint32Array.from({ length: 256 }, (_, index) => {
32
+ let crc = index;
33
+ for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
34
+ return crc >>> 0;
35
+ });
36
+ function validPngPixels(bytes: Buffer, width: number, height: number): boolean {
37
+ const compressed: Buffer[] = [];
38
+ let offset = 8, header = false, ended = false, palette = false, depth = 0, color = 0, interlace = 0;
39
+ while (offset + 12 <= bytes.length) {
40
+ const length = bytes.readUInt32BE(offset), end = offset + 8 + length;
41
+ if (end + 4 > bytes.length) return false;
42
+ const kind = bytes.toString("latin1", offset + 4, offset + 8);
43
+ if (!/^[A-Za-z]{4}$/.test(kind)) return false;
44
+ let crc = 0xffffffff;
45
+ for (let i = offset + 4; i < end; i++) crc = crcTable[(crc ^ bytes[i]!) & 255]! ^ (crc >>> 8);
46
+ if (((crc ^ 0xffffffff) >>> 0) !== bytes.readUInt32BE(end)) return false;
47
+ if (!header && kind !== "IHDR") return false;
48
+ if (kind === "IHDR") {
49
+ if (header || length !== 13) return false;
50
+ header = true; depth = bytes[offset + 16]!; color = bytes[offset + 17]!; interlace = bytes[offset + 20]!;
51
+ const depths: Record<number, number[]> = { 0: [1, 2, 4, 8, 16], 2: [8, 16], 3: [1, 2, 4, 8], 4: [8, 16], 6: [8, 16] };
52
+ if (!depths[color]?.includes(depth) || bytes[offset + 18] !== 0 || bytes[offset + 19] !== 0 || interlace > 1) return false;
53
+ } else if (kind === "IDAT") compressed.push(bytes.subarray(offset + 8, end));
54
+ else if (kind === "PLTE") { if (!length || length > 768 || length % 3) return false; palette = true; }
55
+ else if (kind === "IEND") { ended = length === 0 && end + 4 === bytes.length; break; }
56
+ else if (kind === "acTL" || !/^[a-z]/.test(kind)) return false;
57
+ offset = end + 4;
58
+ }
59
+ if (!ended || !compressed.length || (color === 3 && !palette)) return false;
60
+ const channels: Record<number, number> = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 };
61
+ const passes = interlace ? [[0, 0, 8, 8], [4, 0, 8, 8], [0, 4, 4, 8], [2, 0, 4, 4], [0, 2, 2, 4], [1, 0, 2, 2], [0, 1, 1, 2]] : [[0, 0, 1, 1]];
62
+ try {
63
+ const raw = inflateSync(Buffer.concat(compressed), { maxOutputLength: 68 * 1024 * 1024 });
64
+ let cursor = 0;
65
+ for (const [x, y, dx, dy] of passes) {
66
+ const w = Math.max(0, Math.ceil((width - x!) / dx!)), h = Math.max(0, Math.ceil((height - y!) / dy!));
67
+ if (!w || !h) continue;
68
+ const row = Math.ceil(w * depth * channels[color]! / 8) + 1;
69
+ for (let line = 0; line < h; line++) { if (cursor + row > raw.length || raw[cursor]! > 4) return false; cursor += row; }
70
+ }
71
+ return cursor === raw.length;
72
+ } catch { return false; }
73
+ }
74
+
75
+ export function validateGeneratedPng(bytes: Buffer): { width: number; height: number } {
76
+ const dimensions = parseImageDimensions(bytes);
77
+ if (bytes.length > IMAGE_MAX_BYTES || bytes.length < 32 || bytes.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a"
78
+ || !dimensions || dimensions.width > 4096 || dimensions.height > 4096 || dimensions.width * dimensions.height > 16_777_216 || !validPngPixels(bytes, dimensions.width, dimensions.height)) {
79
+ throw new Error("Generated image is not a supported PNG or exceeds the image size limit.");
80
+ }
81
+ return dimensions;
82
+ }
83
+
84
+ async function abortable<T>(work: Promise<T>, signal: AbortSignal): Promise<T> {
85
+ signal.throwIfAborted();
86
+ let abort: (() => void) | undefined;
87
+ try {
88
+ return await Promise.race([work, new Promise<never>((_, reject) => {
89
+ abort = () => reject(signal.reason ?? new Error("Image generation cancelled."));
90
+ signal.addEventListener("abort", abort, { once: true });
91
+ if (signal.aborted) abort();
92
+ })]);
93
+ } finally { if (abort) signal.removeEventListener("abort", abort); }
94
+ }
95
+
96
+ /** Host-owned model request, like the conversation provider. It has its own
97
+ * bounded HTTP budget, not the ordinary tool HTTP-fetch budget. No retries:
98
+ * retrying an interrupted generation can charge for another image. */
99
+ export async function generateCodexImage(options: CodexImageOptions, args: ImageGenerationRequest, signal?: AbortSignal): Promise<GeneratedImage> {
100
+ if (!options.model || options.model.length > 256 || /[\x00-\x1f\x7f]/.test(options.model)) throw new Error("Select a valid Codex model before generating images.");
101
+ if (!args.prompt.trim() || Buffer.byteLength(args.prompt) > 16_000) throw new Error("Image prompt must be 1–16000 UTF-8 bytes.");
102
+ const requestSignal = AbortSignal.any([AbortSignal.timeout(options.timeoutMs ?? IMAGE_TIMEOUT_MS), ...(signal ? [signal] : [])]);
103
+ requestSignal.throwIfAborted();
104
+ const credentials = await abortable(options.getCredentials(requestSignal), requestSignal);
105
+ requestSignal.throwIfAborted();
106
+ const body = JSON.stringify({ model: options.model, instructions: "Generate exactly one image with the image generation tool, following the user's prompt.",
107
+ input: [{ role: "user", content: args.prompt }], store: false, stream: true,
108
+ tools: [{ type: "image_generation", model: "gpt-image-2", output_format: "png", quality: args.quality ?? "auto",
109
+ size: args.size ?? "auto", background: args.background ?? "auto" }], tool_choice: { type: "image_generation" } });
110
+ const requestBytes = Buffer.byteLength(body);
111
+ const response = await abortable((options.fetch ?? fetch)(`${CODEX_RESPONSES_BASE_URL}/responses`, {
112
+ method: "POST", headers: { Authorization: `Bearer ${credentials.accessToken}`, "Content-Type": "application/json", originator: "zap",
113
+ ...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) },
114
+ body, signal: requestSignal, redirect: "error",
115
+ }), requestSignal);
116
+ if (!response.ok || !response.body) {
117
+ void response.body?.cancel().catch(() => {});
118
+ throw new Error(`Codex image generation failed (HTTP ${response.status}). Check Codex sign-in, model access and usage limits.`);
119
+ }
120
+ const reader = response.body.getReader();
121
+ const decoder = new TextDecoder();
122
+ const images = new Map<string, { bytes: Buffer; width: number; height: number }>();
123
+ let responseBytes = 0, buffer = "", data: string[] = [], completed = false;
124
+ const capture = (item: any) => {
125
+ if (item?.type !== "image_generation_call") return;
126
+ if (item.status !== "completed" || typeof item.id !== "string" || typeof item.result !== "string") {
127
+ throw new Error("Codex returned an incomplete image generation result.");
128
+ }
129
+ if (item.result.length > Math.ceil(IMAGE_MAX_BYTES / 3) * 4 || !/^[A-Za-z0-9+/]+={0,2}$/.test(item.result)) {
130
+ throw new Error("Codex returned an invalid or oversized image payload.");
131
+ }
132
+ if (images.has(item.id)) {
133
+ if (images.get(item.id)!.bytes.toString("base64") !== item.result) throw new Error("Codex returned conflicting image results.");
134
+ return;
135
+ }
136
+ if (images.size) throw new Error("Codex returned more than one image for a single-image request.");
137
+ const bytes = Buffer.from(item.result, "base64");
138
+ if (bytes.toString("base64") !== item.result) throw new Error("Codex returned an invalid image encoding.");
139
+ images.set(item.id, { bytes, ...validateGeneratedPng(bytes) });
140
+ };
141
+ const dispatch = () => {
142
+ if (!data.length) return;
143
+ const payload = data.join("\n"); data = [];
144
+ if (payload === "[DONE]") return;
145
+ let event: any;
146
+ try { event = JSON.parse(payload); } catch { throw new Error("Invalid Codex image generation stream."); }
147
+ if (event.type === "response.output_item.done") capture(event.item);
148
+ if (event.type === "response.completed") {
149
+ if (event.response?.status !== "completed") throw new Error("Codex image generation did not complete.");
150
+ for (const item of event.response.output ?? []) capture(item);
151
+ completed = true;
152
+ } else if (["response.failed", "response.incomplete", "error"].includes(event.type)) {
153
+ throw new Error("Codex image generation failed or was incomplete. It was not automatically retried.");
154
+ }
155
+ };
156
+ const consume = (text: string) => {
157
+ buffer += text;
158
+ let newline: number;
159
+ while ((newline = buffer.indexOf("\n")) !== -1) {
160
+ const line = buffer.slice(0, newline).replace(/\r$/, ""); buffer = buffer.slice(newline + 1);
161
+ if (!line) dispatch();
162
+ else if (line.startsWith("data:")) data.push(line.slice(5).replace(/^ /, ""));
163
+ }
164
+ };
165
+ try {
166
+ while (!completed) {
167
+ requestSignal.throwIfAborted();
168
+ let timer: ReturnType<typeof setTimeout> | undefined;
169
+ const onAbort = () => { void reader.cancel().catch(() => {}); };
170
+ requestSignal.addEventListener("abort", onAbort, { once: true });
171
+ try {
172
+ const part = await Promise.race([reader.read(), new Promise<never>((_, reject) => {
173
+ timer = setTimeout(() => { reject(new Error("Codex image generation stream timed out.")); void reader.cancel().catch(() => {}); }, options.idleMs ?? 90_000);
174
+ })]);
175
+ requestSignal.throwIfAborted();
176
+ if (part.done) { consume(decoder.decode() + "\n\n"); break; }
177
+ responseBytes += part.value.byteLength;
178
+ if (responseBytes > Math.min(options.maxResponseBytes ?? IMAGE_RESPONSE_MAX_BYTES, IMAGE_RESPONSE_MAX_BYTES)) throw new Error("Codex image generation response exceeds its byte limit.");
179
+ consume(decoder.decode(part.value, { stream: true }));
180
+ } finally { if (timer) clearTimeout(timer); requestSignal.removeEventListener("abort", onAbort); }
181
+ }
182
+ requestSignal.throwIfAborted();
183
+ if (!completed || images.size !== 1) throw new Error("Codex stream ended without a completed image. It was not automatically retried.");
184
+ return { ...images.values().next().value!, requestBytes, responseBytes };
185
+ } finally { void reader.cancel().catch(() => {}); try { reader.releaseLock(); } catch {} }
186
+ }
package/zapsdk/index.ts CHANGED
@@ -12,6 +12,9 @@ export { type LLMProvider, type LLMCallOptions, type ProviderRequestEvent } from
12
12
  export { ProviderRequestTimeoutError } from "./core/provider-request.js";
13
13
  export { AnthropicProvider, type AnthropicProviderOptions } from "./core/providers/anthropic.js";
14
14
  export { ContextOverflowError } from "./core/errors.js";
15
+ export { generateCodexImage, type CodexImageOptions, type GeneratedImage, type ImageGenerationRequest } from "./core/providers/codex-image-generation.js";
16
+ export { generateImageTool, type GenerateImageOptions } from "./builtin-tools/generate-image.js";
17
+ export { type GeneratedImageArtifact, type GeneratedImageMeta } from "./utils/generated-image.js";
15
18
  export { OpenAIResponsesProvider, type OpenAIResponsesProviderOptions } from "./core/providers/openai-responses.js";
16
19
  export { OpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from "./core/providers/openai-compatible.js";
17
20
  export { RetryProvider, type RetryOptions, type CallOptions } from "./core/retry.js";
@@ -0,0 +1,84 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
3
+ import { mkdir } from "node:fs/promises";
4
+ import { atomicWrite } from "../builtin-tools/filesystem.js";
5
+ import { join } from "node:path";
6
+ import { Resvg } from "@resvg/resvg-js";
7
+ import { IMAGE_MAX_BYTES, validateGeneratedPng, type GeneratedImage } from "../core/providers/codex-image-generation.js";
8
+
9
+ export interface GeneratedImageArtifact {
10
+ id: string;
11
+ filePath?: string;
12
+ cachePath?: string;
13
+ mediaType: "image/png";
14
+ width: number;
15
+ height: number;
16
+ bytes: number;
17
+ /** Small RGB thumbnail, never provider-controlled terminal escape sequences. */
18
+ thumbnail?: { width: number; height: number; rgb: string };
19
+ }
20
+ export interface GeneratedImageMeta {
21
+ generatedImage: GeneratedImageArtifact;
22
+ providerRequest: { requestBytes: number; responseBytes: number };
23
+ }
24
+ const hash = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
25
+
26
+ export function generatedImageArtifact(meta: unknown): GeneratedImageArtifact | undefined {
27
+ const image = (meta as GeneratedImageMeta | undefined)?.generatedImage;
28
+ if (!image || typeof image.id !== "string" || !/^[a-f0-9]{64}$/.test(image.id) || image.mediaType !== "image/png" || !Number.isSafeInteger(image.bytes)
29
+ || image.bytes < 32 || image.bytes > IMAGE_MAX_BYTES || !Number.isSafeInteger(image.width) || !Number.isSafeInteger(image.height)
30
+ || image.width < 1 || image.height < 1 || image.width > 4096 || image.height > 4096) return;
31
+ return { id: image.id, mediaType: "image/png", width: image.width, height: image.height, bytes: image.bytes,
32
+ ...(typeof image.filePath === "string" && image.filePath.length <= 4096 && !/[\x00-\x1f\x7f]/.test(image.filePath) ? { filePath: image.filePath } : {}),
33
+ ...(typeof image.cachePath === "string" && image.cachePath.length <= 4096 && !/[\x00-\x1f\x7f]/.test(image.cachePath) ? { cachePath: image.cachePath } : {}),
34
+ ...(image.thumbnail ? { thumbnail: image.thumbnail } : {}) };
35
+ }
36
+
37
+ export function generatedImageThumbnail(bytes: Buffer): GeneratedImageArtifact["thumbnail"] {
38
+ const { width, height } = validateGeneratedPng(bytes);
39
+ const w = 32, h = Math.max(2, Math.min(32, Math.round(w * height / width)));
40
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="100%" height="100%" fill="white"/><image href="data:image/png;base64,${bytes.toString("base64")}" width="${w}" height="${h}"/></svg>`;
41
+ const rendered = new Resvg(svg, { font: { loadSystemFonts: false } }).render();
42
+ const rgba = rendered.pixels, rgb = Buffer.alloc(w * h * 3);
43
+ for (let i = 0; i < w * h; i++) rgba.copy(rgb, i * 3, i * 4, i * 4 + 3);
44
+ return { width: w, height: h, rgb: rgb.toString("hex") };
45
+ }
46
+
47
+ /** Runtime-owned artifact storage is separate from model-chosen workspace writes.
48
+ * A cache key is always a digest; restore never reads an arbitrary metadata path. */
49
+ export async function cacheGeneratedImage(directory: string, image: GeneratedImage): Promise<GeneratedImageArtifact> {
50
+ const dimensions = validateGeneratedPng(image.bytes);
51
+ const thumbnail = generatedImageThumbnail(image.bytes); // Decode/validate before publishing.
52
+ const id = hash(image.bytes), path = join(directory, `${id}.png`);
53
+ await mkdir(directory, { recursive: true, mode: 0o700 });
54
+ try { await atomicWrite(path, image.bytes, { replaceExisting: false, mode: 0o600 }); }
55
+ catch (error) {
56
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
57
+ const existing = restoreGeneratedImage(directory, { generatedImage: { id, mediaType: "image/png", ...dimensions, bytes: image.bytes.length } });
58
+ if (!existing?.equals(image.bytes)) throw new Error("Generated image artifact cache collision.");
59
+ }
60
+ return { id, cachePath: path, mediaType: "image/png", ...dimensions, bytes: image.bytes.length, thumbnail };
61
+ }
62
+
63
+ export function restoreGeneratedImage(directory: string, meta: unknown): Buffer | undefined {
64
+ const image = generatedImageArtifact(meta);
65
+ if (!image) return;
66
+ let fd: number | undefined;
67
+ try {
68
+ if (lstatSync(join(directory, `${image.id}.png`)).isSymbolicLink()) return;
69
+ fd = openSync(join(directory, `${image.id}.png`), constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
70
+ const stat = fstatSync(fd);
71
+ if (!stat.isFile() || stat.size !== image.bytes || stat.size > IMAGE_MAX_BYTES) return;
72
+ const bytes = Buffer.alloc(image.bytes);
73
+ let offset = 0;
74
+ while (offset < bytes.length) {
75
+ const count = readSync(fd, bytes, offset, bytes.length - offset, offset);
76
+ if (!count) return;
77
+ offset += count;
78
+ }
79
+ if (fstatSync(fd).size !== image.bytes) return;
80
+ const size = validateGeneratedPng(bytes);
81
+ if (hash(bytes) !== image.id || size.width !== image.width || size.height !== image.height) return;
82
+ return bytes;
83
+ } catch { return; } finally { if (fd !== undefined) closeSync(fd); }
84
+ }