Skip to content

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

Python

Merge #103 /images command (PR #222)

justrach21ae0f96dd1b
diff --cc scripts/eval/tier1-manifest.json
index 3ecaca26,00000000..43580977
mode 100644,000000..100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@@ -1,72 -1,0 +1,72 @@@
+{
+ "schema": "codegraff.eval.tier1.manifest.v1",
+ "comment": [
+ "Tier 1 of the internal eval set: the deterministic invariants the pre-push hook enforces.",
+ "No network, no model calls. Tier 2 (model-backed behavior) lives in evals/ and is opt-in.",
+ "test_count_baseline is a ratchet: the suite may grow, it may never shrink. A drop means a",
+ "module stopped being referenced from the test root and its tests silently vanished."
+ ],
+ "test_roots": [
+ "src/main.zig",
+ "src/repl.zig"
+ ],
- "test_count_baseline": 504,
++ "test_count_baseline": 517,
+ "required_invariants": [
+ {
+ "id": "goal-epochs",
+ "test": "epochs: nextEpoch clears the live goal AND every parked epoch; currentEpoch 0 without a goal",
+ "why": "#318: a new goal inherited the previous goal's checklist and was born done."
+ },
+ {
+ "id": "todo-preserve",
+ "test": "a replace keeps omitted completed items and still drops omitted open ones",
+ "why": "2896b32: a replace deleted completed items the model omitted, erasing finished work."
+ },
+ {
+ "id": "todo-empty-write",
+ "test": "a write with zero usable items is rejected untouched, never completion evidence (#318)",
+ "why": "6300514: an empty todo_write wiped the checklist and read as completion."
+ },
+ {
+ "id": "loop-expired",
+ "test": "/loop: a passed wall-clock deadline stops as expired and flips nothing",
+ "why": "6300514: a timed run past its deadline must stop as expired, not as accepted."
+ },
+ {
+ "id": "loop-idle",
+ "test": "/loop: a restored all-[x] list is idle, not accepted (#318)",
+ "why": "#318: a leftover finished checklist ended a fresh /loop at iteration 1."
+ },
+ {
+ "id": "goal-loop-one-run",
+ "test": "/goal and /loop produce the same run; only /goal adopts the objective",
+ "why": "010b9ad: /goal and /loop are one autonomous run; they must not drift apart."
+ },
+ {
+ "id": "compaction-keeps-goal",
+ "test": "compactionSnapshot: no live goal, no checklist, and a capped render (#318)",
+ "why": "#318: compaction dropped the goal and its completed items mid-run."
+ },
+ {
+ "id": "completion-gate",
+ "test": "completionGate: open list refused once, no-checklist needs confirm, done list accepts, review exempt (#318)",
+ "why": "#318: the model could claim completion over an unfinished checklist."
+ },
+ {
+ "id": "child-deadline",
+ "test": "childTaskPrompt: the same absolute deadline reaches every child, minus a margin",
+ "why": "d33c4a4: a timed /loop must hand its deadline down, or children outlive the run."
+ }
+ ],
+ "docs_only_paths": [
+ "*.md",
+ "docs/*",
+ "plans/*",
+ "social/*",
+ "socials/*",
+ "assets/*",
+ "benchmarks/*.png",
+ "*.png",
+ "LICENSE"
+ ]
+}
diff --cc src/commands_model.zig
index 8c0bae96,4ea7b4d5..3f7226db
--- a/src/commands_model.zig
+++ b/src/commands_model.zig
@@@ -44,6 -44,7 +44,8 @@@ const fallback_config = @import("fallba
const serde = @import("serde.zig");
const oauth = @import("oauth.zig");
++const oauth_helpers = @import("oauth_helpers.zig"); // openBrowser moved here; the #103 branch predates that
+ const images = @import("images.zig");
const reasoning_levels = [_]PickItem{
.{ .name = "Low", .desc = "Fast responses with lighter reasoning" },
@@@ -59,8 -60,36 +61,35 @@@ const stageImagePath = vision.stageImag
const visionCapable = vision.visionCapable;
const grabClipboardImage = vision.grabClipboardImage;
+ /// Serialized JSON of the most recent turn (from the user's last typed prompt to
+ /// the end) — what /images scans for image URLs. Provider-agnostic: URLs in
+ /// assistant text and tool outputs survive JSON serialization intact.
+ fn recentTurnText(root: *Agent, arena: Allocator) []const u8 {
+ const msgs = root.messages.items;
+ var start: usize = 0;
+ var k = msgs.len;
+ while (k > 0) : (k -= 1) {
+ // Stop at the genuinely most-recent user turn — plain text OR an image
+ // attachment (array content) — but not an anthropic tool_result-only user
+ // message; cleanUserTurn is exactly that discriminator.
+ if (Agent.cleanUserTurn(msgs[k - 1])) {
+ start = k - 1;
+ break;
+ }
+ }
+ var aw: Io.Writer.Allocating = .init(arena);
+ for (msgs[start..]) |m| {
+ // A fresh Stringify per message: one instance can only serialize a single
+ // top-level value. Newline-delimited is fine — we only scan for URLs.
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.write(m) catch {};
+ aw.writer.writeByte('\n') catch {};
+ }
+ return aw.writer.buffered();
+ }
+
fn providerKnown(id: []const u8) bool {
- for (provider_specs) |spec| if (std.mem.eql(u8, spec.id, id)) return true;
- return false;
+ return provider_mod.specFor(id) != null;
}
fn showFallback(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
@@@ -520,6 -542,40 +549,40 @@@ pub fn tryHandle(root: *Agent, keys: *K
try out.flush();
return true;
}
+ if (std.mem.eql(u8, line, "/images")) {
+ // Transient: serialize + scan the last turn in a scratch arena freed on
+ // return, so /images never accumulates in the long-lived session arena (#124).
+ var scratch = std.heap.ArenaAllocator.init(root.gpa);
+ defer scratch.deinit();
+ const sa = scratch.allocator();
+ const urls = images.extractImageUrls(sa, recentTurnText(root, sa)) catch &[_][]const u8{};
+ if (urls.len == 0) {
+ try out.writeAll("no image URLs in the last response — /images opens images from the most recent turn's output (e.g. a `gh issue view` with attachments)\n");
+ try out.flush();
+ return true;
+ }
+ // GRAFF_NO_BROWSER (headless/SSH) suppresses the spawn; the command then
+ // just lists the URLs, which also lets a test assert them without opening
+ // real browser tabs.
+ const suppress = main_mod.g_no_browser;
+ // Cap the spawn so a reply full of image URLs can't flood the browser with
+ // tabs; the full list is always printed so the rest are one copy away.
+ const max_open = 8;
+ if (!suppress) {
+ const n = @min(urls.len, max_open);
- for (urls[0..n]) |u| oauth.openBrowser(root.io, u);
++ for (urls[0..n]) |u| oauth_helpers.openBrowser(root.io, u);
+ }
+ if (urls.len == 1) {
+ try out.print("{s} {s}\n", .{ if (suppress) "image:" else "opening", urls[0] });
+ } else {
+ try out.print("{s} {d} images:\n", .{ if (suppress) "found" else "opening", urls.len });
+ for (urls, 1..) |u, n| try out.print(" {d}. {s}\n", .{ n, u });
+ if (!suppress and urls.len > max_open)
+ try out.print("(opened the first {d}; open the rest from the list above)\n", .{max_open});
+ }
+ try out.flush();
+ return true;
+ }
if (std.mem.startsWith(u8, line, "/image")) {
const path = std.mem.trim(u8, line["/image".len..], " \t");
if (path.len == 0) {
diff --cc src/main.zig
index 2cc098f3,0a8689ac..8c173264
--- a/src/main.zig
+++ b/src/main.zig
@@@ -180,6 -185,8 +180,7 @@@ pub var g_worktree_autocommit: bool = t
/// report its capacity next to the scratch arena's.
pub var g_session_arena: ?*std.heap.ArenaAllocator = null;
pub var g_mem_debug: bool = false;
-/// GRAFF_NO_BROWSER=1: don't spawn a browser (headless/SSH); /images just lists the URLs.
-pub var g_no_browser: bool = false;
++pub var g_no_browser: bool = false; // GRAFF_NO_BROWSER=1: headless/SSH, /images just lists the URLs
/// Short task label for terminal/TUI headers (mirrors the GUI's first-prompt fallback: the user's first message as a compact tab/session title).
// Session-title + header rendering + provider-response text parsers live in title.zig.
const title_mod = @import("title.zig");
@@@ -253,22 -257,13 +254,23 @@@ pub fn main(init: std.process.Init) !vo
// reset each request() so a long REPL/--json/serve session's RSS stays flat.
var scratch_state = std.heap.ArenaAllocator.init(gpa);
defer scratch_state.deinit();
+ defer hooks.deinitCodedbCache(gpa, io);
g_session_arena = init.arena;
g_mem_debug = init.environ_map.get("GRAFF_MEM_DEBUG") != null;
+ g_no_browser = init.environ_map.get("GRAFF_NO_BROWSER") != null;
// Windows: let the console interpret ANSI/VT escapes so the harness's color and cursor sequences render instead of literal text.
if (builtin.os.tag == .windows) tty.enableVtOutput();
+ // Environment supplies the default; an explicit CLI flag parsed below has
+ // the usual higher precedence for this invocation.
+ if (init.environ_map.get("GRAFF_MAX_MODEL_CALLS")) |raw| {
+ max_model_calls = std.fmt.parseInt(u64, raw, 10) catch
+ std.process.fatal("GRAFF_MAX_MODEL_CALLS needs a non-negative integer, got '{s}'", .{raw});
+ }
// CLI flags: the Flags struct + parsing loop live in args.zig; downstream code reads flags.<name> in place of ~27 locals this block used to declare.
const flags = try args.parse(init);
+ learning_privacy.init(flags.learning_privacy_flag, init.environ_map.get("GRAFF_LEARNING_PRIVACY"));
+ var invocation_budget: run_budget_mod.RunBudget = .{ .max_model_calls = max_model_calls };
+ boot.mark(init.io, "args");
// GRAFF_CODEX_URL: override the codex responses endpoint (localhost mocks / integration tests). Parsed BEFORE subcommand dispatch and
// resolveKeys — `graff models [refresh]` fetches the catalog inside runSubcommand and the initial Keys.build runs inside resolveKeys.
// environ_map slices are process-lifetime (resolveKeys stores them into Keys the same way), so the value is kept as-is without duping.