Skip to content

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

Python

fix: citation PUA, ACP cancel, bash wait, handle previews

Rach Pradhan83dc8b3236b2
diff --git a/TUI/app.zig b/TUI/app.zig
index 836406de..d4af99ca 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -6,6 +6,7 @@ const std = @import("std");
const engine = @import("engine.zig");
const input_mod = @import("input.zig");
const theme_mod = @import("theme.zig");
+const sanitize = @import("sanitize.zig");
pub const Screen = enum { welcome, agent };
pub const Focus = enum { prompt, scrollback };
@@ -281,7 +282,7 @@ pub const Model = struct {
}
pub fn push(self: *Model, kind: EntryKind, text: []const u8) !void {
- const owned = try sanitized(self.alloc, text);
+ const owned = try sanitize.sanitized(self.alloc, text);
errdefer self.alloc.free(owned);
try self.history.append(.{ .kind = kind, .text = owned, .folded = kind == .tool, .at_ms = self.now_ms });
if (kind == .user or kind == .assistant) {
@@ -298,11 +299,11 @@ pub const Model = struct {
pub fn pushTool(self: *Model, info: ToolInfo) !void {
const name = try self.alloc.dupe(u8, info.name);
errdefer self.alloc.free(name);
- const summary = try sanitized(self.alloc, info.summary);
+ const summary = try sanitize.sanitized(self.alloc, info.summary);
errdefer self.alloc.free(summary);
- const detail = try sanitized(self.alloc, info.detail);
+ const detail = try sanitize.sanitized(self.alloc, info.detail);
errdefer self.alloc.free(detail);
- const raw = try sanitized(self.alloc, info.raw);
+ const raw = try sanitize.sanitized(self.alloc, info.raw);
errdefer self.alloc.free(raw);
const text = try self.alloc.dupe(u8, summary);
@@ -341,7 +342,7 @@ pub const Model = struct {
pub fn pushFmt(self: *Model, kind: EntryKind, comptime fmt: []const u8, args: anytype) !void {
const raw = try std.fmt.allocPrint(self.alloc, fmt, args);
defer self.alloc.free(raw);
- const text = try sanitized(self.alloc, raw);
+ const text = try sanitize.sanitized(self.alloc, raw);
errdefer self.alloc.free(text);
try self.history.append(.{ .kind = kind, .text = text });
}
@@ -564,35 +565,3 @@ pub const Model = struct {
self.overlay_sel = 0;
}
};
-
-/// History entries render verbatim inside the alt screen — drop escape
-/// sequences and stray C0 controls a tool result (or the model) may carry.
-/// The fast path used to look only for ESC and CR, so a BEL/BS/NUL with
-/// neither leaked into the frame and the painter wrote it to the tty.
-fn sanitized(alloc: std.mem.Allocator, text: []const u8) ![]u8 {
- var dirty = false;
- for (text) |c| {
- if (c == 0x1b or c == 0x7f or (c < 0x20 and c != '\n' and c != '\t')) {
- dirty = true;
- break;
- }
- }
- if (!dirty) return alloc.dupe(u8, text);
- var out = std.array_list.Managed(u8).init(alloc);
- errdefer out.deinit();
- var i: usize = 0;
- while (i < text.len) {
- const c = text[i];
- if (c == 0x1b) {
- i = theme_mod.skipEsc(text, i);
- continue;
- }
- if ((c < 0x20 and c != '\n' and c != '\t') or c == 0x7f) {
- i += 1;
- continue;
- }
- try out.append(c);
- i += 1;
- }
- return out.toOwnedSlice();
-}
diff --git a/TUI/issue_805_tests.zig b/TUI/issue_805_tests.zig
new file mode 100644
index 00000000..4dfa1c19
--- /dev/null
+++ b/TUI/issue_805_tests.zig
@@ -0,0 +1,17 @@
+//! Citation control markup must not appear as raw PUA in the TUI transcript (#805).
+
+const std = @import("std");
+const sim = @import("sim.zig");
+
+test "TUI transcript strips citation annotations (#805)" {
+ var term: sim.Term = undefined;
+ term.init(std.testing.allocator, 80, 24);
+ defer term.deinit();
+ try term.model.push(.assistant, "See the docs\u{E200}cite\u{E202}turn0view0\u{E201} for details.");
+ try std.testing.expectEqualStrings("See the docs for details.", term.model.history.items[0].text);
+ const vis = try term.screen();
+ defer std.testing.allocator.free(vis);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "See the docs for details.") != null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "turn0view0") == null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "\u{E200}") == null);
+}
diff --git a/TUI/root.zig b/TUI/root.zig
index 060bf2af..307b2b6e 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -92,6 +92,8 @@ test {
_ = @import("issue_789_tests.zig");
_ = @import("issue_788_tests.zig");
_ = @import("issue_798_tests.zig");
+ _ = @import("sanitize.zig");
+ _ = @import("issue_805_tests.zig");
_ = @import("composer_links.zig");
_ = @import("input.zig");
_ = @import("keys.zig");
diff --git a/TUI/sanitize.zig b/TUI/sanitize.zig
new file mode 100644
index 00000000..06566b7b
--- /dev/null
+++ b/TUI/sanitize.zig
@@ -0,0 +1,78 @@
+//! History-entry sanitizer: drop terminal controls and citation PUA (#805).
+
+const std = @import("std");
+const theme_mod = @import("theme.zig");
+
+fn citeSkip(text: []const u8, i: usize) usize {
+ if (i + 2 >= text.len) return i;
+ if (text[i] != 0xEE or text[i + 1] != 0x88) return i;
+ const b = text[i + 2];
+ if (b < 0x80 or b > 0x82) return i;
+ if (b != 0x80) return i + 3;
+ var j = i + 3;
+ while (j + 2 < text.len) {
+ if (text[j] == 0xEE and text[j + 1] == 0x88 and text[j + 2] == 0x81) return j + 3;
+ j += 1;
+ }
+ return text.len;
+}
+
+fn citeContains(text: []const u8) bool {
+ var i: usize = 0;
+ while (i < text.len) : (i += 1) {
+ if (citeSkip(text, i) != i) return true;
+ }
+ return false;
+}
+
+/// History entries render verbatim inside the alt screen — drop escape
+/// sequences, stray C0, and provider citation annotations a model may carry.
+pub fn sanitized(alloc: std.mem.Allocator, text: []const u8) ![]u8 {
+ var dirty = citeContains(text);
+ if (!dirty) {
+ for (text) |c| {
+ if (c == 0x1b or c == 0x7f or (c < 0x20 and c != '\n' and c != '\t')) {
+ dirty = true;
+ break;
+ }
+ }
+ }
+ if (!dirty) return alloc.dupe(u8, text);
+ var out = std.array_list.Managed(u8).init(alloc);
+ errdefer out.deinit();
+ var i: usize = 0;
+ while (i < text.len) {
+ const skipped = citeSkip(text, i);
+ if (skipped != i) {
+ i = skipped;
+ continue;
+ }
+ const c = text[i];
+ if (c == 0x1b) {
+ i = theme_mod.skipEsc(text, i);
+ continue;
+ }
+ if ((c < 0x20 and c != '\n' and c != '\t') or c == 0x7f) {
+ i += 1;
+ continue;
+ }
+ try out.append(c);
+ i += 1;
+ }
+ return out.toOwnedSlice();
+}
+
+test "citation control markup is stripped from TUI history (#805)" {
+ const a = std.testing.allocator;
+ const raw = "hello\u{E200}cite\u{E202}turn0view0\u{E201} world";
+ const got = try sanitized(a, raw);
+ defer a.free(got);
+ try std.testing.expectEqualStrings("hello world", got);
+}
+
+test "C0 still drops without touching letters" {
+ const a = std.testing.allocator;
+ const got = try sanitized(a, "safe\x07text\rhere");
+ defer a.free(got);
+ try std.testing.expectEqualStrings("safetexthere", got);
+}
diff --git a/docs/adr/0091-persistent-jobs-honor-wait-ms.md b/docs/adr/0091-persistent-jobs-honor-wait-ms.md
new file mode 100644
index 00000000..83306344
--- /dev/null
+++ b/docs/adr/0091-persistent-jobs-honor-wait-ms.md
@@ -0,0 +1,28 @@
+# 0091. Persistent bash jobs honor wait_ms as a timeout
+
+Status: accepted 2026-09-08
+
+## Context
+
+ADR 0010 maps every positive `bash_output.wait_ms` to a 10-hour wait-until-exit
+so models stop polling `wait_ms=30000`. That is correct for finite work
+(a rebuild, a test suite) that was auto-backgrounded.
+
+It is a footgun for a job started with `run_in_background: true`. Those are
+servers. A caller that passes `wait_ms: 1000` meaning "snapshot in one second"
+blocks until interrupt (#810).
+
+## Decision
+
+- Finite jobs (auto-backgrounded foreground bash): ADR 0010 unchanged.
+ `wait_ms > 0` waits until exit (10h cap). Elapsed-time pulses keep the wait
+ distinguishable from a hang (#807).
+- Persistent jobs (`run_in_background: true`): `wait_ms` is a real millisecond
+ timeout, then a running snapshot. `wait_ms = 0` is still an immediate snapshot.
+
+## Consequences
+
+Checking a long-lived server with `wait_ms: 1000` returns in one second.
+A `wait_ms=30000` poll loop on a server also returns every 30s — that is the
+cost of making the field mean what it is named for processes that do not exit.
+Finite jobs still absorb the legacy 30s poll as wait-until-exit.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index f3908d8a..982f6451 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -101,6 +101,7 @@ record only when you need the evidence or the edge cases.
| [0088](0088-failed-children-return-partial-evidence.md) | Failed children return bounded partial evidence with error status intact, including an excerpt for workflow synthesis. |
| [0089](0089-canonical-compaction-windows-survive-recovery.md) | Preserve standalone compaction windows across pruning and resume; opaque recovery uses the server or reports failure without discarding history. |
| [0090](0090-project-constraints-require-explicit-scope.md) | Local steering stays local; durable project constraints require explicit scope and exact current-user text, while legacy unscoped records are reviewable. |
+| [0091](0091-persistent-jobs-honor-wait-ms.md) | Persistent `run_in_background` jobs honor `wait_ms` as a timeout; finite jobs still wait until exit (ADR 0010). |
## When to write one
diff --git a/src/acp.zig b/src/acp.zig
index 60c226d8..1b0a62bd 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -166,10 +166,13 @@ const LiveTurn = struct {
out: *Io.Writer,
session_id: []const u8 = "",
saw_text: bool = false,
+ inbox: ?*@import("acp_inbox.zig").Inbox = null,
fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
const self: *LiveTurn = @ptrCast(@alignCast(ctx));
agent_mod.Agent.prepareRootTurn(); // #753: a prior stream cancel must not steal the continuation
+ if (self.inbox) |inbox| inbox.begin();
+ defer if (self.inbox) |inbox| inbox.end();
switch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, text)) {
.started => {},
.skipped => return "",
@@ -229,7 +232,10 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
engine.implementation_version = main_mod.harness_version;
engine.cancel_flag.store(false, .release);
engine.on_cancel = syncEscCancel;
- var live: LiveTurn = .{ .root = root, .keys = keys, .out = out };
+ var inbox: @import("acp_inbox.zig").Inbox = .{ .gpa = gpa, .io = io, .reader = in };
+ inbox.start();
+ defer inbox.deinit();
+ var live: LiveTurn = .{ .root = root, .keys = keys, .out = out, .inbox = &inbox };
var d: Dispatch = .{
.turn = LiveTurn.run,
.ctx = &live,
@@ -240,7 +246,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
.extra = liveModels,
};
while (true) {
- const line = (in.takeDelimiter('\n') catch break) orelse break;
+ const line = (inbox.next(arena) catch break) orelse break;
handleLine(&d, arena, out, line) catch |err| {
std.debug.print("acp: dispatch failed: {t}\n", .{err});
break;
diff --git a/src/acp_engine.zig b/src/acp_engine.zig
index a3277801..445061bd 100644
--- a/src/acp_engine.zig
+++ b/src/acp_engine.zig
@@ -90,6 +90,8 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)
}
if (d.after_user) |after| after(d.ctx, arena, text);
const final = d.turn(d.ctx, arena, text) catch |err| {
+ if (err == error.Interrupted or err == error.Canceled)
+ return respond(w, req, .{ .stopReason = "cancelled" });
if (err == error.RunBudgetExhausted)
return respond(w, req, .{ .stopReason = "max_turn_requests" });
return respondError(w, req, err_internal, @errorName(err));
diff --git a/src/acp_inbox.zig b/src/acp_inbox.zig
new file mode 100644
index 00000000..cec6e689
--- /dev/null
+++ b/src/acp_inbox.zig
@@ -0,0 +1,132 @@
+//! Own ACP stdin while dispatch is busy; cancellation never waits behind a turn (#809).
+const std = @import("std");
+const Io = std.Io;
+const Agent = @import("agent.zig").Agent;
+const proto = @import("acp_protocol.zig");
+const cancel_source = @import("cancel_source.zig");
+
+pub const Inbox = struct {
+ gpa: std.mem.Allocator,
+ io: Io,
+ reader: *Io.Reader,
+ mutex: Io.Mutex = .init,
+ ready: Io.Condition = .init,
+ lines: std.ArrayList([]u8) = .empty,
+ eof: bool = false,
+ session_id: ?[]u8 = null,
+ cancelled: bool = false,
+ active: bool = false,
+ future: ?Io.Future(void) = null,
+
+ pub fn start(self: *Inbox) void {
+ self.future = self.io.async(pump, .{self});
+ }
+
+ pub fn deinit(self: *Inbox) void {
+ if (self.future) |*f| f.cancel(self.io);
+ for (self.lines.items) |line| self.gpa.free(line);
+ self.lines.deinit(self.gpa);
+ if (self.session_id) |sid| self.gpa.free(sid);
+ }
+
+ pub fn next(self: *Inbox, arena: std.mem.Allocator) !?[]const u8 {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ while (self.lines.items.len == 0 and !self.eof)
+ self.ready.waitUncancelable(self.io, &self.mutex);
+ if (self.lines.items.len == 0) return null;
+ const line = self.lines.orderedRemove(0);
+ defer self.gpa.free(line);
+ return try arena.dupe(u8, line);
+ }
+
+ /// Called after prepareRootTurn, under the same lock as incoming cancel.
+ pub fn begin(self: *Inbox) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ self.active = true;
+ if (self.cancelled) cancel_source.cancel(.acp_cancel);
+ }
+
+ pub fn end(self: *Inbox) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ self.active = false;
+ self.cancelled = false;
+ if (self.session_id) |sid| self.gpa.free(sid);
+ self.session_id = null;
+ }
+
+ fn accept(self: *Inbox, line: []const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(self.gpa);
+ defer arena.deinit();
+ const req = proto.parseRequest(arena.allocator(), line);
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (req) |r| {
+ const sid: ?[]const u8 = blk: {
+ const params = r.params orelse break :blk null;
+ if (params != .object) break :blk null;
+ const value = params.object.get("sessionId") orelse break :blk null;
+ break :blk if (value == .string) value.string else null;
+ };
+ if (std.mem.eql(u8, r.method, "session/cancel") and r.id == null) {
+ if (self.session_id) |current| {
+ if (sid == null or std.mem.eql(u8, sid.?, current)) {
+ self.cancelled = true;
+ if (self.active) cancel_source.cancel(.acp_cancel);
+ }
+ }
+ return;
+ }
+ if (std.mem.eql(u8, r.method, "session/prompt") and self.session_id == null)
+ self.session_id = try self.gpa.dupe(u8, sid orelse "");
+ }
+ const copy = try self.gpa.dupe(u8, line);
+ errdefer self.gpa.free(copy);
+ try self.lines.append(self.gpa, copy);
+ self.ready.broadcast(self.io);
+ }
+
+ fn pump(self: *Inbox) void {
+ while (true) {
+ const line = (self.reader.takeDelimiter('\n') catch break) orelse break;
+ self.accept(line) catch break;
+ }
+ self.mutex.lockUncancelable(self.io);
+ self.eof = true;
+ self.ready.broadcast(self.io);
+ self.mutex.unlock(self.io);
+ }
+};
+
+test "ACP cancel interrupts active turn and does not cancel its successor" {
+ var reader: Io.Reader = .fixed("");
+ var inbox: Inbox = .{ .gpa = std.testing.allocator, .io = std.testing.io, .reader = &reader };
+ defer inbox.deinit();
+ defer Agent.esc_cancel.store(false, .release);
+ try inbox.accept("{\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s\"}}");
+ Agent.esc_cancel.store(false, .release);
+ inbox.begin();
+ try inbox.accept("{\"method\":\"session/cancel\",\"params\":{\"sessionId\":\"other\"}}");
+ try std.testing.expect(!Agent.esc_cancel.load(.acquire));
+ try inbox.accept("{\"method\":\"session/cancel\",\"params\":{\"sessionId\":\"s\"}}");
+ try std.testing.expect(Agent.esc_cancel.load(.acquire));
+ inbox.end();
+ Agent.esc_cancel.store(false, .release);
+ try inbox.accept("{\"method\":\"session/cancel\"}");
+ inbox.begin();
+ try std.testing.expect(!Agent.esc_cancel.load(.acquire));
+}
+
+test "ACP cancellation before turn setup survives the reset" {
+ var reader: Io.Reader = .fixed("");
+ var inbox: Inbox = .{ .gpa = std.testing.allocator, .io = std.testing.io, .reader = &reader };
+ defer inbox.deinit();
+ defer Agent.esc_cancel.store(false, .release);
+ try inbox.accept("{\"method\":\"session/prompt\"}");
+ try inbox.accept("{\"method\":\"session/cancel\"}");
+ Agent.esc_cancel.store(false, .release);
+ inbox.begin();
+ try std.testing.expect(Agent.esc_cancel.load(.acquire));
+}
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index d9654d5c..ba6d09ff 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -57,6 +57,7 @@ const util = @import("util.zig"); // #225: unixMs, for the clock_sleep interrupt
// #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.
const tool_handle = @import("tool_handle.zig");
+const cite_markup = @import("cite_markup.zig");
// escWatchTask/drainStdin/rawNonblockStdin live in agent_interrupt.zig;
// esc_cancel/esc_watch_done STAY declared on the Agent struct (never alias
@@ -348,8 +349,9 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {
if (!self.sub) engine_sink.forAgent(self).emit(self.io, .completion_deferred); // root-only notice, as ever
return .{ .text = refusal, .is_error = true };
}
- const result = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "result") orelse "") else "";
- self.completed = try self.arena.dupe(u8, result);
+ const raw = if (tools_mod.json_args.object(call.input)) |o| (tools_mod.json_args.str(o, "result") orelse "") else "";
+ const result = try cite_markup.dupe(self.arena, raw);
+ self.completed = result;
if (!self.sub) task_outcome.noteGoalCompleted(self);
// .complete retires the epoch (goal_state.currentEpoch) and the checklist parks - readable, no longer current, never deleted (#318).
// A --goal standing objective is exempt: the completion is recorded above, the steering stays, and only /goal clear|pause|<new> retires it.
diff --git a/src/cite_markup.zig b/src/cite_markup.zig
new file mode 100644
index 00000000..50d45f44
--- /dev/null
+++ b/src/cite_markup.zig
@@ -0,0 +1,111 @@
+//! Provider citation control annotations (U+E200…U+E202).
+//!
+//! Hosted web search requires markers such as
+//! `\u{E200}cite\u{E202}turn0view0\u{E201}`. Those private-use glyphs are not
+//! a renderable citation on the line REPL or TUI, so they must be stripped
+//! before copy-ready text, including `attempt_completion` results (#805, #811).
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+
+/// UTF-8 U+E200 (annotation start), U+E201 (end), U+E202 (separator).
+const pua_lead = [_]u8{ 0xEE, 0x88 };
+const mark_start: u8 = 0x80;
+const mark_end: u8 = 0x81;
+const mark_sep: u8 = 0x82;
+
+pub fn isMark(text: []const u8, i: usize) ?u8 {
+ if (i + 2 >= text.len) return null;
+ if (text[i] != pua_lead[0] or text[i + 1] != pua_lead[1]) return null;
+ const b = text[i + 2];
+ if (b < mark_start or b > mark_sep) return null;
+ return b;
+}
+
+pub fn contains(text: []const u8) bool {
+ var i: usize = 0;
+ while (i < text.len) : (i += 1) {
+ if (isMark(text, i) != null) return true;
+ }
+ return false;
+}
+
+/// Index after a citation span starting at `i`, or `i` when `i` is not a mark.
+pub fn skip(text: []const u8, i: usize) usize {
+ const mark = isMark(text, i) orelse return i;
+ if (mark != mark_start) return i + 3;
+ var j = i + 3;
+ while (j < text.len) {
+ if (isMark(text, j) == mark_end) return j + 3;
+ j += 1;
+ }
+ return text.len;
+}
+
+pub fn strippedLen(text: []const u8) usize {
+ var n: usize = 0;
+ var i: usize = 0;
+ while (i < text.len) {
+ const j = skip(text, i);
+ if (j != i) {
+ i = j;
+ continue;
+ }
+ n += 1;
+ i += 1;
+ }
+ return n;
+}
+
+/// Always a new slice owned by `alloc`.
+pub fn dupe(alloc: Allocator, text: []const u8) ![]u8 {
+ if (!contains(text)) return alloc.dupe(u8, text);
+ var aw: std.Io.Writer.Allocating = .init(alloc);
+ errdefer aw.deinit();
+ var i: usize = 0;
+ while (i < text.len) {
+ const j = skip(text, i);
+ if (j != i) {
+ i = j;
+ continue;
+ }
+ try aw.writer.writeByte(text[i]);
+ i += 1;
+ }
+ return aw.toOwnedSlice();
+}
+
+test "citation annotations strip to surrounding prose (#805, #811)" {
+ const a = std.testing.allocator;
+ const raw = "See the docs\u{E200}cite\u{E202}turn0view0\u{E201} for details.";
+ try std.testing.expect(contains(raw));
+ const got = try dupe(a, raw);
+ defer a.free(got);
+ try std.testing.expectEqualStrings("See the docs for details.", got);
+ try std.testing.expectEqual(@as(usize, got.len), strippedLen(raw));
+}
+
+test "unpaired separator and end marks are dropped" {
+ const a = std.testing.allocator;
+ const raw = "a\u{E202}b\u{E201}c";
+ const got = try dupe(a, raw);
+ defer a.free(got);
+ try std.testing.expectEqualStrings("abc", got);
+}
+
+test "clean text is unchanged" {
+ const a = std.testing.allocator;
+ const raw = "no citations here";
+ try std.testing.expect(!contains(raw));
+ const got = try dupe(a, raw);
+ defer a.free(got);
+ try std.testing.expectEqualStrings(raw, got);
+}
+
+test "open annotation at EOF is dropped" {
+ const a = std.testing.allocator;
+ const raw = "tail\u{E200}cite\u{E202}turn0search0";
+ const got = try dupe(a, raw);
+ defer a.free(got);
+ try std.testing.expectEqualStrings("tail", got);
+}
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index d2256c1c..08e382f5 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -74,9 +74,10 @@ fn startedText(gpa: Allocator, id: u32, cmd: []const u8, ssh: bool, auto_bg: boo
const w = &aw.writer;
try w.print("[job {d} started: {s}]\n", .{ id, cmd });
if (auto_bg) {
- try w.print("Command exceeded the {d}s foreground wait and was automatically moved to the background. Process is still running. ", .{wait_s});
+ try w.print("Command exceeded the {d}s foreground wait and was automatically moved to the background. Process is still running. Waiting via bash_output shows elapsed-time pulses so a long rebuild is distinguishable from a hang. You are notified on exit — do not poll. bash_output(id {d}, wait_ms>0) waits until it exits; omit wait_ms for a snapshot. bash_kill stops it.", .{ wait_s, id });
+ } else {
+ try w.print("This is a persistent job. bash_output wait_ms is a snapshot timeout, not wait-until-exit — omit wait_ms for an immediate snapshot. You are notified on exit — do not poll. bash_output(id {d}) reads unread output. bash_kill stops it.", .{id});
}
- try w.print("You are notified on exit — do not poll. bash_output(id {d}, wait_ms>0) blocks until it exits; omit wait_ms for a snapshot. bash_kill stops it.", .{id});
if (ssh) try w.writeAll(" Killing the local SSH job cannot prove a detached remote process stopped; verify the remote host.");
if (partial.len > 0) {
try w.writeAll("\n");
@@ -220,6 +221,7 @@ pub fn exec(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
.stream = if (!ctx.from_sub and !bg) exec_bash_stream.emit else null,
.stream_ctx = if (!ctx.from_sub and !bg) &live else null,
.quiet = !bg, // foreground wait is not a /jobs event until auto-bg
+ .persistent = bg,
}) catch |err| return .{ .text = try spawnFailText(gpa, err), .is_error = true };
if (bg) {
return .{ .text = try startedText(gpa, job.id, job.cmd, ssh, false, 0, "") };
diff --git a/src/handle_preview.zig b/src/handle_preview.zig
index d1653062..2dcfeb23 100644
--- a/src/handle_preview.zig
+++ b/src/handle_preview.zig
@@ -107,3 +107,71 @@ test "notableExcerpt stays empty when nothing looks like a failure" {
const excerpt = try notableExcerpt(a, "cache=miss status=OK\nall good\n", 0, 512);
try std.testing.expectEqualStrings("", excerpt);
}
+
+pub const head_lines: usize = 24;
+pub const tail_lines: usize = 12;
+pub const head_bytes: usize = 2048;
+pub const tail_bytes: usize = 1024;
+
+fn takeLines(text: []const u8, from_start: bool, max_lines: usize, max_bytes: usize) []const u8 {
+ if (text.len == 0 or max_lines == 0 or max_bytes == 0) return "";
+ if (from_start) {
+ var lines: usize = 0;
+ var i: usize = 0;
+ while (i < text.len and i < max_bytes and lines < max_lines) {
+ if (text[i] == '\n') lines += 1;
+ i += 1;
+ }
+ while (i > 0 and i < text.len and (text[i] & 0xC0) == 0x80) i -= 1;
+ return text[0..i];
+ }
+ var lines: usize = 0;
+ var i = text.len;
+ while (i > 0 and (text.len - i) < max_bytes and lines < max_lines) {
+ i -= 1;
+ if (text[i] == '\n') lines += 1;
+ }
+ if (i > 0 and text[i] == '\n') i += 1;
+ while (i < text.len and (text[i] & 0xC0) == 0x80) i += 1;
+ return text[i..];
+}
+
+/// First/last excerpt for a spilled result. Empty when `budget` cannot hold
+/// a useful head. The full bytes stay on the handle.
+pub fn compactPreview(arena: Allocator, text: []const u8, budget: usize) ![]const u8 {
+ if (budget < 80) return utilUtf8Prefix(text, budget);
+ const head = takeLines(text, true, head_lines, @min(head_bytes, budget / 2));
+ const tail = takeLines(text, false, tail_lines, @min(tail_bytes, budget / 4));
+ if (tail.len == 0 or std.mem.endsWith(u8, head, tail) or head.len + tail.len >= text.len)
+ return arena.dupe(u8, utilUtf8Prefix(text, budget));
+ const gap = "[... {d} bytes omitted; page with read_tool_result(handle, offset, limit) or query ...]\n";
+ const omitted = text.len - head.len - tail.len;
+ var aw: std.Io.Writer.Allocating = .init(arena);
+ try aw.writer.writeAll(head);
+ if (head.len == 0 or head[head.len - 1] != '\n') try aw.writer.writeByte('\n');
+ try aw.writer.print(gap, .{omitted});
+ try aw.writer.writeAll(tail);
+ const out = aw.writer.buffered();
+ if (out.len > budget) return arena.dupe(u8, utilUtf8Prefix(text, budget));
+ return out;
+}
+
+fn utilUtf8Prefix(text: []const u8, n: usize) []const u8 {
+ return @import("util.zig").utf8Prefix(text, n);
+}
+
+test "compactPreview keeps the head and a tail window (#808)" {
+ const a = std.testing.allocator;
+ var arena_state = std.heap.ArenaAllocator.init(a);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const big = try arena.alloc(u8, 8000);
+ @memset(big, 'x');
+ @memcpy(big[0..5], "HEAD\n");
+ @memcpy(big[big.len - 5 ..], "\nTAIL");
+ const got = try compactPreview(arena, big, 4096);
+ try std.testing.expect(std.mem.startsWith(u8, got, "HEAD"));
+ try std.testing.expect(std.mem.indexOf(u8, got, "TAIL") != null);
+ try std.testing.expect(std.mem.indexOf(u8, got, "read_tool_result") != null);
+ try std.testing.expect(got.len < big.len);
+}
diff --git a/src/job_notify.zig b/src/job_notify.zig
index 9030bdc1..903ea932 100644
--- a/src/job_notify.zig
+++ b/src/job_notify.zig
@@ -133,9 +133,17 @@ pub fn dismiss(io: Io, id: u32) void {
/// The tool result for a bash_output wait that ended before the job did.
/// An Esc used to be rendered by setting the elapsed counter to the 10-hour
/// deadline, so the model read "36000s elapsed" for a 36-second wait.
-pub fn printRunning(w: *Io.Writer, id: u32, waited_ms: u64, interrupted: bool) !void {
+pub fn printRunning(w: *Io.Writer, id: u32, waited_ms: u64, interrupted: bool, persistent: bool) !void {
var ebuf: [16]u8 = undefined;
const el = tool_pulse.formatElapsed(&ebuf, waited_ms);
+ if (persistent) {
+ if (interrupted) {
+ try w.print("[job {d}: running · {s} waited, then interrupted — persistent server; wait_ms is a snapshot timeout, not wait-until-exit]", .{ id, el });
+ } else {
+ try w.print("[job {d}: running · {s} elapsed — persistent server; wait_ms is a snapshot timeout. omit wait_ms for an immediate snapshot]", .{ id, el });
+ }
+ return;
+ }
if (interrupted) {
try w.print("[job {d}: running · {s} waited, then interrupted — you are notified on exit; do not call bash_output again]", .{ id, el });
} else {
@@ -147,9 +155,9 @@ pub fn printRunning(w: *Io.Writer, id: u32, waited_ms: u64, interrupted: bool) !
/// wait runs long (#607). ADR 0010 keeps the wait single-hop; this only tells
/// the human it is alive. Presentation pulse: --json drops it, and a session
/// with no bound sink (subagents) stays quiet.
-pub fn stillRunning(io: Io, id: u32, waited_ms: u64) void {
+pub fn stillRunning(io: Io, id: u32, waited_ms: u64, unread: usize) void {
var ebuf: [16]u8 = undefined;
- tool_pulse.emitNotice(io, "· bash_output · job {d} still running · {s}", .{ id, tool_pulse.formatElapsed(&ebuf, waited_ms) });
+ tool_pulse.emitNotice(io, "· bash_output · job {d} still running · {s} · {d} unread byte(s)", .{ id, tool_pulse.formatElapsed(&ebuf, waited_ms), unread });
}
/// Drain queued notices into `buf` (step boundary: everything). Null when
@@ -256,10 +264,10 @@ test "dismiss drops a queued notice, or the one the pump has not queued yet (ADR
test "printRunning reports the wait that happened, not the deadline (ADR 0061)" {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
- try printRunning(&aw.writer, 181, 36_000, true);
+ try printRunning(&aw.writer, 181, 36_000, true, false);
try std.testing.expectEqualStrings("[job 181: running · 36s waited, then interrupted — you are notified on exit; do not call bash_output again]", aw.written());
aw.clearRetainingCapacity();
- try printRunning(&aw.writer, 5, 125_000, false);
+ try printRunning(&aw.writer, 5, 125_000, false, false);
try std.testing.expectEqualStrings("[job 5: running · 2m05s elapsed — you are notified on exit; do not call bash_output again]", aw.written());
}
diff --git a/src/job_wait.zig b/src/job_wait.zig
index 926d8bfc..fa302389 100644
--- a/src/job_wait.zig
+++ b/src/job_wait.zig
@@ -19,11 +19,18 @@ pub const legacy_poll_ms: u64 = 30_000;
/// Map a model-supplied `wait_ms` onto a real deadline.
///
/// * `0` — snapshot now (do not block).
-/// * `> 0` — wait until exit (or Esc), always `wait_cap_ms`. Mid-range
-/// "safety timeouts" (60s–240s) used to be honored as a bounded
-/// deadline (#640) and bounced the model every few minutes.
+/// * `> 0` on a finite job — wait until exit (or Esc), always `wait_cap_ms`.
+/// Mid-range "safety timeouts" used to bounce the model every few minutes
+/// (#640 / ADR 0010).
+/// * `> 0` on a persistent server (`run_in_background`) — honor `wait_ms` as
+/// a millisecond cap, then return a running snapshot (ADR 0091 / #810).
pub fn resolveDeadline(wait_ms: u64) u64 {
+ return resolveDeadlineFor(wait_ms, false);
+}
+
+pub fn resolveDeadlineFor(wait_ms: u64, persistent: bool) u64 {
if (wait_ms == 0) return 0;
+ if (persistent) return @min(wait_ms, wait_cap_ms);
return wait_cap_ms;
}
@@ -46,3 +53,10 @@ test "resolveDeadline: mid-range and huge values are the 10h exit cap (#640)" {
test "resolveDeadline: 10h is 36_000_000 ms" {
try std.testing.expectEqual(@as(u64, 36_000_000), wait_cap_ms);
}
+
+test "resolveDeadlineFor: persistent jobs honor wait_ms as a timeout (#810)" {
+ try std.testing.expectEqual(@as(u64, 0), resolveDeadlineFor(0, true));
+ try std.testing.expectEqual(@as(u64, 1000), resolveDeadlineFor(1000, true));
+ try std.testing.expectEqual(wait_cap_ms, resolveDeadlineFor(wait_cap_ms + 1, true));
+ try std.testing.expectEqual(wait_cap_ms, resolveDeadlineFor(1000, false));
+}
diff --git a/src/jobs.zig b/src/jobs.zig
index dd939f32..2355917c 100644
--- a/src/jobs.zig
+++ b/src/jobs.zig
@@ -81,6 +81,7 @@ const Job = struct { // session-global; pump drains pipes; survives Esc
kill_requested: bool = false,
dropped: bool = false,
quiet: bool = false, // skip job_notify until auto-bg (#620)
+ persistent: bool = false, // started with run_in_background (#810)
future: Io.Future(void) = undefined,
stream: ?process_runner.StreamFn = null,
stream_ctx: ?*anyopaque = null,
@@ -296,6 +297,7 @@ pub const SpawnOpts = struct {
stream: ?process_runner.StreamFn = null,
stream_ctx: ?*anyopaque = null,
quiet: bool = false,
+ persistent: bool = false,
};
pub fn spawnJob(gpa: Allocator, io: Io, cmd: []const u8) !*Job {
@@ -329,6 +331,7 @@ pub fn spawnJobOpts(gpa: Allocator, io: Io, cmd: []const u8, opts: SpawnOpts) !*
.stream = opts.stream,
.stream_ctx = opts.stream_ctx,
.quiet = opts.quiet,
+ .persistent = opts.persistent,
.cwd = cwd_copy,
.started_ms = util.unixMs(io),
.last_active_ms = nowMs(io),
@@ -369,12 +372,13 @@ pub fn spawnJobOpts(gpa: Allocator, io: Io, cmd: []const u8, opts: SpawnOpts) !*
}
/// bash_output: unread output + status. wait_ms=0 is a snapshot. wait_ms>0
-/// blocks until the job exits (or Esc), not until the next byte (ADR 0010).
+/// blocks until the job exits (or Esc) for finite jobs (ADR 0010). Persistent
+/// servers honor wait_ms as a millisecond cap (ADR 0091 / #810).
pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {
- const deadline = job_wait.resolveDeadline(wait_ms);
var waited: u64 = 0;
var interrupted = false; // Esc: report what was waited, not the 10h cap (ADR 0061)
- var still = tool_pulse.Pulse{}; // #607: dim chrome per silence threshold; ADR 0010 keeps the wait single-hop
+ var still = tool_pulse.Pulse{ .interval_ms = 15_000 }; // #807: pulse often enough to tell hang from work
+ var unread: usize = 0;
while (true) {
g_jobs.mutex.lockUncancelable(io);
const job = g_jobs.find(id) orelse {
@@ -382,6 +386,8 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {
return .{ .text = try std.fmt.allocPrint(gpa, "no background job {d} — it may never have started; /jobs lists them", .{id}), .is_error = true };
};
job.last_active_ms = nowMs(io); // a read or a blocking wait is activity (#199)
+ const deadline = job_wait.resolveDeadlineFor(wait_ms, job.persistent);
+ unread = job.buf.items.len - job.cursor;
const fresh = job.buf.items[job.cursor..];
if (job.done or interrupted or waited >= deadline) {
errdefer g_jobs.mutex.unlock(io);
@@ -389,7 +395,7 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {
errdefer aw.deinit();
const w = &aw.writer;
if (!job.done) {
- try job_notify.printRunning(w, id, waited, interrupted);
+ try job_notify.printRunning(w, id, waited, interrupted, job.persistent);
} else if (job.stopped_idle) {
try job_idle.printStopped(w, id, job_idle.policy.stop_ms);
} else if (job.killed) {
@@ -425,7 +431,7 @@ pub fn jobOutput(gpa: Allocator, io: Io, id: u32, wait_ms: u64) !ToolOutput {
continue;
};
waited += 100;
- if (still.due(waited)) job_notify.stillRunning(io, id, waited);
+ if (still.due(waited)) job_notify.stillRunning(io, id, waited, unread);
}
}
diff --git a/src/jobs_tests.zig b/src/jobs_tests.zig
index 08b69133..d6bce488 100644
--- a/src/jobs_tests.zig
+++ b/src/jobs_tests.zig
@@ -109,6 +109,19 @@ test "isolated capped runs clean descendants after timeout and normal exit" {
try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "completed-marker", .{}));
}
+test "bash_output wait_ms on a persistent job is a snapshot timeout (#810)" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ jobs.g_jobs = .{};
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const id = (try jobs.spawnJobOpts(gpa, io, "sleep 8", .{ .persistent = true })).id;
+ defer jobs.jobsReap(gpa, io);
+ const snap = try jobs.jobOutput(gpa, io, id, 400);
+ defer gpa.free(snap.text);
+ try std.testing.expect(std.mem.indexOf(u8, snap.text, "running") != null);
+ try std.testing.expect(std.mem.indexOf(u8, snap.text, "persistent server") != null);
+}
+
test "bash_output wait_ms>0 waits for exit, not the next byte (ADR 0010)" {
if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
jobs.g_jobs = .{};
diff --git a/src/main.zig b/src/main.zig
index 85b18902..3901663b 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -54,7 +54,7 @@ test { // unit_tests' root is main.zig only, so reference every split-out module
_ = models_cache;
_ = ansi;
_ = serve;
- _ = @import("json_inbox.zig");
+ _ = .{ @import("json_inbox.zig"), @import("acp_inbox.zig"), @import("cite_markup.zig") };
_ = util;
_ = learn_store;
_ = learn_eval;
diff --git a/src/repl_util.zig b/src/repl_util.zig
index deaa3fdf..35bd4d1e 100644
--- a/src/repl_util.zig
+++ b/src/repl_util.zig
@@ -5,6 +5,7 @@
const std = @import("std");
const zz = @import("zigzag");
+const cite_markup = @import("cite_markup.zig");
pub const accent = zz.Color.fromRgb(0x05, 0x96, 0x69); // codegraff.com emerald accent (#059669)
@@ -75,6 +76,11 @@ pub fn stripControl(a: std.mem.Allocator, s: []const u8) []const u8 {
} else if (c == '\r') {
i += 1;
} else {
+ const skipped = cite_markup.skip(s, i);
+ if (skipped != i) {
+ i = skipped;
+ continue;
+ }
out.append(c) catch {};
i += 1;
}
@@ -114,3 +120,10 @@ pub fn parseToggle(arg: []const u8, current: bool) bool {
pub fn onOff(v: bool) []const u8 {
return if (v) "on" else "off";
}
+
+test "stripControl drops citation annotations (#811)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const got = stripControl(arena_state.allocator(), "See the docs\u{E200}cite\u{E202}turn0view0\u{E201} for details.");
+ try std.testing.expectEqualStrings("See the docs for details.", got);
+}
diff --git a/src/schema.zig b/src/schema.zig
index 0cf13d40..b7616f98 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -60,9 +60,9 @@ pub const base_specs = [_]ToolSpec{
},
.{
.name = "bash_output",
- .desc = "Read a background bash job's unread output and status. wait_ms=0 (or omitted) is a snapshot. wait_ms>0 blocks until the job exits (capped at 10 hours). Do not poll in a loop — one wait covers exit.",
+ .desc = "Read a background bash job's unread output and status. wait_ms=0 (or omitted) is a snapshot. For a finite job, wait_ms>0 blocks until exit (10h cap). For a job started with run_in_background (a server), wait_ms is an actual millisecond timeout before a running snapshot — it will not wait for exit. Do not poll in a loop.",
.schema =
- \\{"type": "object", "properties": {"id": {"type": "integer", "description": "Job id returned by bash with run_in_background"}, "wait_ms": {"type": "integer", "description": "0 = snapshot now. >0 = block until the job exits (capped at 10 hours). Do not poll every 30s."}}, "required": ["id"]}
+ \\{"type": "object", "properties": {"id": {"type": "integer", "description": "Job id returned by bash with run_in_background"}, "wait_ms": {"type": "integer", "description": "0 = snapshot now. Finite jobs: >0 waits until exit (10h cap). Persistent servers: >0 is a millisecond timeout, then a running snapshot."}}, "required": ["id"]}
,
},
.{
diff --git a/src/tool_handle.zig b/src/tool_handle.zig
index 63678def..a70a33a1 100644
--- a/src/tool_handle.zig
+++ b/src/tool_handle.zig
@@ -140,11 +140,11 @@ pub fn forResult(gpa: Allocator, arena: Allocator, target: Target, text: []const
// Notable lines past the head (FAILED / ERROR / panic) ride the first
// payload so a fat log does not cost a pager turn for "what broke?".
const room = threshold - (marker.len + 2);
- const excerpt_budget = @min(handle_preview.max_notable_bytes, room / 4);
- const skip = if (room > excerpt_budget) room - excerpt_budget else room;
- const excerpt = handle_preview.notableExcerpt(arena, text, skip, excerpt_budget) catch "";
- const used = marker.len + excerpt.len + (if (excerpt.len == 0) @as(usize, 2) else 4);
- const head = util.utf8Prefix(text, if (used < threshold) threshold - used else 0);
+ const preview_cap = @min(room, @as(usize, 4096));
+ const excerpt_budget = @min(handle_preview.max_notable_bytes, preview_cap / 4);
+ const head_budget = if (preview_cap > excerpt_budget) preview_cap - excerpt_budget else preview_cap;
+ const head = handle_preview.compactPreview(arena, text, head_budget) catch util.utf8Prefix(text, head_budget);
+ const excerpt = handle_preview.notableExcerpt(arena, text, head.len, excerpt_budget) catch "";
if (excerpt.len == 0) return .{
.text = try std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ head, marker }),
.path = path,
@@ -162,7 +162,7 @@ pub fn forResult(gpa: Allocator, arena: Allocator, target: Target, text: []const
/// STANDING prompt (~225 tokens on every call of every session, mostly
/// buying nothing). agent_tools appends this to the FIRST handle an agent
/// produces — the #445 pattern: guidance delivered when it earns its tokens.
-pub const first_note = " [handle protocol, applies to every such handle: never pull a whole handle file back into the conversation — slice ranges — and the file stays readable for the rest of the session.]";
+pub const first_note = " [handle protocol: page with read_tool_result(handle, offset, limit) or query; never pull the whole file back into the conversation. The file stays readable for the rest of the session.]";
/// The #541 append, pure so the once-per-agent contract is testable without
/// an Io or a live Agent: `shown` is the agent's own flag, flipped exactly
@@ -372,7 +372,7 @@ test "#440: over the threshold returns preview + handle path + byte count + shap
const big = try a.alloc(u8, 40_000);
@memset(big, 'x');
for (0..399) |i| big[(i + 1) * 100 - 1] = '\n'; // 400 lines
- @memcpy(big[39_000..][0..needle.len], needle);
+ @memcpy(big[20_000..][0..needle.len], needle); // middle: not in the head or tail window
const threshold: usize = 4096;
const r = try forResult(std.testing.allocator, a, testTarget(&tmp), big, threshold);
@@ -438,7 +438,8 @@ test "#440: the threshold is a knob — the same payload is bounded by whatever
const roomy = try forResult(std.testing.allocator, a, testTarget(&tmp), payload, 16_384);
try std.testing.expect(tight.text.len <= 4096);
try std.testing.expect(roomy.text.len <= 16_384);
- try std.testing.expect(roomy.text.len > tight.text.len);
+ try std.testing.expect(std.mem.indexOf(u8, tight.text, "read_tool_result") != null);
+ try std.testing.expect(std.mem.indexOf(u8, roomy.text, "read_tool_result") != null);
// Raise it past the payload and the handle contract does not apply at all.
const off = try forResult(std.testing.allocator, a, testTarget(&tmp), payload, 32_768);
try std.testing.expect(off.path == null);