Skip to content

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

Python

fix(repl): preserve immediate multiline ask answers

Rach Pradhana7c7446e673d
diff --git a/scripts/test-pty-ask-user-paste.py b/scripts/test-pty-ask-user-paste.py
new file mode 100644
index 00000000..0ab75244
--- /dev/null
+++ b/scripts/test-pty-ask-user-paste.py
@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+"""Real-PTY regression for immediate multiline paste into ask_user."""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import tempfile
+
+from codex_ws_mock import CodexMock, RecordedRequest, turn_events
+from pty_harness import PtySession
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+
+def events(request: RecordedRequest) -> list[dict]:
+ if request.ordinal == 1:
+ return [
+ {
+ "type": "response.output_item.done",
+ "item": {
+ "type": "function_call",
+ "id": "fc_ask_paste",
+ "call_id": "call_ask_paste",
+ "name": "ask_user",
+ "arguments": json.dumps(
+ {
+ "question": "Paste details",
+ "options": ["one", "two"],
+ }
+ ),
+ "status": "completed",
+ },
+ },
+ turn_events("resp_ask_paste_1")[1],
+ ]
+
+ response = turn_events("resp_ask_paste_2")
+ response[0]["item"]["content"][0]["text"] = "ASK_PASTE_DONE"
+ return response
+
+
+def main() -> None:
+ mock = CodexMock(events_for_request=events)
+ port = mock.start()
+ try:
+ with tempfile.TemporaryDirectory(prefix="graff-ask-paste-") 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-paste-mock",
+ "account_id": "acct-ask-paste",
+ }
+ },
+ 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 = {
+ "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",
+ }
+ ambient = tuple(
+ name
+ for name in os.environ
+ if (
+ name.startswith("GRAFF_")
+ or name.startswith("CODEX_")
+ or name == "NO_COLOR"
+ )
+ and name not in env
+ )
+
+ with PtySession(
+ GRAFF,
+ ["--model", "codex", "--no-telemetry"],
+ cwd=tmp,
+ env=env,
+ unset_env=ambient,
+ timeout=15.0,
+ ) as session:
+ session.wait_for_literal("] ›")
+ session.send_line("ask me for details")
+ session.wait_for_literal("your answer ›")
+
+ cursor = len(session.raw)
+ session.send(b"\x1b[200~first line\nsecond line\x1b[201~")
+ session.wait_for_literal(
+ "[Pasted text #1 +2 lines]",
+ start=cursor,
+ )
+ session.send_key("enter")
+ session.wait_for_literal("ASK_PASTE_DONE", start=cursor)
+
+ requests = mock.recorded_requests()
+ assert len(requests) == 2, f"expected 2 requests, got {len(requests)}"
+ payload = json.dumps(requests[-1].body, ensure_ascii=False)
+ assert "first line\\nsecond line" in payload, payload
+ 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 feff54ba..5bb5949d 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -113,7 +113,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);