zapagent 1.14.22 → 1.14.23

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 CHANGED
@@ -71,7 +71,7 @@ Interact in the terminal and follow task progress in the live browser view.
71
71
  On first use, enter `/connect` and follow the setup prompts to connect your model service. Then describe what you want: “Read the materials in this folder, summarize the key points, and write a report.”
72
72
 
73
73
  Use your model service account and API key, or select **OpenAI Codex (ChatGPT)**
74
- to sign in with a ChatGPT account using OAuth. Usage and model access depend on
74
+ to sign in with a ChatGPT account using OAuth. Codex connections also support image generation: ask Zap to create an image and save it to a new `.png` file. [Image generation](docs/usage.md#image-generation-with-codex). Usage and model access depend on
75
75
  your provider/account. [Connection guide](docs/usage.md#getting-started).
76
76
 
77
77
  Update from your terminal with `zap update` (or `zap update --yes` for unattended installation).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zapagent",
3
- "version": "1.14.22",
3
+ "version": "1.14.23",
4
4
  "packageManager": "bun@1.3.14",
5
5
  "author": "",
6
6
  "main": "src/index.tsx",
package/src/acp/events.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { SessionUpdate, StopReason, ToolKind } from "@agentclientprotocol/sdk"
1
+ import type { SessionUpdate, StopReason, ToolKind, ToolCallContent } from "@agentclientprotocol/sdk"
2
2
  import type { AgentEvent } from "../../zapsdk/agent/events.js"
3
3
 
4
4
  export function acpStopReason(reason: string): StopReason {
@@ -46,9 +46,11 @@ export class AcpEventMapper {
46
46
  }
47
47
  if (event.type === "content_final" && event.kind === "tool_result") {
48
48
  const text = typeof event.result.output === "string" ? event.result.output : JSON.stringify(event.result.output ?? "")
49
+ const images: ToolCallContent[] = event.toolName === "generate_image" ? (event.result.contentBlocks ?? []).flatMap(block =>
50
+ block.type === "image" && block.base64 ? [{ type: "content" as const, content: { type: "image" as const, data: block.base64, mimeType: block.mediaType } }] : []) : []
49
51
  return [{ sessionUpdate: "tool_call_update", toolCallId: id(event.id),
50
52
  status: event.result.success === false ? "failed" : "completed", rawOutput: event.result,
51
- content: [{ type: "content", content: { type: "text", text: event.result.error ?? text } }] }]
53
+ content: [{ type: "content", content: { type: "text", text: event.result.error ?? text } }, ...images] }]
52
54
  }
53
55
  return []
54
56
  }
@@ -1,3 +1,5 @@
1
+ import { getAppDataDir } from "../zapsdk/utils/platform.js"
2
+ import { generateCodexImage } from "../zapsdk/core/providers/codex-image-generation.js"
1
3
  import { modelCanonicalIds } from "./provider-metadata.js"
2
4
  import { getCodexCredentials } from "./codex-auth.js"
3
5
  import { serviceTools } from "../zapsdk/services/tools.js"
@@ -37,7 +39,7 @@ import { createExecutionEnvironment, resolveExecutionBackend, type ExecutionEnvi
37
39
  const CWD_SENSITIVE_TOOLS = new Set([
38
40
  "read_file", "write_file", "edit_file", "multi_edit",
39
41
  "delete_file", "move_file", "list_tree", "bash",
40
- "search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent",
42
+ "search_files", "glob_files", "read_document", "browser_screenshot", "delegate_agent", "generate_image",
41
43
  ])
42
44
 
43
45
  function safeHost(url: string): string {
@@ -84,6 +86,11 @@ export function buildAgentObjects(
84
86
  const apiKey = rawApiKey || "unconfigured"
85
87
  const model = config.active.model
86
88
  const maxOutputTokens = getActiveMaxOutputTokens(config)
89
+ const imageCapability = active?.authMode === "codex-oauth" ? {
90
+ generate: (request: import("../zapsdk/core/providers/codex-image-generation.js").ImageGenerationRequest, signal?: AbortSignal) =>
91
+ generateCodexImage({ model: typeof active.extraRequestParams?.model === "string" ? active.extraRequestParams.model : model, getCredentials: getCodexCredentials }, request, signal),
92
+ artifactDirectory: join(getAppDataDir(), "generated-images"),
93
+ } : undefined
87
94
  // Protocol selection: explicit `protocol` field on the provider wins;
88
95
  // fall back to host substring detection so legacy configs (saved before
89
96
  // the field existed) still route the official Anthropic endpoint to
@@ -163,6 +170,7 @@ export function buildAgentObjects(
163
170
  globFiles: { allowedPaths, useExecutionGrants: true },
164
171
  documentRead: { allowedPaths, useExecutionGrants: true },
165
172
  browserScreenshot: { allowedPaths },
173
+ generateImage: imageCapability ? { ...imageCapability, allowedPaths, protectedPaths, useExecutionGrants: true, defaultCwd: effectiveCwd } : undefined,
166
174
  executeCommand: {
167
175
  timeoutMs: 60000,
168
176
  defaultCwd: effectiveCwd,
@@ -241,6 +249,7 @@ export function buildAgentObjects(
241
249
  globFiles: { allowedPaths, useExecutionGrants: true },
242
250
  documentRead: { allowedPaths, useExecutionGrants: true },
243
251
  browserScreenshot: { allowedPaths },
252
+ generateImage: imageCapability ? { ...imageCapability, allowedPaths, protectedPaths, useExecutionGrants: true, defaultCwd: workspaceCwd } : undefined,
244
253
  executeCommand: {
245
254
  timeoutMs: 60000,
246
255
  defaultCwd: workspaceCwd,
@@ -1,3 +1,4 @@
1
+ import { generatedImageArtifact, type GeneratedImageArtifact } from "../../zapsdk/utils/generated-image.js"
1
2
  import type { AgentOutcomeV1 } from "../../zapsdk/runtime/outcome.js"
2
3
  import type { InlineAcceptanceRecord } from "../../zapsdk/runtime/inline-acceptance.js"
3
4
  // Output formatters for headless runs. Three modes, all sharing one observer
@@ -36,6 +37,7 @@ export type StopReason =
36
37
  | "capability_unavailable"
37
38
 
38
39
  export interface ToolCallRecord {
40
+ generatedImage?: Omit<GeneratedImageArtifact, "thumbnail">
39
41
  name: string
40
42
  args: Record<string, unknown>
41
43
  ok: boolean
@@ -156,7 +158,10 @@ export function createFormatter(format: OutputFormat, quiet: boolean, resultSche
156
158
  const errMsg = !ok
157
159
  ? (event.result.error ?? (typeof event.result.output === "string" ? event.result.output : ""))
158
160
  : undefined
161
+ const image = event.toolName === "generate_image" ? generatedImageArtifact(event.result.meta) : undefined
162
+ const artifact = image ? (({ thumbnail, ...metadata }) => metadata)(image) : undefined
159
163
  const audit = {
164
+ ...(artifact ? { generatedImage: artifact } : {}),
160
165
  ...(event.result.runtime?.service ? { service: event.result.runtime.service } : {}),
161
166
  ...(event.result.runtime?.serviceOperation ? { serviceOperation: event.result.runtime.serviceOperation } : {}),
162
167
  ...(event.result.runtime?.resultSourcePolicy ? { resultSourcePolicy: event.result.runtime.resultSourcePolicy } : {}),
package/src/session.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  stat as statAsync,
13
13
  } from "node:fs/promises"
14
14
  import { createHash, randomUUID } from "node:crypto"
15
+ import { generatedImageArtifact, restoreGeneratedImage } from "../zapsdk/utils/generated-image.js"
15
16
  import { getAppDataDir } from "../zapsdk/utils/platform.js"
16
17
  import { legacyProjectDataSegment, resolveProjectDataSegment } from "../zapsdk/utils/project-paths.js"
17
18
  import type { ImageContent, Message } from "../zapsdk/index.js"
@@ -1984,7 +1985,25 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
1984
1985
  // toolCalls keyed by id — duplicates from replaceLog chaining are
1985
1986
  // de-duped in place. Order is preserved by tracking insertion order.
1986
1987
  const pendingToolCalls: { id: string; name: string; arguments: Record<string, unknown> }[] = []
1987
- const pendingToolResults = new Map<string, { content: string; success?: boolean; suppression?: "duplicate" }>()
1988
+ const pendingToolResults = new Map<string, { content: string; success?: boolean; suppression?: "duplicate"; meta?: unknown; generatedBlock?: ImageContent }>()
1989
+ // Restore recent generated pixels from authenticated runtime artifacts only.
1990
+ // Older outputs retain their paths; avoid loading an unbounded image history.
1991
+ const generatedBlocks = new Map<SessionLog, ImageContent>()
1992
+ const seenGeneratedCalls = new Set<string>()
1993
+ let generatedBytes = 0
1994
+ for (const log of [...logs].reverse()) {
1995
+ if (log.restore === false || log.type !== "result" || log.tool?.name !== "generate_image") continue
1996
+ if (!log.tool.id || seenGeneratedCalls.has(log.tool.id)) continue
1997
+ seenGeneratedCalls.add(log.tool.id)
1998
+ const artifact = generatedImageArtifact(log.tool.meta)
1999
+ if (!artifact || generatedBlocks.size >= 4 || generatedBytes + artifact.bytes > 16 * 1024 * 1024) continue
2000
+ const bytes = restoreGeneratedImage(join(getAppDataDir(), "generated-images"), log.tool.meta)
2001
+ if (!bytes) continue
2002
+ generatedBytes += bytes.length
2003
+ generatedBlocks.set(log, { type: "image", filePath: join(getAppDataDir(), "generated-images", `${artifact.id}.png`),
2004
+ mediaType: "image/png", base64: bytes.toString("base64"), source: "generate_image" })
2005
+ }
2006
+
1988
2007
 
1989
2008
  const flushPending = () => {
1990
2009
  if (pendingToolCalls.length > 0) {
@@ -1993,6 +2012,8 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
1993
2012
  for (const tc of pendingToolCalls) {
1994
2013
  const got = pendingToolResults.get(tc.id)
1995
2014
  if (got) {
2015
+ const artifact = tc.name === "generate_image" ? generatedImageArtifact(got.meta) : undefined
2016
+ const generatedBlock = got.generatedBlock
1996
2017
  completed.push({
1997
2018
  id: tc.id,
1998
2019
  name: tc.name,
@@ -2000,6 +2021,8 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
2000
2021
  result: {
2001
2022
  success: got.success ?? true,
2002
2023
  output: got.content,
2024
+ ...(artifact ? { meta: { generatedImage: artifact } } : {}),
2025
+ ...(generatedBlock ? { contentBlocks: [generatedBlock] } : {}),
2003
2026
  ...(got.suppression ? { runtime: { suppression: got.suppression } } : {}),
2004
2027
  },
2005
2028
  // Legacy logs lack status evidence. Preserve their output without
@@ -2078,6 +2101,8 @@ export function sessionLogsToTurns(logs: SessionLog[]): Turn[] {
2078
2101
  content: log.tool.output ?? "",
2079
2102
  success: log.tool.success,
2080
2103
  suppression: log.tool.suppression,
2104
+ meta: log.tool.name === "generate_image" ? log.tool.meta : undefined,
2105
+ generatedBlock: generatedBlocks.get(log),
2081
2106
  })
2082
2107
  }
2083
2108
  }
@@ -9,6 +9,7 @@
9
9
  // continuation rows leak back to col 0. <IndentedRow> bakes the right
10
10
  // pattern in once and every renderer reuses it.
11
11
 
12
+ import { GeneratedImageResult } from "./generated-image.js"
12
13
  import { Fragment, memo, useMemo, useRef } from "react"
13
14
  import { Box, Static, Text } from "ink"
14
15
  import type { LogEntry } from "./types.js"
@@ -488,6 +489,7 @@ export const ToolResult = memo(function ToolResult({ log }: { log: LogEntry }) {
488
489
  <Text color={c.text.muted}>{lines.join("\n")}</Text>
489
490
  </IndentedRow>
490
491
  )}
492
+ {tool.name === "generate_image" && <IndentedRow width={NESTED_COLS}><GeneratedImageResult meta={tool.meta} /></IndentedRow>}
491
493
  {checkpointWarning && (
492
494
  <IndentedRow width={NESTED_COLS}>
493
495
  <Text color={c.warning}>{`⚠ ${checkpointWarning}`}</Text>
@@ -0,0 +1,31 @@
1
+ /** @jsxImportSource react */
2
+ import { Box, Text } from "ink"
3
+ import { generatedImageArtifact } from "../../zapsdk/utils/generated-image.js"
4
+ import { c } from "./theme.js"
5
+
6
+ /** Stored pixels are small, validated RGB data; no file reads or provider ANSI. */
7
+ export function GeneratedImageResult({ meta }: { meta: unknown }) {
8
+ const image = generatedImageArtifact(meta)
9
+ if (!image) return null
10
+ const thumbnail = image.thumbnail
11
+ const rows: string[] = []
12
+ if (thumbnail && Number.isInteger(thumbnail.width) && Number.isInteger(thumbnail.height)
13
+ && thumbnail.width > 0 && thumbnail.width <= 32 && thumbnail.height > 0 && thumbnail.height <= 32
14
+ && typeof thumbnail.rgb === "string" && thumbnail.rgb.length === thumbnail.width * thumbnail.height * 6
15
+ && /^[a-f0-9]+$/.test(thumbnail.rgb)) {
16
+ const rgb = Buffer.from(thumbnail.rgb, "hex")
17
+ const color = (x: number, y: number) => {
18
+ const offset = (Math.min(y, thumbnail.height - 1) * thumbnail.width + x) * 3
19
+ return `${rgb[offset]};${rgb[offset + 1]};${rgb[offset + 2]}`
20
+ }
21
+ for (let y = 0; y < thumbnail.height; y += 2) {
22
+ let line = ""
23
+ for (let x = 0; x < thumbnail.width; x++) line += `\x1b[38;2;${color(x, y)}m\x1b[48;2;${color(x, y + 1)}m▀`
24
+ rows.push(line + "\x1b[0m")
25
+ }
26
+ }
27
+ return <Box flexDirection="column">
28
+ {rows.map((row, index) => <Text key={index}>{row}</Text>)}
29
+ <Text color={c.text.faint}>{`PNG · ${image.width}×${image.height} · ${(image.bytes / 1024).toFixed(0)} KB`}</Text>
30
+ </Box>
31
+ }
@@ -69,6 +69,7 @@ function formatArgs(name: string, args: Record<string, unknown> | undefined): st
69
69
  if (args.source) return oneLine(`${normalizePath(String(args.source))} -> ${normalizePath(String(args.destination ?? ""))}`)
70
70
  if (args.command ?? args.cmd) return oneLine(String(args.command ?? args.cmd).replace(/\s*\n\s*/g, " "))
71
71
  if (name === "bash" && args.check_steps) return oneLine(shellCommandDisplay(args))
72
+ if (name === "generate_image" && args.output_path) return oneLine(normalizePath(String(args.output_path)))
72
73
  if (args.pattern) return oneLine(args.pattern)
73
74
  if (args.query) return oneLine(args.query)
74
75
  if (args.url) return oneLine(args.url)
@@ -89,7 +90,7 @@ const TOOL_ALIASES: Record<string, string> = {
89
90
  read_document: "ReadDocument", read_pdf: "ReadPdf", read_docx: "ReadDocx",
90
91
  current_time: "Time", memory_save: "Memory", memory_review: "MemoryReview", memory_merge: "MemoryMerge",
91
92
  cron_create: "CronCreate", cron_delete: "CronDelete", cron_list: "CronList",
92
- monitor: "Monitor",
93
+ monitor: "Monitor", generate_image: "GenerateImage",
93
94
  }
94
95
 
95
96
  export function getToolAlias(name: string): string {
@@ -108,7 +109,7 @@ const TOOL_ICONS: Record<string, string> = {
108
109
  read_file: "→", write_file: "←", append_file: "+", edit_file: "←", multi_edit: "←",
109
110
  delete_file: "✕", move_file: "↔", execute_command: "$", bash: "$",
110
111
  glob_files: "✱", search_files: "✱", web_search: "◈", http_fetch: "%",
111
- agent: "◇", list_directory: "→",
112
+ agent: "◇", list_directory: "→", generate_image: "▧",
112
113
  }
113
114
 
114
115
  export function getToolIcon(toolName: string): string {
@@ -1,4 +1,4 @@
1
- import { readFile, writeFile, readdir, mkdir, unlink, rename, link, stat, lstat, realpath } from "node:fs/promises";
1
+ import { open, readFile, readdir, mkdir, unlink, rename, link, stat, lstat, realpath } from "node:fs/promises";
2
2
  import { lstatSync, realpathSync } from "node:fs";
3
3
  import { basename, dirname, resolve, join, relative, isAbsolute, sep } from "node:path";
4
4
  import { randomBytes } from "node:crypto";
@@ -155,19 +155,29 @@ export function canonicalizeWithNearestExistingAncestorSync(path: string): strin
155
155
  export interface AtomicWriteOptions {
156
156
  /** Fail atomically if the destination appeared after the caller observed it missing. */
157
157
  replaceExisting?: boolean;
158
+ signal?: AbortSignal;
159
+ beforeCommit?: () => void | Promise<void>;
160
+ mode?: number;
158
161
  }
159
162
 
160
163
  /** Write via a same-directory temporary file, then atomically publish it. */
161
164
  export async function atomicWrite(
162
165
  filePath: string,
163
- content: string,
166
+ content: string | Uint8Array,
164
167
  options: AtomicWriteOptions = {},
165
168
  ): Promise<void> {
166
169
  const abs = resolve(filePath);
170
+ options.signal?.throwIfAborted();
167
171
  await mkdir(dirname(abs), { recursive: true });
168
172
  const tmp = `${abs}.tmp.${randomBytes(4).toString("hex")}`;
173
+ let ownsTemporaryFile = false;
169
174
  try {
170
- await writeFile(tmp, content, "utf-8");
175
+ const handle = await open(tmp, "wx", options.mode);
176
+ ownsTemporaryFile = true;
177
+ try { await handle.writeFile(content, { encoding: "utf-8", signal: options.signal }); }
178
+ finally { await handle.close(); }
179
+ await options.beforeCommit?.();
180
+ options.signal?.throwIfAborted();
171
181
  if (options.replaceExisting === false) {
172
182
  // A same-filesystem hard link is an atomic create-if-absent operation.
173
183
  // Unlike rename(), it cannot overwrite a destination created after the
@@ -178,7 +188,7 @@ export async function atomicWrite(
178
188
  }
179
189
  await rename(tmp, abs);
180
190
  } catch (err) {
181
- try { await unlink(tmp); } catch {}
191
+ if (ownsTemporaryFile) try { await unlink(tmp); } catch {}
182
192
  throw err;
183
193
  }
184
194
  }
@@ -0,0 +1,96 @@
1
+ import { access, lstat, mkdir, realpath } from "node:fs/promises";
2
+ import { constants } from "node:fs";
3
+ import { dirname, extname, join } from "node:path";
4
+ import { z } from "zod";
5
+ import type { Tool, ToolResult } from "../tools/types.js";
6
+ import type { GeneratedImage, ImageGenerationRequest } from "../core/providers/codex-image-generation.js";
7
+ import { IMAGE_TIMEOUT_MS } from "../core/providers/codex-image-generation.js";
8
+ import { cacheGeneratedImage, type GeneratedImageMeta } from "../utils/generated-image.js";
9
+ import { atomicWrite, isToolPathWriteAllowed, resolveToolEffectPaths, resolveToolPath, resolveToolPathCanonical, type FileAccessOptions } from "./filesystem.js";
10
+
11
+ export interface GenerateImageOptions extends FileAccessOptions {
12
+ defaultCwd?: string;
13
+ protectedPaths?: string[];
14
+ /** Host-owned model capability: pinned authenticated provider, independently
15
+ * bounded request/response bytes and deadlines, and no automatic retries.
16
+ * Model HTTP uses the provider budget; workspace bytes use execution grants. */
17
+ generate: (request: ImageGenerationRequest, signal?: AbortSignal) => Promise<GeneratedImage>;
18
+ /** Trusted runtime storage, never chosen by model arguments. Retains completed
19
+ * results if a workspace write fails, until the user removes the artifacts. */
20
+ artifactDirectory: string;
21
+ }
22
+
23
+ export function generateImageTool(options: GenerateImageOptions): Tool {
24
+ const cwd = options.defaultCwd ?? process.cwd();
25
+ return {
26
+ definition: {
27
+ name: "generate_image",
28
+ description: "Generate a PNG image with your Codex/ChatGPT account and save it to output_path. Use for illustrations, UI assets, photos, backgrounds and transparent cutouts. Creates a new file; never overwrites an existing file. Generation uses account image limits.",
29
+ prompt: "Use generate_image when the user asks to create an image. Choose a descriptive .png output_path in the workspace, then report the saved image path. Describe the desired visual in prompt; background=transparent produces a cutout. The provider chooses the final pixel dimensions. If a completed image has a local save error, recover the cached artifact reported by the tool instead of generating again. Do not retry a failed or interrupted generation without an explicit user request.",
30
+ parameters: z.object({
31
+ prompt: z.string().min(1).max(16000).describe("Visual description: subject, composition, style and constraints"),
32
+ output_path: z.string().min(1).max(1024).regex(/^[^\x00-\x1f\x7f]+$/).describe("New .png path, relative to the workspace or absolute; an existing file is never replaced"),
33
+ quality: z.enum(["auto", "low", "medium", "high"]).optional(),
34
+ size: z.enum(["auto", "1024x1024", "1536x1024", "1024x1536"]).optional().describe("Requested shape/size; returned dimensions may differ"),
35
+ background: z.enum(["auto", "opaque", "transparent"]).optional(),
36
+ }),
37
+ permission: "confirm", executionLocation: "host", timeoutMs: IMAGE_TIMEOUT_MS + 10_000,
38
+ checkpointTracking: "files",
39
+ writesPath: args => [resolveToolPath(String(args.output_path), cwd)],
40
+ resolveEffects: args => ({
41
+ filesystem: [{ kind: "filesystem", operation: "create", paths: resolveToolEffectPaths(String(args.output_path), cwd) }],
42
+ network: [{ kind: "network", operation: "mutate", destinations: ["https://chatgpt.com/backend-api/codex/responses"], methods: ["POST"] }],
43
+ external: [{ kind: "external", system: "openai:codex:image-generation", operation: "mutate" }],
44
+ process: [], workspace: { mode: "root-integration" }, confidence: "declared",
45
+ }),
46
+ },
47
+ handler: async (args, signal, context) => {
48
+ const path = resolveToolPath(String(args.output_path), cwd);
49
+ let meta: GeneratedImageMeta | undefined;
50
+ let providerCompleted = false;
51
+ try {
52
+ signal?.throwIfAborted();
53
+ if (extname(path).toLowerCase() !== ".png") throw new Error("Image output_path must end in .png.");
54
+ const check = async (expected?: string) => {
55
+ signal?.throwIfAborted();
56
+ if (!(await isToolPathWriteAllowed(path, options, context))) throw new Error("Image output path is outside the granted writable paths or is protected.");
57
+ const canonical = resolveToolPathCanonical(path, cwd);
58
+ if (expected && canonical !== expected) throw new Error("Image output path changed during generation; recover the cached image.");
59
+ try { await lstat(path); throw new Error("Image output already exists. Choose a new .png path; no generation was retried."); }
60
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; }
61
+ return canonical;
62
+ };
63
+ const target = await check();
64
+ // Fail unwritable/missing parents before spending image usage.
65
+ await mkdir(dirname(path), { recursive: true });
66
+ const parent = await realpath(dirname(path));
67
+ await check(target);
68
+ await mkdir(options.artifactDirectory, { recursive: true, mode: 0o700 });
69
+ await access(options.artifactDirectory, constants.W_OK);
70
+ const image = await options.generate({ prompt: String(args.prompt), quality: args.quality as ImageGenerationRequest["quality"],
71
+ size: args.size as ImageGenerationRequest["size"], background: args.background as ImageGenerationRequest["background"] }, signal);
72
+ // Cache only a confirmed provider result. Runtime artifact storage uses
73
+ // the provider's image bound, separately from workspace execution bytes.
74
+ providerCompleted = true;
75
+ const artifact = await cacheGeneratedImage(options.artifactDirectory, image);
76
+ meta = { generatedImage: artifact, providerRequest: { requestBytes: image.requestBytes, responseBytes: image.responseBytes } };
77
+ signal?.throwIfAborted();
78
+ context?.resources?.consumeFiles();
79
+ context?.resources?.consumeFileBytes(image.bytes.length);
80
+ await check(target);
81
+ if (await realpath(dirname(path)) !== parent) throw new Error("Image output directory changed during generation.");
82
+ await atomicWrite(target, image.bytes, { replaceExisting: false, signal, mode: 0o600, beforeCommit: async () => {
83
+ await check(target);
84
+ if (await realpath(dirname(path)) !== parent) throw new Error("Image output directory changed during generation.");
85
+ } });
86
+ artifact.filePath = path;
87
+ return { success: true, output: `Generated image saved to ${path}\nPNG · ${artifact.width}×${artifact.height} · ${image.bytes.length} bytes`, meta,
88
+ contentBlocks: [{ type: "image", filePath: path, mediaType: "image/png", base64: image.bytes.toString("base64"), source: "generate_image" }] };
89
+ } catch (error) {
90
+ const failure = error instanceof Error ? error.message : "Image generation failed.";
91
+ const recovery = meta ? `\nGeneration completed; recover the existing PNG at ${join(options.artifactDirectory, `${meta.generatedImage.id}.png`)}. Do not generate it again.` : providerCompleted ? "\nImage generation completed but persistence failed. Do not generate it again automatically." : "";
92
+ return { success: false, output: recovery.trim(), error: failure + recovery, ...(meta ? { meta } : {}) } satisfies ToolResult;
93
+ }
94
+ },
95
+ };
96
+ }
@@ -21,6 +21,7 @@ import { currentTimeTool } from "./time.js";
21
21
  import { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions } from "./document.js";
22
22
  import { todoWriteTool, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
23
23
  import { askUserQuestionTool, type AskUserToolOptions } from "./ask-user.js";
24
+ import { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
24
25
  import { browserScreenshotTool, type BrowserScreenshotOptions } from "./browser.js";
25
26
  import { enterPlanModeTool, exitPlanModeTool, type PlanModeToolsOptions, type PlanModeCallbacks } from "./plan-mode.js";
26
27
  import { skillTool, type SkillToolOptions } from "./skill.js";
@@ -59,6 +60,7 @@ export { readDocumentTool, readPdfTool, readDocxTool, type DocumentReadOptions }
59
60
  export { todoWriteTool, renderTodoList, type TodoWriteToolOptions, type TodoStore, type Todo, type TodoStatus } from "./todo.js";
60
61
  export { enterPlanModeTool, exitPlanModeTool, type PlanModeToolsOptions, type PlanModeCallbacks } from "./plan-mode.js";
61
62
  export { askUserQuestionTool, type AskUserToolOptions, type AskUserCallbacks, type AskUserQuestion, type AskUserAnswer } from "./ask-user.js";
63
+ export { generateImageTool, type GenerateImageOptions } from "./generate-image.js";
62
64
  export { browserScreenshotTool, findBrowser, type BrowserScreenshotOptions } from "./browser.js";
63
65
  export { skillTool, type SkillToolOptions } from "./skill.js";
64
66
  export {
@@ -97,6 +99,8 @@ export interface BuiltinToolsOptions {
97
99
  listTree?: ListTreeOptions;
98
100
  documentRead?: DocumentReadOptions;
99
101
  browserScreenshot?: BrowserScreenshotOptions;
102
+ /** Only registered when the host supplies an authenticated image capability. */
103
+ generateImage?: GenerateImageOptions;
100
104
  webSearch?: WebSearchOptions;
101
105
  /** Required for the main agent to get `todo_write`. When omitted (e.g.
102
106
  * subagent registries), `todo_write` is not registered — mirrors CCB's
@@ -148,6 +152,7 @@ export function createBuiltinRegistry(options: BuiltinToolsOptions = {}): ToolRe
148
152
  if (!exclude.has("delete_file")) registry.register(deleteFileTool({ defaultCwd, ...options.deleteFile }));
149
153
  if (!exclude.has("move_file")) registry.register(moveFileTool({ defaultCwd, ...options.moveFile }));
150
154
  if (!exclude.has("list_tree")) registry.register(listTreeTool({ defaultCwd, ...options.listTree }));
155
+ if (options.generateImage && !exclude.has("generate_image")) registry.register(generateImageTool({ defaultCwd, ...options.generateImage }));
151
156
  if (!exclude.has("bash")) registry.register(executeCommandTool(options.executeCommand));
152
157
  if (!exclude.has("http_fetch")) registry.register(httpFetchTool(options.httpFetch));
153
158
  if (!exclude.has("http_request")) registry.register(httpRequestTool(options.httpRequest));
@@ -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
+ }