Skip to content

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

Python
9.2 KB
Raw Blame
//! 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");
const acp_ask = @import("acp_ask.zig");
const acp_elicit = @import("acp_elicit.zig");
const ask_user_args = @import("ask_user_args.zig");
const style = &@import("ansi.zig").style;

/// Set once at startup (session_start.zig): a `-p` run, or a piped session
/// outside --json/ACP, has nobody to answer, so the root catalog leaves the
/// tool out (ADR 0231). The model used to call it and spend a round trip on
/// "no human is attached".
pub var g_no_human: bool = false;

/// The g_no_human rule. main.zig settles it before the system prompt is
/// composed (ADR 0232: the todo nudges stay out when nobody watches), and
/// session start applies it again. The TUI's terminal shows on stdout.
pub fn detectNoHuman(io: std.Io, oneshot: bool, json: bool, acp: bool) bool {
    const terminal = (std.Io.File.stdin().isTty(io) catch false) or (std.Io.File.stdout().isTty(io) catch false);
    return oneshot or (!json and !acp and !terminal);
}

/// Block the root agent for an ask_user reply; subagents have no stdin.
pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
    // #1308: aliases, a `questions` list, and double-encoded arguments all
    // carry the question; a call with none goes back to the model, not a
    // "(no question)" card.
    const args = try ask_user_args.normalize(self.arena, call.input);
    const question = args.question orelse return .{ .text = ask_user_args.missing_text, .is_error = true };
    const input = args.input;
    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;
        };
        // ACP owns stdin (`root.in` is null). A client that cannot show the
        // question must not leave the turn waiting on it (acp_elicit.zig).
        if (self.in == null and acp_elicit.mode == .none)
            return .{ .text = acp_elicit.unsupported_text, .is_error = true };
        try emitAskUser(self, call_id, question, input);
        // Answers arrive as the elicitation response or session/answer.
        if (self.in == null) {
            if (self.tracer) |tr| tr.note("ask_user_wait", @tagName(acp_elicit.mode));
            const got = try acp_ask.wait(self.arena);
            acp_elicit.finish();
            if (self.tracer) |tr| tr.note("ask_user_outcome", @tagName(got.outcome));
            if (got.outcome != .answered) return .{ .text = noAnswerText(got.outcome), .is_error = true };
            return finishAnswer(self, std.mem.trim(u8, got.text, " \t\r"));
        }
        const in = self.in.?;
        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);
    }
    const in = self.in orelse return .{
        .text = "no human is attached — make a reasonable assumption and continue",
        .is_error = true,
    };
    const w = self.out.?;
    // Named tool row even when the question streamed: announce is silent for
    // streamed args, and the result line used to skip this meta tool.
    try w.print("  {s}⚙{s} ask_user  {s}\n", .{ style.accent, style.reset, question });
    if (tools_mod.json_args.object(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"));
}

/// #1322: only a user's explicit cancel reads as a cancel. A question the
/// client returned with nothing bound to it may never have been shown, so
/// the model must not take it as a refusal and end the turn.
pub fn noAnswerText(outcome: acp_ask.Outcome) []const u8 {
    return switch (outcome) {
        .answered => unreachable,
        .dismissed => "user cancelled the follow-up",
        .declined => "the user declined to answer this question. Continue without it and do not ask it again.",
        .unanswered => "no answer came back: the client returned the question without a reply, so the user may not have seen it. This is not a refusal. Continue with a reasonable, reversible assumption and state it, or ask the question in your reply.",
    };
}

test "noAnswerText keeps cancel as cancel and never calls a lost question a cancel (#1322)" {
    try std.testing.expectEqualStrings("user cancelled the follow-up", noAnswerText(.dismissed));
    try std.testing.expect(std.mem.indexOf(u8, noAnswerText(.unanswered), "cancel") == null);
    try std.testing.expect(std.mem.indexOf(u8, noAnswerText(.unanswered), "not a refusal") != null);
    try std.testing.expect(std.mem.indexOf(u8, noAnswerText(.declined), "declined") != null);
}

fn finishAnswer(self: *Agent, raw: []const u8) !ExecResult {
    const answer = try self.arena.dupe(u8, raw);
    // #1342: the answer is user-authored text note_constraint may record.
    @import("ask_user_answers.zig").record(@import("ask_user_answers.zig").turnKey(@import("playbook_glue.zig").currentUserText(self)), answer);
    vision.stageGuiImageAttachment(self, answer);
    _ = vision_queue.retainReferenced(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();
}

test "no human: the prompt leaves the todo nudges out and the tool stays loadable (ADR 0232)" {
    const prompts = @import("prompts.zig");
    var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena_state.deinit();
    const saved = g_no_human;
    defer g_no_human = saved;
    g_no_human = false;
    try std.testing.expectEqual(prompts.toolAdvertised("todo_write"), prompts.detectCaps().todos);
    g_no_human = true;
    try std.testing.expect(!prompts.detectCaps().todos);
    const base = try prompts.composeBase(arena_state.allocator(), prompts.detectCaps());
    try std.testing.expect(std.mem.indexOf(u8, base, "todo_write") == null);
    try std.testing.expect(@import("native_fold.zig").isFolded("todo_write"));
}