Skip to content

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

Python

fix(repl): end ask_user cleanly on piped EOF (#478)

Rach Pradhan26beb7542696
diff --git a/scripts/test-piped-ask-user-eof.py b/scripts/test-piped-ask-user-eof.py
new file mode 100644
index 00000000..f8bb8b45
--- /dev/null
+++ b/scripts/test-piped-ask-user-eof.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Regression for #478: ask_user must not wedge after piped stdin reaches EOF."""
+
+from __future__ import annotations
+
+import json
+import os
+import subprocess
+import sys
+import tempfile
+
+from codex_ws_mock import CodexMock, RecordedRequest, turn_events
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+FINAL_REPLY = "ASK_EOF_DONE"
+
+
+def events(request: RecordedRequest) -> list[dict]:
+ if request.ordinal == 1:
+ return [
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "function_call",
+ "id": "fc_ask_eof",
+ "call_id": "call_ask_eof",
+ "name": "ask_user",
+ "arguments": json.dumps({"question": "Need input?"}),
+ "status": "completed",
+ },
+ },
+ turn_events("resp_ask_eof_1")[1],
+ ]
+
+ response = turn_events("resp_ask_eof_2")
+ response[0]["item"]["content"][0]["text"] = FINAL_REPLY
+ return response
+
+
+def main() -> None:
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-ask-eof-") as tmp:
+ codex_home = os.path.join(tmp, "codex-home")
+ os.makedirs(codex_home)
+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:
+ json.dump(
+ {
+ "tokens": {
+ "access_token": "ask-eof-mock",
+ "account_id": "acct-ask-eof",
+ }
+ },
+ fh,
+ )
+
+ harness_dir = os.path.join(tmp, ".harness")
+ os.makedirs(harness_dir)
+ with open(os.path.join(harness_dir, "settings.json"), "w", encoding="utf-8") as fh:
+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)
+
+ env = os.environ.copy()
+ for name in tuple(env):
+ if name.startswith("GRAFF_") or name.startswith("CODEX_"):
+ env.pop(name)
+ env.update(
+ {
+ "HOME": tmp,
+ "CODEX_HOME": codex_home,
+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",
+ "GRAFF_CODEX_WS": "off",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ "NO_COLOR": "1",
+ }
+ )
+
+ proc = subprocess.run(
+ [GRAFF, "--model", "codex", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ input="ask me a question using ask_user\n",
+ text=True,
+ capture_output=True,
+ timeout=15,
+ check=False,
+ )
+ if proc.returncode != 0:
+ raise AssertionError(
+ f"graff exited {proc.returncode}\nstdout={proc.stdout}\nstderr={proc.stderr}"
+ )
+ if FINAL_REPLY not in proc.stdout:
+ raise AssertionError(f"missing final reply in stdout: {proc.stdout!r}")
+
+ requests = mock.recorded_requests()
+ root_requests = [request for request in requests if "tools" in request.body]
+ if len(root_requests) != 2:
+ raise AssertionError(
+ f"expected two root model calls, got {len(root_requests)}: "
+ f"{[request.body for request in requests]!r}\nstdout={proc.stdout!r}"
+ )
+ followup = json.dumps(root_requests[1].body)
+ if "function_call_output" not in followup:
+ raise AssertionError(f"missing ask_user tool result: {followup}")
+ if "user ended input without answering" not in followup:
+ raise AssertionError(f"EOF result was not explicit: {followup}")
+ finally:
+ mock.stop()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 7d47e251..82aeed74 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -404,9 +404,6 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
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)" });
};
- try w.writeAll(" your answer › ");
- try w.flush();
-
// 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
@@ -416,7 +413,7 @@ pub fn askUser(self: *Agent, call: ToolCall) !ExecResult {
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)) orelse return .{
+ 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,
};
diff --git a/src/mainloop.zig b/src/mainloop.zig
index e914bb2a..f4e3275b 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -114,7 +114,7 @@ pub fn run(ctx: *Ctx) !void {
break :blk try std.fmt.allocPrint(ctx.arena, "/loop {s}\n{s}", .{ note, pace });
} else if (ctx.interactive) blk: {
try ctx.root.prompt();
- break :blk (try readline.readLine(ctx.root, ctx.in, ctx.out, ctx.gpa, ctx.history, ctx.linebuf)) orelse break;
+ break :blk (try readline.readLine(ctx.root, ctx.in, ctx.out, ctx.gpa, ctx.history, ctx.linebuf, null)) orelse break;
} else (try ctx.in.takeDelimiter('\n')) orelse break;
// The title may have completed while readline was waiting. Apply it
// before starting the newly-entered turn, still without ever waiting.
diff --git a/src/readline.zig b/src/readline.zig
index 0899a241..965d59f7 100644
--- a/src/readline.zig
+++ b/src/readline.zig
@@ -69,20 +69,18 @@ pub fn readLine(
gpa: Allocator,
history: *std.ArrayList([]const u8),
buf: *std.ArrayList(u8),
+ prompt_text: ?[]const u8,
) !?[]const u8 {
const raw_state = tty.enterRaw(true) orelse return in.takeDelimiter('\n');
defer tty.restore(raw_state);
-
buf.clearRetainingCapacity();
var cur: usize = 0; // cursor index within buf
var nav: HistoryNav = .init(history.items.len); // history + unsent-draft nav (#101)
defer if (nav.draft) |d| gpa.free(d);
- out.writeAll("\x1b[?2004h") catch {}; // enable bracketed paste (terminal wraps pastes in ESC[200~ … ESC[201~)
+ out.writeAll("\x1b[?2004h") catch {}; // terminal wraps pastes in ESC[200~ … ESC[201~
defer out.writeAll("\x1b[?2004l") catch {};
out.flush() catch {};
-
- // Where does input start? Ask the terminal (DSR 6) for the column right
- // after the prompt; the renderer treats those columns as a fixed prefix
+ // Ask the terminal (DSR 6) where input starts; the renderer treats those columns as a fixed prefix
// and wraps the input across rows below it. Cursor moves in redraw are all
// relative (never an absolute DECSC anchor), so a wrap-induced scroll
// shifts the whole block together and never strands the prompt. Typed-
@@ -138,16 +136,17 @@ pub fn readLine(
}
}
}
- // Narrow terminal: when the prompt leaves too little room (the token-
- // stats prompt nearly fills a small window), give the input its own
- // row — what shells do — rather than wrapping in a sliver beside the
- // prompt.
+ if (prompt_text) |text| {
+ out.writeAll(text) catch {};
+ prompt_col += std.unicode.utf8CountCodepoints(text) catch text.len;
+ out.flush() catch {};
+ }
+ // Narrow terminal: put input on its own row rather than wrapping in a sliver.
if (termCols() < prompt_col + 16) {
out.writeAll("\r\n") catch {};
out.flush() catch {};
prompt_col = 1;
}
-
// Tab-completion cycle state.
var comp_items: std.ArrayList([]const u8) = .empty;
defer comp_items.deinit(gpa);