graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: keep ask_user images and pin them across compaction (#586)
Rachae03d7148673
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d2ebf5ec..953cc585 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,15 @@ current is part of cutting a release.raw terminal buffer, not the prose stream. Background jobs inject agrok-build-style completion wake at the next step and, in the TUI,start a turn while idle. Do not poll.+- `ask_user` pasted images reach the next model request as real vision+ blocks (a follow-up user message after the text tool result). Nine+ `[Image]` placeholders with no pixels was #580. If nothing staged, the+ tool result says so and names path / paste-text / next-prompt fallbacks.+- Compaction and emergency trim stop before an unresolved current user+ prompt and keep its image blocks verbatim (#581). A retry does not move+ that cut. If the live prompt is the whole history, compact fails+ explicitly instead of summarizing attachments to text. Traces emit+ `compact_cut` with the boundary and preserved image count, not pixels.- Test ratchet: unit suite 1486.## v0.0.267 (2026-08-19)diff --git a/docs/adr/0015-ask-user-images-are-a-follow-up-user-message.md b/docs/adr/0015-ask-user-images-are-a-follow-up-user-message.mdnew file mode 100644index 00000000..e6a41c54--- /dev/null+++ b/docs/adr/0015-ask-user-images-are-a-follow-up-user-message.md@@ -0,0 +1,32 @@+# 0015. ask_user images are a follow-up user message++Status: accepted 2026-08-20++## Context++#580: the clarification UI accepted screenshots, but `ask_user`'s tool+result was literal `[Image]` placeholders. Responses `function_call_output`+and OpenAI `role:tool` content are strings. Anthropic `tool_result` can+carry image blocks, but a shared shape that works on every wire is a+user message with the same vision blocks a normal prompt already builds.++Putting base64 in `function_call_output.output` would also blow the+Responses 16k output cap (#95's sibling) and the per-output handle contract.++## Decision++- Stage every successful paste/drop/`@[path]` on a 16-slot queue (the last+ image still fills `pending_image` for history nav).+- `ask_user` returns text only. After that tool result is appended,+ `vision_queue.flushPending` adds one user message with the queued+ image blocks, same builder as the main prompt.+- If the reply has `[Image]` markers and the queue is empty, the tool+ result names path / paste-text / next-prompt fallbacks instead of+ implying the pixels arrived.++## Consequences++The next model request sees the text result and the pixels. Compaction+must keep that follow-up (and the opening user prompt of an unresolved+turn) verbatim — see #581. Revisit inlining images into Anthropic+`tool_result` only if a provider rejects the extra user message.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c301fb4f..5e45f1ff 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -25,6 +25,7 @@ record only when you need the evidence or the edge cases.| [0012](0012-overflow-handles-named-limits-extra-roots.md) | Fat tool results become `tr_N` handles; named `--context-limit` caps prefix bytes; `--add-dir` extra roots are PathConfine allow-lists, not cwd/skill/session sources. || [0013](0013-list-dir-lives-in-codedb.md) | Directory listing is `codedb list_dir` (in-process BFS, gitignore, 10k cap), not a new always-on catalog tool. || [0014](0014-session-resume-carries-the-room-cursor.md) | `/resume` restores the peer-channel byte cursor and inbox; it does not replay the room into history. |+| [0015](0015-ask-user-images-are-a-follow-up-user-message.md) | `ask_user` images ride a follow-up user message after the text tool result; Responses/OpenAI tool output stays text-only. |## When to write onediff --git a/docs/releases/v0.0.268.md b/docs/releases/v0.0.268.mdindex 2e689289..6ccf23f6 100644--- a/docs/releases/v0.0.268.md+++ b/docs/releases/v0.0.268.md@@ -50,6 +50,14 @@ next agent step sees it, and an idle TUI starts a turn. Combined withADR 0010 (wait-for-exit already in 0.0.267), the model should not poll`bash_output` every 30s.+## Images in ask_user and compaction++Pasted screenshots in an `ask_user` reply used to arrive as `[Image]`+placeholders (#580). They now ride a follow-up user vision message after+the text tool result (ADR 0015). Compaction and emergency trim stop+before an unresolved current prompt so those blocks are not summarized+to text (#581).+## DistributionPrebuilt archives are available for Linux, macOS, and Windows on arm64 anddiff --git a/src/agent.zig b/src/agent.zigindex b8133be8..ac9a6898 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -135,7 +135,9 @@ pub const Agent = struct {md_indent: usize = 0, // hanging indent for wrapped continuation linesmd_width: usize = 0, // cached termCols() for the current line (0 = unset)snapshots: ?*tools_mod.Snapshots = null, // file-edit history for /rewind (root only)- pending_image: ?vision.PendingImage = null, // staged by /image, sent with the next turn+ pending_image: ?vision.PendingImage = null, // last staged image (history nav)+ pending_images: [16]vision.PendingImage = @splat(.{ .media_type = "", .b64 = "", .label = "" }),+ pending_image_len: u8 = 0, // queued pastes for this turn (#580)home: []const u8 = "", // $HOME, for /key persistence (set by main)model_catalog: ?models_cache.LazyCodexCatalog = null, // demand-loaded dynamic Codex rows (root only)stored_keys_loaded: bool = true, // false after an explicit-provider launch; model surfaces fill the remaining Keychain slots@@ -431,8 +433,8 @@ pub const Agent = struct {pub const gateTool = @import("agent_tools.zig").gateTool;pub const firstWord = @import("agent_tools.zig").firstWord;pub const handleMeta = @import("agent_tools.zig").handleMeta;- pub const askUser = @import("agent_tools.zig").askUser;- pub const emitAskUser = @import("agent_tools.zig").emitAskUser;+ pub const askUser = @import("ask_user.zig").askUser;+ pub const emitAskUser = @import("ask_user.zig").emitAskUser;pub const sayToolUse = @import("agent_tools.zig").sayToolUse;pub const sayToolResult = @import("agent_tools.zig").sayToolResult;pub const renderTodos = goal_state.renderTodos; // body in goal_state.zig (600-line cap)diff --git a/src/agent_compact.zig b/src/agent_compact.zigindex 92e2d3c4..ef3992cb 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -5,7 +5,6 @@ const std = @import("std");const Value = std.json.Value;const Allocator = std.mem.Allocator;const utf8Prefix = @import("util.zig").utf8Prefix;-const context_tokens = @import("context_tokens.zig");const main_mod = @import("main.zig");const agent_mod = @import("agent.zig");@@ -39,31 +38,17 @@ pub const appendEvalLog = agent_eval.appendEvalLog;pub const runJudge = agent_eval.runJudge;pub const recent_context_tokens: u64 = 8_000;+const compact_cut = @import("compact_cut.zig");+pub const recentContextStart = compact_cut.recentContextStart;+pub const cleanUserTurn = compact_cut.cleanUserTurn;+pub const turnOpeningUserIndex = compact_cut.turnOpeningUserIndex;+pub const emergencyCutIndex = compact_cut.emergencyCutIndex;/// Head-cap for a child's pinned task prompt when restated in a handoff./// ~2k tokens; head-capped because a workflow child's prompt carries the/// previous phase's results as a TAIL, so the head is the instruction.pub const task_pin_cap: usize = 8_000;-/// Pick the earliest clean user-turn boundary whose suffix fits in the recent-/// context budget. Returning items.len means "summarize everything". We never-/// split at a tool output, so retained call/result history stays valid.-pub fn recentContextStart(items: []const Value, token_budget: u64) usize {- if (items.len == 0 or token_budget == 0) return items.len;- var total: u64 = 0;- var start = items.len;- var i = items.len;- while (i > 0) {- i -= 1;- total +|= context_tokens.estimatedTokens(items[i]);- if (total > token_budget) break;- if (cleanUserTurn(items[i])) start = i;- }- // If the entire conversation fits, summarizing all is the only operation- // that can actually reduce context; otherwise compaction would be a no-op.- return if (start == 0) items.len else start;-}-/// Ask the model for a context-handoff summary (no tools), then restart/// history from that summary.pub fn summaryResponseComplete(self: *Agent, root: std.json.ObjectMap) bool {@@ -150,6 +135,13 @@ pub fn compact(self: *Agent) anyerror!usize {const live_context_local_tokens = self.context_local_tokens;const live_effective_context = self.effectiveContextTokens();const recent_start = recentContextStart(live_messages.items, recent_context_tokens);+ compact_cut.noteCut(self.tracer, live_messages.items, recent_start);+ // #581: pinning the live prompt at index 0 means there is no completed+ // prefix to summarize. Dropping it would replace current images with text.+ if (recent_start == 0) {+ if (!main_mod.json_mode) try self.say("[compaction skipped: the current prompt's attachments must stay verbatim]\n", .{});+ return error.ActivePromptPinned;+ }const recent_messages = live_messages.items[recent_start..];var summary_messages = std.json.Array.init(compact_arena);try summary_messages.ensureTotalCapacity(recent_start);@@ -329,28 +321,6 @@ pub fn pinChildTask(self: *Agent) void {self.task_prompt = self.arena.dupe(u8, c.string) catch null;}-pub fn cleanUserTurn(m: Value) bool {- if (m != .object) return false;- const role = m.object.get("role") orelse return false;- if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;- const content = m.object.get("content") orelse return true;- switch (content) {- .string => |s| return !peer_context.isPeerInjectContent(s),- .array => |arr| {- // An anthropic user message that only carries tool_result blocks- // is the response half of a tool call — it can't begin a- // conversation, so it is not a safe trim boundary.- for (arr.items) |blk| {- if (blk != .object) continue;- const t = blk.object.get("type") orelse continue;- if (t == .string and std.mem.eql(u8, t.string, "tool_result")) return false;- }- return true;- },- else => return true,- }-}-/// #174: drop Responses `reasoning` items older than the last user message,/// in place (no allocation). These are exactly the items the backend discards/// from chained context (previous_response_id), so removing them can't lose@@ -381,19 +351,6 @@ pub fn dropPriorTurnReasoning(self: *Agent) usize {return dropped;}-/// Index to cut history at for an emergency trim: the first clean user turn-/// at or after the midpoint, so messages[cut..] is always a valid-/// conversation start (never an orphaned tool_result). null when there is no-/// safe cut — too short, or only tool_result user messages remain.-pub fn emergencyCutIndex(items: []const Value) ?usize {- if (items.len < 4) return null;- var i: usize = items.len / 2;- while (i < items.len) : (i += 1) {- if (cleanUserTurn(items[i])) return i;- }- return null;-}-/// Re-pair the meter after removing locally measurable context. The server-only/// delta remains intact, while the current local component reflects the trim.fn accountForReclaimedTokens(self: *Agent, reclaimed_tokens: u64) void {@@ -560,7 +517,7 @@ pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {self.compact_transport_failures = 0;return; // user hit Esc mid-compaction},- error.EmptySummary, error.IncompleteSummary => {}, // compact() already explained it+ error.EmptySummary, error.IncompleteSummary, error.ActivePromptPinned => {}, // compact() already explained itelse => {if (main_mod.json_mode)self.emit(.{ .type = "error", .message = std.fmt.allocPrint(self.arena, "auto-compaction failed: {s}", .{@errorName(err)}) catch "auto-compaction failed" })diff --git a/src/agent_steps.zig b/src/agent_steps.zigindex ae347261..0349f04d 100644--- a/src/agent_steps.zig+++ b/src/agent_steps.zig@@ -22,6 +22,7 @@ const util = @import("util.zig");const eval_control = @import("agent_eval_control.zig");const codex_chain = @import("codex_chain.zig");const toolResultMessage = messages_mod.toolResultMessage;+const vision_queue = @import("vision_queue.zig");fn surfaceUnstreamedText(self: *Agent, text: []const u8) !void {if (self.sub or self.streamed_text or text.len == 0) return;@@ -141,6 +142,7 @@ pub fn stepResponses(self: *Agent, response: std.json.ObjectMap) !?[]const u8 {const fco = try toolResultMessage(self.arena, .responses, call.id, r.text, r.is_error);try self.messages.append(fco);}+ try vision_queue.flushPending(self);if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) {if (try grantRepairTurn(self)) return null;return eval_control.verifier_hard_stop;@@ -201,6 +203,7 @@ pub fn stepAnthropic(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {try user_msg.put(self.arena, "role", .{ .string = "user" });try user_msg.put(self.arena, "content", .{ .array = blocks });try self.messages.append(.{ .object = user_msg });+ try vision_queue.flushPending(self);if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) {if (try grantRepairTurn(self)) return null;@@ -289,6 +292,7 @@ pub fn stepOpenAI(self: *Agent, root: std.json.ObjectMap) !?[]const u8 {const tool_msg = try toolResultMessage(self.arena, .openai, call.id, r.text, r.is_error);try self.messages.append(tool_msg);}+ try vision_queue.flushPending(self);if (eval_control.shouldStopAfterBatch(calls.items, self.eval_repair_pending)) {if (try grantRepairTurn(self)) return null;return eval_control.verifier_hard_stop;diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex 860f6ac9..946cf6e2 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -11,17 +11,12 @@ const Io = std.Io;const Value = std.json.Value;const main_mod = @import("main.zig");-const json_inbox = @import("json_inbox.zig");const review = @import("review.zig");const agent_mod = @import("agent.zig");const Agent = agent_mod.Agent;const ToolCall = tools_mod.ToolCall;const ExecResult = tools_mod.ExecResult;-const AnswerRequest = tools_mod.AnswerRequest;-const answerParseError = tools_mod.answerParseError;-const parseAnswerRequest = tools_mod.parseAnswerRequest;-// #422 slice 1c: every emission here leaves as a typed event; the terminal// palette lives in agent_tool_render.zig, behind the sink. `term.zig` stays// because raw/nonblocking stdin for the Esc watcher below is frontend INPUT,@@ -56,8 +51,6 @@ const playbook_glue = @import("playbook_glue.zig"); // #381: the note_constraintconst mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the load_tool_schemas meta armconst native_fold = @import("native_fold.zig"); // folded native power tools: load_tool_schemas's native halfconst util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupted-elapsed measurement-const readline = @import("readline.zig"); // ask_user answers get the same full editor as the main prompt-const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event// #440: the ONE size contract for a tool result — preview + durable handle +// byte count + shape hint, applied at tool time, clamped under the send-time cap.@@ -372,74 +365,6 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {return .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };}-/// Block the root agent for an ask_user reply; subagents have no stdin.-pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {- const in = self.in orelse return .{- .text = "no human is attached — make a reasonable assumption and continue",- .is_error = true,- };- const w = self.out.?;- const question = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "question") orelse "(no question)") else "(no question)";- if (main_mod.json_mode) {- const call_id = if (call.id.len > 0) call.id else blk: {- const id = try std.fmt.allocPrint(self.arena, "ask_user-{d}", .{self.next_ask_id});- self.next_ask_id += 1;- break :blk id;- };- try self.emitAskUser(call_id, question, call.input);- const raw = (try json_inbox.reply(self.arena, in)) orelse return .{- .text = "user ended input without answering",- .is_error = true,- };- const parsed = std.json.parseFromSliceLeaky(Value, self.arena, std.mem.trim(u8, raw, " \t\r"), .{ .allocate = .alloc_always }) catch return .{- .text = "invalid answer JSON for ask_user",- .is_error = true,- };- const answer = parseAnswerRequest(parsed, call_id) catch |err| return .{- .text = answerParseError(err),- .is_error = true,- };- if (answer.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };- return .{ .text = try self.arena.dupe(u8, answer.text), .is_error = false };- }- // Skip the re-print only when the question streamed live in full.- if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});- if (tools_mod.json_args.object(call.input)) |o| if (tools_mod.json_args.arrayOf(o, "options")) |opts| {- for (opts, 1..) |opt, n| try w.print(" {d}) {s}\n", .{ n, tools_mod.json_args.text(opt) orelse "(non-text option)" });- };- // Route the reply through the same full-line editor as the main prompt:- // cursor editing, bracketed paste, the `@` file picker, and Ctrl-V- // clipboard images. A bare takeDelimiter here stripped all of that from- // ask_user. Answers get a scratch history so they never pollute the main- // prompt's up-arrow recall.- var answer_history: std.ArrayList([]const u8) = .empty;- defer answer_history.deinit(self.arena);- var answer_buf: std.ArrayList(u8) = .empty;- defer answer_buf.deinit(self.arena);- const raw = (try readline.readLine(self, in, w, self.arena, &answer_history, &answer_buf, " your answer › ")) orelse return .{- .text = "user ended input without answering",- .is_error = true,- };- const answer = std.mem.trim(u8, raw, " \t\r");- return .{ .text = try self.arena.dupe(u8, answer), .is_error = false };-}--pub fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, input: Value) !void {- const w = self.out orelse return;- // Same envelope as Agent.emit — hand-rolled only because `input` is a- // std.json.Value; #330's `seq` must ride this line too or a supervisor- // would see a hole exactly where it is asked to answer.- const ev = .{ .type = "ask_user", .call_id = call_id, .question = question, .input = input };- if (main_mod.json_mode) {- try protocol_seq.writeEvent(w, ev);- } else {- var s: std.json.Stringify = .{ .writer = w };- try s.write(ev);- }- try w.writeByte('\n');- try w.flush();-}-/// The call's announcement moment, as one pair of events: the bracket a/// --json supervisor times against, and the ⚙ line the terminal draws for the/// first of the two. Which of them a frontend surfaces (the wire skipsdiff --git a/src/ask_user.zig b/src/ask_user.zignew file mode 100644index 00000000..0866468f--- /dev/null+++ b/src/ask_user.zig@@ -0,0 +1,103 @@+//! ask_user: block the root agent for a human reply (#580).+//!+//! The TUI answer uses the same readline as the main prompt, so Ctrl-V / drop+//! stage images on the agent. Those pixels used to stay in `pending_image`+//! while the tool result was literal `[Image]` placeholders. We leave the+//! queue staged for `vision_queue.flushPending` after the tool result, and+//! promote GUI `@[path]` markers the same way the main prompt does.++const std = @import("std");+const Value = std.json.Value;++const main_mod = @import("main.zig");+const json_inbox = @import("json_inbox.zig");+const Agent = @import("agent.zig").Agent;+const tools_mod = @import("tools.zig");+const ToolCall = tools_mod.ToolCall;+const ExecResult = tools_mod.ExecResult;+const answerParseError = tools_mod.answerParseError;+const parseAnswerRequest = tools_mod.parseAnswerRequest;+const readline = @import("readline.zig");+const protocol_seq = @import("protocol_seq.zig");+const vision = @import("vision.zig");+const vision_queue = @import("vision_queue.zig");++/// Block the root agent for an ask_user reply; subagents have no stdin.+pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {+ const in = self.in orelse return .{+ .text = "no human is attached — make a reasonable assumption and continue",+ .is_error = true,+ };+ const w = self.out.?;+ const question = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "question") orelse "(no question)") else "(no question)";+ if (main_mod.json_mode) {+ const call_id = if (call.id.len > 0) call.id else blk: {+ const id = try std.fmt.allocPrint(self.arena, "ask_user-{d}", .{self.next_ask_id});+ self.next_ask_id += 1;+ break :blk id;+ };+ try emitAskUser(self, call_id, question, call.input);+ const raw = (try json_inbox.reply(self.arena, in)) orelse return .{+ .text = "user ended input without answering",+ .is_error = true,+ };+ const parsed = std.json.parseFromSliceLeaky(Value, self.arena, std.mem.trim(u8, raw, " \t\r"), .{ .allocate = .alloc_always }) catch return .{+ .text = "invalid answer JSON for ask_user",+ .is_error = true,+ };+ const answer = parseAnswerRequest(parsed, call_id) catch |err| return .{+ .text = answerParseError(err),+ .is_error = true,+ };+ if (answer.cancelled) return .{ .text = "user cancelled the follow-up", .is_error = true };+ return finishAnswer(self, answer.text);+ }+ // Skip the re-print only when the question streamed live in full.+ if (!self.argStreamedFully(call)) try w.print("\n❓ {s}\n", .{question});+ if (tools_mod.json_args.object(call.input)) |o| if (tools_mod.json_args.arrayOf(o, "options")) |opts| {+ for (opts, 1..) |opt, n| try w.print(" {d}) {s}\n", .{ n, tools_mod.json_args.text(opt) orelse "(non-text option)" });+ };+ // Route the reply through the same full-line editor as the main prompt:+ // cursor editing, bracketed paste, the `@` file picker, and Ctrl-V+ // clipboard images. A bare takeDelimiter here stripped all of that from+ // ask_user. Answers get a scratch history so they never pollute the main+ // prompt's up-arrow recall.+ var answer_history: std.ArrayList([]const u8) = .empty;+ defer answer_history.deinit(self.arena);+ var answer_buf: std.ArrayList(u8) = .empty;+ defer answer_buf.deinit(self.arena);+ const raw = (try readline.readLine(self, in, w, self.arena, &answer_history, &answer_buf, " your answer › ")) orelse return .{+ .text = "user ended input without answering",+ .is_error = true,+ };+ return finishAnswer(self, std.mem.trim(u8, raw, " \t\r"));+}++fn finishAnswer(self: *Agent, raw: []const u8) !ExecResult {+ const answer = try self.arena.dupe(u8, raw);+ vision.stageGuiImageAttachment(self, answer);+ // Pixels stay queued for flushPending after the text tool result. If the+ // reply only has `[Image]` markers and nothing staged, say so instead of+ // letting the model treat placeholders as screenshots.+ const text = if (self.pending_image_len == 0)+ try vision_queue.withUnsupportedNote(self.arena, answer)+ else+ answer;+ return .{ .text = text, .is_error = false };+}++pub fn emitAskUser(self: *Agent, call_id: []const u8, question: []const u8, input: Value) !void {+ const w = self.out orelse return;+ // Same envelope as Agent.emit — hand-rolled only because `input` is a+ // std.json.Value; #330's `seq` must ride this line too or a supervisor+ // would see a hole exactly where it is asked to answer.+ const ev = .{ .type = "ask_user", .call_id = call_id, .question = question, .input = input };+ if (main_mod.json_mode) {+ try protocol_seq.writeEvent(w, ev);+ } else {+ var s: std.json.Stringify = .{ .writer = w };+ try s.write(ev);+ }+ try w.writeByte('\n');+ try w.flush();+}diff --git a/src/cli.zig b/src/cli.zigindex b67fc581..62543d32 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -24,6 +24,7 @@ pub const changelog_text =\\0.0.268\\ • Codex-shaped .harness/agents/*.toml (and ~/.codex/agents) pin model/effort\\ • Live bash chunks + idle job notify + raw terminal (do not poll)+ \\ • ask_user pastes reach the model as vision blocks; compact keeps the live prompt's images\\\\0.0.267\\ • bash_output/agent_output wait_ms>0 blocks until exit (10h), not a 30s polldiff --git a/src/compact_cut.zig b/src/compact_cut.zignew file mode 100644index 00000000..6363e390--- /dev/null+++ b/src/compact_cut.zig@@ -0,0 +1,278 @@+//! Compaction cut: which suffix stays verbatim (#581).+//!+//! `recentContextStart` keeps a recent clean-user suffix inside an 8k token+//! budget. Mid-turn that walk can fill the budget on the tool tail and never+//! reach the opening user message — so an unresolved image prompt was+//! summarized into text. Pin that opening turn while the current prompt is+//! still unresolved, except a child's index-0 mandate (restated via pinChildTask).++const std = @import("std");+const Value = std.json.Value;++const context_tokens = @import("context_tokens.zig");+const peer_context = @import("peer_context.zig");+const trace = @import("trace.zig");++/// Last clean user turn — the opening prompt of the current (or just-finished)+/// turn. Tool-result-only user messages are not clean (see `cleanUserTurn`).+pub fn turnOpeningUserIndex(items: []const Value) ?usize {+ var i = items.len;+ while (i > 0) {+ i -= 1;+ if (cleanUserTurn(items[i])) return i;+ }+ return null;+}++/// True when history ends on a completed model reply (assistant / Responses+/// `message`). Tool outputs, function_call, reasoning, or a trailing user+/// prompt mean the opening turn is still live.+pub fn lastIsResolved(items: []const Value) bool {+ if (items.len == 0) return false;+ const m = items[items.len - 1];+ if (m != .object) return false;+ if (m.object.get("type")) |t| if (t == .string) {+ if (std.mem.eql(u8, t.string, "message")) return true;+ if (std.mem.eql(u8, t.string, "function_call")) return false;+ if (std.mem.eql(u8, t.string, "function_call_output")) return false;+ if (std.mem.eql(u8, t.string, "reasoning")) return false;+ };+ const role = m.object.get("role") orelse return false;+ return role == .string and std.mem.eql(u8, role.string, "assistant");+}++pub fn countImageBlocks(m: Value) u32 {+ if (m != .object) return 0;+ const content = m.object.get("content") orelse return 0;+ if (content != .array) return 0;+ var n: u32 = 0;+ for (content.array.items) |blk| {+ if (blk != .object) continue;+ const t = blk.object.get("type") orelse continue;+ if (t != .string) continue;+ if (std.mem.eql(u8, t.string, "image") or+ std.mem.eql(u8, t.string, "image_url") or+ std.mem.eql(u8, t.string, "input_image")) n += 1;+ }+ return n;+}++pub fn countImagesFrom(items: []const Value) u32 {+ var n: u32 = 0;+ for (items) |m| n += countImageBlocks(m);+ return n;+}++pub fn messageHasImage(m: Value) bool {+ return countImageBlocks(m) > 0;+}++/// Keep the opening user of an unresolved turn when it is not a child's+/// index-0 mandate (those are restated by pinChildTask) or when it carries+/// image blocks (a first-turn paste must not be summarized to text).+fn mustKeepOpening(items: []const Value, t: usize) bool {+ return t > 0 or messageHasImage(items[t]);+}++fn pinOpening(items: []const Value) ?usize {+ if (lastIsResolved(items)) return null;+ const t = turnOpeningUserIndex(items) orelse return null;+ return if (mustKeepOpening(items, t)) t else null;+}++/// Pick the earliest clean user-turn boundary whose suffix fits in the recent+/// context budget. Returning items.len means "summarize everything". We never+/// split at a tool output, so retained call/result history stays valid.+///+/// #581: while the current prompt is unresolved, never put its opening user+/// message (or its image blocks) in the summarized prefix.+pub fn recentContextStart(items: []const Value, token_budget: u64) usize {+ if (items.len == 0 or token_budget == 0) return items.len;+ var total: u64 = 0;+ var start = items.len;+ var i = items.len;+ while (i > 0) {+ i -= 1;+ total +|= context_tokens.estimatedTokens(items[i]);+ if (total > token_budget) break;+ if (cleanUserTurn(items[i])) start = i;+ }+ // If the entire conversation fits, summarizing all is the only operation+ // that can actually reduce context; otherwise compaction would be a no-op.+ if (start == 0) start = items.len;+ if (pinOpening(items)) |t| {+ if (start > t) start = t;+ }+ return start;+}++/// Index to cut history at for an emergency trim: the first clean user turn+/// at or after the midpoint, so messages[cut..] is always a valid+/// conversation start (never an orphaned tool_result). null when there is no+/// safe cut — too short, only tool_result user messages remain, or the only+/// candidate would drop an unresolved image prompt (#581).+pub fn emergencyCutIndex(items: []const Value) ?usize {+ if (items.len < 4) return null;+ const pin = pinOpening(items);+ var i: usize = items.len / 2;+ while (i < items.len) : (i += 1) {+ if (pin) |t| if (i > t) break;+ if (cleanUserTurn(items[i])) return i;+ }+ return null;+}++/// Counts only: boundary index + preserved current-suffix image blocks. Never+/// the pixels (#581).+pub fn noteCut(tracer: ?*trace.Tracer, items: []const Value, start: usize) void {+ const t = tracer orelse return;+ t.write(.{+ .ev = "compact_cut",+ .boundary = start,+ .preserved_images = countImagesFrom(items[start..]),+ .unresolved = !lastIsResolved(items),+ });+}++pub fn cleanUserTurn(m: Value) bool {+ if (m != .object) return false;+ const role = m.object.get("role") orelse return false;+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return false;+ const content = m.object.get("content") orelse return true;+ switch (content) {+ .string => |s| return !peer_context.isPeerInjectContent(s),+ .array => |arr| {+ // An anthropic user message that only carries tool_result blocks+ // is the response half of a tool call — it can't begin a+ // conversation, so it is not a safe trim boundary.+ for (arr.items) |blk| {+ if (blk != .object) continue;+ const t = blk.object.get("type") orelse continue;+ if (t == .string and std.mem.eql(u8, t.string, "tool_result")) return false;+ }+ return true;+ },+ else => return true,+ }+}++fn imageUser(arena: std.mem.Allocator, kind: []const u8, payload: []const u8) !Value {+ var image: std.json.ObjectMap = .empty;+ try image.put(arena, "type", .{ .string = kind });+ if (std.mem.eql(u8, kind, "image_url")) {+ var image_url: std.json.ObjectMap = .empty;+ try image_url.put(arena, "url", .{ .string = payload });+ try image.put(arena, "image_url", .{ .object = image_url });+ } else {+ try image.put(arena, "image_url", .{ .string = payload });+ }+ var content = std.json.Array.init(arena);+ var tb: std.json.ObjectMap = .empty;+ try tb.put(arena, "type", .{ .string = "text" });+ try tb.put(arena, "text", .{ .string = "read these screenshots" });+ try content.append(.{ .object = tb });+ try content.append(.{ .object = image });+ var user: std.json.ObjectMap = .empty;+ try user.put(arena, "role", .{ .string = "user" });+ try user.put(arena, "content", .{ .array = content });+ return .{ .object = user };+}++fn toolTail(arena: std.mem.Allocator, msgs: *std.json.Array, n: usize) !void {+ const util = @import("util.zig");+ var i: usize = 0;+ while (i < n) : (i += 1) {+ var fco: std.json.ObjectMap = .empty;+ try fco.put(arena, "type", .{ .string = "function_call_output" });+ try fco.put(arena, "call_id", .{ .string = "c" });+ try fco.put(arena, "output", .{ .string = &util.repeatBytes("y", 8_000) });+ try msgs.append(.{ .object = fco });+ }+}++test "unresolved image prompt is pinned even when the tool tail fills the budget" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const textMessage = @import("messages.zig").textMessage;+ const util = @import("util.zig");++ var msgs = std.json.Array.init(arena);+ try msgs.append(try textMessage(arena, "user", "old request"));+ try msgs.append(try textMessage(arena, "assistant", &util.repeatBytes("x", 20_000)));+ try msgs.append(try imageUser(arena, "image_url", "data:image/png;base64,AAA"));+ try toolTail(arena, &msgs, 6);++ const start = recentContextStart(msgs.items, 8_000);+ try std.testing.expectEqual(@as(usize, 2), start);+ try std.testing.expect(cleanUserTurn(msgs.items[start]));+ try std.testing.expectEqual(@as(u32, 1), countImagesFrom(msgs.items[start..]));+}++test "just-submitted image prompt is not summarized away" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const textMessage = @import("messages.zig").textMessage;+ const util = @import("util.zig");++ var msgs = std.json.Array.init(arena);+ try msgs.append(try textMessage(arena, "user", &util.repeatBytes("z", 40_000)));+ try msgs.append(try textMessage(arena, "assistant", "old answer"));+ try msgs.append(try imageUser(arena, "input_image", "data:image/png;base64,BBB"));++ const start = recentContextStart(msgs.items, 8_000);+ try std.testing.expectEqual(@as(usize, 2), start);+}++test "HungRequest retry does not move the cut across the live image prompt" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const textMessage = @import("messages.zig").textMessage;+ const util = @import("util.zig");++ var msgs = std.json.Array.init(arena);+ try msgs.append(try textMessage(arena, "user", "old request"));+ try msgs.append(try textMessage(arena, "assistant", &util.repeatBytes("x", 20_000)));+ try msgs.append(try imageUser(arena, "image_url", "data:image/png;base64,AAA"));+ try toolTail(arena, &msgs, 6);++ const first = recentContextStart(msgs.items, 8_000);+ const again = recentContextStart(msgs.items, 8_000);+ try std.testing.expectEqual(first, again);+ try std.testing.expectEqual(@as(usize, 2), again);+}++test "emergencyCutIndex refuses to drop an unresolved image prompt" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const textMessage = @import("messages.zig").textMessage;+ const util = @import("util.zig");++ var msgs = std.json.Array.init(arena);+ try msgs.append(try textMessage(arena, "user", "old request"));+ try msgs.append(try textMessage(arena, "assistant", &util.repeatBytes("x", 20_000)));+ try msgs.append(try imageUser(arena, "image_url", "data:image/png;base64,AAA"));+ try toolTail(arena, &msgs, 6);++ try std.testing.expectEqual(@as(?usize, null), emergencyCutIndex(msgs.items));+}++test "first-turn unresolved images refuse a summarize-all cut" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ var msgs = std.json.Array.init(arena);+ try msgs.append(try imageUser(arena, "image_url", "data:image/png;base64,AAA"));+ try toolTail(arena, &msgs, 6);++ try std.testing.expectEqual(@as(usize, 0), recentContextStart(msgs.items, 8_000));+}diff --git a/src/mainloop.zig b/src/mainloop.zigindex c792fb05..2cd72694 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -389,10 +389,7 @@ pub fn run(ctx: *Ctx) !void {var review_context = review.Context.begin(ctx.arena, ctx.root, ctx.root.review_mode);if (ctx.root.review_mode) ctx.root.rebaseContextMeter();defer if (review_context.restore(ctx.root)) ctx.root.rebaseContextMeter();- if (ctx.root.pending_image) |img| {- try ctx.root.messages.append(try vision.imageMessage(ctx.arena, ctx.root.provider.kind, ultracode_msg.text, img));- ctx.root.pending_image = null;- } else try ctx.root.messages.append(try messages.textMessage(ctx.arena, "user", ultracode_msg.text));+ try ctx.root.messages.append(try @import("vision_queue.zig").consumePromptImages(ctx.arena, ctx.root, ultracode_msg.text));ctx.root.snapshots.?.turn += 1; // tag file edits in this turn (matches /rewind numbering)ctx.root.recap_generation +%= 1; // #419: a starting turn supersedes any recap job still in flightif (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(base_msg.len, std.math.maxInt(u32))), ctx.root.provider.model);diff --git a/src/schema.zig b/src/schema.zigindex bbc7a2b8..1c8b4bf4 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -141,7 +141,7 @@ const meta_specs = [_]ToolSpec{.{ .name = "note_constraint", .desc = "Record a standing user constraint in this project's playbook (.graff/playbook.jsonl). Call it the moment the user rejects, forbids or vetoes something, passing ONE short imperative line stating what must not happen (e.g. never add scroll hints or progress dots). The recorded line is injected verbatim into every later subagent, workflow and pipeline brief and into your own system context, in this session and in future ones, so it survives compaction and reaches fresh agents that never saw the rejection. Append-only: this tool cannot edit, retire or list items - only the user can, with /never. Recording the same constraint twice is harmless and does nothing.", .schema = "{\"type\": \"object\", \"properties\": {\"text\": {\"type\": \"string\", \"description\": \"One short imperative line in the user's own terms, stating what must not happen\"}}, \"required\": [\"text\"]}" },.{.name = "ask_user",- .desc = "Ask the human a question and wait for their typed reply, which is returned as this tool's result. Use when you need a decision, clarification, or missing information. This routes the human turn through the tool channel — the user is just another tool you can call.",+ .desc = "Ask the human a question and wait for their reply (typed text and/or pasted images). Images reach you as vision blocks on the next request, same as a normal prompt. Use for a decision, clarification, or missing information.",.schema =\\{"type": "object", "properties": {"question": {"type": "string", "description": "The question to ask the user"}, "options": {"type": "array", "items": {"type": "string"}, "description": "Optional suggested answers, shown numbered"}}, "required": ["question"]},diff --git a/src/vision.zig b/src/vision.zigindex 4a2a71f1..22bd2174 100644--- a/src/vision.zig+++ b/src/vision.zig@@ -72,6 +72,12 @@ pub fn imageMediaType(path: []const u8) []const u8 {/// A user message carrying text + one image, in the provider's wire format.pub fn imageMessage(arena: Allocator, kind: Provider.Kind, text: []const u8, img: PendingImage) !Value {+ return imageMessages(arena, kind, text, &.{img});+}++/// A user message carrying text + every staged image, in the provider's wire+/// format. Used by the main prompt and by ask_user follow-ups (#580).+pub fn imageMessages(arena: Allocator, kind: Provider.Kind, text: []const u8, imgs: []const PendingImage) !Value {var msg: std.json.ObjectMap = .empty;try msg.put(arena, "role", .{ .string = "user" });var content = std.json.Array.init(arena);@@ -81,28 +87,30 @@ pub fn imageMessage(arena: Allocator, kind: Provider.Kind, text: []const u8, imgtry tb.put(arena, "text", .{ .string = try arena.dupe(u8, text) });try content.append(.{ .object = tb });- var ib: std.json.ObjectMap = .empty;- switch (kind) {- .anthropic => {- try ib.put(arena, "type", .{ .string = "image" });- var src: std.json.ObjectMap = .empty;- try src.put(arena, "type", .{ .string = "base64" });- try src.put(arena, "media_type", .{ .string = img.media_type });- try src.put(arena, "data", .{ .string = img.b64 });- try ib.put(arena, "source", .{ .object = src });- },- .openai => {- try ib.put(arena, "type", .{ .string = "image_url" });- var iu: std.json.ObjectMap = .empty;- try iu.put(arena, "url", .{ .string = try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 }) });- try ib.put(arena, "image_url", .{ .object = iu });- },- .responses => {- try ib.put(arena, "type", .{ .string = "input_image" });- try ib.put(arena, "image_url", .{ .string = try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 }) });- },+ for (imgs) |img| {+ var ib: std.json.ObjectMap = .empty;+ switch (kind) {+ .anthropic => {+ try ib.put(arena, "type", .{ .string = "image" });+ var src: std.json.ObjectMap = .empty;+ try src.put(arena, "type", .{ .string = "base64" });+ try src.put(arena, "media_type", .{ .string = img.media_type });+ try src.put(arena, "data", .{ .string = img.b64 });+ try ib.put(arena, "source", .{ .object = src });+ },+ .openai => {+ try ib.put(arena, "type", .{ .string = "image_url" });+ var iu: std.json.ObjectMap = .empty;+ try iu.put(arena, "url", .{ .string = try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 }) });+ try ib.put(arena, "image_url", .{ .object = iu });+ },+ .responses => {+ try ib.put(arena, "type", .{ .string = "input_image" });+ try ib.put(arena, "image_url", .{ .string = try std.fmt.allocPrint(arena, "data:{s};base64,{s}", .{ img.media_type, img.b64 }) });+ },+ }+ try content.append(.{ .object = ib });}- try content.append(.{ .object = ib });try msg.put(arena, "content", .{ .array = content });return .{ .object = msg };}@@ -157,7 +165,7 @@ pub fn stageImagePath(root: *Agent, path: []const u8) StageResult {// `fitToBudget` re-checks the magic bytes; without both, `sips -Z` would// keep the source encoding and we'd send JPEG bytes as `image/png`.const media = imageMediaType(fit.path);- root.pending_image = .{ .media_type = media, .b64 = b64, .label = arena.dupe(u8, path) catch path };+ @import("vision_queue.zig").stage(root, .{ .media_type = media, .b64 = b64, .label = arena.dupe(u8, path) catch path });return .{ .ok = .{ .bytes = fit.bytes, .media_type = media } };}@@ -218,14 +226,13 @@ pub fn tracePasteResult(root: *Agent, flavor: Flavor, r: StageResult) void {/// that holds both the registry and the provider.pub fn stageGuiImageAttachment(root: *Agent, msg: []const u8) void {if (root.registry) |reg| if (mcpImageHandoff(reg, visionCapable(root.provider), &root.pending_image)) return; // #249- if (root.pending_image != null) return;if (!visionCapable(root.provider)) return;var search: usize = 0;while (std.mem.indexOfPos(u8, msg, search, "@[")) |open| {const rest = msg[open + 2 ..];const close = std.mem.indexOfScalar(u8, rest, ']') orelse break;const path = rest[0..close];- if (isImagePath(path) and stageImagePath(root, path).isOk()) return;+ if (isImagePath(path)) _ = stageImagePath(root, path);search = open + 2 + close + 1;}}diff --git a/src/vision_queue.zig b/src/vision_queue.zignew file mode 100644index 00000000..86e169ec--- /dev/null+++ b/src/vision_queue.zig@@ -0,0 +1,117 @@+//! Multi-image staging queue (#580).+//!+//! Ctrl-V / drop / `@[path]` used to overwrite a single `pending_image` slot,+//! so nine ask_user pastes left nine `[Image]` markers and one payload. This+//! queue keeps every successful stage (cap 16) until the next model request+//! consumes them as real vision blocks.++const std = @import("std");+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const vision = @import("vision.zig");+const PendingImage = vision.PendingImage;+const messages = @import("messages.zig");+const compact_cut = @import("compact_cut.zig");++pub const cap = 16;++pub const unsupported_note =+ "[ask_user: those image attachments did not reach the model. Save the files and pass their paths, paste the text, or send the images in your next normal prompt.]";++pub fn stage(root: *Agent, img: PendingImage) void {+ root.pending_image = img;+ if (root.pending_image_len < cap) {+ root.pending_images[root.pending_image_len] = img;+ root.pending_image_len += 1;+ return;+ }+ root.pending_images[cap - 1] = img;+}++pub fn take(root: *Agent) []const PendingImage {+ const n = root.pending_image_len;+ root.pending_image_len = 0;+ root.pending_image = null;+ return root.pending_images[0..n];+}++pub fn consumePromptImages(arena: Allocator, root: *Agent, text: []const u8) !Value {+ const imgs = take(root);+ if (imgs.len == 0) return messages.textMessage(arena, "user", text);+ return vision.imageMessages(arena, root.provider.kind, text, imgs);+}++/// After an ask_user (or any tool that staged pixels) tool result, attach the+/// queued images as a follow-up user message. Responses/OpenAI tool output is+/// text-only; this is the shared multimodal shape.+pub fn flushPending(root: *Agent) !void {+ const imgs = take(root);+ if (imgs.len == 0) return;+ try root.messages.append(try vision.imageMessages(root.arena, root.provider.kind, "", imgs));+}++pub fn withUnsupportedNote(arena: Allocator, answer: []const u8) ![]const u8 {+ if (std.mem.indexOf(u8, answer, "[Image]") == null) return answer;+ return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ answer, unsupported_note });+}++test "queue keeps two staged images in order" {+ var root: Agent = .{+ .gpa = std.testing.allocator,+ .arena = std.testing.allocator,+ .io = undefined,+ .client = undefined,+ .provider = .{ .id = "xai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "grok-4", .context = 100_000 },+ .messages = undefined,+ .sub = false,+ .label = "test",+ .out = null,+ };+ stage(&root, .{ .media_type = "image/png", .b64 = "AAA", .label = "one.png" });+ stage(&root, .{ .media_type = "image/png", .b64 = "BBB", .label = "two.png" });+ try std.testing.expectEqual(@as(u8, 2), root.pending_image_len);+ const imgs = take(&root);+ try std.testing.expectEqual(@as(usize, 2), imgs.len);+ try std.testing.expectEqualStrings("AAA", imgs[0].b64);+ try std.testing.expectEqualStrings("BBB", imgs[1].b64);+ try std.testing.expectEqual(@as(u8, 0), root.pending_image_len);+ try std.testing.expect(root.pending_image == null);+}++test "ask_user images become follow-up vision blocks (#580)" {+ const a = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(a);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var root: Agent = .{+ .gpa = a,+ .arena = arena,+ .io = undefined,+ .client = undefined,+ .provider = .{ .id = "xai", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "grok-4", .context = 100_000 },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "test",+ .out = null,+ };+ stage(&root, .{ .media_type = "image/png", .b64 = "AAA", .label = "q1.png" });+ stage(&root, .{ .media_type = "image/png", .b64 = "BBB", .label = "q2.png" });+ try root.messages.append(try messages.toolResultMessage(arena, .responses, "ask1", "[Image] [Image]", false));+ try flushPending(&root);+ try std.testing.expectEqual(@as(usize, 2), root.messages.items.len);+ try std.testing.expectEqual(@as(u32, 2), compact_cut.countImageBlocks(root.messages.items[1]));+ const content = root.messages.items[1].object.get("content").?.array.items;+ try std.testing.expectEqualStrings("input_image", content[1].object.get("type").?.string);+ try std.testing.expectEqualStrings("input_image", content[2].object.get("type").?.string);+ try std.testing.expect(std.mem.indexOf(u8, content[1].object.get("image_url").?.string, "AAA") != null);+ try std.testing.expect(std.mem.indexOf(u8, content[2].object.get("image_url").?.string, "BBB") != null);+}++test "placeholder-only ask_user reply gets an explicit fallback" {+ const note = try withUnsupportedNote(std.testing.allocator, "[Image] [Image]");+ defer std.testing.allocator.free(note);+ try std.testing.expect(std.mem.indexOf(u8, note, "did not reach the model") != null);+ try std.testing.expect(std.mem.indexOf(u8, note, "next normal prompt") != null);+}