Skip to content

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

Python

ask_user: read the question from every argument shape models send

justrachce11d5a2b7e6
diff --git a/scripts/test-acp-ask-user.py b/scripts/test-acp-ask-user.py
index ff9ac02a..61c1e86b 100644
--- a/scripts/test-acp-ask-user.py
+++ b/scripts/test-acp-ask-user.py
@@ -4,6 +4,8 @@
- no capability: the tool returns at once and the turn ends (no freeze)
- clientCapabilities.elicitation.form: standard elicitation/create, answer flows back
- _meta["graff/askUser"]: graff's gui_ask_user + session/answer (apps/native)
+- a `questions: [{question, options: [{label}]}]` call still carries its
+ question and choices to the form (#1308)
"""
import json, os, queue, shutil, signal, subprocess, sys, tempfile, threading, time
from pathlib import Path
@@ -24,13 +26,17 @@ def tool_results(model):
def run(binary, case):
+ arguments = {'question': QUESTION, 'options': ['npm', 'GitHub release']}
+ if case == 'questions':
+ arguments = {'questions': [{'question': QUESTION, 'options': [{'label': 'npm'}, {'label': 'GitHub release'}]}]}
model = ScriptedModel([
- {'tool': 'ask_user', 'arguments': {'question': QUESTION, 'options': ['npm', 'GitHub release']}},
+ {'tool': 'ask_user', 'arguments': arguments},
{'text': 'Done.'},
])
caps = {
'none': {'fs': {}},
'elicitation': {'fs': {}, 'elicitation': {'form': {}}},
+ 'questions': {'fs': {}, 'elicitation': {'form': {}}},
'legacy': {'fs': {}, '_meta': {'graff/askUser': True}},
}[case]
# Windows keeps the killed process's files open briefly; do not fail on cleanup.
@@ -72,7 +78,7 @@ def run(binary, case):
if m.get('id') == id and 'method' not in m:
return m
if m.get('method') == 'elicitation/create':
- assert case == 'elicitation', m
+ assert case in ('elicitation', 'questions'), m
params = m['params']
assert params['mode'] == 'form' and params['message'] == QUESTION, params
answer = params['requestedSchema']['properties']['answer']
@@ -118,5 +124,5 @@ def run(binary, case):
if __name__ == '__main__':
binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else 'zig-out/bin/graff').resolve())
- for case in ['none', 'elicitation', 'legacy']:
+ for case in ['none', 'elicitation', 'questions', 'legacy']:
run(binary, case)
diff --git a/src/ask_user.zig b/src/ask_user.zig
index 94395420..23fbbd2b 100644
--- a/src/ask_user.zig
+++ b/src/ask_user.zig
@@ -23,11 +23,17 @@ 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;
/// Block the root agent for an ask_user reply; subagents have no stdin.
pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
- const question = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "question") orelse "(no question)") else "(no question)";
+ // #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});
@@ -38,7 +44,7 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
// 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, call.input);
+ 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));
@@ -71,7 +77,7 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
// 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(call.input)) |o| if (tools_mod.json_args.arrayOf(o, "options")) |opts| {
+ 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:
diff --git a/src/ask_user_args.zig b/src/ask_user_args.zig
new file mode 100644
index 00000000..bdeda231
--- /dev/null
+++ b/src/ask_user_args.zig
@@ -0,0 +1,125 @@
+//! ask_user argument shapes (#1308).
+//!
+//! The schema asks for `{question, options}`, but models also send the
+//! arguments double-encoded as a JSON string, name the question `prompt` or
+//! `message`, or use a `questions: [{question, options: [{label}]}]` list.
+//! Reading only `question` showed a "(no question)" heading over options that
+//! did render. `normalize` folds those shapes into `{question, options}` with
+//! string options; a call with no question text at all goes back to the model
+//! as an error instead of reaching the user.
+
+const std = @import("std");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+const json_args = @import("json_args.zig");
+
+pub const missing_text = "ask_user needs a non-empty `question` string. Call it again with the question text in `question` and any choices in `options`.";
+
+const question_keys = [_][]const u8{ "question", "prompt", "message", "text", "query", "title", "header" };
+
+pub const Args = struct {
+ /// Null when no field carries non-empty question text.
+ question: ?[]const u8,
+ /// The arguments with `question` and string `options` filled in.
+ input: Value,
+};
+
+pub fn normalize(a: Allocator, raw: Value) !Args {
+ var input = raw;
+ if (raw == .string) {
+ const parsed: ?Value = std.json.parseFromSliceLeaky(Value, a, raw.string, .{ .allocate = .alloc_always }) catch null;
+ if (parsed != null and parsed.? == .object) {
+ input = parsed.?;
+ } else {
+ const q = nonEmpty(raw.string) orelse return .{ .question = null, .input = raw };
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "question", .{ .string = q });
+ return .{ .question = q, .input = .{ .object = obj } };
+ }
+ }
+ const src = json_args.object(input) orelse return .{ .question = null, .input = raw };
+ var question = questionIn(src);
+ var options = json_args.arrayOf(src, "options");
+ if (json_args.arrayOf(src, "questions")) |items| if (items.len > 0) if (json_args.object(items[0])) |first| {
+ if (question == null) question = questionIn(first);
+ if (options == null) options = json_args.arrayOf(first, "options");
+ };
+ var obj = try src.clone(a);
+ if (question) |q| try obj.put(a, "question", .{ .string = q });
+ if (options) |opts| {
+ var labels = std.json.Array.init(a);
+ try labels.ensureTotalCapacity(opts.len);
+ for (opts) |opt| labels.appendAssumeCapacity(if (optionLabel(opt)) |l| .{ .string = l } else opt);
+ try obj.put(a, "options", .{ .array = labels });
+ }
+ return .{ .question = question, .input = .{ .object = obj } };
+}
+
+fn questionIn(o: std.json.ObjectMap) ?[]const u8 {
+ for (question_keys) |k| if (json_args.str(o, k)) |s| if (nonEmpty(s)) |q| return q;
+ return null;
+}
+
+fn optionLabel(opt: Value) ?[]const u8 {
+ if (opt == .string) return opt.string;
+ const o = json_args.object(opt) orelse return null;
+ return json_args.str(o, "label") orelse json_args.str(o, "text") orelse json_args.str(o, "value");
+}
+
+fn nonEmpty(s: []const u8) ?[]const u8 {
+ const t = std.mem.trim(u8, s, " \t\r\n");
+ return if (t.len == 0) null else t;
+}
+
+const testing = std.testing;
+
+fn run(a: Allocator, json: []const u8) !Args {
+ return normalize(a, try std.json.parseFromSliceLeaky(Value, a, json, .{}));
+}
+
+test "the schema shape passes through unchanged" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const got = try run(arena.allocator(), "{\"question\":\"Which target?\",\"options\":[\"npm\",\"GitHub\"]}");
+ try testing.expectEqualStrings("Which target?", got.question.?);
+ const opts = got.input.object.get("options").?.array.items;
+ try testing.expectEqualStrings("GitHub", opts[1].string);
+}
+
+test "question aliases and a double-encoded argument string are read" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try testing.expectEqualStrings("Ship it?", (try run(a, "{\"prompt\":\"Ship it?\",\"options\":[\"yes\",\"no\"]}")).question.?);
+ const enc = try run(a, "\"{\\\"question\\\":\\\"Which one?\\\",\\\"options\\\":[\\\"a\\\",\\\"b\\\"]}\"");
+ try testing.expectEqualStrings("Which one?", enc.question.?);
+ try testing.expectEqual(@as(usize, 2), enc.input.object.get("options").?.array.items.len);
+ const plain = try run(a, "\"Proceed with the migration?\"");
+ try testing.expectEqualStrings("Proceed with the migration?", plain.question.?);
+ try testing.expectEqualStrings("Proceed with the migration?", plain.input.object.get("question").?.string);
+}
+
+test "a questions list supplies the question and labelled options" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const got = try run(arena.allocator(),
+ \\{"questions":[{"question":"Which database?","header":"DB","options":[{"label":"Postgres","description":"x"},{"label":"SQLite"}]}]}
+ );
+ try testing.expectEqualStrings("Which database?", got.question.?);
+ try testing.expectEqualStrings("Which database?", got.input.object.get("question").?.string);
+ const opts = got.input.object.get("options").?.array.items;
+ try testing.expectEqual(@as(usize, 2), opts.len);
+ try testing.expectEqualStrings("Postgres", opts[0].string);
+ try testing.expectEqualStrings("SQLite", opts[1].string);
+}
+
+test "options without any question text leave the question null" {
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try testing.expect((try run(a, "{\"options\":[\"a\",\"b\"]}")).question == null);
+ try testing.expect((try run(a, "{\"question\":\" \",\"options\":[\"a\"]}")).question == null);
+ try testing.expect((try run(a, "{\"question\":42}")).question == null);
+ try testing.expect((try run(a, "[1,2]")).question == null);
+ try testing.expect((try run(a, "\"\"")).question == null);
+}
diff --git a/src/main.zig b/src/main.zig
index ab429737..448a6f04 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -579,7 +579,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig") }; // h2 stream path, and graff's request/response contract over the pinned http-zig
_ = @import("tui_acp_updates.zig");
_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root
- _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig") };
+ _ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("ask_user_args.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig") };
_ = @import("task_outcome.zig"); // goal-outcome telemetry events
_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here
_ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig"), @import("rlm_order_tests.zig"), @import("async_tool_policy.zig"), @import("agent_async_tools.zig"), @import("request_usage_attempts.zig"), @import("learn_formal.zig") };