Skip to content

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

Python

feat(tools): codex-gated imagegen tool backed by the copied imagegen skill CLI (#352)

justrach3f463b80ba9b
diff --git a/src/agent.zig b/src/agent.zig
index 68eae367..eb556f29 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -251,15 +251,16 @@ pub const Agent = struct {
return schema.providerTakesEffort(self.provider.kind, self.provider.id, self.provider.model);
}
- /// #330: a child's catalog is a comptime constant, so the gate picks the
- /// pre-filtered twin rather than rebuilding one per subagent. Root catalogs
- /// are filtered where they are assembled (schema.effectiveRootSpecs).
+ /// #330/#352: a child's catalog is a comptime constant, so both gates just
+ /// pick the pre-built twin rather than rebuilding one per subagent —
+ /// schema.subToolsJson owns that choice. Root catalogs are filtered where
+ /// they are assembled (schema.effectiveRootSpecs).
pub fn toolsJson(self: *const Agent) []const u8 {
- const gated = no_local_tools.enabled;
+ if (self.sub) return schema.subToolsJson(self.provider.kind, no_local_tools.enabled);
return switch (self.provider.kind) {
- .anthropic => if (self.sub) (if (gated) schema.tools_anthropic_sub_remote else schema.tools_anthropic_sub) else self.tools_anthropic,
- .openai => if (self.sub) (if (gated) schema.tools_openai_sub_remote else schema.tools_openai_sub) else self.tools_openai,
- .responses => if (self.sub) (if (gated) schema.tools_responses_sub_remote else schema.tools_responses_sub) else self.tools_responses,
+ .anthropic => self.tools_anthropic,
+ .openai => self.tools_openai,
+ .responses => self.tools_responses,
};
}
diff --git a/src/exec.zig b/src/exec.zig
index a8098532..698ae3c0 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -67,6 +67,7 @@ const hooks = @import("hooks.zig");
const telemetry = @import("telemetry.zig");
const learning_privacy = @import("learning_privacy.zig");
const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate
+const imagegen = @import("imagegen.zig"); // #352: the codex-gated image tool (advertising lives in schema.zig/tool_gates.zig)
/// Wall-clock ceiling for one *subagent* bash command. Subagents run on pool
/// threads with no TTY, so there is no Esc to kill a runaway command — without
@@ -462,6 +463,9 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// Loads one SKILL.md body (or lists them). Rescans on every call, so a
// skill written this session is loadable without a restart.
if (std.mem.eql(u8, call.name, "skill")) return skill_docs.execSkill(gpa, io, input);
+ // #352: codex-gated. execImagegen answers a call that was never advertised
+ // (an unavailable session) with the same honest error it gives the model.
+ if (std.mem.eql(u8, call.name, imagegen.tool_name)) return imagegen.execImagegen(ctx, input);
if (std.mem.eql(u8, call.name, "subagent")) return execSubagent(ctx, input);
if (std.mem.eql(u8, call.name, "workflow")) return execWorkflow(ctx, input);
if (std.mem.eql(u8, call.name, "agent_output")) {
diff --git a/src/imagegen.zig b/src/imagegen.zig
new file mode 100644
index 00000000..1e07c109
--- /dev/null
+++ b/src/imagegen.zig
@@ -0,0 +1,553 @@
+//! #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).
+//!
+//! 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.
+//!
+//! 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.
+//!
+//! 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.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+const tools = @import("tools.zig");
+const ToolCtx = tools.ToolCtx;
+const ToolOutput = tools.ToolOutput;
+const strField = tools.strField;
+const missingArg = tools.missingArg;
+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 skill = @import("imagegen_skill.zig");
+const verify = @import("imagegen_verify.zig");
+
+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_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"]}
+;
+
+/// 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.
+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.
+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.
+pub var api_key_present: bool = false;
+
+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 {
+ available = false;
+ script_path = "";
+ skill_dir = "";
+ api_key_present = if (api_key) |value| value.len > 0 else false;
+
+ const src = skill.codexSkillDir(arena, codex_home, 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.needsSync(io, arena, src, dest)) skill.sync(io, arena, src, dest) catch {};
+ if (engineScript(io, arena, dest)) |path| {
+ script_path = path;
+ skill_dir = dest;
+ }
+ }
+ if (script_path.len == 0) {
+ script_path = engineScript(io, arena, src) orelse return;
+ skill_dir = src;
+ }
+ available = true;
+}
+
+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;
+ if (st.kind != .file) return null;
+ 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 {
+ const gpa = ctx.gpa;
+ 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);
+
+ 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 = "" };
+ inline for (.{ "model", "size", "quality", "background", "output_format" }) |field| {
+ if (strField(input, field)) |value| {
+ if (!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;
+ }
+ }
+ 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}),
+ .is_error = true,
+ }
+ else
+ null;
+
+ const out_rel = if (strField(input, "out")) |p|
+ p
+ else
+ 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 })
+ else
+ out_rel;
+ args.out = resolved;
+
+ const before = verify.snapshot(io, resolved);
+ // Taken BEFORE the spawn: anything the 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,
+ };
+
+ // Exit 0 is where #352's fabrication began, so it proves nothing on its own.
+ 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);
+ 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 },
+ ),
+ .is_error = true,
+ };
+
+ const size_bytes = after.?.size;
+ const dims = pixelDims(arena, 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() },
+ ) };
+}
+
+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];
+}
+
+/// 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;
+}
+
+/// 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 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;
+}
+
+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" });
+ 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);
+ }
+ // --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"));
+}
+
+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));
+}
+
+test "#352: default out paths stay unique across many rapid calls (the subagent fan-out case)" {
+ 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 base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+
+ var seen: std.StringHashMapUnmanaged(void) = .empty;
+ defer seen.deinit(testing.allocator);
+ 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" {
+ 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;
+ defer {
+ available = saved_available;
+ script_path = saved_script;
+ skill_dir = saved_dir;
+ api_key_present = saved_key;
+ }
+
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+ const codex_home = try std.fmt.allocPrint(arena, "{s}/codex", .{base});
+ const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});
+
+ // 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);
+ try testing.expect(!available);
+ try testing.expectEqualStrings("", script_path);
+ try testing.expect(!api_key_present); // and the key check is honest about being unset
+
+ // Install the skill where Codex keeps it.
+ const src = try std.fmt.allocPrint(arena, "{s}/{s}", .{ codex_home, skill.codex_rel });
+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/scripts", .{src}));
+ for ([_]struct { path: []const u8, data: []const u8 }{
+ .{ .path = "SKILL.md", .data = "---\nname: imagegen\ndescription: d\n---\n\n# Image Generation Skill\nuse image_gen\n" },
+ .{ .path = "LICENSE.txt", .data = "LICENSE BODY" },
+ .{ .path = "scripts/image_gen.py", .data = "print('gen')" },
+ }) |f| try Io.Dir.cwd().writeFile(io, .{
+ .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ src, f.path }),
+ .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.
+ 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));
+ try testing.expect(std.mem.indexOf(u8, md, "<!-- graff addendum -->") != null);
+ try testing.expect(std.mem.indexOf(u8, md, "one subagent per") != null);
+ 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, "");
+ try testing.expect(available and !api_key_present);
+}
+
+test "#352: the honest no-key error refuses to generate and says why" {
+ const gpa = testing.allocator;
+ const saved_available = available;
+ const saved_script = script_path;
+ const saved_key = api_key_present;
+ defer {
+ available = saved_available;
+ script_path = saved_script;
+ api_key_present = saved_key;
+ }
+
+ 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,
+ .io = testing.io,
+ .client = &client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .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);
+
+ // Detected, but no key: still nothing spawned, and the message says so.
+ available = true;
+ script_path = "/nonexistent/image_gen.py"; // never reached
+ 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.
+ 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);
+}
+
+test {
+ _ = skill;
+ _ = verify;
+}
diff --git a/src/imagegen_skill.zig b/src/imagegen_skill.zig
new file mode 100644
index 00000000..90bceab2
--- /dev/null
+++ b/src/imagegen_skill.zig
@@ -0,0 +1,275 @@
+//! #352: locating the Codex `imagegen` skill and mirroring it into graff's own
+//! personal skill tier.
+//!
+//! The skill is the tool's reason to exist. Codex ships it at
+//! `$CODEX_HOME/skills/.system/imagegen/` (CODEX_HOME defaults to ~/.codex),
+//! and its `scripts/image_gen.py` is the only image engine that actually
+//! renders anything for us: the `image_gen` tool the SKILL.md calls "preferred"
+//! is hosted server-side inside the Codex app and never fires here (#352).
+//!
+//! Two things happen when it is found:
+//! 1. the `imagegen` tool becomes available (tool_gates.zig);
+//! 2. the whole skill directory is copied into `~/.harness/skills/imagegen/`
+//! so `skill imagegen` resolves through graff's existing personal-tier
+//! scan (skill_docs.zig) with its references/, scripts/ and LICENSE.txt
+//! intact — a skill separated from its license is not a skill we should
+//! be shipping around.
+//!
+//! The copy is not verbatim: a graff addendum is spliced in directly after the
+//! frontmatter, because following the document as written would send the model
+//! straight at a tool that does not exist here. The addendum is first in the
+//! body on purpose — a correction that arrives after 24 KB of instructions for
+//! the wrong tool has already lost.
+//!
+//! Refresh policy: copy when the destination is missing, or when the source
+//! SKILL.md is newer than the copy. Otherwise leave it alone — a user who
+//! edited their copy keeps their edits until Codex itself ships a new version.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+
+/// Where Codex keeps it, relative to CODEX_HOME.
+pub const codex_rel = "skills/.system/imagegen";
+/// Where we mirror it, relative to $HOME (graff's personal skill tier).
+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.
+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;
+ };
+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ base, codex_rel }) catch null;
+}
+
+/// `$HOME/.harness/skills/imagegen`.
+pub fn installDir(arena: Allocator, home: ?[]const u8) ?[]const u8 {
+ const h = home orelse return null;
+ if (h.len == 0) return null;
+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ h, install_rel }) catch null;
+}
+
+/// mtime of `<dir>/SKILL.md`, or null when there is no readable SKILL.md —
+/// which is also the "is this really the skill?" test.
+pub fn skillMtime(io: Io, arena: Allocator, dir: []const u8) ?i128 {
+ const path = std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dir}) catch return null;
+ const st = Io.Dir.cwd().statFile(io, path, .{}) catch return null;
+ if (st.kind != .file) return null;
+ return st.mtime.nanoseconds;
+}
+
+pub fn present(io: Io, arena: Allocator, dir: []const u8) bool {
+ return skillMtime(io, arena, dir) != null;
+}
+
+/// Copy when the destination has no SKILL.md, or the source's is newer.
+pub fn needsSync(io: Io, arena: Allocator, src: []const u8, dest: []const u8) bool {
+ const src_mtime = skillMtime(io, arena, src) orelse return false; // nothing to copy
+ const dest_mtime = skillMtime(io, arena, dest) orelse return true; // nothing copied yet
+ return src_mtime > dest_mtime;
+}
+
+/// Mirror the skill, then overwrite the copied SKILL.md with the addended
+/// version. Best-effort per entry: one unreadable asset must not cost us the
+/// scripts and the license.
+pub fn sync(io: Io, arena: Allocator, src: []const u8, dest: []const u8) !void {
+ try copyTree(io, arena, src, dest, 0);
+ const src_md = try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{src});
+ const dest_md = try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dest});
+ const original = try Io.Dir.cwd().readFileAlloc(io, src_md, arena, .limited(skill_md_cap));
+ const patched = try withAddendum(arena, original);
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = dest_md, .data = patched });
+}
+
+fn copyTree(io: Io, arena: Allocator, src: []const u8, dest: []const u8, depth: u8) !void {
+ if (depth > max_depth) return;
+ try Io.Dir.cwd().createDirPath(io, dest);
+ var dir = try Io.Dir.cwd().openDir(io, src, .{ .iterate = true });
+ defer dir.close(io);
+ var it = dir.iterate();
+ while (it.next(io) catch null) |entry| {
+ const from = std.fmt.allocPrint(arena, "{s}/{s}", .{ src, entry.name }) catch continue;
+ const to = std.fmt.allocPrint(arena, "{s}/{s}", .{ dest, entry.name }) catch continue;
+ switch (entry.kind) {
+ // sym_link included: copyFile follows it, so a symlinked script
+ // lands as a real file in the copy rather than a dangling link.
+ .file, .sym_link => Io.Dir.cwd().copyFile(from, Io.Dir.cwd(), to, io, .{}) catch continue,
+ .directory => copyTree(io, arena, from, to, depth + 1) catch continue,
+ else => {},
+ }
+ }
+}
+
+/// The correction spliced into the copied SKILL.md. Everything in it is a
+/// statement about THIS harness that the upstream document gets wrong.
+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:
+ \\>
+ \\> - **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.
+ \\> - **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
+ \\> back. That is how generations run concurrently — a single agent calling
+ \\> `imagegen` N times in a row is serial and much slower.
+ \\
+ \\<!-- end graff addendum -->
+;
+
+/// Splice the addendum in directly after the YAML frontmatter (or at the very
+/// top when there is none), leaving the frontmatter itself untouched so
+/// skill_docs.zig still parses `name:`/`description:` out of it.
+pub fn withAddendum(arena: Allocator, original: []const u8) ![]u8 {
+ const split = bodyStart(original);
+ return std.fmt.allocPrint(arena, "{s}{s}\n\n{s}", .{ original[0..split], addendum, original[split..] });
+}
+
+/// Byte offset where the body begins: past a leading `---\n … \n---\n` block.
+fn bodyStart(data: []const u8) usize {
+ const fence_len: usize = if (std.mem.startsWith(u8, data, "---\r\n"))
+ 5
+ else if (std.mem.startsWith(u8, data, "---\n"))
+ 4
+ else
+ return 0;
+ const close = std.mem.indexOfPos(u8, data, fence_len, "\n---") orelse return 0;
+ var i = close + "\n---".len;
+ while (i < data.len and (data[i] == '\r' or data[i] == '-')) i += 1;
+ if (i < data.len and data[i] == '\n') i += 1;
+ return i;
+}
+
+const testing = std.testing;
+
+test "#352: CODEX_HOME wins over HOME, and both produce the .system skill path" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ try testing.expectEqualStrings(
+ "/tmp/cx/skills/.system/imagegen",
+ codexSkillDir(arena, "/tmp/cx", "/home/u").?,
+ );
+ try testing.expectEqualStrings(
+ "/home/u/.codex/skills/.system/imagegen",
+ codexSkillDir(arena, null, "/home/u").?,
+ );
+ // An empty CODEX_HOME is not a location; fall back to HOME.
+ try testing.expectEqualStrings(
+ "/home/u/.codex/skills/.system/imagegen",
+ codexSkillDir(arena, "", "/home/u").?,
+ );
+ try testing.expect(codexSkillDir(arena, null, null) == null);
+ try testing.expect(installDir(arena, null) == null);
+ try testing.expectEqualStrings("/home/u/.harness/skills/imagegen", installDir(arena, "/home/u").?);
+}
+
+test "#352: the addendum goes after the frontmatter, before the body" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const doc = "---\nname: \"imagegen\"\ndescription: \"d\"\n---\n\n# Image Generation Skill\nbody text\n";
+ const out = try withAddendum(arena, doc);
+ try testing.expect(std.mem.startsWith(u8, out, "---\nname: \"imagegen\"")); // frontmatter untouched
+ const marker = std.mem.indexOf(u8, out, "<!-- graff addendum -->").?;
+ 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);
+
+ // No frontmatter: the addendum still leads.
+ const bare = try withAddendum(arena, "# Just a body\n");
+ try testing.expect(std.mem.startsWith(u8, bare, "<!-- graff addendum -->"));
+ // CRLF frontmatter is still recognised as frontmatter.
+ const crlf = try withAddendum(arena, "---\r\nname: x\r\n---\r\nbody\n");
+ try testing.expect(std.mem.startsWith(u8, crlf, "---\r\nname: x"));
+}
+
+test "#352: sync mirrors the tree with LICENSE + scripts, and only re-copies when the source is newer" {
+ 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 base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+ const src = try std.fmt.allocPrint(arena, "{s}/codex/skills/.system/imagegen", .{base});
+ const dest = try std.fmt.allocPrint(arena, "{s}/home/.harness/skills/imagegen", .{base});
+
+ // Nothing on disk yet: not present, nothing to sync.
+ try testing.expect(!present(io, arena, src));
+ try testing.expect(!needsSync(io, arena, src, dest));
+
+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/scripts", .{src}));
+ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/references", .{src}));
+ for ([_]struct { path: []const u8, data: []const u8 }{
+ .{ .path = "SKILL.md", .data = "---\nname: imagegen\ndescription: d\n---\n\n# Body\noriginal\n" },
+ .{ .path = "LICENSE.txt", .data = "LICENSE BODY" },
+ .{ .path = "scripts/image_gen.py", .data = "print('gen')" },
+ .{ .path = "references/cli.md", .data = "# cli" },
+ }) |f| try Io.Dir.cwd().writeFile(io, .{
+ .sub_path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ src, f.path }),
+ .data = f.data,
+ });
+
+ try testing.expect(present(io, arena, src));
+ try testing.expect(needsSync(io, arena, src, dest));
+ try sync(io, arena, src, dest);
+
+ // Everything that matters made the trip, at the same relative paths.
+ for ([_][]const u8{ "LICENSE.txt", "scripts/image_gen.py", "references/cli.md" }) |rel| {
+ const copied = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/{s}", .{ dest, rel }), arena, .limited(4096));
+ try testing.expect(copied.len > 0);
+ }
+ const md = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dest}), arena, .limited(1 << 16));
+ try testing.expect(std.mem.indexOf(u8, md, "<!-- graff addendum -->") != null);
+ try testing.expect(std.mem.indexOf(u8, md, "original") != null); // body preserved
+ try testing.expect(std.mem.startsWith(u8, md, "---\nname: imagegen"));
+
+ // Freshly synced: no re-copy, and a local edit survives.
+ try testing.expect(!needsSync(io, arena, src, dest));
+ const edited = try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{dest});
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = edited, .data = "---\nname: imagegen\ndescription: d\n---\nmine\n" });
+ try testing.expect(!needsSync(io, arena, src, dest)); // the copy is now NEWER than the source
+
+ // A newer upstream SKILL.md is the one thing that re-copies.
+ const src_md = try std.fmt.allocPrint(arena, "{s}/SKILL.md", .{src});
+ const dest_mtime = skillMtime(io, arena, dest).?;
+ try Io.Dir.cwd().setTimestamps(io, src_md, .{
+ .modify_timestamp = .{ .new = .{ .nanoseconds = @intCast(dest_mtime + std.time.ns_per_s) } },
+ });
+ try testing.expect(needsSync(io, arena, src, dest));
+}
diff --git a/src/imagegen_verify.zig b/src/imagegen_verify.zig
new file mode 100644
index 00000000..8b78c6a3
--- /dev/null
+++ b/src/imagegen_verify.zig
@@ -0,0 +1,221 @@
+//! #352 anti-fabrication verification for the `imagegen` tool.
+//!
+//! Why this module exists at all: during the #352 investigation a model was
+//! asked to generate a 64x64 PNG, could not (the hosted `image_gen` tool is
+//! server-side and never fires outside the Codex app), 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". Every part
+//! of that sentence was true except the part that mattered: the image was not
+//! generated by that turn. An md5 comparison is what caught it.
+//!
+//! So a successful `imagegen` result is not a claim, it is a receipt. The
+//! generator's exit code is necessary and nowhere near sufficient; the file it
+//! points at has to independently prove it is a NEW artifact:
+//! * it exists;
+//! * its mtime is at or after the moment we spawned the generator (a stale
+//! glob fails here — this is the check that would have caught #352);
+//! * if it existed before the run, its size or mtime actually moved (a
+//! no-op rewrite of the same bytes is not a generation);
+//! * it is bigger than a floor no real image undercuts (a 0-byte or
+//! truncated download is not an image);
+//! * its leading bytes match the container the caller asked for (a JSON
+//! error body saved to `out.png` is not a PNG).
+//! Any single failure is a tool error naming the failed check. There is no
+//! path to a success result that skips one.
+//!
+//! Everything here is pure over metadata + the file's first bytes, so the
+//! whole decision table is unit-testable with synthetic values and never
+//! needs a network, an API key, or a real generator.
+
+const std = @import("std");
+const Io = std.Io;
+
+/// Below this a "generated image" is a truncated download or an error page.
+pub const min_bytes: u64 = 1024;
+
+/// Filesystem mtime granularity varies (APFS is nanoseconds, some network and
+/// FAT-derived filesystems round to 1-2 seconds), so the freshness comparison
+/// gets a small slack rather than risking a false "stale" on a file that WAS
+/// just written. The #352 artifact was two weeks old; the `unchanged` check
+/// below covers anything that lands inside the slack window.
+pub const mtime_slack_ns: i128 = 2 * std.time.ns_per_s;
+
+pub const Format = enum {
+ png,
+ jpeg,
+ webp,
+
+ /// An explicit `output_format` argument (the CLI's spelling).
+ pub fn fromName(name: []const u8) ?Format {
+ if (std.ascii.eqlIgnoreCase(name, "png")) return .png;
+ if (std.ascii.eqlIgnoreCase(name, "jpeg") or std.ascii.eqlIgnoreCase(name, "jpg")) return .jpeg;
+ if (std.ascii.eqlIgnoreCase(name, "webp")) return .webp;
+ return null;
+ }
+
+ /// The container implied by the output path's extension. PNG is the
+ /// default because it is the CLI's default output format.
+ pub fn fromPath(path: []const u8) Format {
+ const dot = std.mem.lastIndexOfScalar(u8, path, '.') orelse return .png;
+ return fromName(path[dot + 1 ..]) orelse .png;
+ }
+
+ /// Container signature check against the file's leading bytes.
+ pub fn magicOk(self: Format, head: []const u8) bool {
+ return switch (self) {
+ .png => head.len >= 8 and std.mem.eql(u8, head[0..8], "\x89PNG\r\n\x1a\n"),
+ .jpeg => head.len >= 3 and std.mem.eql(u8, head[0..3], "\xff\xd8\xff"),
+ // RIFF....WEBP — the 4 bytes between the two tags are the length.
+ .webp => head.len >= 12 and std.mem.eql(u8, head[0..4], "RIFF") and std.mem.eql(u8, head[8..12], "WEBP"),
+ };
+ }
+
+ pub fn label(self: Format) []const u8 {
+ return switch (self) {
+ .png => "png",
+ .jpeg => "jpeg",
+ .webp => "webp",
+ };
+ }
+};
+
+/// What we knew about the output path at one instant. `existed = false` is the
+/// normal case (a fresh default path); the other fields are then meaningless.
+pub const Snapshot = struct {
+ existed: bool = false,
+ size: u64 = 0,
+ mtime_ns: i128 = 0,
+};
+
+/// Read the output path's current metadata. Absent is a valid answer, not an
+/// error — it is the expected state before a generation.
+pub fn snapshot(io: Io, path: []const u8) Snapshot {
+ const st = Io.Dir.cwd().statFile(io, path, .{}) catch return .{};
+ return .{ .existed = true, .size = st.size, .mtime_ns = st.mtime.nanoseconds };
+}
+
+pub const Verdict = enum {
+ ok,
+ /// The generator exited 0 and wrote nothing at the path it was given.
+ missing,
+ /// The file predates the run — the #352 stale-glob signature.
+ stale,
+ /// The pre-existing file is byte-for-byte where it was.
+ unchanged,
+ /// Too small to be an image (truncated download / error page).
+ too_small,
+ /// Leading bytes are not the requested container.
+ bad_magic,
+
+ pub fn failedCheck(self: Verdict) []const u8 {
+ return switch (self) {
+ .ok => "none",
+ .missing => "output-file-exists",
+ .stale => "output-file-is-fresh (mtime at or after spawn)",
+ .unchanged => "output-file-changed (pre-existing file was not rewritten)",
+ .too_small => "output-file-size-floor",
+ .bad_magic => "output-file-magic-bytes",
+ };
+ }
+
+ pub fn detail(self: Verdict) []const u8 {
+ return switch (self) {
+ .ok => "",
+ .missing => "the generator exited 0 but no file exists at the requested path, so nothing was generated",
+ .stale => "the file at that path is OLDER than this run — it is a pre-existing artifact, not a newly generated image (this is exactly the #352 failure: a stale file passed off as a fresh generation)",
+ .unchanged => "the file at that path existed before this run and its size and mtime are unchanged, so this run did not write it",
+ .too_small => "the file is far too small to be a real image — most likely a truncated download or an error body",
+ .bad_magic => "the file's leading bytes are not the requested image container, so whatever was written is not that image format",
+ };
+ }
+};
+
+/// The whole decision, in order. `after == null` means the path does not exist
+/// after the run. `head` is the file's first bytes (>= 12 is enough for every
+/// signature we check).
+pub fn evaluate(before: Snapshot, after: ?Snapshot, started_ns: i128, head: []const u8, fmt: Format) Verdict {
+ const now = after orelse return .missing;
+ if (now.mtime_ns + mtime_slack_ns < started_ns) return .stale;
+ if (before.existed and now.size == before.size and now.mtime_ns == before.mtime_ns) return .unchanged;
+ if (now.size < min_bytes) return .too_small;
+ if (!fmt.magicOk(head)) return .bad_magic;
+ return .ok;
+}
+
+const png_head = "\x89PNG\r\n\x1a\n" ++ "IHDR-ish padding";
+const spawn_ns: i128 = 1_000_000_000_000;
+
+test "#352: a fresh, big-enough, correctly-signed file is the only thing that passes" {
+ const fresh: Snapshot = .{ .existed = true, .size = 8192, .mtime_ns = spawn_ns + 5_000_000 };
+ try std.testing.expectEqual(Verdict.ok, evaluate(.{}, fresh, spawn_ns, png_head, .png));
+}
+
+test "#352: a stale glob is rejected even though it is a real, valid PNG" {
+ // The actual #352 artifact: a genuine PNG, correct magic, plenty big —
+ // and two weeks old. Exit code and file-type checks both pass; only the
+ // freshness check catches it.
+ const two_weeks_ns: i128 = 14 * 24 * 60 * 60 * std.time.ns_per_s;
+ const stale: Snapshot = .{ .existed = true, .size = 8279, .mtime_ns = spawn_ns - two_weeks_ns };
+ try std.testing.expectEqual(Verdict.stale, evaluate(.{}, stale, spawn_ns, png_head, .png));
+ // ...and a file written a hair before the spawn still counts as fresh,
+ // because filesystem mtime granularity is not ours to trust.
+ const borderline: Snapshot = .{ .existed = true, .size = 8279, .mtime_ns = spawn_ns - std.time.ns_per_s };
+ try std.testing.expectEqual(Verdict.ok, evaluate(.{}, borderline, spawn_ns, png_head, .png));
+}
+
+test "#352: a pre-existing file that did not move is not a generation" {
+ const before: Snapshot = .{ .existed = true, .size = 4096, .mtime_ns = spawn_ns + 1 };
+ // Same size, same mtime: the generator did not touch it. (mtime is inside
+ // the slack window, so the freshness check alone would have let it pass.)
+ try std.testing.expectEqual(Verdict.unchanged, evaluate(before, before, spawn_ns, png_head, .png));
+ // One byte different is enough to prove a rewrite.
+ const rewritten: Snapshot = .{ .existed = true, .size = 4097, .mtime_ns = spawn_ns + 1 };
+ try std.testing.expectEqual(Verdict.ok, evaluate(before, rewritten, spawn_ns, png_head, .png));
+}
+
+test "#352: missing, undersized and wrong-container outputs each fail their own check" {
+ try std.testing.expectEqual(Verdict.missing, evaluate(.{}, null, spawn_ns, "", .png));
+
+ const tiny: Snapshot = .{ .existed = true, .size = 64, .mtime_ns = spawn_ns + 1 };
+ try std.testing.expectEqual(Verdict.too_small, evaluate(.{}, tiny, spawn_ns, png_head, .png));
+
+ const big: Snapshot = .{ .existed = true, .size = 9000, .mtime_ns = spawn_ns + 1 };
+ // An OpenAI JSON error body saved to out.png: fresh, big, and not a PNG.
+ try std.testing.expectEqual(Verdict.bad_magic, evaluate(.{}, big, spawn_ns, "{\"error\": {\"message\"", .png));
+ // A real PNG when JPEG was asked for is equally wrong.
+ try std.testing.expectEqual(Verdict.bad_magic, evaluate(.{}, big, spawn_ns, png_head, .jpeg));
+
+ try std.testing.expect(std.mem.indexOf(u8, Verdict.stale.detail(), "#352") != null);
+ try std.testing.expectEqualStrings("none", Verdict.ok.failedCheck());
+}
+
+test "#352: container signatures and the format each output path implies" {
+ try std.testing.expect(Format.png.magicOk(png_head));
+ try std.testing.expect(!Format.png.magicOk("\x89PNG")); // truncated signature
+ try std.testing.expect(Format.jpeg.magicOk("\xff\xd8\xff\xe0JFIF"));
+ try std.testing.expect(Format.webp.magicOk("RIFF\x24\x00\x00\x00WEBPVP8 "));
+ try std.testing.expect(!Format.webp.magicOk("RIFF\x24\x00\x00\x00WAVEfmt ")); // RIFF, wrong payload
+
+ try std.testing.expectEqual(Format.png, Format.fromPath("out/render.png"));
+ try std.testing.expectEqual(Format.jpeg, Format.fromPath("a.JPG"));
+ try std.testing.expectEqual(Format.webp, Format.fromPath("dir.png/thing.webp"));
+ try std.testing.expectEqual(Format.png, Format.fromPath("no-extension")); // CLI default
+ try std.testing.expectEqual(Format.jpeg, Format.fromName("jpeg").?);
+ try std.testing.expect(Format.fromName("gif") == null);
+}
+
+test "#352: snapshot reports absence as absence and reads back a real file's size" {
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const dir_path = real_buf[0..try tmp.dir.realPath(io, &real_buf)];
+ const path = try std.fmt.allocPrint(std.testing.allocator, "{s}/shot.png", .{dir_path});
+ defer std.testing.allocator.free(path);
+
+ try std.testing.expect(!snapshot(io, path).existed);
+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = png_head });
+ const after = snapshot(io, path);
+ try std.testing.expect(after.existed);
+ try std.testing.expectEqual(@as(u64, png_head.len), after.size);
+}
diff --git a/src/main.zig b/src/main.zig
index 2d52c6ba..67a60137 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"));
+ 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"));
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/schema.zig b/src/schema.zig
index 71de1a47..2f1378ff 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -15,6 +15,12 @@ const pricing = @import("pricing.zig");
const learn_store = @import("learn_store.zig");
const skill_docs = @import("skill_docs.zig"); // SKILL.md playbooks: the `skill` tool's name/desc/schema live there
const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)
+const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capability
+const imagegen = @import("imagegen.zig"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle
+const render = @import("schema_render.zig"); // the comptime provider-tool renderers moved out when #352's optional-tool catalogs doubled the number held here (600-line ceiling)
+const anthropicToolsJson = render.anthropicToolsJson;
+const openaiToolsJson = render.openaiToolsJson;
+const responsesToolsJson = render.responsesToolsJson;
const root = @import("main.zig");
const provider_mod = @import("provider.zig");
@@ -231,6 +237,14 @@ pub fn isMetaName(name: []const u8) bool {
std.mem.eql(u8, name, "clock_sleep");
}
+// #352: optional built-ins — advertised only while tool_gates says they are
+// available. They live in `base_specs`' orbit rather than the root-only block
+// because a subagent has to be able to call them: the documented way to make
+// several images is one subagent per image, each calling `imagegen` once.
+const optional_specs = [_]ToolSpec{
+ .{ .name = imagegen.tool_name, .desc = imagegen.tool_desc, .schema = imagegen.tool_schema },
+};
+
// Comptime-rendered tool lists for subagents (base only, both formats).
pub const tools_anthropic_sub = anthropicToolsJson(&base_specs);
pub const tools_openai_sub = openaiToolsJson(&base_specs);
@@ -244,41 +258,36 @@ pub const tools_anthropic_sub_remote = anthropicToolsJson(base_specs_remote);
pub const tools_openai_sub_remote = openaiToolsJson(base_specs_remote);
pub const tools_responses_sub_remote = responsesToolsJson(base_specs_remote);
-fn anthropicToolsJson(comptime specs: []const ToolSpec) []const u8 {
- comptime {
- var out: []const u8 = "[";
- for (specs, 0..) |t, i| {
- if (i > 0) out = out ++ ",";
- out = out ++ "{\"name\":\"" ++ t.name ++ "\",\"description\":\"" ++ t.desc ++
- "\",\"input_schema\":" ++ t.schema ++ "}";
- }
- return out ++ "]";
- }
-}
-
-fn openaiToolsJson(comptime specs: []const ToolSpec) []const u8 {
- comptime {
- var out: []const u8 = "[";
- for (specs, 0..) |t, i| {
- if (i > 0) out = out ++ ",";
- out = out ++ "{\"type\":\"function\",\"function\":{\"name\":\"" ++ t.name ++
- "\",\"description\":\"" ++ t.desc ++ "\",\"parameters\":" ++ t.schema ++ "}}";
- }
- return out ++ "]";
- }
-}
-
-fn responsesToolsJson(comptime specs: []const ToolSpec) []const u8 {
- comptime {
- var out: []const u8 = "[";
- for (specs, 0..) |t, i| {
- if (i > 0) out = out ++ ",";
- out = out ++ "{\"type\":\"function\",\"name\":\"" ++ t.name ++
- "\",\"description\":\"" ++ t.desc ++ "\",\"parameters\":" ++ t.schema ++
- ",\"strict\":false}";
- }
- return out ++ "]";
- }
+// #352 layer 1, subagent half: the same catalogs WITH the optional tools. A
+// child's catalog is a comptime constant, so every combination is built once
+// at compile time and merely selected at runtime by subToolsJson.
+const base_specs_optional = base_specs ++ optional_specs;
+const base_specs_optional_remote = no_local_tools.remoteSpecs(ToolSpec, &base_specs_optional);
+pub const tools_anthropic_sub_optional = anthropicToolsJson(&base_specs_optional);
+pub const tools_openai_sub_optional = openaiToolsJson(&base_specs_optional);
+pub const tools_responses_sub_optional = responsesToolsJson(&base_specs_optional);
+pub const tools_anthropic_sub_optional_remote = anthropicToolsJson(base_specs_optional_remote);
+pub const tools_openai_sub_optional_remote = openaiToolsJson(base_specs_optional_remote);
+pub const tools_responses_sub_optional_remote = responsesToolsJson(base_specs_optional_remote);
+
+/// The catalog a SUBAGENT is served, across both gates: `--no-local-tools`
+/// subtracts, an available optional tool adds. Sole caller is Agent.toolsJson.
+pub fn subToolsJson(kind: Provider.Kind, gated: bool) []const u8 {
+ const optional = tool_gates.anyAvailable();
+ return switch (kind) {
+ .anthropic => if (gated)
+ (if (optional) tools_anthropic_sub_optional_remote else tools_anthropic_sub_remote)
+ else
+ (if (optional) tools_anthropic_sub_optional else tools_anthropic_sub),
+ .openai => if (gated)
+ (if (optional) tools_openai_sub_optional_remote else tools_openai_sub_remote)
+ else
+ (if (optional) tools_openai_sub_optional else tools_openai_sub),
+ .responses => if (gated)
+ (if (optional) tools_responses_sub_optional_remote else tools_responses_sub_remote)
+ else
+ (if (optional) tools_responses_sub_optional else tools_responses_sub),
+ };
}
/// Render built-in specs + discovered MCP tools into one provider-specific
@@ -304,12 +313,15 @@ pub fn renderRootTools(
/// #330 layer 1, root half: the gate then drops the host-touching tools from
/// whichever catalog was chosen, so they are never advertised to a provider.
/// MCP tools are appended afterwards by renderRootTools and stay untouched.
+/// #352 layer 1, root half: the additive gate then appends each optional tool
+/// whose backing capability startup actually found on this machine.
pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {
const chosen: []const ToolSpec = if (root.g_clock_sleep)
(if (learn_store.active_agent_loaded) &root_specs else &root_specs_without_learning)
else
(if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional);
- return no_local_tools.filterRootSpecs(ToolSpec, arena, chosen);
+ const filtered = try no_local_tools.filterRootSpecs(ToolSpec, arena, chosen);
+ return tool_gates.withAvailable(ToolSpec, arena, filtered, &optional_specs);
}
const Schema = union(enum) { raw: []const u8, value: Value };
@@ -461,7 +473,11 @@ pub fn emitSchema(w: *Io.Writer) !void {
try s.endArray();
try s.objectField("tools");
try s.beginArray();
- for (root_specs) |t| {
+ // Optional tools (#352) are listed unconditionally even though they are
+ // advertised only when available: this document is the SDK codegen
+ // contract and must stay byte-identical across machines. Each such tool's
+ // description states what it needs in order to exist.
+ for (root_specs ++ optional_specs) |t| {
try s.beginObject();
try s.objectField("name");
try s.write(t.name);
@@ -482,8 +498,10 @@ pub fn emitSchema(w: *Io.Writer) !void {
try w.writeByte('\n');
try w.flush();
}
-test { // #330: the gate's own tests (advertising, dispatch, env) live with it
+test { // #330/#352: each gate's own tests (advertising, dispatch, env) live with it
_ = no_local_tools;
+ _ = tool_gates;
+ _ = render;
}
test "providerDisplayName & providerLoginKind: id mapping with sane fallbacks" {
try std.testing.expectEqualStrings("OpenAI", providerDisplayName("openai"));
diff --git a/src/schema_render.zig b/src/schema_render.zig
new file mode 100644
index 00000000..093db248
--- /dev/null
+++ b/src/schema_render.zig
@@ -0,0 +1,72 @@
+//! Comptime provider-tool renderers: one ToolSpec list in, one provider-shaped
+//! JSON tools array out. Split out of schema.zig (600-line ceiling) when the
+//! optional-tool catalogs (#352 imagegen) doubled the number of comptime
+//! catalogs schema.zig has to hold. Pure comptime string building — no imports
+//! beyond std, so schema.zig can call these while building its own constants.
+//!
+//! `specs` is `anytype` rather than `[]const schema.ToolSpec` only to avoid an
+//! import cycle back into schema.zig; every caller passes a comptime list of
+//! structs with `.name`, `.desc` and `.schema`, and `.desc` must stay free of
+//! characters needing JSON escapes (the descriptions are spliced in verbatim).
+
+const std = @import("std");
+
+pub fn anthropicToolsJson(comptime specs: anytype) []const u8 {
+ comptime {
+ var out: []const u8 = "[";
+ for (specs, 0..) |t, i| {
+ if (i > 0) out = out ++ ",";
+ out = out ++ "{\"name\":\"" ++ t.name ++ "\",\"description\":\"" ++ t.desc ++
+ "\",\"input_schema\":" ++ t.schema ++ "}";
+ }
+ return out ++ "]";
+ }
+}
+
+pub fn openaiToolsJson(comptime specs: anytype) []const u8 {
+ comptime {
+ var out: []const u8 = "[";
+ for (specs, 0..) |t, i| {
+ if (i > 0) out = out ++ ",";
+ out = out ++ "{\"type\":\"function\",\"function\":{\"name\":\"" ++ t.name ++
+ "\",\"description\":\"" ++ t.desc ++ "\",\"parameters\":" ++ t.schema ++ "}}";
+ }
+ return out ++ "]";
+ }
+}
+
+pub fn responsesToolsJson(comptime specs: anytype) []const u8 {
+ comptime {
+ var out: []const u8 = "[";
+ for (specs, 0..) |t, i| {
+ if (i > 0) out = out ++ ",";
+ out = out ++ "{\"type\":\"function\",\"name\":\"" ++ t.name ++
+ "\",\"description\":\"" ++ t.desc ++ "\",\"parameters\":" ++ t.schema ++
+ ",\"strict\":false}";
+ }
+ return out ++ "]";
+ }
+}
+
+test "renderers emit one entry per spec in each provider shape" {
+ const Spec = struct { name: []const u8, desc: []const u8, schema: []const u8 };
+ const specs = [_]Spec{
+ .{ .name = "a", .desc = "first", .schema = "{}" },
+ .{ .name = "b", .desc = "second", .schema = "{}" },
+ };
+ // Comptime-only by construction: the catalogs are compile-time constants,
+ // so the call has to be forced into a comptime context here too.
+ const anthropic = comptime anthropicToolsJson(&specs);
+ const openai = comptime openaiToolsJson(&specs);
+ const responses = comptime responsesToolsJson(&specs);
+ try std.testing.expectEqualStrings(
+ "[{\"name\":\"a\",\"description\":\"first\",\"input_schema\":{}},{\"name\":\"b\",\"description\":\"second\",\"input_schema\":{}}]",
+ anthropic,
+ );
+ try std.testing.expect(std.mem.indexOf(u8, openai, "\"type\":\"function\",\"function\":{\"name\":\"a\"") != null);
+ try std.testing.expect(std.mem.endsWith(u8, responses, ",\"strict\":false}]"));
+ // Every rendered catalog must still parse as JSON.
+ var parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, openai, .{});
+ defer parsed.deinit();
+ try std.testing.expectEqual(@as(usize, 2), parsed.value.array.items.len);
+}
diff --git a/src/startup.zig b/src/startup.zig
index b0e7ad8b..15528c38 100644
--- a/src/startup.zig
+++ b/src/startup.zig
@@ -46,6 +46,7 @@ const prompts = @import("prompts.zig");
const learn_store = @import("learn_store.zig");
const learn_bootstrap = @import("learn_bootstrap.zig");
const learn_auto = @import("learn_auto.zig");
+const imagegen = @import("imagegen.zig"); // #352: codex-skill detection + the personal-tier skill mirror
pub const ResolvedKeys = struct {
keys: provider_mod.Keys,
@@ -342,6 +343,8 @@ 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,
) ![]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;
@@ -380,6 +383,14 @@ pub fn buildSystemPrompt(
const note = skills.codedbproNote(mn.server, codedbpro_licensed, mn.note);
sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ sys_normal, note });
}
+ // #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);
+ if (imagegen.available and !quiet) {
+ try out.print("imagegen: Codex skill found — tool enabled, playbook at {s}\n", .{imagegen.skill_dir});
+ try out.flush();
+ }
// Markdown skills (skill_docs.zig): names + trigger descriptions only. The
// bodies stay on disk until the model calls the `skill` tool, so a large
// installed skill set costs a line each rather than its full text. Loaded
diff --git a/src/tool_gates.zig b/src/tool_gates.zig
new file mode 100644
index 00000000..74fea8b4
--- /dev/null
+++ b/src/tool_gates.zig
@@ -0,0 +1,182 @@
+//! #352: optional built-in tools — catalog entries that exist only when a
+//! runtime availability check passes.
+//!
+//! `no_local_tools.zig` is the SUBTRACTIVE gate (a flag removes tools that
+//! would otherwise always be there). This is the ADDITIVE one: a tool whose
+//! backing capability lives outside the binary is absent from every catalog
+//! until startup proves the capability is installed, so a provider is never
+//! told about a tool that cannot possibly succeed on this machine — and the
+//! model cannot burn a turn discovering that for itself.
+//!
+//! Same shape as the subtractive gate, deliberately:
+//! * a name test (`isOptional`) independent of any flag, so the comptime
+//! catalogs and the runtime assembly share one list;
+//! * a process-global boolean per tool, set once at startup and never
+//! flipped mid-session, so subagents/workflow workers/judges inherit it
+//! with no per-agent plumbing to forget.
+//!
+//! Adding a second optional tool is one row in `gates` plus its ToolSpec in
+//! schema.zig's `optional_specs` — no new branching anywhere.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+const imagegen = @import("imagegen.zig");
+
+/// One optional built-in and the flag that decides whether it is advertised.
+pub const Gate = struct {
+ name: []const u8,
+ /// Read at catalog-assembly time; owned by the tool's own module.
+ flag: *const bool,
+};
+
+pub const gates = [_]Gate{
+ // #352: needs the Codex imagegen skill on disk (its bundled CLI is the
+ // only engine that actually renders an image — the hosted `image_gen`
+ // tool is server-side and never fires outside the Codex app).
+ .{ .name = imagegen.tool_name, .flag = &imagegen.available },
+};
+
+/// A name test only, independent of whether the tool is currently available.
+pub fn isOptional(name: []const u8) bool {
+ for (gates) |gate| {
+ if (std.mem.eql(u8, name, gate.name)) return true;
+ }
+ return false;
+}
+
+/// Whether this tool may be advertised right now. Non-optional names are
+/// always advertised, so callers can ask about any tool name.
+pub fn advertised(name: []const u8) bool {
+ for (gates) |gate| {
+ if (std.mem.eql(u8, name, gate.name)) return gate.flag.*;
+ }
+ return true;
+}
+
+/// True when at least one optional tool is available — the selector the
+/// comptime subagent catalogs switch on.
+pub fn anyAvailable() bool {
+ for (gates) |gate| {
+ if (gate.flag.*) return true;
+ }
+ return false;
+}
+
+/// Layer 2's predicate: a call to an optional tool that is NOT available must
+/// be refused before anything runs, even though it was never advertised — a
+/// provider can hallucinate a tool name it saw in a previous session or in
+/// this document.
+pub fn blocks(name: []const u8) bool {
+ return isOptional(name) and !advertised(name);
+}
+
+/// `base` plus every currently-available optional spec, in `gates` order.
+/// Returns `base` untouched when none are available, so the common path
+/// allocates nothing (mirrors no_local_tools.filterRootSpecs).
+pub fn withAvailable(comptime Spec: type, arena: Allocator, base: []const Spec, optional: []const Spec) ![]const Spec {
+ var extra: usize = 0;
+ for (optional) |spec| {
+ if (advertised(spec.name)) extra += 1;
+ }
+ if (extra == 0) return base;
+ const buf = try arena.alloc(Spec, base.len + extra);
+ @memcpy(buf[0..base.len], base);
+ var i = base.len;
+ for (optional) |spec| {
+ if (!advertised(spec.name)) continue;
+ buf[i] = spec;
+ i += 1;
+ }
+ return buf[0..i];
+}
+
+test "#352: an optional tool is advertised only while its flag is set; other names are unaffected" {
+ const saved = imagegen.available;
+ defer imagegen.available = saved;
+
+ try std.testing.expect(isOptional("imagegen"));
+ try std.testing.expect(!isOptional("bash"));
+ try std.testing.expect(!isOptional("skill"));
+
+ imagegen.available = false;
+ try std.testing.expect(!advertised("imagegen"));
+ try std.testing.expect(!anyAvailable());
+ try std.testing.expect(blocks("imagegen"));
+ try std.testing.expect(advertised("bash")); // never optional -> always advertised
+ try std.testing.expect(!blocks("bash"));
+
+ imagegen.available = true;
+ try std.testing.expect(advertised("imagegen"));
+ try std.testing.expect(anyAvailable());
+ try std.testing.expect(!blocks("imagegen"));
+}
+
+test "#352: withAvailable appends only available optionals, and does not allocate when none are" {
+ const Spec = struct { name: []const u8 };
+ const base = [_]Spec{ .{ .name = "bash" }, .{ .name = "webfetch" } };
+ const optional = [_]Spec{.{ .name = "imagegen" }};
+
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const saved = imagegen.available;
+ defer imagegen.available = saved;
+
+ imagegen.available = false;
+ const without = try withAvailable(Spec, arena, &base, &optional);
+ try std.testing.expectEqual(base.len, without.len);
+ try std.testing.expectEqual(@as(usize, 0), arena_state.queryCapacity());
+
+ imagegen.available = true;
+ const with = try withAvailable(Spec, arena, &base, &optional);
+ try std.testing.expectEqual(base.len + 1, with.len);
+ try std.testing.expectEqualStrings("bash", with[0].name);
+ try std.testing.expectEqualStrings("imagegen", with[2].name); // appended last, base order preserved
+}
+
+test "#352: neither the root nor the SUBAGENT catalog mentions imagegen until it is available" {
+ // Imported inside the test, like no_local_tools does: schema.zig imports
+ // this module at the top level, so the pair is a cycle at file scope.
+ const schema = @import("schema.zig");
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ const saved = imagegen.available;
+ defer imagegen.available = saved;
+
+ const kinds = [_]@import("provider.zig").Provider.Kind{ .anthropic, .openai, .responses };
+
+ imagegen.available = false;
+ const closed = try schema.effectiveRootSpecs(arena);
+ for (closed) |spec| try std.testing.expect(!std.mem.eql(u8, spec.name, "imagegen"));
+ // The subagent fan-out is the documented way to make several images, so a
+ // child must see exactly the same gate the root does — in every wire format.
+ for (kinds) |kind| for ([_]bool{ false, true }) |gated| {
+ try std.testing.expect(std.mem.indexOf(u8, schema.subToolsJson(kind, gated), "\"imagegen\"") == null);
+ };
+
+ imagegen.available = true;
+ const open = try schema.effectiveRootSpecs(arena);
+ try std.testing.expectEqual(closed.len + 1, open.len);
+ var root_has = false;
+ for (open) |spec| {
+ if (std.mem.eql(u8, spec.name, "imagegen")) root_has = true;
+ }
+ try std.testing.expect(root_has);
+ for (kinds) |kind| for ([_]bool{ false, true }) |gated| {
+ const catalog = schema.subToolsJson(kind, gated);
+ try std.testing.expect(std.mem.indexOf(u8, catalog, "\"imagegen\"") != null);
+ // --no-local-tools still subtracts inside the optional twin: the two
+ // gates compose rather than one cancelling the other.
+ try std.testing.expectEqual(!gated, std.mem.indexOf(u8, catalog, "\"name\":\"bash\"") != null or
+ std.mem.indexOf(u8, catalog, "\"name\": \"bash\"") != null);
+ var parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, catalog, .{});
+ defer parsed.deinit();
+ try std.testing.expect(parsed.value.array.items.len > 1);
+ };
+ // Subagents still cannot spawn subagents, optional tools or not.
+ try std.testing.expect(std.mem.indexOf(u8, schema.subToolsJson(.anthropic, false), "\"name\":\"subagent\"") == null);
+}