Skip to content

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

Python

Report ACP cancellation provenance

justrach7df5617f84ad
diff --git a/scripts/test-acp-ask-user.py b/scripts/test-acp-ask-user.py
index 3f6e0e5c..d1e24bdf 100644
--- a/scripts/test-acp-ask-user.py
+++ b/scripts/test-acp-ask-user.py
@@ -29,15 +29,18 @@ 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': arguments},
- {'text': 'Done.'},
- ])
+ replies = [{'tool': 'ask_user', 'arguments': arguments}]
+ if case == 'delayed':
+ replies.append({'tool': 'ask_user', 'arguments': arguments})
+ replies.append({'text': 'Done.'})
+ model = ScriptedModel(replies)
caps = {
'none': {'fs': {}},
'elicitation': {'fs': {}, 'elicitation': {'form': {}}},
'questions': {'fs': {}, 'elicitation': {'form': {}}},
'legacy': {'fs': {}, '_meta': {'graff/askUser': True}},
+ 'delayed': {'fs': {}, 'elicitation': {'form': {}}},
+ 'cancel': {'fs': {}, 'elicitation': {'form': {}}},
}[case]
# Windows keeps the killed process's files open briefly; do not fail on cleanup.
temp = tempfile.mkdtemp(prefix='acp-ask-user-')
@@ -68,6 +71,7 @@ def run(binary, case):
proc.stdin.flush()
seen = []
+ elicitations = []
def wait(id, timeout=30):
deadline = time.monotonic() + timeout
@@ -78,14 +82,22 @@ def run(binary, case):
if m.get('id') == id and 'method' not in m:
return m
if m.get('method') == 'elicitation/create':
- assert case in ('elicitation', 'questions'), m
+ assert case in ('elicitation', 'questions', 'delayed', 'cancel'), m
params = m['params']
assert params['mode'] == 'form' and params['message'] == QUESTION, params
answer = params['requestedSchema']['properties']['answer']
assert answer['enum'] == ['npm', 'GitHub release'], answer
- # A stale ID must not answer the live question.
- send({'id': 'graff-elicit-0', 'result': {'action': 'accept', 'content': {'answer': 'wrong'}}})
- send({'id': m['id'], 'result': {'action': 'accept', 'content': {'answer': 'npm'}}})
+ elicitations.append(m['id'])
+ if case == 'cancel':
+ send({'method': 'session/cancel', 'params': {'sessionId': sid}})
+ continue
+ if case == 'delayed':
+ time.sleep(.2)
+ # A stale ID must not answer this or the next question.
+ stale = elicitations[0] if len(elicitations) > 1 else 'graff-elicit-0'
+ send({'id': stale, 'result': {'action': 'accept', 'content': {'answer': 'wrong'}}})
+ answer_text = 'GitHub release' if len(elicitations) > 1 else 'npm'
+ send({'id': m['id'], 'result': {'action': 'accept', 'content': {'answer': answer_text}}})
update = (m.get('params') or {}).get('update') or {}
if update.get('sessionUpdate') == 'gui_ask_user':
assert case == 'legacy', m
@@ -99,6 +111,14 @@ def run(binary, case):
started = time.monotonic()
send({'id': 3, 'method': 'session/prompt', 'params': {'sessionId': sid, 'prompt': [{'type': 'text', 'text': 'Ask me.'}]}})
done = wait(3, timeout=20)
+ if case == 'cancel':
+ assert done.get('result', {}).get('stopReason') == 'cancelled', done
+ meta = done['result'].get('_meta', {})
+ assert meta.get('graff/cancelSource') == 'acp_cancel', done
+ assert 'interrupted by user' in meta.get('graff/cancelMessage', ''), done
+ assert len(model.requests) == 1, 'explicit cancellation continued the model'
+ print('PASS ACP ask_user', case, flush=True)
+ return
assert done.get('result', {}).get('stopReason') == 'end_turn', done
results = tool_results(model)
assert results, 'ask_user result never reached the model'
@@ -109,7 +129,11 @@ def run(binary, case):
assert 'elicitation/create' not in methods and 'gui_ask_user' not in updates
assert time.monotonic() - started < 10, 'ask_user waited on a client that cannot answer'
else:
- assert 'npm' in results[-1] and 'wrong' not in results[-1], results
+ expected = 'GitHub release' if case == 'delayed' else 'npm'
+ assert expected in results[-1] and not any('wrong' in r for r in results), results
+ if case == 'delayed':
+ assert len(elicitations) == 2 and len(model.requests) == 3
+ assert 'npm' in results and 'GitHub release' in results
print('PASS ACP ask_user', case, flush=True)
finally:
if os.name == 'posix':
@@ -124,5 +148,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', 'questions', 'legacy']:
+ for case in ['none', 'elicitation', 'questions', 'legacy', 'delayed', 'cancel']:
run(binary, case)
diff --git a/src/acp.zig b/src/acp.zig
index f375d0e7..b298de11 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -55,14 +55,6 @@ pub fn isAcpSubcommand(positional: []const u8) bool {
return true;
}
-fn syncEscCancel() void {
- @import("cancel_source.zig").cancel(.acp_cancel); // #728
-}
-
-fn liveCancelled() bool {
- return agent_mod.Agent.esc_cancel.load(.acquire);
-}
-
/// A slash command typed in a client runs the same handler the REPL runs,
/// so the menu the agent advertises is not a menu of things that then get
/// sent to the model as prose. A command-shaped `/word` outside the catalog
@@ -189,8 +181,8 @@ fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Reque
pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u8) !void {
engine.implementation_version = main_mod.harness_version;
- engine.on_cancel = syncEscCancel;
- engine.extra_cancelled = liveCancelled;
+ engine.on_cancel = LiveTurn.signalCancel;
+ engine.extra_cancelled = LiveTurn.cancelled;
return engine.handleLine(d, arena, w, line);
}
@@ -214,7 +206,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
main_mod.g_out = null;
engine.implementation_version = main_mod.harness_version;
engine.cancel_flag.store(false, .release);
- engine.on_cancel = syncEscCancel;
+ engine.on_cancel = LiveTurn.signalCancel;
var transport_lock: Io.Mutex = .init;
var framed: @import("acp_line_writer.zig").LineWriter = undefined;
framed.init(io, out, &transport_lock);
@@ -243,6 +235,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_
var d: Dispatch = .{
.turn = LiveTurn.run,
.error_message = LiveTurn.errorMessage,
+ .cancel_info = LiveTurn.cancelInfo,
.ctx = &live,
.seed = @bitCast(util.unixMs(io)),
.slash = liveSlash,
diff --git a/src/acp_engine.zig b/src/acp_engine.zig
index feb54de7..29cebe27 100644
--- a/src/acp_engine.zig
+++ b/src/acp_engine.zig
@@ -61,6 +61,8 @@ pub const SetConfigFn = *const fn (ctx: *anyopaque, value: []const u8) anyerror!
/// The request's `mcpServers` on session/new and session/load (acp_mcp_servers.zig).
pub const McpServersFn = *const fn (ctx: *anyopaque, arena: Allocator, params: ?std.json.Value) anyerror!void;
+pub const Cancellation = struct { source: []const u8, message: []const u8 };
+
pub const Dispatch = struct {
turn: TurnFn,
ctx: *anyopaque,
@@ -79,6 +81,7 @@ pub const Dispatch = struct {
set_config: ?SetConfigFn = null,
mcp_servers: ?McpServersFn = null,
error_message: ?*const fn (ctx: *anyopaque, err: anyerror) []const u8 = null,
+ cancel_info: ?*const fn (ctx: *anyopaque) ?Cancellation = null,
/// Live CLI: adopt the client's cwd, report `_meta["graff/worktree"]` (acp_workspace.zig).
workspace: ?acp_workspace.Env = null,
/// ACP v1 draft subagent updates are opt-in at initialize.
@@ -165,8 +168,14 @@ pub fn stripSgr(arena: Allocator, s: []const u8) ![]const u8 {
}
fn turnError(d: *Dispatch, w: *Io.Writer, req: proto.Request, err: anyerror) !void {
- if (err == error.Interrupted or err == error.Canceled)
+ if (err == error.Interrupted or err == error.Canceled) {
+ if (d.cancel_info) |read| if (read(d.ctx)) |info|
+ return respond(w, req, .{ .stopReason = "cancelled", ._meta = .{
+ .@"graff/cancelSource" = info.source,
+ .@"graff/cancelMessage" = info.message,
+ } });
return respond(w, req, .{ .stopReason = "cancelled" });
+ }
if (err == error.RunBudgetExhausted)
return respond(w, req, .{ .stopReason = "max_turn_requests" });
return respondError(w, req, err_internal, if (d.error_message) |message| message(d.ctx, err) else @errorName(err));
diff --git a/src/acp_engine_test.zig b/src/acp_engine_test.zig
index 65c8a9cb..c7268d84 100644
--- a/src/acp_engine_test.zig
+++ b/src/acp_engine_test.zig
@@ -57,3 +57,24 @@ test "live context occupancy precedes the terminal prompt reply" {
const terminal = std.mem.indexOf(u8, output, "\"stopReason\":\"end_turn\"") orelse return error.MissingTerminalReply;
try std.testing.expect(occupancy < terminal);
}
+
+test "interrupted ACP prompt preserves cancellation provenance in its terminal response" {
+ const Fixture = struct {
+ fn turn(_: *anyopaque, _: Allocator, _: []const u8) anyerror![]const u8 {
+ return error.Interrupted;
+ }
+ fn cancelled(_: *anyopaque) ?engine.Cancellation {
+ return .{ .source = "none", .message = "harness cancelled the turn" };
+ }
+ };
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var buffer: [4096]u8 = undefined;
+ var writer: Io.Writer = .fixed(&buffer);
+ var dispatch: Dispatch = .{ .turn = Fixture.turn, .ctx = undefined, .cancel_info = Fixture.cancelled };
+ try handleLine(&dispatch, arena.allocator(), &writer, "{\"id\":7,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"continue\"}]}}");
+ const output = writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, output, "\"stopReason\":\"cancelled\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, output, "\"graff/cancelSource\":\"none\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, output, "harness cancelled the turn") != null);
+}
diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zig
index 8db79ae5..56f38d9e 100644
--- a/src/acp_live_turn.zig
+++ b/src/acp_live_turn.zig
@@ -30,6 +30,7 @@ pub const LiveTurn = struct {
model_override: ?provider_mod.Provider = null,
/// The context count the last mid-turn meter carried.
last_meter_used: u64 = 0,
+ cancelled_source: ?cancel_source.Source = null,
/// Mid-turn `usage_update`, only when the count moved since the last one.
fn stepMeter(ctx: *anyopaque, w: *Io.Writer) void {
@@ -47,8 +48,23 @@ pub const LiveTurn = struct {
return if (err == error.ApiError) self.root.last_api_error orelse "Provider request failed" else @errorName(err);
}
+ pub fn signalCancel() void {
+ cancel_source.cancel(.acp_cancel); // #728
+ }
+
+ pub fn cancelled() bool {
+ return agent_mod.Agent.esc_cancel.load(.acquire);
+ }
+
+ pub fn cancelInfo(ctx: *anyopaque) ?@import("acp_engine.zig").Cancellation {
+ const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ const source = self.cancelled_source orelse return null;
+ return .{ .source = @tagName(source), .message = cancel_source.marker(source) };
+ }
+
pub fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {
const self: *LiveTurn = @ptrCast(@alignCast(ctx));
+ self.cancelled_source = null;
var output_lock: Io.Mutex = .init;
if (self.inbox) |inbox| if (inbox.permission) |bridge| bridge.setOutputLock(&output_lock);
defer if (self.inbox) |inbox| if (inbox.permission) |bridge| bridge.setOutputLock(null);
@@ -140,9 +156,17 @@ pub const LiveTurn = struct {
self.root.rebaseContextMeter();
}
const final = result catch |err| {
+ if (err == error.Interrupted or err == error.Canceled) {
+ self.cancelled_source = cancel_source.take(self.root.tracer);
+ if (!isolated) try self.root.messages.append(try messages.textMessage(
+ arena,
+ "assistant",
+ cancel_source.marker(self.cancelled_source.?),
+ ));
+ }
if (isolated) {
const marker = if (err == error.Interrupted or err == error.Canceled)
- cancel_source.marker(cancel_source.take(self.root.tracer))
+ cancel_source.marker(self.cancelled_source.?)
else
try std.fmt.allocPrint(arena, "[review ended early: {s}; findings are incomplete]", .{@errorName(err)});
const partial = std.mem.trim(u8, self.root.partial_text.items, " \t\r\n");