Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(tools): make the hosted codex image_gen tool imagegen's preferred engine (#352)

justrachd4feaf4e3b55
diff --git a/src/imagegen.zig b/src/imagegen.zig
index 1e07c109..e1bcc9c3 100644
--- a/src/imagegen.zig
+++ b/src/imagegen.zig
@@ -1,34 +1,41 @@
//! #352: the `imagegen` tool — text prompt in, one VERIFIED image file out.
//!
-//! Why it is gated (tool_gates.zig) rather than always present: the engine is
-//! not in this binary. It is `scripts/image_gen.py`, shipped with the Codex
-//! `imagegen` skill at $CODEX_HOME/skills/.system/imagegen. When that skill is
-//! not installed there is no image generator on this machine, and advertising
-//! a tool that can only ever answer "not installed" costs schema tokens and a
-//! wasted turn. So the tool appears in the catalogs — root AND subagent — only
-//! after startup finds the skill, at which point graff also mirrors it into
-//! ~/.harness/skills/imagegen so `skill imagegen` loads the playbook that
-//! documents this CLI (imagegen_skill.zig).
+//! Two engines, both real, neither trusted:
+//! * `codex` (preferred, imagegen_codex.zig) drives the hosted `image_gen`
+//! tool through `codex exec`. It rides the user's existing ChatGPT auth, so
+//! it needs no API key and no separately-billed account.
+//! * `openai_api` (fallback, imagegen_openai.zig) runs the Codex imagegen
+//! skill's bundled `scripts/image_gen.py` against the images API. It needs
+//! OPENAI_API_KEY, and it is the only engine that honours the model /
+//! quality / background / output_format knobs.
+//! `auto` prefers codex, except when one of those knobs is set — then it takes
+//! the engine that can actually apply them rather than silently dropping them.
//!
-//! Why it does not shell out to codex: it cannot. The `image_gen` tool the
-//! skill calls "preferred" runs server-side inside the Codex app and never
-//! fires in `codex exec` — during #352 codex 0.141.0 was asked for a 64x64 PNG,
-//! produced none, and reported success anyway by resizing a two-week-old file
-//! out of ~/.codex/generated_images/. The CLI plus OPENAI_API_KEY is the only
-//! path that actually renders anything, so it is the only path here.
+//! Why the tool is gated at all (tool_gates.zig): both engines descend from the
+//! Codex imagegen skill at $CODEX_HOME/skills/.system/imagegen — the fallback
+//! literally runs its script, and the skill is the playbook for driving either.
+//! On a machine without it there is nothing to advertise, so `imagegen` is
+//! absent from every catalog rather than present and permanently apologetic.
//!
-//! Which is also why every success is a receipt rather than a claim: the
-//! result is emitted only after imagegen_verify.zig confirms a file exists at
-//! the requested path, is newer than this call, actually changed if it already
-//! existed, clears a size floor and carries the right container signature.
+//! Why every success is a receipt rather than a claim: during #352 codex 0.141.0
+//! was asked for a 64x64 PNG, could not make one (its model lacked the
+//! image-generation capability, so `image_gen` was never in its tools array),
+//! and reported success anyway — it globbed a two-week-old file out of
+//! ~/.codex/generated_images/, resized it with sips, and wrote "Verified it is
+//! a 64x64 PNG". An md5 comparison is what caught it. That engine does work on
+//! 0.146.0 with an image-capable model, which makes availability a property of
+//! the installed CLI version and the configured model — and makes verification
+//! permanent rather than a phase: imagegen_verify.zig has to confirm a file
+//! exists at the requested path, is newer than this call, changed if it already
+//! existed, clears a size floor, and carries a real container signature. No
+//! branch returns success with a check skipped.
//!
//! Concurrency: one call makes one image, synchronously, fully verified. N
//! images means N subagents (graff's existing fan-out), each calling this once
-//! — rather than a job queue in here that would put the per-image proof back
-//! at arm's length from the agent that has to report it.
+//! — rather than a job queue in here that would put the per-image proof back at
+//! arm's length from the agent that has to report it.
const std = @import("std");
-const builtin = @import("builtin");
const Io = std.Io;
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
@@ -42,60 +49,73 @@ const outsideCwd = tools.outsideCwd;
const approvals_mod = @import("approvals.zig");
const confinedPath = approvals_mod.confinedPath;
const noSymlinkEscape = approvals_mod.noSymlinkEscape;
-const jobs = @import("jobs.zig");
-const util = @import("util.zig");
+const skills = @import("skills.zig");
const skill = @import("imagegen_skill.zig");
const verify = @import("imagegen_verify.zig");
+const run_mod = @import("imagegen_run.zig");
+const codex = @import("imagegen_codex.zig");
+const openai = @import("imagegen_openai.zig");
+const sips = @import("imagegen_sips.zig");
+const select = @import("imagegen_select.zig");
+pub const Engine = select.Engine;
pub const tool_name = "imagegen";
-pub const tool_desc = "Generate an image from a text prompt and write it to one file under the working directory. Backed by the Codex imagegen skill's bundled CLI (scripts/image_gen.py, default model gpt-image-2), which graff copied into ~/.harness/skills/imagegen — load that skill with the skill tool for prompting guidance; it refers to this tool as $imagegen (a provider tool name cannot contain a dollar sign, so it is plain imagegen here). Requires OPENAI_API_KEY in graff's environment: the hosted codex image_gen tool is unavailable outside the Codex app, so there is no keyless path and without the key this generates nothing. Returns the path, byte size, format and pixel size of a VERIFIED freshly generated file — the call only succeeds once the file is proven to exist, to be newer than the call, to clear a size floor and to carry the right image signature, so never report an image this tool did not hand you a verified path for. One call makes one image; for multiple images spawn one subagent per image (each calls imagegen once and reports its verified path back) so the generations run concurrently.";
+pub const tool_desc = "Generate an image from a text prompt and write it to one file under the working directory. Two engines: by default (engine auto) it drives the hosted image_gen tool through your logged-in codex CLI, which needs NO API key; the fallback engine openai_api runs the Codex imagegen skill's bundled scripts/image_gen.py (model gpt-image-2) and does need OPENAI_API_KEY, but it is the only engine that applies the model, quality, background and output_format options. graff copied that skill into ~/.harness/skills/imagegen - load it with the skill tool for prompting guidance; it refers to this tool as $imagegen (a provider tool name cannot contain a dollar sign, so it is plain imagegen here). Every result is freshness-verified by graff itself and never by the generator: the call only succeeds once the file is proven to exist, to be newer than the call, to clear a size floor and to carry a real image signature, so never report an image this tool did not hand you a verified path for. One call makes one image; for multiple images spawn one subagent per image (each calls imagegen once and reports its verified path back) so the generations run concurrently.";
pub const tool_schema =
- \\{"type": "object", "properties": {"prompt": {"type": "string", "description": "What to draw. Be specific about subject, style, composition and background; the imagegen skill's references/prompting.md is worth loading first."}, "out": {"type": "string", "description": "Output file path, relative to the working directory (extension picks the container: .png, .jpg, .webp). Default: a fresh, collision-proof imagegen-<nonce>.png in the working directory."}, "size": {"type": "string", "description": "Pixel size, e.g. 1024x1024, 1536x1024, 1024x1536, or auto (default)."}, "model": {"type": "string", "description": "Image model. Default gpt-image-2; use gpt-image-1.5 for true model-native transparency."}, "quality": {"type": "string", "description": "low, medium (default) or high."}, "background": {"type": "string", "description": "transparent or opaque. Transparency needs a transparency-capable model and a png or webp output."}, "output_format": {"type": "string", "description": "png, jpeg or webp. Defaults to the extension of out."}}, "required": ["prompt"]}
+ \\{"type": "object", "properties": {"prompt": {"type": "string", "description": "What to draw. Be specific about subject, style, composition and background; the imagegen skill's references/prompting.md is worth loading first."}, "out": {"type": "string", "description": "Output file path, relative to the working directory. Default: a fresh, collision-proof imagegen-<nonce>.png in the working directory."}, "engine": {"type": "string", "enum": ["auto", "codex", "openai_api"], "description": "Which generator to use. auto (default) prefers codex - the hosted image_gen tool via your logged-in codex CLI, no API key needed - and falls back to the OPENAI_API_KEY CLI. The options below marked openai_api-only select that engine."}, "size": {"type": "string", "description": "Pixel size, e.g. 1024x1024 or 1024x1536. Both engines support it (the codex engine generates at native size and graff resizes the result itself)."}, "model": {"type": "string", "description": "openai_api-only. Image model; default gpt-image-2, or gpt-image-1.5 for true model-native transparency."}, "quality": {"type": "string", "description": "openai_api-only. low, medium (default) or high."}, "background": {"type": "string", "description": "openai_api-only. transparent or opaque."}, "output_format": {"type": "string", "description": "openai_api-only. png, jpeg or webp. The codex engine always produces png."}}, "required": ["prompt"]}
;
/// Set once at startup by `detect`, then read by every catalog assembly and by
/// dispatch. Process-global for the same reason the #330 gate is: subagents,
-/// workflow workers and judges all run in-process, so one flag covers the
-/// whole agent tree with nothing per-agent to forget to inherit.
+/// workflow workers and judges all run in-process, so one flag covers the whole
+/// agent tree with nothing per-agent to forget to inherit.
pub var available: bool = false;
-/// Absolute path to the `image_gen.py` we will actually run (the mirrored copy
-/// when the mirror succeeded, otherwise Codex's own).
-pub var script_path: []const u8 = "";
-/// Directory that script came from, for the tool's own error text.
+/// Directory the mirrored (or, if the mirror failed, the original) skill lives
+/// in — reported at startup, and where the fallback engine's script comes from.
pub var skill_dir: []const u8 = "";
-/// Whether OPENAI_API_KEY was set in graff's environment at startup. Captured
-/// there because that is where the environment map lives; graff never mutates
-/// its own environment, so this cannot go stale mid-session.
+/// `image_gen.py` for the openai_api engine.
+pub var script_path: []const u8 = "";
+/// OPENAI_API_KEY was set in graff's environment at startup. Captured there
+/// because that is where the environment map lives; graff never mutates its own
+/// environment, so this cannot go stale mid-session.
pub var api_key_present: bool = false;
+/// A `codex` binary is on PATH and $CODEX_HOME/auth.json exists.
+pub var codex_ready: bool = false;
+/// $CODEX_HOME/generated_images — where graff goes looking for the artifact.
+pub var save_root: []const u8 = "";
+/// Parent for the private empty cwd each codex run gets.
+pub var scratch_root: []const u8 = "/tmp";
+
+/// Everything `detect` needs from the environment, by value rather than as a
+/// map, so a test can drive it with plain strings.
+pub const Env = struct {
+ codex_home: ?[]const u8 = null,
+ home: ?[]const u8 = null,
+ openai_api_key: ?[]const u8 = null,
+ tmp_dir: ?[]const u8 = null,
+};
-pub const default_model = "gpt-image-2";
-/// One generation is a network round trip through an image model; 4 minutes is
-/// generous for the slowest (high quality, large size) and still bounded, so a
-/// hung request cannot pin a pool thread for the rest of the session.
-pub const deadline_ms: u64 = 240 * 1000;
-const stdout_cap = 64 * 1024;
-const stderr_cap = 32 * 1024;
-/// How much generator stderr rides along with a failure. Enough for a stack
-/// trace or an API error body, not enough to flood the context.
-const stderr_tail_cap = 1600;
-
-/// Find the Codex skill, mirror it, and decide whether the tool exists this
-/// session. Called once at startup, before the skill scan and before any tool
-/// catalog is rendered. Takes the two environment values it needs by value
-/// rather than an environ map, so a test can drive it with plain strings.
-pub fn detect(io: Io, arena: Allocator, codex_home: ?[]const u8, home: ?[]const u8, api_key: ?[]const u8) void {
+/// Find the Codex skill, mirror it, work out which engines this machine can
+/// actually run, and decide whether the tool exists this session. Called once
+/// at startup, before the skill scan and before any tool catalog is rendered.
+pub fn detect(io: Io, arena: Allocator, env: Env) void {
available = false;
script_path = "";
skill_dir = "";
- api_key_present = if (api_key) |value| value.len > 0 else false;
+ save_root = "";
+ codex_ready = false;
+ api_key_present = if (env.openai_api_key) |value| value.len > 0 else false;
+ if (env.tmp_dir) |t| if (t.len > 0) {
+ scratch_root = std.mem.trimEnd(u8, t, "/");
+ };
- const src = skill.codexSkillDir(arena, codex_home, home) orelse return;
+ const src = skill.codexSkillDir(arena, env.codex_home, env.home) orelse return;
if (!skill.present(io, arena, src)) return; // no Codex skill -> no tool
// Prefer the mirrored copy: it is the one `skill imagegen` loads, so tool
// and playbook stay the same version. A failed mirror (read-only HOME, a
// half-copied tree) must not cost us the tool — fall back to Codex's own.
- if (skill.installDir(arena, home)) |dest| {
+ if (skill.installDir(arena, env.home)) |dest| {
if (skill.needsSync(io, arena, src, dest)) skill.sync(io, arena, src, dest) catch {};
if (engineScript(io, arena, dest)) |path| {
script_path = path;
@@ -106,9 +126,32 @@ pub fn detect(io: Io, arena: Allocator, codex_home: ?[]const u8, home: ?[]const
script_path = engineScript(io, arena, src) orelse return;
skill_dir = src;
}
+ detectCodex(io, arena, env);
available = true;
}
+/// The codex engine needs the CLI itself AND a login: `codex exec` without an
+/// auth.json only ever produces an interactive login prompt, which in a tool
+/// call is an unkillable hang rather than an error.
+fn detectCodex(io: Io, arena: Allocator, env: Env) void {
+ const codex_home = skill.codexHomeDir(arena, env.codex_home, env.home) orelse return;
+ const auth = std.fmt.allocPrint(arena, "{s}/auth.json", .{codex_home}) catch return;
+ _ = Io.Dir.cwd().statFile(io, auth, .{}) catch return;
+ if (!skills.binOnPath(io, "codex")) return;
+ save_root = std.fmt.allocPrint(arena, "{s}/{s}", .{ codex_home, codex.save_root_rel }) catch return;
+ codex_ready = true;
+}
+
+/// Which engines this session can actually run, for the startup line. A
+/// detected tool with no usable engine says so up front rather than waiting
+/// for the model to discover it mid-turn.
+pub fn engineSummary() []const u8 {
+ if (codex_ready and api_key_present) return "codex + openai_api";
+ if (codex_ready) return "codex engine";
+ if (api_key_present) return "openai_api engine";
+ return "NO usable engine: needs `codex login` or OPENAI_API_KEY";
+}
+
fn engineScript(io: Io, arena: Allocator, dir: []const u8) ?[]const u8 {
const path = std.fmt.allocPrint(arena, "{s}/scripts/image_gen.py", .{dir}) catch return null;
const st = Io.Dir.cwd().statFile(io, path, .{}) catch return null;
@@ -116,94 +159,10 @@ fn engineScript(io: Io, arena: Allocator, dir: []const u8) ?[]const u8 {
return path;
}
-pub const Args = struct {
- prompt: []const u8,
- out: []const u8,
- model: []const u8 = default_model,
- size: ?[]const u8 = null,
- quality: ?[]const u8 = null,
- background: ?[]const u8 = null,
- output_format: ?[]const u8 = null,
-};
-
-/// `python3 <script> generate --prompt <p> --out <path> --force --model <m> …`
-///
-/// `--force` because the caller may have named a path that exists and the CLI
-/// would otherwise refuse; whether the rewrite actually happened is not the
-/// CLI's word to take, it is what verification decides afterwards.
-pub fn buildArgv(arena: Allocator, script: []const u8, a: Args) ![]const []const u8 {
- var argv: std.ArrayList([]const u8) = .empty;
- try argv.appendSlice(arena, &.{
- "python3", script, "generate",
- "--prompt", a.prompt, "--out",
- a.out, "--force", "--model",
- a.model,
- });
- if (a.size) |v| try argv.appendSlice(arena, &.{ "--size", v });
- if (a.quality) |v| try argv.appendSlice(arena, &.{ "--quality", v });
- if (a.background) |v| try argv.appendSlice(arena, &.{ "--background", v });
- if (a.output_format) |v| try argv.appendSlice(arena, &.{ "--output-format", v });
- return argv.items;
-}
-
-/// Optional values land straight in an argv slot, so they must not be able to
-/// impersonate a flag or smuggle a second argument. The real vocabulary here
-/// is short (1024x1024, high, transparent, gpt-image-1.5), so the allowed
-/// characters can be narrow.
-pub fn okFlagValue(value: []const u8) bool {
- if (value.len == 0 or value.len > 64) return false;
- if (value[0] == '-') return false;
- for (value) |c| switch (c) {
- 'a'...'z', 'A'...'Z', '0'...'9', '_', '-', '.' => {},
- else => return false,
- };
- return true;
-}
-
-/// Distinguishes concurrent default output paths. Two subagents generating
-/// into the same cwd in the same second is the normal case for the fan-out
-/// pattern this tool documents, so a timestamp is not enough: 80 bits of
-/// CSPRNG entropy separates processes, and the process-lifetime counter
-/// separates same-process callers even if the RNG were to repeat.
-var out_seq: std.atomic.Value(u32) = .init(0);
-const nonce_len = 20 + 1 + 8; // hex(10 bytes) + '-' + hex(u32)
-
-pub fn makeNonce(io: Io, buf: *[nonce_len]u8) []const u8 {
- const seq = out_seq.fetchAdd(1, .monotonic);
- var raw: [10]u8 = undefined;
- io.randomSecure(&raw) catch {
- // Never fall back to something a sibling could reproduce: the clock
- // plus the counter still differ per call.
- const ns: u128 = @bitCast(@as(i128, Io.Timestamp.now(io, .real).nanoseconds));
- std.mem.writeInt(u64, raw[0..8], @truncate(ns), .little);
- std.mem.writeInt(u16, raw[8..10], @truncate(seq), .little);
- };
- const hex = std.fmt.bytesToHex(raw, .lower);
- return std.fmt.bufPrint(buf, "{s}-{x:0>8}", .{ &hex, seq }) catch buf[0..0];
-}
-
-/// A cwd-relative path that does not exist yet. `base` is the agent's isolated
-/// worktree when it has one, so the existence check looks where the file will
-/// actually be written.
-pub fn defaultOutPath(io: Io, arena: Allocator, base: ?[]const u8, ext: []const u8) ![]const u8 {
- var attempt: u8 = 0;
- while (attempt < 8) : (attempt += 1) {
- var buf: [nonce_len]u8 = undefined;
- const rel = try std.fmt.allocPrint(arena, "imagegen-{s}.{s}", .{ makeNonce(io, &buf), ext });
- const full: []const u8 = if (base) |b| try std.fmt.allocPrint(arena, "{s}/{s}", .{ b, rel }) else rel;
- if (Io.Dir.cwd().statFile(io, full, .{})) |_| continue else |_| return rel;
- }
- return error.PathAlreadyExists;
-}
-
fn errText(gpa: Allocator, text: []const u8) !ToolOutput {
return .{ .text = try gpa.dupe(u8, text), .is_error = true };
}
-const unavailable_text = "imagegen is not available in this session: graff did not find the Codex imagegen skill at $CODEX_HOME/skills/.system/imagegen (CODEX_HOME defaults to ~/.codex), and its scripts/image_gen.py is the only image generator this harness can run. Install the Codex imagegen skill and restart graff. Do not substitute an existing file for a generated one.";
-
-const no_key_text = "imagegen needs OPENAI_API_KEY exported in graff's environment, and it was not set when this session started. The tool runs the Codex imagegen skill's scripts/image_gen.py CLI, which is the only image engine available here: the hosted codex image_gen tool is server-side and never fires outside the Codex app (issue #352), so there is no keyless path. NOTHING was generated — do not report an image, and do not pass off an existing file as one. Export OPENAI_API_KEY, restart graff, then call imagegen again.";
-
/// Runs on a pool thread. Every failure is an is_error result; there is no
/// branch that returns success without the full verification passing.
pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
@@ -211,27 +170,41 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
const io = ctx.io;
// Layer 2 of the gate: refuse a name a provider hallucinated from an
// earlier session even though it was never advertised here.
- if (!available or script_path.len == 0) return errText(gpa, unavailable_text);
+ if (!available) return errText(gpa, select.no_skill_text);
const prompt = strField(input, "prompt") orelse return missingArg(gpa, "prompt");
if (std.mem.trim(u8, prompt, " \t\r\n").len == 0)
return errText(gpa, "prompt must not be empty — describe the image to generate");
- if (!api_key_present) return errText(gpa, no_key_text);
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
const arena = arena_state.allocator();
- var args: Args = .{ .prompt = prompt, .out = "" };
+ var args: openai.Args = .{ .prompt = prompt, .out = "" };
inline for (.{ "model", "size", "quality", "background", "output_format" }) |field| {
if (strField(input, field)) |value| {
- if (!okFlagValue(value)) return .{
+ if (!openai.okFlagValue(value)) return .{
.text = try std.fmt.allocPrint(gpa, "invalid {s} value '{s}' — letters, digits, dot, dash and underscore only (e.g. size 1024x1024, quality high, model gpt-image-1.5)", .{ field, value }),
.is_error = true,
};
if (comptime std.mem.eql(u8, field, "model")) args.model = value else @field(args, field) = value;
}
}
+ // parseEngine maps both "auto" and garbage to null, so the name is checked
+ // first — an unrecognised engine must be an error, not a silent auto.
+ const requested: ?Engine = if (strField(input, "engine")) |name| blk: {
+ if (!select.knownEngineName(name)) return .{
+ .text = try std.fmt.allocPrint(gpa, "unknown engine '{s}' — use auto, codex or openai_api", .{name}),
+ .is_error = true,
+ };
+ break :blk select.parseEngine(name);
+ } else null;
+ const tuned = select.firstTunedParam(input);
+ const engine = switch (select.choose(requested, codex_ready, api_key_present and script_path.len > 0, tuned != null)) {
+ .use => |e| e,
+ .refuse => |reason| return .{ .text = try select.refusalText(gpa, reason, tuned), .is_error = true },
+ };
+
const explicit_format: ?verify.Format = if (args.output_format) |name|
verify.Format.fromName(name) orelse return .{
.text = try std.fmt.allocPrint(gpa, "unsupported output_format '{s}' — use png, jpeg or webp", .{name}),
@@ -239,6 +212,15 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
}
else
null;
+ // The hosted image_gen tool has no size parameter, so for that engine graff
+ // resizes afterwards — which means the value has to be one sips accepts.
+ const resize_to: ?sips.Size = if (engine == .codex) blk: {
+ const text = args.size orelse break :blk null;
+ break :blk sips.parseSize(text) orelse return .{
+ .text = try std.fmt.allocPrint(gpa, "the codex engine generates at native size and graff resizes with sips, which needs a concrete <width>x<height> — '{s}' is not one. Use e.g. 1024x1024, or pass engine \"openai_api\" (which accepts auto).", .{text}),
+ .is_error = true,
+ };
+ } else null;
const out_rel = if (strField(input, "out")) |p|
p
@@ -246,7 +228,6 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
defaultOutPath(io, arena, ctx.agent_cwd, if (explicit_format) |f| f.label() else "png") catch
return errText(gpa, "could not pick an unused default output path — pass out explicitly");
if (!confinedPath(out_rel) or !noSymlinkEscape(io, out_rel, ctx.agent_cwd)) return outsideCwd(gpa, out_rel);
- const format = explicit_format orelse verify.Format.fromPath(out_rel);
// #276 P0-1: a worktree-isolated agent writes inside its own worktree.
const resolved: []const u8 = if (ctx.agent_cwd) |base|
try std.fmt.allocPrint(arena, "{s}/{s}", .{ base, out_rel })
@@ -255,143 +236,193 @@ pub fn execImagegen(ctx: ToolCtx, input: Value) !ToolOutput {
args.out = resolved;
const before = verify.snapshot(io, resolved);
- // Taken BEFORE the spawn: anything the generator produces must be at least
+ // Taken BEFORE the spawn: anything a generator produces must be at least
// this new, and a file older than this is by definition not from this run.
const started_ns = Io.Timestamp.now(io, .real).nanoseconds;
- const argv = try buildArgv(arena, script_path, args);
- const run = jobs.runCappedWithOptions(gpa, io, argv, stdout_cap, stderr_cap, deadline_ms, jobs.toolRunOptions(ctx.agent_cwd)) catch |err| switch (err) {
- error.FileNotFound => return errText(gpa, "python3 is not on PATH, so the imagegen CLI cannot run. Install Python 3, then call imagegen again. Nothing was generated."),
- else => return tools.failure(gpa, err),
- };
- defer {
- gpa.free(run.stdout);
- gpa.free(run.stderr);
- }
- const err_tail = tail(run.stderr, stderr_tail_cap);
-
- if (run.cancelled) return .{ .text = try gpa.dupe(u8, "imagegen was cancelled — nothing was generated"), .is_error = true, .cancelled = true };
- if (run.timed_out) return .{
- .text = try std.fmt.allocPrint(gpa, "imagegen timed out after {d}s and the generator was killed — nothing verified was produced. Retry, or try a smaller size or lower quality.\nstderr tail:\n{s}", .{ deadline_ms / 1000, err_tail }),
- .is_error = true,
- };
- const exited: ?u8 = if (run.term == .exited) run.term.exited else null;
- if (exited == null or exited.? != 0) return .{
- .text = try std.fmt.allocPrint(gpa, "imagegen failed: {s} exited {?d}. Nothing was generated — do not report an image.\nstderr tail:\n{s}", .{ std.fs.path.basename(script_path), exited, err_tail }),
- .is_error = true,
+ const produced: verify.Format = switch (engine) {
+ .codex => switch (try runCodex(gpa, arena, io, prompt, resolved, started_ns)) {
+ .ok => |f| f,
+ .fail => |out| return out,
+ },
+ .openai_api => switch (try runOpenai(gpa, arena, io, ctx.agent_cwd, args)) {
+ .ok => explicit_format orelse verify.Format.fromPath(out_rel),
+ .fail => |out| return out,
+ },
};
- // Exit 0 is where #352's fabrication began, so it proves nothing on its own.
+ // Same verification for both engines, on the file the caller will open.
var head_buf: [16]u8 = undefined;
const after: ?verify.Snapshot = blk: {
const shot = verify.snapshot(io, resolved);
break :blk if (shot.existed) shot else null;
};
- const head = headBytes(io, resolved, &head_buf);
- const verdict = verify.evaluate(before, after, started_ns, head, format);
+ const verdict = verify.evaluate(before, after, started_ns, headBytes(io, resolved, &head_buf), produced);
if (verdict != .ok) return .{
.text = try std.fmt.allocPrint(
gpa,
- "imagegen could NOT verify a freshly generated image and is therefore reporting failure, even though the generator exited 0.\nfailed check: {s}\nwhat that means: {s}\npath: {s}\nDo not claim an image was produced, and do not substitute another file for it.\nstderr tail:\n{s}",
- .{ verdict.failedCheck(), verdict.detail(), out_rel, err_tail },
+ "imagegen could NOT verify a freshly generated image and is therefore reporting failure, even though the {s} engine reported success.\nfailed check: {s}\nwhat that means: {s}\npath: {s}\nDo not claim an image was produced, and do not substitute another file for it.",
+ .{ @tagName(engine), verdict.failedCheck(), verdict.detail(), out_rel },
),
.is_error = true,
};
- const size_bytes = after.?.size;
- const dims = pixelDims(arena, io, resolved);
+ // Resize last, on the already-verified copy, with graff's own hands (#352:
+ // leaving the resize to the model is how a stale file became "64x64").
+ var note: []const u8 = "";
+ if (resize_to) |size| if (!sips.resize(arena, io, resolved, size)) {
+ note = if (sips.available)
+ " — WARNING: the requested resize failed, so this is the native-size image"
+ else
+ " — note: native size (the codex engine cannot request a size, and sips resizing is macOS-only)";
+ };
+ const measured = sips.dims(arena, io, resolved);
+ const final = verify.snapshot(io, resolved);
return .{ .text = try std.fmt.allocPrint(
gpa,
- "generated and verified: {s} ({d} bytes, {s}{s}, model {s}). Checks passed: file exists, mtime is newer than this call, size above the {d}-byte floor, and the leading bytes match the {s} signature.",
- .{ out_rel, size_bytes, format.label(), dims orelse "", args.model, verify.min_bytes, format.label() },
+ "generated and verified: {s} ({d} bytes, {s}{s}, engine {s}){s}. Checks passed: the file exists, its mtime is newer than this call, its size is above the {d}-byte floor, and its leading bytes match the {s} signature.",
+ .{
+ out_rel,
+ final.size,
+ produced.label(),
+ if (measured) |m| try std.fmt.allocPrint(arena, ", {d}x{d} px", .{ m.w, m.h }) else "",
+ @tagName(engine),
+ note,
+ verify.min_bytes,
+ produced.label(),
+ },
) };
}
-fn headBytes(io: Io, path: []const u8, buf: []u8) []const u8 {
- const file = Io.Dir.cwd().openFile(io, path, .{}) catch return &.{};
- defer file.close(io);
- const n = file.readPositionalAll(io, buf, 0) catch return &.{};
- return buf[0..n];
+const EngineResult = union(enum) { ok: verify.Format, fail: ToolOutput };
+
+/// The codex engine: spawn, then do every piece of artifact handling ourselves.
+fn runCodex(gpa: Allocator, arena: Allocator, io: Io, prompt: []const u8, resolved: []const u8, started_ns: i128) !EngineResult {
+ if (save_root.len == 0) return .{ .fail = try errText(gpa, select.no_skill_text) };
+ // A private empty cwd: --sandbox workspace-write makes the working
+ // directory writable, and an image generation has no business being able
+ // to write into the repo it was called from.
+ const scratch = makeScratch(io, arena) orelse
+ return .{ .fail = try errText(gpa, "could not create a private scratch directory for the codex engine — set TMPDIR to a writable location, or pass engine \"openai_api\". Nothing was generated.") };
+ defer Io.Dir.cwd().deleteTree(io, scratch) catch {};
+
+ const argv = try codex.buildArgv(arena, try codex.buildPrompt(arena, prompt));
+ const out = run_mod.run(arena, io, argv, codex.deadline_ms, scratch) catch |err| switch (err) {
+ error.FileNotFound => return .{ .fail = try errText(gpa, "the codex CLI is no longer on PATH, so the preferred imagegen engine cannot run. Reinstall it (bun install -g @openai/codex) or pass engine \"openai_api\". Nothing was generated.") },
+ else => return .{ .fail = tools.failure(gpa, err) },
+ };
+ const tails = try std.fmt.allocPrint(arena, "{s}\n{s}", .{ run_mod.tail(out.stdout, 900), run_mod.tail(out.stderr, 900) });
+
+ if (out.cancelled) return .{ .fail = .{ .text = try gpa.dupe(u8, "imagegen was cancelled — nothing was generated"), .is_error = true, .cancelled = true } };
+ if (out.timed_out) return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "the codex engine timed out after {d}s and was killed — nothing verified was produced.\ntranscript tail:\n{s}", .{ codex.deadline_ms / 1000, tails }),
+ .is_error = true,
+ } };
+ if (codex.tooOld(out.stdout) or codex.tooOld(out.stderr)) return .{ .fail = try errText(gpa, codex.too_old_text) };
+ if (codex.saidUnavailable(out.stdout)) return .{ .fail = try errText(gpa, codex.unavailable_text) };
+ if (!out.ranClean()) return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "codex exec failed (exit {?d}) — nothing was generated.\ntranscript tail:\n{s}", .{ out.exit_code, tails }),
+ .is_error = true,
+ } };
+
+ // Exit 0 proves nothing — #352 WAS exit 0, with a confident transcript.
+ // The artifact on disk is the only evidence that counts.
+ const floor = codex.freshnessFloor(started_ns);
+ const art = codex.newestFresh(io, arena, save_root, floor) orelse return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "{s}\ntranscript tail:\n{s}", .{ codex.no_artifact_text, tails }),
+ .is_error = true,
+ } };
+
+ var head_buf: [16]u8 = undefined;
+ const head = headBytes(io, art.path, &head_buf);
+ const produced = verify.Format.detect(head) orelse return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "codex left a fresh file at {s} but its leading bytes are not a PNG, JPEG or WebP, so it is not an image. Nothing usable was generated.", .{art.path}),
+ .is_error = true,
+ } };
+ const verdict = verify.evaluate(.{}, .{ .existed = true, .size = art.size, .mtime_ns = art.mtime_ns }, floor, head, produced);
+ if (verdict != .ok) return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "the file codex produced failed verification.\nfailed check: {s}\nwhat that means: {s}\nartifact: {s}", .{ verdict.failedCheck(), verdict.detail(), art.path }),
+ .is_error = true,
+ } };
+
+ Io.Dir.cwd().copyFile(art.path, Io.Dir.cwd(), resolved, io, .{ .make_path = true }) catch |err| return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "codex generated a verified image at {s} but graff could not copy it to {s}: {t}", .{ art.path, resolved, err }),
+ .is_error = true,
+ } };
+ return .{ .ok = produced };
}
-/// The LAST bytes of the generator's stderr — a Python traceback puts the
-/// useful line at the end, and an API error body is short.
-fn tail(text: []const u8, cap: usize) []const u8 {
- if (text.len <= cap) return text;
- const cut = text[text.len - cap ..];
- // Start at a line boundary so the excerpt does not open mid-UTF-8.
- return if (std.mem.indexOfScalar(u8, cut, '\n')) |nl| cut[nl + 1 ..] else cut;
+/// The fallback engine: the CLI writes the output path itself.
+fn runOpenai(gpa: Allocator, arena: Allocator, io: Io, agent_cwd: ?[]const u8, args: openai.Args) !EngineResult {
+ const argv = try openai.buildArgv(arena, script_path, args);
+ const out = run_mod.run(arena, io, argv, openai.deadline_ms, agent_cwd) catch |err| switch (err) {
+ error.FileNotFound => return .{ .fail = try errText(gpa, openai.no_python_text) },
+ else => return .{ .fail = tools.failure(gpa, err) },
+ };
+ const err_tail = run_mod.tail(out.stderr, 1600);
+ if (out.cancelled) return .{ .fail = .{ .text = try gpa.dupe(u8, "imagegen was cancelled — nothing was generated"), .is_error = true, .cancelled = true } };
+ if (out.timed_out) return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "imagegen timed out after {d}s and the generator was killed — nothing verified was produced. Retry, or try a smaller size or lower quality.\nstderr tail:\n{s}", .{ openai.deadline_ms / 1000, err_tail }),
+ .is_error = true,
+ } };
+ if (!out.ranClean()) return .{ .fail = .{
+ .text = try std.fmt.allocPrint(gpa, "imagegen failed: image_gen.py exited {?d}. Nothing was generated — do not report an image.\nstderr tail:\n{s}", .{ out.exit_code, err_tail }),
+ .is_error = true,
+ } };
+ return .{ .ok = .png }; // the caller substitutes the requested container
}
-/// Pixel dimensions, macOS only and strictly best-effort: this is extra
-/// reporting detail, never part of the pass/fail decision.
-fn pixelDims(arena: Allocator, io: Io, path: []const u8) ?[]const u8 {
- if (builtin.os.tag != .macos) return null;
- const run = jobs.runCapped(arena, io, &.{ "sips", "-g", "pixelWidth", "-g", "pixelHeight", path }, 4096, 1024, 10_000) catch return null;
- if (run.term != .exited or run.term.exited != 0) return null;
- const w = fieldAfter(run.stdout, "pixelWidth:") orelse return null;
- const h = fieldAfter(run.stdout, "pixelHeight:") orelse return null;
- return std.fmt.allocPrint(arena, ", {s}x{s} px", .{ w, h }) catch null;
+fn makeScratch(io: Io, arena: Allocator) ?[]const u8 {
+ var buf: [nonce_len]u8 = undefined;
+ const path = std.fmt.allocPrint(arena, "{s}/graff-imagegen-{s}", .{ scratch_root, makeNonce(io, &buf) }) catch return null;
+ Io.Dir.cwd().createDirPath(io, path) catch return null;
+ return path;
}
-fn fieldAfter(text: []const u8, key: []const u8) ?[]const u8 {
- const at = std.mem.indexOf(u8, text, key) orelse return null;
- const rest = text[at + key.len ..];
- const line_end = std.mem.indexOfScalar(u8, rest, '\n') orelse rest.len;
- const value = std.mem.trim(u8, rest[0..line_end], " \t\r");
- return if (value.len > 0 and value.len < 12) value else null;
+fn headBytes(io: Io, path: []const u8, buf: []u8) []const u8 {
+ const file = Io.Dir.cwd().openFile(io, path, .{}) catch return &.{};
+ defer file.close(io);
+ const n = file.readPositionalAll(io, buf, 0) catch return &.{};
+ return buf[0..n];
}
-const testing = std.testing;
+/// Distinguishes concurrent default output paths and scratch directories. Two
+/// subagents generating into the same cwd in the same second is the normal case
+/// for the fan-out pattern this tool documents, so a timestamp is not enough:
+/// 80 bits of CSPRNG entropy separates processes, and the process-lifetime
+/// counter separates same-process callers even if the RNG were to repeat.
+var out_seq: std.atomic.Value(u32) = .init(0);
+const nonce_len = 20 + 1 + 8; // hex(10 bytes) + '-' + hex(u32)
-test "#352: argv is a generate call with the required flags, optionals only when given" {
- var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
- defer arena_state.deinit();
- const arena = arena_state.allocator();
+pub fn makeNonce(io: Io, buf: *[nonce_len]u8) []const u8 {
+ const seq = out_seq.fetchAdd(1, .monotonic);
+ var raw: [10]u8 = undefined;
+ io.randomSecure(&raw) catch {
+ // Never fall back to something a sibling could reproduce: the clock
+ // plus the counter still differ per call.
+ const ns: u128 = @bitCast(@as(i128, Io.Timestamp.now(io, .real).nanoseconds));
+ std.mem.writeInt(u64, raw[0..8], @truncate(ns), .little);
+ std.mem.writeInt(u16, raw[8..10], @truncate(seq), .little);
+ };
+ const hex = std.fmt.bytesToHex(raw, .lower);
+ return std.fmt.bufPrint(buf, "{s}-{x:0>8}", .{ &hex, seq }) catch buf[0..0];
+}
- const minimal = try buildArgv(arena, "/s/image_gen.py", .{ .prompt = "a red circle", .out = "out.png" });
- try testing.expectEqualStrings("python3", minimal[0]);
- try testing.expectEqualStrings("/s/image_gen.py", minimal[1]);
- try testing.expectEqualStrings("generate", minimal[2]);
- try testing.expectEqualStrings("--prompt", minimal[3]);
- try testing.expectEqualStrings("a red circle", minimal[4]);
- try testing.expectEqualStrings("--out", minimal[5]);
- try testing.expectEqualStrings("out.png", minimal[6]);
- try testing.expectEqualStrings("--force", minimal[7]);
- try testing.expectEqualStrings("--model", minimal[8]);
- try testing.expectEqualStrings(default_model, minimal[9]);
- try testing.expectEqual(@as(usize, 10), minimal.len); // no stray optional flags
-
- const full = try buildArgv(arena, "/s/image_gen.py", .{
- .prompt = "p",
- .out = "o.webp",
- .model = "gpt-image-1.5",
- .size = "1024x1536",
- .quality = "high",
- .background = "transparent",
- .output_format = "webp",
- });
- try testing.expectEqual(@as(usize, 18), full.len);
- for ([_][]const u8{ "--size", "1024x1536", "--quality", "high", "--background", "transparent", "--output-format", "webp" }) |want| {
- var found = false;
- for (full) |arg| {
- if (std.mem.eql(u8, arg, want)) found = true;
- }
- try testing.expect(found);
+/// A cwd-relative path that does not exist yet. `base` is the agent's isolated
+/// worktree when it has one, so the existence check looks where the file will
+/// actually be written.
+pub fn defaultOutPath(io: Io, arena: Allocator, base: ?[]const u8, ext: []const u8) ![]const u8 {
+ var attempt: u8 = 0;
+ while (attempt < 8) : (attempt += 1) {
+ var buf: [nonce_len]u8 = undefined;
+ const rel = try std.fmt.allocPrint(arena, "imagegen-{s}.{s}", .{ makeNonce(io, &buf), ext });
+ const full: []const u8 = if (base) |b| try std.fmt.allocPrint(arena, "{s}/{s}", .{ b, rel }) else rel;
+ if (Io.Dir.cwd().statFile(io, full, .{})) |_| continue else |_| return rel;
}
- // --dry-run is never assembled: it prints a plan and writes no file, so it
- // could only ever produce an unverifiable "success".
- for (full) |arg| try testing.expect(!std.mem.eql(u8, arg, "--dry-run"));
+ return error.PathAlreadyExists;
}
-test "#352: optional values cannot impersonate a flag or smuggle an argument" {
- for ([_][]const u8{ "1024x1024", "auto", "high", "transparent", "gpt-image-1.5", "PNG" }) |ok|
- try testing.expect(okFlagValue(ok));
- for ([_][]const u8{ "", "--out", "-q", "1024 1024", "a;rm -rf /", "$(id)", "a\nb", "a/b" }) |bad|
- try testing.expect(!okFlagValue(bad));
- var long: [65]u8 = @splat('a');
- try testing.expect(!okFlagValue(&long));
-}
+const testing = std.testing;
test "#352: default out paths stay unique across many rapid calls (the subagent fan-out case)" {
const io = testing.io;
@@ -409,31 +440,28 @@ test "#352: default out paths stay unique across many rapid calls (the subagent
for (0..256) |_| {
const path = try defaultOutPath(io, arena, base, "png");
try testing.expect(std.mem.startsWith(u8, path, "imagegen-"));
- try testing.expect(std.mem.endsWith(u8, path, ".png"));
try testing.expect(confinedPath(path)); // a default path is always writable by the file tools
try testing.expect((try seen.fetchPut(testing.allocator, path, {})) == null);
}
- // An existing file at the drawn name is skipped rather than overwritten.
const taken = try defaultOutPath(io, arena, base, "png");
try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ base, taken }), .data = "x" });
try testing.expect(!std.mem.eql(u8, taken, try defaultOutPath(io, arena, base, "png")));
}
-test "#352: detect gates on the Codex skill and mirrors it into the personal tier" {
+test "#352: detect gates on the Codex skill, mirrors it, and decides which engines this machine has" {
const io = testing.io;
var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
- const saved_available = available;
- const saved_script = script_path;
- const saved_dir = skill_dir;
- const saved_key = api_key_present;
+ const saved = .{ available, script_path, skill_dir, api_key_present, codex_ready, save_root };
defer {
- available = saved_available;
- script_path = saved_script;
- skill_dir = saved_dir;
- api_key_present = saved_key;
+ available = saved[0];
+ script_path = saved[1];
+ skill_dir = saved[2];
+ api_key_present = saved[3];
+ codex_ready = saved[4];
+ save_root = saved[5];
}
var tmp = testing.tmpDir(.{});
@@ -445,10 +473,10 @@ test "#352: detect gates on the Codex skill and mirrors it into the personal tie
// A CODEX_HOME with no skill in it: the tool does not exist.
try Io.Dir.cwd().createDirPath(io, codex_home);
- detect(io, arena, codex_home, home, null);
+ detect(io, arena, .{ .codex_home = codex_home, .home = home });
try testing.expect(!available);
try testing.expectEqualStrings("", script_path);
- try testing.expect(!api_key_present); // and the key check is honest about being unset
+ try testing.expect(!api_key_present and !codex_ready);
// Install the skill where Codex keeps it.
const src = try std.fmt.allocPrint(arena, "{s}/{s}", .{ codex_home, skill.codex_rel });
@@ -462,14 +490,14 @@ test "#352: detect gates on the Codex skill and mirrors it into the personal tie
.data = f.data,
});
- detect(io, arena, codex_home, home, "sk-test");
- try testing.expect(available);
- try testing.expect(api_key_present);
- // The mirrored copy is what runs, so tool and playbook are the same version.
+ detect(io, arena, .{ .codex_home = codex_home, .home = home, .openai_api_key = "sk-test" });
+ try testing.expect(available and api_key_present);
+ // No auth.json in this fake CODEX_HOME, so the codex engine is not offered
+ // however the real CLI happens to be installed on the test machine.
+ try testing.expect(!codex_ready);
+
const dest = try std.fmt.allocPrint(arena, "{s}/{s}", .{ home, skill.install_rel });
try testing.expectEqualStrings(dest, skill_dir);
- try testing.expectEqualStrings(try std.fmt.allocPrint(arena, "{s}/scripts/image_gen.py", .{dest}), script_path);
- // …with its license, and with the addendum leading the body.
const license = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/LICENSE.txt", .{dest}), arena, .limited(4096));
try testing.expectEqualStrings("LICENSE BODY", license);
const md = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dest}), arena, .limited(1 << 16));
@@ -478,24 +506,31 @@ test "#352: detect gates on the Codex skill and mirrors it into the personal tie
try testing.expect(std.mem.indexOf(u8, md, "use image_gen") != null); // original body kept
// An empty key is not a key.
- detect(io, arena, codex_home, home, "");
+ detect(io, arena, .{ .codex_home = codex_home, .home = home, .openai_api_key = "" });
try testing.expect(available and !api_key_present);
}
-test "#352: the honest no-key error refuses to generate and says why" {
+test "#352: with no usable engine the tool refuses up front and spawns nothing" {
const gpa = testing.allocator;
- const saved_available = available;
- const saved_script = script_path;
- const saved_key = api_key_present;
+ const saved = .{ available, script_path, api_key_present, codex_ready };
defer {
- available = saved_available;
- script_path = saved_script;
- api_key_present = saved_key;
+ available = saved[0];
+ script_path = saved[1];
+ api_key_present = saved[2];
+ codex_ready = saved[3];
}
+ // Any spawn at all is a test failure: nothing below should reach one.
+ const S = struct {
+ fn boom(_: Allocator, _: Io, _: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
+ return error.TestUnexpectedSpawn;
+ }
+ };
+ const saved_hook = run_mod.hook;
+ defer run_mod.hook = saved_hook;
+ run_mod.hook = S.boom;
var parsed = try std.json.parseFromSlice(Value, gpa, "{\"prompt\":\"a red circle\"}", .{});
defer parsed.deinit();
-
var client: std.http.Client = undefined;
const ctx: ToolCtx = .{
.gpa = gpa,
@@ -508,46 +543,35 @@ test "#352: the honest no-key error refuses to generate and says why" {
.tracer = null,
};
- // Not detected at all: refused before anything is spawned.
available = false;
- script_path = "";
const off = try execImagegen(ctx, parsed.value);
defer gpa.free(off.text);
- try testing.expect(off.is_error);
- try testing.expect(std.mem.indexOf(u8, off.text, "CODEX_HOME") != null);
+ try testing.expect(off.is_error and std.mem.indexOf(u8, off.text, "CODEX_HOME") != null);
- // Detected, but no key: still nothing spawned, and the message says so.
+ // Detected, but neither engine usable: the refusal names both requirements.
available = true;
- script_path = "/nonexistent/image_gen.py"; // never reached
+ codex_ready = false;
api_key_present = false;
- const no_key = try execImagegen(ctx, parsed.value);
- defer gpa.free(no_key.text);
- try testing.expect(no_key.is_error);
- try testing.expect(std.mem.indexOf(u8, no_key.text, "OPENAI_API_KEY") != null);
- try testing.expect(std.mem.indexOf(u8, no_key.text, "#352") != null);
- try testing.expect(std.mem.indexOf(u8, no_key.text, "NOTHING was generated") != null);
-
- // A missing prompt is caught before the key check, as a plain missing-arg.
+ script_path = "/nonexistent/image_gen.py";
+ const none = try execImagegen(ctx, parsed.value);
+ defer gpa.free(none.text);
+ try testing.expect(none.is_error);
+ for ([_][]const u8{ "codex login", "OPENAI_API_KEY", "#352", "NOTHING was generated" }) |needle|
+ try testing.expect(std.mem.indexOf(u8, none.text, needle) != null);
+
var empty = try std.json.parseFromSlice(Value, gpa, "{}", .{});
defer empty.deinit();
const no_prompt = try execImagegen(ctx, empty.value);
defer gpa.free(no_prompt.text);
- try testing.expect(no_prompt.is_error);
- try testing.expect(std.mem.indexOf(u8, no_prompt.text, "prompt") != null);
-}
-
-test "#352: stderr tails keep the end of a traceback and start on a line boundary" {
- try testing.expectEqualStrings("short", tail("short", 100));
- const long = "line one\nline two\nline three\n";
- const cut = tail(long, 14);
- try testing.expect(std.mem.indexOf(u8, cut, "line three") != null);
- try testing.expect(std.mem.indexOf(u8, cut, "line one") == null);
- try testing.expect(std.mem.indexOfScalar(u8, cut, '\n') == null or cut[0] != '\n');
- try testing.expectEqualStrings("1024", fieldAfter(" pixelWidth: 1024\n pixelHeight: 768\n", "pixelWidth:").?);
- try testing.expect(fieldAfter("nothing here", "pixelWidth:") == null);
+ try testing.expect(no_prompt.is_error and std.mem.indexOf(u8, no_prompt.text, "prompt") != null);
}
test {
_ = skill;
_ = verify;
+ _ = select;
+ _ = codex;
+ _ = openai;
+ _ = sips;
+ _ = run_mod;
}
diff --git a/src/imagegen_codex.zig b/src/imagegen_codex.zig
new file mode 100644
index 00000000..9ff7c357
--- /dev/null
+++ b/src/imagegen_codex.zig
@@ -0,0 +1,236 @@
+//! #352: the preferred imagegen engine — the hosted `image_gen` tool, driven
+//! headlessly through `codex exec`.
+//!
+//! This is the engine the #352 investigation concluded did NOT work, and the
+//! conclusion was version-bound rather than wrong. codex 0.141.0 could not run
+//! the only local model carrying the image_generation + namespace_tools
+//! capabilities, so `image_gen` never entered its Responses tools array and the
+//! model — asked for an image it had no way to make — invented one from a
+//! two-week-old file. codex 0.146.0 with gpt-5.6-sol does fire the tool
+//! headlessly and drops a real PNG under $CODEX_HOME/generated_images. Whether
+//! this engine works is therefore a property of the installed CLI version AND
+//! the configured model, which is precisely why nothing here trusts it.
+//!
+//! What graff refuses to trust, concretely:
+//! * the transcript — codex's own words about what it produced are exactly
+//! what fabricated #352, so they are diagnostics and nothing more;
+//! * the exit code — 0 with a chatty success narrative is the fabrication
+//! signature, so a clean exit with no fresh artifact is a hard error;
+//! * the model's file handling — the controlled prompt tells it not to copy,
+//! move or convert anything. graff scans save_root itself, picks the newest
+//! file whose mtime is at or after the spawn, verifies its magic bytes, and
+//! does the copy and any resize with its own hands.
+//!
+//! The child also runs in a private empty scratch directory rather than the
+//! user's checkout: `--sandbox workspace-write` makes the cwd writable, and
+//! there is no reason for an image generation to be able to write into the
+//! repo it was called from.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const run_mod = @import("imagegen_run.zig");
+
+/// A hosted image generation is a slow round trip plus codex's own startup;
+/// 6 minutes is generous and still bounded.
+pub const deadline_ms: u64 = 360 * 1000;
+
+/// Where codex saves what `image_gen` returns, relative to CODEX_HOME.
+pub const save_root_rel = "generated_images";
+
+const max_scan_depth: u8 = 4; // real layout is <save_root>/<session>/<call>.png
+
+/// codex exec, non-interactive, with the feature flag forced on so the tool is
+/// offered even when the user's config.toml never enabled it. The model comes
+/// from the user's own codex config — graff does not pick one, because which
+/// models carry the image capabilities is codex's business, not ours.
+pub fn buildArgv(arena: Allocator, prompt: []const u8) ![]const []const u8 {
+ return arena.dupe([]const u8, &.{
+ "codex", "exec",
+ "--sandbox", "workspace-write",
+ "-c", "features.image_generation=true",
+ prompt,
+ });
+}
+
+/// The instruction codex actually receives. It pins the tool, forbids the file
+/// handling graff is about to do itself, and asks for a short reply so a long
+/// narrative cannot crowd out the stderr tail we keep for diagnostics.
+pub fn buildPrompt(arena: Allocator, user_prompt: []const u8) ![]const u8 {
+ return std.fmt.allocPrint(arena,
+ \\Call the built-in image_gen tool exactly once to generate this image:
+ \\
+ \\{s}
+ \\
+ \\Rules: use the image_gen tool and nothing else. Do NOT copy, move, rename or
+ \\convert any file, do NOT resize the image, and do NOT run shell commands to
+ \\save or inspect it - the program that called you collects the generated file
+ \\itself. If the image_gen tool is not available to you, say exactly
+ \\IMAGE_GEN_UNAVAILABLE and stop. Otherwise reply with one short line once the
+ \\tool call has returned.
+ , .{user_prompt});
+}
+
+pub const Artifact = struct {
+ path: []const u8,
+ size: u64,
+ mtime_ns: i128,
+};
+
+/// The newest regular file under `root` whose mtime is at or after `since_ns`.
+///
+/// This is the anti-fabrication check for this engine: codex writes each
+/// generation to a fresh path under save_root, so a run that produced nothing
+/// leaves nothing new behind no matter how confidently it says otherwise.
+/// `since_ns` should be floored to the second by the caller — some filesystems
+/// truncate mtime, and a genuine artifact must not read as stale because of it.
+///
+/// Dotfiles are skipped: the real save_root on this machine contains a
+/// .DS_Store, and Finder rewriting it must never be mistaken for an image.
+pub fn newestFresh(io: Io, arena: Allocator, root: []const u8, since_ns: i128) ?Artifact {
+ var best: ?Artifact = null;
+ scan(io, arena, root, since_ns, 0, &best);
+ return best;
+}
+
+fn scan(io: Io, arena: Allocator, dir_path: []const u8, since_ns: i128, depth: u8, best: *?Artifact) void {
+ if (depth > max_scan_depth) return;
+ var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return;
+ defer dir.close(io);
+ var it = dir.iterate();
+ while (it.next(io) catch null) |entry| {
+ if (entry.name.len == 0 or entry.name[0] == '.') continue;
+ const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ dir_path, entry.name }) catch continue;
+ switch (entry.kind) {
+ .directory => scan(io, arena, path, since_ns, depth + 1, best),
+ .file => {
+ const st = Io.Dir.cwd().statFile(io, path, .{}) catch continue;
+ if (st.kind != .file) continue;
+ if (st.mtime.nanoseconds < since_ns) continue; // predates this run
+ if (best.*) |cur| {
+ if (st.mtime.nanoseconds <= cur.mtime_ns) continue;
+ }
+ best.* = .{ .path = path, .size = st.size, .mtime_ns = st.mtime.nanoseconds };
+ },
+ else => {},
+ }
+ }
+}
+
+/// Floor to the whole second, so a coarse-granularity filesystem truncating a
+/// genuine artifact's mtime cannot make it read as older than the spawn.
+pub fn freshnessFloor(started_ns: i128) i128 {
+ const s = std.time.ns_per_s;
+ return started_ns - @mod(started_ns, s);
+}
+
+/// codex answers a model it cannot serve with a 400 naming the CLI version.
+/// That is a fixable local problem, so it gets a fixable local answer instead
+/// of a raw transcript dump.
+pub fn tooOld(text: []const u8) bool {
+ return std.mem.indexOf(u8, text, "requires a newer version of Codex") != null or
+ std.mem.indexOf(u8, text, "requires a newer version of codex") != null;
+}
+
+pub const too_old_text = "the installed codex CLI is too old for the model your codex config selects, so the hosted image_gen tool was never offered. Upgrade it (bun install -g @openai/codex) and call imagegen again, or pass engine \"openai_api\" to use the OPENAI_API_KEY path instead. Nothing was generated.";
+
+/// The model told us outright that it had no image_gen tool. Worth its own
+/// message: it is the honest version of what #352 fabricated.
+pub fn saidUnavailable(text: []const u8) bool {
+ return std.mem.indexOf(u8, text, "IMAGE_GEN_UNAVAILABLE") != null;
+}
+
+pub const unavailable_text = "codex ran, but reported that the hosted image_gen tool was not available to it — the model your codex config selects does not carry the image-generation capability. Check `codex features list` shows image_generation stable/true and that your configured model supports it, or pass engine \"openai_api\" to use the OPENAI_API_KEY path. Nothing was generated.";
+
+/// No fresh artifact after a clean exit. This is #352's exact signature, so
+/// the message says so rather than leaving it as a puzzling empty result.
+pub const no_artifact_text = "codex exited successfully but left NO new file under its generated_images directory, so no image was generated no matter what its transcript says. This is the #352 failure mode: the hosted image_gen tool is only offered when the CLI version and the configured model both support it, and a model without it will happily narrate a success it did not perform. Nothing was generated — do not report an image.";
+
+const testing = std.testing;
+
+test "#352: argv forces the feature flag on and runs codex non-interactively" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const argv = try buildArgv(arena, "PROMPT");
+ const want = [_][]const u8{ "codex", "exec", "--sandbox", "workspace-write", "-c", "features.image_generation=true", "PROMPT" };
+ try testing.expectEqual(want.len, argv.len);
+ for (want, argv) |w, got| try testing.expectEqualStrings(w, got);
+ // No model is pinned: which models carry the capability is codex's call.
+ for (argv) |a| try testing.expect(!std.mem.eql(u8, a, "--model") and !std.mem.eql(u8, a, "-m"));
+}
+
+test "#352: the controlled prompt carries the user's text and forbids the file handling graff does itself" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const p = try buildPrompt(arena, "a red circle on white");
+ try testing.expect(std.mem.indexOf(u8, p, "a red circle on white") != null);
+ try testing.expect(std.mem.indexOf(u8, p, "image_gen tool exactly once") != null);
+ for ([_][]const u8{ "Do NOT copy, move, rename or", "do NOT resize", "IMAGE_GEN_UNAVAILABLE" }) |needle|
+ try testing.expect(std.mem.indexOf(u8, p, needle) != null);
+}
+
+test "#352: discovery picks the newest FRESH file, ignores stale ones and dotfiles, and finds nothing when nothing was written" {
+ const io = testing.io;
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const root = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+
+ const day_ns: i128 = 24 * 60 * 60 * std.time.ns_per_s;
+ const now = Io.Timestamp.now(io, .real).nanoseconds;
+ const marker = now - 60 * std.time.ns_per_s; // "this run started a minute ago"
+
+ // Mirror the real layout: <root>/<session>/<call>.png, plus a .DS_Store.
+ const session = try std.fmt.allocPrint(arena, "{s}/019f-session", .{root});
+ try Io.Dir.cwd().createDirPath(io, session);
+ const stale = try std.fmt.allocPrint(arena, "{s}/exec-old.png", .{session});
+ const fresh = try std.fmt.allocPrint(arena, "{s}/exec-new.png", .{session});
+ const fresher = try std.fmt.allocPrint(arena, "{s}/exec-newest.png", .{session});
+ const junk = try std.fmt.allocPrint(arena, "{s}/.DS_Store", .{root});
+ for ([_][]const u8{ stale, fresh, fresher, junk }) |p|
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = p, .data = "\x89PNG\r\n\x1a\n" ++ "payload" });
+
+ // Stale = written two weeks ago; the .DS_Store is fresh but must be skipped.
+ try Io.Dir.cwd().setTimestamps(io, stale, .{ .modify_timestamp = .{ .new = .{ .nanoseconds = @intCast(now - 14 * day_ns) } } });
+ try Io.Dir.cwd().setTimestamps(io, fresh, .{ .modify_timestamp = .{ .new = .{ .nanoseconds = @intCast(now - 30 * std.time.ns_per_s) } } });
+ try Io.Dir.cwd().setTimestamps(io, fresher, .{ .modify_timestamp = .{ .new = .{ .nanoseconds = @intCast(now - 5 * std.time.ns_per_s) } } });
+
+ const picked = newestFresh(io, arena, root, marker).?;
+ try testing.expect(std.mem.endsWith(u8, picked.path, "exec-newest.png"));
+
+ // A marker AFTER everything on disk finds nothing — the fabrication case,
+ // and the state a run that generated nothing leaves behind.
+ try testing.expect(newestFresh(io, arena, root, now + std.time.ns_per_s) == null);
+ // An absent save_root is "no artifact", not a crash.
+ try testing.expect(newestFresh(io, arena, "/nonexistent/generated_images", 0) == null);
+ // Only the stale file is old enough to be excluded by a two-week marker.
+ try testing.expect(newestFresh(io, arena, root, now - 13 * day_ns) != null);
+}
+
+test "#352: freshnessFloor only ever loosens by less than a second" {
+ const s: i128 = std.time.ns_per_s;
+ try testing.expectEqual(@as(i128, 5 * s), freshnessFloor(5 * s));
+ try testing.expectEqual(@as(i128, 5 * s), freshnessFloor(5 * s + 999_999_999));
+ try testing.expect(freshnessFloor(7 * s + 1) > 6 * s);
+}
+
+test "#352: a too-old CLI and a self-reported missing tool each get their own actionable message" {
+ try testing.expect(tooOld("stream error: unexpected status 400: this model requires a newer version of Codex."));
+ try testing.expect(!tooOld("some other 400"));
+ try testing.expect(std.mem.indexOf(u8, too_old_text, "bun install -g @openai/codex") != null);
+
+ try testing.expect(saidUnavailable("IMAGE_GEN_UNAVAILABLE"));
+ try testing.expect(!saidUnavailable("image generated fine"));
+ try testing.expect(std.mem.indexOf(u8, unavailable_text, "codex features list") != null);
+ // The empty-handed success case names #352 so the failure is recognisable.
+ try testing.expect(std.mem.indexOf(u8, no_artifact_text, "#352") != null);
+}
diff --git a/src/imagegen_openai.zig b/src/imagegen_openai.zig
new file mode 100644
index 00000000..2a251c0d
--- /dev/null
+++ b/src/imagegen_openai.zig
@@ -0,0 +1,111 @@
+//! #352: the fallback imagegen engine — the Codex imagegen skill's bundled
+//! `scripts/image_gen.py`, driven directly against the OpenAI images API.
+//!
+//! It is the fallback rather than the default because it needs an
+//! OPENAI_API_KEY the codex engine does not (that one rides the user's
+//! existing ChatGPT auth), and because it bills separately. It stays because
+//! it is the only engine that honours the model/quality/background/
+//! output_format knobs at all — the hosted image_gen tool exposes none of
+//! them — and because a codex CLI too old for an image-capable model is a
+//! situation this path is unaffected by.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+pub const default_model = "gpt-image-2";
+/// One generation is a network round trip through an image model; 4 minutes is
+/// generous for the slowest (high quality, large size) and still bounded.
+pub const deadline_ms: u64 = 240 * 1000;
+
+pub const Args = struct {
+ prompt: []const u8,
+ out: []const u8,
+ model: []const u8 = default_model,
+ size: ?[]const u8 = null,
+ quality: ?[]const u8 = null,
+ background: ?[]const u8 = null,
+ output_format: ?[]const u8 = null,
+};
+
+/// `python3 <script> generate --prompt <p> --out <path> --force --model <m> …`
+///
+/// `--force` because the caller may have named a path that exists and the CLI
+/// would otherwise refuse; whether the rewrite actually happened is not the
+/// CLI's word to take, it is what verification decides afterwards.
+///
+/// `--dry-run` is deliberately never assembled: it prints a plan and writes no
+/// file, so it could only ever produce an unverifiable "success".
+pub fn buildArgv(arena: Allocator, script: []const u8, a: Args) ![]const []const u8 {
+ var argv: std.ArrayList([]const u8) = .empty;
+ try argv.appendSlice(arena, &.{
+ "python3", script, "generate",
+ "--prompt", a.prompt, "--out",
+ a.out, "--force", "--model",
+ a.model,
+ });
+ if (a.size) |v| try argv.appendSlice(arena, &.{ "--size", v });
+ if (a.quality) |v| try argv.appendSlice(arena, &.{ "--quality", v });
+ if (a.background) |v| try argv.appendSlice(arena, &.{ "--background", v });
+ if (a.output_format) |v| try argv.appendSlice(arena, &.{ "--output-format", v });
+ return argv.items;
+}
+
+/// Optional values land straight in an argv slot, so they must not be able to
+/// impersonate a flag or smuggle a second argument. The real vocabulary here
+/// is short (1024x1024, high, transparent, gpt-image-1.5), so the allowed
+/// characters can be narrow.
+pub fn okFlagValue(value: []const u8) bool {
+ if (value.len == 0 or value.len > 64) return false;
+ if (value[0] == '-') return false;
+ for (value) |c| switch (c) {
+ 'a'...'z', 'A'...'Z', '0'...'9', '_', '-', '.' => {},
+ else => return false,
+ };
+ return true;
+}
+
+pub const no_python_text = "python3 is not on PATH, so the imagegen CLI fallback cannot run. Install Python 3, or use the codex engine (a logged-in codex CLI needs no Python and no API key). Nothing was generated.";
+
+const testing = std.testing;
+
+test "#352: argv is a generate call with the required flags, optionals only when given" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const minimal = try buildArgv(arena, "/s/image_gen.py", .{ .prompt = "a red circle", .out = "out.png" });
+ const want = [_][]const u8{
+ "python3", "/s/image_gen.py", "generate", "--prompt", "a red circle",
+ "--out", "out.png", "--force", "--model", default_model,
+ };
+ try testing.expectEqual(want.len, minimal.len);
+ for (want, minimal) |w, got| try testing.expectEqualStrings(w, got);
+
+ const full = try buildArgv(arena, "/s/image_gen.py", .{
+ .prompt = "p",
+ .out = "o.webp",
+ .model = "gpt-image-1.5",
+ .size = "1024x1536",
+ .quality = "high",
+ .background = "transparent",
+ .output_format = "webp",
+ });
+ try testing.expectEqual(@as(usize, 18), full.len);
+ for ([_][]const u8{ "--size", "1024x1536", "--quality", "high", "--background", "transparent", "--output-format", "webp" }) |needle| {
+ var found = false;
+ for (full) |arg| {
+ if (std.mem.eql(u8, arg, needle)) found = true;
+ }
+ try testing.expect(found);
+ }
+ for (full) |arg| try testing.expect(!std.mem.eql(u8, arg, "--dry-run"));
+}
+
+test "#352: optional values cannot impersonate a flag or smuggle an argument" {
+ for ([_][]const u8{ "1024x1024", "auto", "high", "transparent", "gpt-image-1.5", "PNG" }) |ok|
+ try testing.expect(okFlagValue(ok));
+ for ([_][]const u8{ "", "--out", "-q", "1024 1024", "a;rm -rf /", "$(id)", "a\nb", "a/b" }) |bad|
+ try testing.expect(!okFlagValue(bad));
+ var long: [65]u8 = @splat('a');
+ try testing.expect(!okFlagValue(&long));
+}
diff --git a/src/imagegen_run.zig b/src/imagegen_run.zig
new file mode 100644
index 00000000..9aae4f38
--- /dev/null
+++ b/src/imagegen_run.zig
@@ -0,0 +1,101 @@
+//! #352: the one place the imagegen tool starts a child process.
+//!
+//! Both engines (codex exec, the image_gen.py CLI) and the sips helpers spawn
+//! through `run`, which exists mostly so the unit tests can replace it. The
+//! tool's whole job is deciding whether a generator really produced an image,
+//! and those decisions have to be testable without a network, an API key, a
+//! codex login, or a 6-minute timeout — so the seam sits at the process
+//! boundary rather than inside each engine.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const jobs = @import("jobs.zig");
+
+pub const Outcome = struct {
+ /// null when the child did not exit normally (signal, timeout, cancel).
+ exit_code: ?u8 = null,
+ stdout: []const u8 = "",
+ stderr: []const u8 = "",
+ timed_out: bool = false,
+ cancelled: bool = false,
+
+ /// Exit 0 and nothing external ended it. NOT proof an image exists —
+ /// #352 was a generator exiting 0 with a fabricated success transcript.
+ pub fn ranClean(self: Outcome) bool {
+ return !self.timed_out and !self.cancelled and self.exit_code != null and self.exit_code.? == 0;
+ }
+};
+
+pub const Fn = *const fn (Allocator, Io, []const []const u8, u64, ?[]const u8) anyerror!Outcome;
+
+/// Test seam. Set by a test, restored by its defer; never set in production.
+pub var hook: ?Fn = null;
+
+const stdout_cap = 64 * 1024;
+const stderr_cap = 32 * 1024;
+
+/// Run `argv` to completion under `deadline_ms`, optionally in `cwd`. Output
+/// is capped and allocated from `arena`, so callers free nothing.
+pub fn run(arena: Allocator, io: Io, argv: []const []const u8, deadline_ms: u64, cwd: ?[]const u8) !Outcome {
+ if (hook) |f| return f(arena, io, argv, deadline_ms, cwd);
+ // toolRunOptions owns the child's process group, so a deadline or an Esc
+ // takes the whole tree down instead of orphaning a running generation.
+ const r = try jobs.runCappedWithOptions(arena, io, argv, stdout_cap, stderr_cap, deadline_ms, jobs.toolRunOptions(cwd));
+ return .{
+ .exit_code = if (r.term == .exited) r.term.exited else null,
+ .stdout = r.stdout,
+ .stderr = r.stderr,
+ .timed_out = r.timed_out,
+ .cancelled = r.cancelled,
+ };
+}
+
+/// The LAST bytes of a generator's output: a Python traceback and a codex
+/// error both put the useful line at the end.
+pub fn tail(text: []const u8, cap: usize) []const u8 {
+ if (text.len <= cap) return text;
+ const cut = text[text.len - cap ..];
+ // Start on a line boundary so the excerpt never opens mid-UTF-8.
+ return if (std.mem.indexOfScalar(u8, cut, '\n')) |nl| cut[nl + 1 ..] else cut;
+}
+
+test "#352: ranClean is exit 0 only, and never confuses a timeout or a cancel for success" {
+ try std.testing.expect((Outcome{ .exit_code = 0 }).ranClean());
+ try std.testing.expect(!(Outcome{ .exit_code = 1 }).ranClean());
+ try std.testing.expect(!(Outcome{ .exit_code = null }).ranClean()); // signalled
+ try std.testing.expect(!(Outcome{ .exit_code = 0, .timed_out = true }).ranClean());
+ try std.testing.expect(!(Outcome{ .exit_code = 0, .cancelled = true }).ranClean());
+}
+
+test "#352: tail keeps the end of a traceback and starts on a line boundary" {
+ try std.testing.expectEqualStrings("short", tail("short", 100));
+ const long = "line one\nline two\nline three\n";
+ const cut = tail(long, 14);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "line three") != null);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "line one") == null);
+ try std.testing.expect(cut.len == 0 or cut[0] != '\n');
+}
+
+test "#352: the hook replaces the spawn entirely, so tests never start a process" {
+ const S = struct {
+ var seen_argv: []const []const u8 = &.{};
+ var seen_cwd: ?[]const u8 = null;
+ fn fake(_: Allocator, _: Io, argv: []const []const u8, _: u64, cwd: ?[]const u8) anyerror!Outcome {
+ seen_argv = argv;
+ seen_cwd = cwd;
+ return .{ .exit_code = 0, .stdout = "faked" };
+ }
+ };
+ const saved = hook;
+ defer hook = saved;
+ hook = S.fake;
+
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const out = try run(arena_state.allocator(), std.testing.io, &.{ "codex", "exec" }, 1, "/tmp/scratch");
+ try std.testing.expectEqualStrings("faked", out.stdout);
+ try std.testing.expectEqualStrings("codex", S.seen_argv[0]);
+ try std.testing.expectEqualStrings("/tmp/scratch", S.seen_cwd.?);
+}
diff --git a/src/imagegen_select.zig b/src/imagegen_select.zig
new file mode 100644
index 00000000..0d797331
--- /dev/null
+++ b/src/imagegen_select.zig
@@ -0,0 +1,186 @@
+//! #352: which imagegen engine a call gets, and what to say when it gets none.
+//!
+//! Pure over three booleans and the caller's request, so the whole matrix is a
+//! table test rather than something you can only find out by spawning codex.
+//!
+//! The one non-obvious rule: `model`, `quality`, `background` and
+//! `output_format` only exist on the openai_api engine — the hosted image_gen
+//! tool exposes none of them. Silently ignoring them on the codex engine would
+//! be the same class of dishonesty this whole tool exists to prevent (the
+//! caller asks for a transparent background, gets an opaque one, and is told it
+//! succeeded), so setting one STEERS `auto` to the engine that can honour it,
+//! and is a hard error when that engine is unavailable or was ruled out
+//! explicitly. `size` is not in that list: graff can deliver it on either
+//! engine, resizing the codex result itself.
+
+const std = @import("std");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+pub const Engine = enum { codex, openai_api };
+
+/// Parameters only the openai_api engine can apply.
+pub const tuned_params = [_][]const u8{ "model", "quality", "background", "output_format" };
+
+pub const Reason = enum {
+ /// Neither engine is usable on this machine.
+ no_engine,
+ /// engine:"codex" but no codex CLI + login.
+ codex_unavailable,
+ /// engine:"openai_api" but no OPENAI_API_KEY (or no script).
+ api_unavailable,
+ /// A tuned param was set, and the only engine that could apply it is not
+ /// available.
+ tuned_needs_api,
+ /// engine:"codex" was explicit AND a tuned param was set — the two cannot
+ /// both be honoured, and dropping one silently is not an option.
+ tuned_not_on_codex,
+};
+
+pub const Choice = union(enum) { use: Engine, refuse: Reason };
+
+pub fn parseEngine(name: []const u8) ?Engine {
+ if (std.ascii.eqlIgnoreCase(name, "auto")) return null; // absent == auto
+ if (std.ascii.eqlIgnoreCase(name, "codex")) return .codex;
+ if (std.ascii.eqlIgnoreCase(name, "openai_api")) return .openai_api;
+ return null;
+}
+
+/// `parseEngine` returns null for both "auto" and garbage, so callers that must
+/// tell them apart ask this first.
+pub fn knownEngineName(name: []const u8) bool {
+ return std.ascii.eqlIgnoreCase(name, "auto") or parseEngine(name) != null;
+}
+
+/// The first openai_api-only parameter present in the call, if any.
+pub fn firstTunedParam(input: Value) ?[]const u8 {
+ if (input != .object) return null;
+ for (tuned_params) |name| {
+ const v = input.object.get(name) orelse continue;
+ if (v == .string and v.string.len > 0) return name;
+ }
+ return null;
+}
+
+pub fn choose(requested: ?Engine, codex_ok: bool, api_ok: bool, tuned: bool) Choice {
+ if (requested) |want| return switch (want) {
+ .codex => if (tuned)
+ .{ .refuse = .tuned_not_on_codex }
+ else if (codex_ok)
+ .{ .use = .codex }
+ else
+ .{ .refuse = .codex_unavailable },
+ .openai_api => if (api_ok) .{ .use = .openai_api } else .{ .refuse = .api_unavailable },
+ };
+ // auto
+ if (tuned) {
+ if (api_ok) return .{ .use = .openai_api };
+ return .{ .refuse = if (codex_ok) .tuned_needs_api else .no_engine };
+ }
+ if (codex_ok) return .{ .use = .codex };
+ if (api_ok) return .{ .use = .openai_api };
+ return .{ .refuse = .no_engine };
+}
+
+/// The tool is not even installed — the gate should have kept us out of here.
+pub const no_skill_text = "imagegen is not available in this session: graff did not find the Codex imagegen skill at $CODEX_HOME/skills/.system/imagegen (CODEX_HOME defaults to ~/.codex), and both of this tool's engines come from it. Install the Codex imagegen skill and restart graff. Do not substitute an existing file for a generated one.";
+
+const nothing_generated = "NOTHING was generated — do not report an image, and do not pass off an existing file as one.";
+
+pub fn refusalText(gpa: Allocator, reason: Reason, tuned: ?[]const u8) ![]u8 {
+ return switch (reason) {
+ .no_engine => std.fmt.allocPrint(gpa,
+ \\imagegen has no usable engine in this session, so it did not run anything. It needs ONE of:
+ \\ - a logged-in codex CLI (preferred, no API key): install it with `bun install -g @openai/codex`, then `codex login`. graff checks for a codex binary on PATH and $CODEX_HOME/auth.json.
+ \\ - OPENAI_API_KEY exported in graff's environment, for the imagegen skill's scripts/image_gen.py fallback. graff reads it at startup, so export it and restart graff.
+ \\The hosted codex image_gen tool is server-side and cannot be reached any other way (issue #352). {s}
+ , .{nothing_generated}),
+ .codex_unavailable => std.fmt.allocPrint(gpa,
+ \\engine "codex" was requested, but this machine has no usable codex CLI: graff needs a `codex` binary on PATH AND $CODEX_HOME/auth.json (run `codex login`). Install it with `bun install -g @openai/codex`, or drop the engine argument to let graff pick, or pass engine "openai_api" if OPENAI_API_KEY is set. {s}
+ , .{nothing_generated}),
+ .api_unavailable => std.fmt.allocPrint(gpa,
+ \\engine "openai_api" was requested, but OPENAI_API_KEY was not set in graff's environment when this session started (or the imagegen skill's scripts/image_gen.py is missing). Export the key and restart graff, or drop the engine argument to use the codex engine, which needs no API key. {s}
+ , .{nothing_generated}),
+ .tuned_needs_api => std.fmt.allocPrint(gpa,
+ \\'{s}' is only supported by the openai_api engine, and OPENAI_API_KEY was not set when this session started. The codex engine is available but drives the hosted image_gen tool, which has no {s} option — graff will not quietly ignore it and call the result a success. Either export OPENAI_API_KEY and restart graff, or drop {s} (and any other of model/quality/background/output_format) and call again to use the codex engine. {s}
+ , .{ tuned orelse "that option", tuned orelse "that", tuned orelse "it", nothing_generated }),
+ .tuned_not_on_codex => std.fmt.allocPrint(gpa,
+ \\engine "codex" was requested together with '{s}', which only the openai_api engine supports — the hosted image_gen tool has no such option, and graff will not ignore it and report success anyway. Drop {s} (and any other of model/quality/background/output_format) to use the codex engine, or pass engine "openai_api" with OPENAI_API_KEY set. size is fine on either engine. {s}
+ , .{ tuned orelse "that option", tuned orelse "it", nothing_generated }),
+ };
+}
+
+const testing = std.testing;
+
+test "#352: engine names parse, and auto is not a garbage name" {
+ try testing.expectEqual(Engine.codex, parseEngine("codex").?);
+ try testing.expectEqual(Engine.openai_api, parseEngine("OPENAI_API").?);
+ try testing.expect(parseEngine("auto") == null);
+ try testing.expect(parseEngine("dall-e") == null);
+ try testing.expect(knownEngineName("auto") and knownEngineName("codex"));
+ try testing.expect(!knownEngineName("dall-e"));
+}
+
+test "#352: the full engine-selection matrix" {
+ // auto, no tuned params: codex wins whenever it is there.
+ try testing.expectEqual(Choice{ .use = .codex }, choose(null, true, true, false));
+ try testing.expectEqual(Choice{ .use = .codex }, choose(null, true, false, false));
+ try testing.expectEqual(Choice{ .use = .openai_api }, choose(null, false, true, false));
+ try testing.expectEqual(Choice{ .refuse = .no_engine }, choose(null, false, false, false));
+
+ // auto + a tuned param: steer to the only engine that can apply it.
+ try testing.expectEqual(Choice{ .use = .openai_api }, choose(null, true, true, true));
+ try testing.expectEqual(Choice{ .use = .openai_api }, choose(null, false, true, true));
+ try testing.expectEqual(Choice{ .refuse = .tuned_needs_api }, choose(null, true, false, true));
+ try testing.expectEqual(Choice{ .refuse = .no_engine }, choose(null, false, false, true));
+
+ // explicit codex
+ try testing.expectEqual(Choice{ .use = .codex }, choose(.codex, true, true, false));
+ try testing.expectEqual(Choice{ .refuse = .codex_unavailable }, choose(.codex, false, true, false));
+ try testing.expectEqual(Choice{ .refuse = .tuned_not_on_codex }, choose(.codex, true, true, true));
+
+ // explicit openai_api
+ try testing.expectEqual(Choice{ .use = .openai_api }, choose(.openai_api, true, true, false));
+ try testing.expectEqual(Choice{ .use = .openai_api }, choose(.openai_api, false, true, true));
+ try testing.expectEqual(Choice{ .refuse = .api_unavailable }, choose(.openai_api, true, false, false));
+}
+
+test "#352: tuned params are detected by name, and size is deliberately not one" {
+ const gpa = testing.allocator;
+ const cases = [_]struct { json: []const u8, want: ?[]const u8 }{
+ .{ .json = "{\"prompt\":\"p\"}", .want = null },
+ .{ .json = "{\"prompt\":\"p\",\"size\":\"1024x1024\"}", .want = null }, // graff resizes, so size works everywhere
+ .{ .json = "{\"prompt\":\"p\",\"out\":\"a.png\",\"engine\":\"codex\"}", .want = null },
+ .{ .json = "{\"prompt\":\"p\",\"background\":\"transparent\"}", .want = "background" },
+ .{ .json = "{\"prompt\":\"p\",\"model\":\"gpt-image-1.5\"}", .want = "model" },
+ .{ .json = "{\"prompt\":\"p\",\"output_format\":\"webp\"}", .want = "output_format" },
+ .{ .json = "{\"prompt\":\"p\",\"quality\":\"\"}", .want = null }, // empty is not a request
+ };
+ for (cases) |c| {
+ var parsed = try std.json.parseFromSlice(Value, gpa, c.json, .{});
+ defer parsed.deinit();
+ const got = firstTunedParam(parsed.value);
+ if (c.want) |w| try testing.expectEqualStrings(w, got.?) else try testing.expect(got == null);
+ }
+}
+
+test "#352: every refusal names what to install or export, and says nothing was generated" {
+ const gpa = testing.allocator;
+ for ([_]Reason{ .no_engine, .codex_unavailable, .api_unavailable, .tuned_needs_api, .tuned_not_on_codex }) |reason| {
+ const text = try refusalText(gpa, reason, "background");
+ defer gpa.free(text);
+ try testing.expect(std.mem.indexOf(u8, text, "NOTHING was generated") != null);
+ try testing.expect(text.len > 120);
+ }
+ const none = try refusalText(gpa, .no_engine, null);
+ defer gpa.free(none);
+ // The both-engines-missing case has to name both requirements.
+ try testing.expect(std.mem.indexOf(u8, none, "codex login") != null);
+ try testing.expect(std.mem.indexOf(u8, none, "OPENAI_API_KEY") != null);
+ try testing.expect(std.mem.indexOf(u8, none, "#352") != null);
+
+ const tuned = try refusalText(gpa, .tuned_not_on_codex, "background");
+ defer gpa.free(tuned);
+ try testing.expect(std.mem.indexOf(u8, tuned, "background") != null);
+ try testing.expect(std.mem.indexOf(u8, tuned, "size is fine on either engine") != null);
+}
diff --git a/src/imagegen_sips.zig b/src/imagegen_sips.zig
new file mode 100644
index 00000000..1a3f7c04
--- /dev/null
+++ b/src/imagegen_sips.zig
@@ -0,0 +1,117 @@
+//! #352: the two macOS `sips` operations the imagegen tool needs — reading an
+//! image's pixel dimensions, and resizing one.
+//!
+//! Resizing is graff's job, never the generator's. The codex engine's hosted
+//! `image_gen` tool has no size parameter, and the #352 transcript is exactly
+//! what happens when a model is left to "make it 64x64" on its own: it reached
+//! for sips itself, resized the wrong (stale) file, and reported the result as
+//! a generation. So when a caller asks for a size, graff runs the resize on the
+//! artifact it has already verified, deterministically, and reports the
+//! dimensions it measured afterwards rather than the ones it asked for.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+const run_mod = @import("imagegen_run.zig");
+
+pub const available = builtin.os.tag == .macos;
+const sips_deadline_ms: u64 = 30 * 1000;
+
+pub const Size = struct { w: u32, h: u32 };
+
+/// "1024x1536" -> 1024 wide, 1536 tall. Rejects anything that is not two plain
+/// positive numbers, so the value can never smuggle an argument into sips.
+pub fn parseSize(text: []const u8) ?Size {
+ const x = std.mem.indexOfAny(u8, text, "xX") orelse return null;
+ const w = std.fmt.parseInt(u32, text[0..x], 10) catch return null;
+ const h = std.fmt.parseInt(u32, text[x + 1 ..], 10) catch return null;
+ if (w == 0 or h == 0 or w > 16384 or h > 16384) return null;
+ return .{ .w = w, .h = h };
+}
+
+/// `sips -z <height> <width> <path>` — sips takes height first.
+pub fn resizeArgv(arena: Allocator, path: []const u8, size: Size) ![]const []const u8 {
+ const h = try std.fmt.allocPrint(arena, "{d}", .{size.h});
+ const w = try std.fmt.allocPrint(arena, "{d}", .{size.w});
+ return arena.dupe([]const u8, &.{ "sips", "-z", h, w, path });
+}
+
+pub fn dimsArgv(arena: Allocator, path: []const u8) ![]const []const u8 {
+ return arena.dupe([]const u8, &.{ "sips", "-g", "pixelWidth", "-g", "pixelHeight", path });
+}
+
+/// Resize in place. Returns false when sips is unavailable or failed — the
+/// caller keeps the native-size image and says so rather than pretending.
+pub fn resize(arena: Allocator, io: Io, path: []const u8, size: Size) bool {
+ if (!available) return false;
+ const argv = resizeArgv(arena, path, size) catch return false;
+ const out = run_mod.run(arena, io, argv, sips_deadline_ms, null) catch return false;
+ return out.ranClean();
+}
+
+/// Measured pixel dimensions, best-effort: reporting detail, never part of a
+/// pass/fail decision.
+pub fn dims(arena: Allocator, io: Io, path: []const u8) ?Size {
+ if (!available) return null;
+ const argv = dimsArgv(arena, path) catch return null;
+ const out = run_mod.run(arena, io, argv, sips_deadline_ms, null) catch return null;
+ if (!out.ranClean()) return null;
+ return .{
+ .w = fieldAfter(out.stdout, "pixelWidth:") orelse return null,
+ .h = fieldAfter(out.stdout, "pixelHeight:") orelse return null,
+ };
+}
+
+fn fieldAfter(text: []const u8, key: []const u8) ?u32 {
+ const at = std.mem.indexOf(u8, text, key) orelse return null;
+ const rest = text[at + key.len ..];
+ const line_end = std.mem.indexOfScalar(u8, rest, '\n') orelse rest.len;
+ return std.fmt.parseInt(u32, std.mem.trim(u8, rest[0..line_end], " \t\r"), 10) catch null;
+}
+
+const testing = std.testing;
+
+test "#352: sizes parse only as two plain numbers, so the value cannot reach sips as a flag" {
+ try testing.expectEqual(Size{ .w = 1024, .h = 1024 }, parseSize("1024x1024").?);
+ try testing.expectEqual(Size{ .w = 1024, .h = 1536 }, parseSize("1024X1536").?);
+ for ([_][]const u8{ "auto", "", "1024", "1024x", "x1024", "-1x2", "0x512", "20000x20000", "10 x 10", "1024x1024 -j" }) |bad|
+ try testing.expect(parseSize(bad) == null);
+}
+
+test "#352: resize passes height before width, and dims reads what sips measured" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const argv = try resizeArgv(arena, "out.png", .{ .w = 64, .h = 128 });
+ // Element-wise: expectEqualSlices on []const u8 would compare pointers.
+ const want = [_][]const u8{ "sips", "-z", "128", "64", "out.png" };
+ try testing.expectEqual(want.len, argv.len);
+ for (want, argv) |w, got| try testing.expectEqualStrings(w, got);
+
+ const S = struct {
+ fn fake(_: Allocator, _: Io, _: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
+ return .{ .exit_code = 0, .stdout = "/tmp/a.png\n pixelWidth: 1024\n pixelHeight: 768\n" };
+ }
+ fn broken(_: Allocator, _: Io, _: []const []const u8, _: u64, _: ?[]const u8) anyerror!run_mod.Outcome {
+ return .{ .exit_code = 1, .stderr = "sips: no such file" };
+ }
+ };
+ const saved = run_mod.hook;
+ defer run_mod.hook = saved;
+
+ run_mod.hook = S.fake;
+ if (available) {
+ try testing.expectEqual(Size{ .w = 1024, .h = 768 }, dims(arena, testing.io, "/tmp/a.png").?);
+ try testing.expect(resize(arena, testing.io, "/tmp/a.png", .{ .w = 64, .h = 64 }));
+ run_mod.hook = S.broken;
+ try testing.expect(!resize(arena, testing.io, "/tmp/a.png", .{ .w = 64, .h = 64 })); // failure is reported, not swallowed
+ try testing.expect(dims(arena, testing.io, "/tmp/a.png") == null);
+ } else {
+ // Off macOS both are honest no-ops; the caller reports native size.
+ try testing.expect(dims(arena, testing.io, "/tmp/a.png") == null);
+ try testing.expect(!resize(arena, testing.io, "/tmp/a.png", .{ .w = 64, .h = 64 }));
+ }
+}
diff --git a/src/imagegen_skill.zig b/src/imagegen_skill.zig
index 90bceab2..2c1014c9 100644
--- a/src/imagegen_skill.zig
+++ b/src/imagegen_skill.zig
@@ -37,17 +37,21 @@ pub const install_rel = ".harness/skills/imagegen";
const max_depth: u8 = 6; // the real tree is 2 deep; this is a runaway-symlink stop
const skill_md_cap = 512 * 1024;
-/// `$CODEX_HOME/skills/.system/imagegen`, or `$HOME/.codex/...` when
-/// CODEX_HOME is unset. Null when neither is known.
+/// $CODEX_HOME, or $HOME/.codex when it is unset. Null when neither is known.
+/// Also where auth.json and generated_images/ live, so the codex engine
+/// resolves both from here.
+pub fn codexHomeDir(arena: Allocator, codex_home: ?[]const u8, home: ?[]const u8) ?[]const u8 {
+ if (codex_home) |value| {
+ if (value.len > 0) return value;
+ }
+ const h = home orelse return null;
+ if (h.len == 0) return null;
+ return std.fmt.allocPrint(arena, "{s}/.codex", .{h}) catch null;
+}
+
+/// `$CODEX_HOME/skills/.system/imagegen`.
pub fn codexSkillDir(arena: Allocator, codex_home: ?[]const u8, home: ?[]const u8) ?[]const u8 {
- const base: []const u8 = blk: {
- if (codex_home) |value| {
- if (value.len > 0) break :blk value;
- }
- const h = home orelse return null;
- if (h.len == 0) return null;
- break :blk std.fmt.allocPrint(arena, "{s}/.codex", .{h}) catch return null;
- };
+ const base = codexHomeDir(arena, codex_home, home) orelse return null;
return std.fmt.allocPrint(arena, "{s}/{s}", .{ base, codex_rel }) catch null;
}
@@ -115,26 +119,35 @@ pub const addendum =
\\<!-- graff addendum -->
\\> **graff note — read this before following anything below.**
\\>
- \\> This is a copy of the Codex `imagegen` skill, installed by graff. Parts of it
- \\> do not apply here:
+ \\> This is a copy of the Codex `imagegen` skill, installed by graff. The skill's
+ \\> prompting guidance, CLI reference and sample prompts are all accurate here.
+ \\> How you invoke it is not:
\\>
- \\> - **There is no built-in `image_gen` tool in graff.** It is hosted server-side
- \\> inside the Codex app and never fires here. Every instruction below that
- \\> says to prefer the built-in tool, or that describes "default built-in tool
- \\> mode", does not apply. Do not claim an image was generated by it.
- \\> - **Use graff's `imagegen` tool instead** (this document calls it `$imagegen`;
- \\> the tool name is plain `imagegen` because provider tool names cannot
- \\> contain `$`). It runs this skill's bundled `scripts/image_gen.py` CLI —
- \\> the fallback path described below — so the CLI reference, prompting guide
- \\> and sample prompts here ARE accurate and worth reading.
- \\> - **`OPENAI_API_KEY` is required.** The CLI is the only engine available, so
- \\> the keyless path this document describes does not exist here. Without the
- \\> key the tool returns an error and generates nothing.
- \\> - **The tool verifies its own output.** It only reports success after the
- \\> file exists, is newer than the run, is large enough, and carries the right
- \\> container signature. Never report a generated image that the tool did not
- \\> return a verified path for, and never substitute an existing file for one
- \\> you failed to generate.
+ \\> - **You cannot call the built-in `image_gen` tool yourself.** It is hosted
+ \\> server-side and is not in your tool list. Every instruction below about
+ \\> "default built-in tool mode" describes something you have no direct access
+ \\> to. Never claim an image was generated by it.
+ \\> - **Call graff's `imagegen` tool instead** (this document calls it
+ \\> `$imagegen`; the tool name is plain `imagegen` because provider tool names
+ \\> cannot contain `$`). It has two engines and picks one for you:
+ \\> - `codex` — the DEFAULT. graff drives the hosted `image_gen` tool through
+ \\> your logged-in `codex` CLI, so this needs **no `OPENAI_API_KEY`** and no
+ \\> separately billed account. It always produces PNG and has no quality or
+ \\> background options.
+ \\> - `openai_api` — the fallback, running this skill's bundled
+ \\> `scripts/image_gen.py`. It needs `OPENAI_API_KEY`, and it is the only
+ \\> engine that applies `model`, `quality`, `background` and
+ \\> `output_format`. Setting any of those selects it automatically.
+ \\> `size` works on either engine — on the codex engine graff resizes the
+ \\> generated file itself afterwards.
+ \\> - **graff verifies every result; the generator's word is never taken.** A
+ \\> success is only returned after graff has confirmed the file exists, is
+ \\> newer than the call, changed if it already existed, clears a size floor,
+ \\> and carries a real image signature. A generator that exits successfully
+ \\> while producing nothing is reported as a FAILURE. Never report an image
+ \\> the tool did not hand you a verified path for, and never substitute an
+ \\> existing file for one you failed to generate — that is exactly the bug
+ \\> this tool was built to make impossible.
\\> - **For several images, fan out with subagents.** Spawn one subagent per
\\> image (`subagent`, or one `workflow` task each); each child calls
\\> `imagegen` exactly once for its own image and reports the verified path
@@ -204,9 +217,16 @@ test "#352: the addendum goes after the frontmatter, before the body" {
const fm_end = std.mem.indexOf(u8, out, "\n---\n").? + "\n---\n".len;
const body = std.mem.indexOf(u8, out, "# Image Generation Skill").?;
try testing.expect(marker >= fm_end and marker < body);
- try testing.expect(std.mem.indexOf(u8, out, "no built-in `image_gen` tool in graff") != null);
- try testing.expect(std.mem.indexOf(u8, out, "OPENAI_API_KEY` is required") != null);
- try testing.expect(std.mem.indexOf(u8, out, "one subagent per") != null);
+ // Both engines and the verification promise have to survive the splice.
+ for ([_][]const u8{
+ "cannot call the built-in `image_gen` tool yourself",
+ "`codex` — the DEFAULT",
+ "no `OPENAI_API_KEY`",
+ "`openai_api` — the fallback",
+ "graff verifies every result",
+ "reported as a FAILURE",
+ "one subagent per",
+ }) |needle| try testing.expect(std.mem.indexOf(u8, out, needle) != null);
// No frontmatter: the addendum still leads.
const bare = try withAddendum(arena, "# Just a body\n");
diff --git a/src/imagegen_verify.zig b/src/imagegen_verify.zig
index 8b78c6a3..043f120c 100644
--- a/src/imagegen_verify.zig
+++ b/src/imagegen_verify.zig
@@ -77,6 +77,16 @@ pub const Format = enum {
.webp => "webp",
};
}
+
+ /// What the bytes actually ARE, as opposed to what a path claims. The
+ /// codex engine does not let the caller choose a container, so the honest
+ /// thing to report is whatever the hosted tool produced.
+ pub fn detect(head: []const u8) ?Format {
+ for ([_]Format{ .png, .jpeg, .webp }) |f| {
+ if (f.magicOk(head)) return f;
+ }
+ return null;
+ }
};
/// What we knew about the output path at one instant. `existed = false` is the
diff --git a/src/main.zig b/src/main.zig
index 67a60137..b5d5540b 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -408,7 +408,7 @@ pub fn main(init: std.process.Init) !void {
// Root system-prompt layering (base + AGENTS.md/HARNESS.md/CLAUDE.md + --append-system-prompt + active-skill lines + connected-MCP notes) lives
// in startup.zig as buildSystemPrompt() — pure over io/arena, returns the composed base by value. buildRootAgent derives every prompt variant
// from it via prompts.setSystemPrompts() (#326).
- const sys_normal = try startup.buildSystemPrompt(io, arena, out, flags.system_prompt_flag, flags.append_system_flag, json_mode or flags.oneshot_prompt != null, mcp_tools, g_codedbpro_licensed, init.environ_map.get("GRAFF_LEARNED_PROMPT"), init.environ_map.get("CODEX_HOME"), init.environ_map.get("OPENAI_API_KEY"));
+ const sys_normal = try startup.buildSystemPrompt(io, arena, out, flags.system_prompt_flag, flags.append_system_flag, json_mode or flags.oneshot_prompt != null, mcp_tools, g_codedbpro_licensed, init.environ_map.get("GRAFF_LEARNED_PROMPT"), init.environ_map);
boot.mark(io, "system prompt");
session_run.learningNotice(io, arena, init.environ_map, out, json_mode or flags.oneshot_prompt != null);
diff --git a/src/startup.zig b/src/startup.zig
index 15528c38..701bf00b 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -343,8 +343,7 @@ pub fn buildSystemPrompt(
mcp_tools: []const mcp.Tool,
codedbpro_licensed: bool,
learned_policy_env: ?[]const u8,
- codex_home_env: ?[]const u8,
- openai_key_env: ?[]const u8,
+ environ: anytype,
) ![]const u8 {
// A learned policy is used unless this session opted out of it.
const learned: ?learn_store.ActiveAgent = if (system_prompt_flag == null and learn_auto.enabled(learned_policy_env)) learnedRootPolicy(io, arena) else null;
@@ -385,10 +384,11 @@ pub fn buildSystemPrompt(
}
// #352: mirror the Codex imagegen skill into ~/.harness/skills BEFORE the
// scan below, so the copied playbook is in this session's catalog. The same
- // call decides whether the `imagegen` tool is advertised (tool_gates.zig).
- imagegen.detect(io, arena, codex_home_env, fleet.g_home, openai_key_env);
+ // call decides whether `imagegen` is advertised (tool_gates.zig) and which
+ // of its two engines this machine can actually run.
+ imagegen.detect(io, arena, .{ .codex_home = environ.get("CODEX_HOME"), .home = fleet.g_home, .openai_api_key = environ.get("OPENAI_API_KEY"), .tmp_dir = environ.get("TMPDIR") });
if (imagegen.available and !quiet) {
- try out.print("imagegen: Codex skill found — tool enabled, playbook at {s}\n", .{imagegen.skill_dir});
+ try out.print("imagegen: Codex skill found — tool enabled ({s}), playbook at {s}\n", .{ imagegen.engineSummary(), imagegen.skill_dir });
try out.flush();
}
// Markdown skills (skill_docs.zig): names + trigger descriptions only. The