graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Answer a resent request from its first run instead of starting a second turn (#1285)
justrach5cd2e9196755
diff --git a/docs/acp-compatibility.md b/docs/acp-compatibility.mdindex 52f02bfc..c4aee2b5 100644--- a/docs/acp-compatibility.md+++ b/docs/acp-compatibility.md@@ -37,6 +37,7 @@ optional feature or draft extension is enabled.| Context meter | Standard `usage_update` (stable in ACP v1): `used` tokens in context and the model's `size`, plus `cost` `{amount, currency: "USD"}` only when every call so far was priced. Sent after tool steps whenever the count moved (so it drops visibly after compaction) and at the end of each prompt turn. | `src/acp_context_meter.zig`, `src/acp_engine_test.zig` || Usage | Connection usage is a namespaced extension. It preserves unknown totals and is not a standard ACP v1 billing contract. | `scripts/test-acp-usage.py`, ADR 0182 || Subagents | Default: a top-level subagent streams its work onto the parent tool call as standard `tool_call_update` content (a rolling log of its tool calls, failures and message tail), with no `status` change and `_meta["graff/subagent"]` = `{sessionId, name, state}`; `GRAFF_ACP_SUBAGENT_PROGRESS=0` disables it. Opt-in preview: the proposed child-session stream (client `subagents` capability plus `GRAFF_ACP_DRAFT_SUBAGENTS=1`) replaces it for foreground children. Detached workers also keep `graff/agents` inspection. Child history is not yet replayed on `session/load`. | `scripts/test-acp-subagent-update.py`, ADR 0194, ADR 0205 |+| Resent prompts | `session/prompt` may carry a client message id as `messageId` or `_meta["graff/messageId"]`. Resending a prompt this process already finished for that session answers with the first turn's `stopReason` instead of starting another turn; a failed turn is not recorded, so its resend runs. The last 32 ids are kept in memory. `graff serve` and remote control take the same id as `message_id` on the request body and replay the first request's events. | `src/resend.zig`, `scripts/test-serve-resume.py` || Saved views | A completed `tool_call_update` whose result saved a `render_html` page or an MCP Apps result also carries `_meta["graff/view"]` = `{kind: "html" \| "mcp_app", id, path}`. `id` is the 32-hex snapshot name under `.graff/views` or `.graff/mcp-apps`; resolve by id and treat `path` as informational. The `[Rendered view](…)` / `[MCP app](…)` text link stays in the content. Replayed on `session/load`. | `scripts/test-acp-view-meta.py`, `src/acp_view_meta.zig` || Compaction | When the root agent compacts (automatically, `/compact`, or server-side), graff sends `compaction_update` `{compactionId, status}`: `in_progress`, then one of `completed` (a local summary rides `summary` as a text block), `failed` (with `error`) or `cancelled`. A provider that compacted in-stream gets one `completed`. ACP v1 marks this unstable, so it is sent only to clients that advertise `clientCapabilities.session.compaction`; ACP v2 clients always get it. | `src/acp_compaction.zig`, `scripts/test-acp-compaction.py` || Transport | ACP uses JSON-RPC over stdio. HTTP/2 checks exercise the model request transport behind ACP; they do not redefine ACP as an HTTP/2 protocol. | `scripts/test-acp-http2.py`, `scripts/test-acp-http2-retry.py` |diff --git a/scripts/test-serve-resume.py b/scripts/test-serve-resume.pyindex 2cd38df2..78927337 100644--- a/scripts/test-serve-resume.py+++ b/scripts/test-serve-resume.py@@ -247,6 +247,20 @@ def main() -> None:raise AssertionError("{'type':'reattach'} did not match the GET replay")print(f" reattach POST: resume_from={mid} matched the GET ({len(reattached)} events)")+ # 2b ── #1285: resending a finished request (same message_id) is+ # answered from the tape — the same events, no second model turn.+ calls = len(mock.recorded_requests())+ sent = stream(serve_port, "POST", f"/v1/sessions/{SESSION}",+ {"type": "user", "text": "RESEND_ME", "message_id": "m-1285"})+ last = expect_contiguous(sent, last + 1, "message_id turn")+ again = stream(serve_port, "POST", f"/v1/sessions/{SESSION}",+ {"type": "user", "text": "RESEND_ME", "message_id": "m-1285"})+ if again != sent:+ raise AssertionError(f"a resend did not replay the first request's events: {again[-1:]!r}")+ if len(mock.recorded_requests()) != calls + 1:+ raise AssertionError("a resend with the same message_id started a second model turn")+ print(f" resend: message_id m-1285 replayed its {len(again)} events, one model call")+# 3 ── drop the socket mid-turn; the run continues, ?from=N catches up ─slow_turn.set()partial: list[dict] = []diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 7391cce7..feb54de7 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -30,6 +30,9 @@ pub var cancel_flag = std.atomic.Value(bool).init(false);pub var on_cancel: ?*const fn () void = null;/// CLI live ACP also watches `Agent.esc_cancel` (Esc / session/cancel).pub var extra_cancelled: ?*const fn () bool = null;+/// #1285: session/prompt message ids this process already ran, by session.+/// Prompts dispatch one at a time, so no lock.+pub var resent: @import("resend.zig").Ledger = .{};pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8;pub const SlashFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8;@@ -176,6 +179,12 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)if (obj) |o| if (util.strFieldObj(o, "sessionId")) |s| break :blk s;break :blk d.session_id orelse "";};+ // #1285: a resent prompt this session already ran answers with that turn's+ // stop reason instead of starting another. A failed turn is not recorded.+ const resend = @import("resend.zig");+ const resend_key: ?u64 = if (obj) |o| (if (resend.acpId(o)) |mid| resend.Ledger.keyOf(sid, mid) else null) else null;+ if (resend_key) |key| if (resent.finished(key)) |prior| return respond(w, req, .{ .stopReason = prior.stopReason() });+ if (resend_key) |key| resent.begin(key, 0);if (d.bind_session) |bind| bind(d.ctx, sid);@import("acp_citations.zig").endTurn(sid); // a failed turn must not leave a marker openconst config_before = configOptions(d, arena) catch |err| return turnError(d, w, req, err);@@ -192,6 +201,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)emitConfigChange(d, arena, w, sid, config_before) catch |config_err| return turnError(d, w, req, config_err);try acp_workspace.emitChange(d.workspace, arena, w, sid, workspace_before);try emitMeter(d, w, sid);+ if (resend_key) |key| resent.finish(key, 0, "end_turn");return respond(w, req, .{ .stopReason = "end_turn" });}}@@ -206,6 +216,7 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)try emitMeter(d, w, sid);const extra = if (extra_cancelled) |f| f() else false;const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";+ if (resend_key) |key| resent.finish(key, 0, stop);try respond(w, req, .{ .stopReason = stop });}diff --git a/src/remote_control.zig b/src/remote_control.zigindex 787346b8..4f3ab8a5 100644--- a/src/remote_control.zig+++ b/src/remote_control.zig@@ -285,7 +285,7 @@ fn runCommand(self: *State, arena: Allocator, cmd: Command) void {// works for a session this supervisor never ran, straight off the disk.if (std.mem.eql(u8, rtype, "reattach")) {var up = upload.Uploader.init(link(self, client), arena, cmd.id, sid);- replayTape(self, arena, &up, sid, from orelse 1);+ replayTape(self, arena, &up, sid, from orelse 1, std.math.maxInt(u64));return up.finish(200, "{\"ok\":true,\"type\":\"reattach\"}");}self.st.mutex.lockUncancelable(io);@@ -370,14 +370,23 @@ fn drain(self: *State, client: *std.http.Client, arena: Allocator, s: *ServeSess// the moment busy is released below, and finish() still names it.const sid = arena.dupe(u8, s.name) catch s.name;var up = upload.Uploader.init(link(self, client), arena, cmd_id, sid);+ const resend = @import("resend.zig");+ const body = std.json.parseFromSliceLeaky(Value, arena, line, .{ .allocate = .alloc_always }) catch .null;+ const resend_key: ?u64 = if (body == .object) (if (resend.bodyId(body.object)) |mid| resend.Ledger.keyOf("", mid) else null) else null;{s.busy.lockUncancelable(io); // serialize requests per sessiondefer s.busy.unlock(io);+ // #1285: as serve, a resend of a finished request replays its events.+ if (resend_key) |key| if (s.resent.finished(key)) |prior| {+ replayTape(self, arena, &up, sid, prior.first_seq, prior.last_seq);+ return up.finish(200, "{\"ok\":true,\"resent\":true}");+ };s.in_flight.store(true, .release);defer s.in_flight.store(false, .release);+ if (resend_key) |key| s.resent.begin(key, s.last_seq + 1);serve.writeChildLine(io, s, line) catch return up.finish(502, "{\"error\":\"session process is gone\"}");- if (from) |n| replayTape(self, arena, &up, sid, n);+ if (from) |n| replayTape(self, arena, &up, sid, n, std.math.maxInt(u64));while (true) {const ev_line = s.rdr.interface.takeDelimiter('\n') catch |err| switch (err) {error.StreamTooLong => break abort(s, &up, "event line exceeded the 1 MiB serve cap — session closed", &dead),@@ -391,6 +400,7 @@ fn drain(self: *State, client: *std.http.Client, arena: Allocator, s: *ServeSessup.push(trimmed);if (events.terminalEvent(trimmed)) {serve.serveClearAnswerState(io, s);+ if (resend_key) |key| s.resent.finish(key, s.last_seq, "");break;}}@@ -411,8 +421,8 @@ fn abort(s: *ServeSession, up: *upload.Uploader, message: []const u8, dead: *boodead.* = true;}-/// Every complete tape line with seq >= from, in order.-fn replayTape(self: *State, arena: Allocator, up: *upload.Uploader, sid: []const u8, from: u64) void {+/// Every complete tape line with from <= seq <= to, in order.+fn replayTape(self: *State, arena: Allocator, up: *upload.Uploader, sid: []const u8, from: u64, to: u64) void {const path = events.logPath(arena, sid) catch return;const data = Io.Dir.cwd().readFileAlloc(self.st.io, path, arena, .limited(events.max_log_bytes)) catch return;var rest = data;@@ -421,7 +431,7 @@ fn replayTape(self: *State, arena: Allocator, up: *upload.Uploader, sid: []constrest = rest[nl + 1 ..];if (line.len == 0) continue;const seq = events.seqOf(line) orelse continue;- if (seq >= from) up.push(line);+ if (seq >= from and seq <= to) up.push(line);}}diff --git a/src/resend.zig b/src/resend.zignew file mode 100644index 00000000..7bb13e43--- /dev/null+++ b/src/resend.zig@@ -0,0 +1,206 @@+//! #1285: a client that loses its connection mid-send cannot tell whether its+//! request landed, so it resends it, and without an id the resend started a+//! second turn. A request may carry a client message id: `message_id` on a+//! serve or remote-control body, `messageId` or `_meta["graff/messageId"]` on+//! ACP session/prompt. The first request with an id runs; a repeat of a+//! finished one is answered from its record instead: serve and remote control+//! replay its events from the session tape, ACP returns its stop reason. A+//! repeat that arrives while the first still runs waits behind it (the+//! per-session request lock) and is then answered the same way.+//!+//! In memory and bounded: an id older than the last `cap` on the session, or+//! one from before a restart, runs again.++const std = @import("std");++/// Longest id accepted; anything longer is treated as no id.+pub const max_id_len = 128;++pub const Entry = struct {+ key: u64,+ done: bool = false,+ /// Serve / remote-control tape: this request's first event and its terminal one.+ first_seq: u64 = 0,+ last_seq: u64 = 0,+ /// ACP: the stop reason the first turn ended with.+ stop_buf: [32]u8 = undefined,+ stop_len: u8 = 0,++ pub fn stopReason(self: *const Entry) []const u8 {+ return self.stop_buf[0..self.stop_len];+ }+};++pub const Ledger = struct {+ pub const cap = 32;+ entries: [cap]Entry = undefined,+ len: usize = 0,+ next: usize = 0, // oldest slot once full++ /// `scope` separates sessions sharing one ledger (ACP); serve passes "".+ pub fn keyOf(scope: []const u8, id: []const u8) u64 {+ var h = std.hash.Wyhash.init(0x1285);+ h.update(scope);+ h.update("\x00");+ h.update(id);+ return h.final();+ }++ /// The finished request this id already ran, if still remembered.+ pub fn finished(self: *Ledger, key: u64) ?Entry {+ for (self.entries[0..self.len]) |e| if (e.key == key and e.done) return e;+ return null;+ }++ /// A request with this id starts. An unfinished earlier one (its handler+ /// failed before the terminal event) is replaced: that turn never ended.+ pub fn begin(self: *Ledger, key: u64, first_seq: u64) void {+ for (self.entries[0..self.len]) |*e| if (e.key == key) {+ e.* = .{ .key = key, .first_seq = first_seq };+ return;+ };+ const slot = if (self.len < cap) blk: {+ self.len += 1;+ break :blk self.len - 1;+ } else blk: {+ const oldest = self.next;+ self.next = (self.next + 1) % cap;+ break :blk oldest;+ };+ self.entries[slot] = .{ .key = key, .first_seq = first_seq };+ }++ pub fn finish(self: *Ledger, key: u64, last_seq: u64, stop: []const u8) void {+ for (self.entries[0..self.len]) |*e| if (e.key == key) {+ e.done = true;+ e.last_seq = last_seq;+ e.stop_len = @intCast(@min(stop.len, e.stop_buf.len));+ @memcpy(e.stop_buf[0..e.stop_len], stop[0..e.stop_len]);+ return;+ };+ }+};++fn usable(v: ?std.json.Value) ?[]const u8 {+ const s = v orelse return null;+ if (s != .string or s.string.len == 0 or s.string.len > max_id_len) return null;+ return s.string;+}++/// Serve / remote control: the body's `message_id`.+pub fn bodyId(body: std.json.ObjectMap) ?[]const u8 {+ return usable(body.get("message_id"));+}++/// ACP session/prompt params: `messageId`, else `_meta["graff/messageId"]`.+pub fn acpId(params: std.json.ObjectMap) ?[]const u8 {+ if (usable(params.get("messageId"))) |id| return id;+ const meta = params.get("_meta") orelse return null;+ if (meta != .object) return null;+ return usable(meta.object.get("graff/messageId"));+}++/// Tape lines with `from <= seq <= to`, in order: the first request's events.+pub fn replayRange(w: *std.Io.Writer, data: []const u8, from: u64, to: u64) !usize {+ const seqOf = @import("protocol_seq.zig").seqOf;+ var emitted: usize = 0;+ var rest = data;+ while (std.mem.indexOfScalar(u8, rest, '\n')) |nl| {+ const line = std.mem.trim(u8, rest[0..nl], " \t\r");+ rest = rest[nl + 1 ..];+ const seq = seqOf(line) orelse continue;+ if (seq < from or seq > to) continue;+ try w.writeAll(line);+ try w.writeByte('\n');+ emitted += 1;+ }+ return emitted;+}++test "#1285: a finished id is answered from its record; an unfinished one runs again" {+ var ledger: Ledger = .{};+ const a = Ledger.keyOf("s1", "m-1");+ try std.testing.expect(ledger.finished(a) == null);+ ledger.begin(a, 7);+ try std.testing.expect(ledger.finished(a) == null); // still running+ ledger.finish(a, 12, "end_turn");+ const prior = ledger.finished(a).?;+ try std.testing.expectEqual(@as(u64, 7), prior.first_seq);+ try std.testing.expectEqual(@as(u64, 12), prior.last_seq);+ try std.testing.expectEqualStrings("end_turn", prior.stopReason());+ // The same id in another session is a different request.+ try std.testing.expect(ledger.finished(Ledger.keyOf("s2", "m-1")) == null);+ // A restarted request replaces the record until it finishes.+ ledger.begin(a, 20);+ try std.testing.expect(ledger.finished(a) == null);+}++test "#1285: the ledger keeps the most recent ids" {+ var ledger: Ledger = .{};+ var i: u64 = 0;+ while (i < Ledger.cap + 5) : (i += 1) {+ var buf: [16]u8 = undefined;+ const key = Ledger.keyOf("", std.fmt.bufPrint(&buf, "m{d}", .{i}) catch unreachable);+ ledger.begin(key, i);+ ledger.finish(key, i, "");+ }+ try std.testing.expect(ledger.finished(Ledger.keyOf("", "m0")) == null); // evicted+ try std.testing.expect(ledger.finished(Ledger.keyOf("", "m36")) != null);+}++test "#1285: ids come from the body or the ACP params, bounded" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const body = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"type\":\"user\",\"text\":\"hi\",\"message_id\":\"m-7\"}", .{});+ try std.testing.expectEqualStrings("m-7", bodyId(body.object).?);+ const meta = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"sessionId\":\"s\",\"_meta\":{\"graff/messageId\":\"m-8\"}}", .{});+ try std.testing.expectEqualStrings("m-8", acpId(meta.object).?);+ const top = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"messageId\":\"m-9\",\"_meta\":{\"graff/messageId\":\"x\"}}", .{});+ try std.testing.expectEqualStrings("m-9", acpId(top.object).?);+ const none = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"message_id\":\"\"}", .{});+ try std.testing.expect(bodyId(none.object) == null);+}++test "#1285: replayRange returns exactly the first request's events" {+ var out: std.Io.Writer.Allocating = .init(std.testing.allocator);+ defer out.deinit();+ const tape = "{\"seq\":1,\"type\":\"a\"}\n{\"seq\":2,\"type\":\"b\"}\n{\"seq\":3,\"type\":\"turn\"}\n{\"seq\":4,\"type\":\"c\"}\n";+ try std.testing.expectEqual(@as(usize, 2), try replayRange(&out.writer, tape, 2, 3));+ try std.testing.expectEqualStrings("{\"seq\":2,\"type\":\"b\"}\n{\"seq\":3,\"type\":\"turn\"}\n", out.written());+}++test "#1285: ACP answers a resent prompt from the first turn" {+ const engine = @import("acp_engine.zig");+ const v2 = @import("acp_v2.zig");+ const Counter = struct {+ var turns: u32 = 0;+ fn turn(_: *anyopaque, arena: std.mem.Allocator, text: []const u8) anyerror![]const u8 {+ turns += 1;+ return std.fmt.allocPrint(arena, "ran:{s}", .{text});+ }+ };+ const gate = v2.gate;+ v2.gate = false;+ defer v2.gate = gate;+ engine.resent = .{};+ defer engine.resent = .{};+ Counter.turns = 0;+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ var out: std.Io.Writer.Allocating = .init(a);+ var d: engine.Dispatch = .{ .turn = Counter.turn, .ctx = undefined };+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":1}}");+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}");+ const send = "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s1\",\"prompt\":\"x\",\"_meta\":{\"graff/messageId\":\"m-1\"}}}";+ const resend = "{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s1\",\"prompt\":\"x\",\"_meta\":{\"graff/messageId\":\"m-1\"}}}";+ try engine.handleLine(&d, a, &out.writer, send);+ try engine.handleLine(&d, a, &out.writer, resend);+ try std.testing.expectEqual(@as(u32, 1), Counter.turns);+ try std.testing.expect(std.mem.indexOf(u8, out.written(), "\"id\":4,\"result\":{\"stopReason\":\"end_turn\"}") != null);+ // A new id, or the same id in another session, is a new turn.+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s1\",\"prompt\":\"y\",\"messageId\":\"m-2\"}}");+ try engine.handleLine(&d, a, &out.writer, "{\"jsonrpc\":\"2.0\",\"id\":6,\"method\":\"session/prompt\",\"params\":{\"sessionId\":\"s2\",\"prompt\":\"x\",\"_meta\":{\"graff/messageId\":\"m-1\"}}}");+ try std.testing.expectEqual(@as(u32, 3), Counter.turns);+}diff --git a/src/schema_serve.zig b/src/schema_serve.zigindex 83f82daf..16e1d317 100644--- a/src/schema_serve.zig+++ b/src/schema_serve.zig@@ -11,7 +11,7 @@ pub const json =\\ {"method": "GET", "path": "/healthz", "description": "liveness + version, no auth"},\\ {"method": "GET", "path": "/v1/schema", "description": "this schema document"},\\ {"method": "POST", "path": "/v1/sessions", "description": "create OR resume a session (a graff --json child); optional JSON body {\"session\",\"model\",\"subagentProvider\",\"subagentModel\",\"allowCrossProviderSubagents\",\"noSubagentTier\",\"yolo\",\"system_prompt\",\"append_system_prompt\",\"maxToolCalls\",\"maxModelCalls\",\"dedupeToolCalls\"} overrides serve-level defaults. \"session\" (aliases \"session_id\"/\"resume\") names a durable session: 1-64 chars of [A-Za-z0-9._-], not starting with . or -; omitted means a fresh 16-hex name. Responds {\"session_id\":\"<name>\",\"resumed\":<bool>,\"last_seq\":<N>} - resumed says a session file already existed, last_seq is where the persisted event tape ends (reconnect with ?from=last_seq+1)"},- \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / review / set_system_prompt / set_model / compact / set_mode / set_agent / set_effort / set_fast / set_ultracode / score / answer / cancel). user/review may include images: [{\"type\":\"image_url\",\"url\":\"https://...\"}|{\"type\":\"image_base64\",\"media_type\":\"image/png\",\"data\":\"...\"}] (max 16), preserved as native provider vision parts; ordinary requests stream application/x-ndjson events until their terminal event (turn/error, or the request-specific ack); answer and cancel return a JSON ack while the original user stream continues; one ordinary request in flight per session at a time. ?from=N or {\"resume_from\":N} replays persisted events with seq >= N before the live stream. {\"type\":\"reattach\"} sends nothing to the child and only replays+follows, so it is safe while another connection is mid-turn"},+ \\ {"method": "POST", "path": "/v1/sessions/{id}", "description": "body is ONE stdio-protocol request object (user / review / set_system_prompt / set_model / compact / set_mode / set_agent / set_effort / set_fast / set_ultracode / score / answer / cancel). user/review may include images: [{\"type\":\"image_url\",\"url\":\"https://...\"}|{\"type\":\"image_base64\",\"media_type\":\"image/png\",\"data\":\"...\"}] (max 16), preserved as native provider vision parts; ordinary requests stream application/x-ndjson events until their terminal event (turn/error, or the request-specific ack); answer and cancel return a JSON ack while the original user stream continues; one ordinary request in flight per session at a time. A request may carry {\"message_id\":\"...\"}: resending a finished request with the same id replays that request's events from the tape instead of running another turn. ?from=N or {\"resume_from\":N} replays persisted events with seq >= N before the live stream. {\"type\":\"reattach\"} sends nothing to the child and only replays+follows, so it is safe while another connection is mid-turn"},\\ {"method": "GET", "path": "/v1/sessions/{id}/events?from=N", "description": "reconnect: replay persisted events with seq >= N (default 1), then keep following the log live while a request is in flight, ending at that request's terminal event. Takes no protocol lock and never writes to the child, and works for a session this process never spawned as long as its event log is in the workspace"},\\ {"method": "DELETE", "path": "/v1/sessions/{id}", "description": "graceful close: waits for any in-flight request, then EOFs the child's stdin. The session file and the event log stay on disk, so the id remains resumable"}\\ ]diff --git a/src/serve.zig b/src/serve.zigindex 4a1ac6cb..1726c4ff 100644--- a/src/serve.zig+++ b/src/serve.zig@@ -71,6 +71,7 @@ pub const ServeSession = struct {awaiting_answer: bool = false,answer_call_id: [128]u8 = undefined,answer_call_id_len: usize = 0,+ resent: @import("resend.zig").Ledger = .{}, // #1285: client message ids this session ran (under busy)};pub const ServeState = struct {@@ -296,11 +297,21 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, transport: *Io.W// `dead` rather than dropping inline: serveDrop FREES the session, and the// busy/in_flight defers below would then run through a dangling pointer.var dead = false;+ const resend_key: ?u64 = if (@import("resend.zig").bodyId(parsed.object)) |mid| @import("resend.zig").Ledger.keyOf("", mid) else null;{s.busy.lockUncancelable(io); // serialize requests per sessiondefer s.busy.unlock(io);+ // #1285: a resend of a request this session already ran gets that+ // request's events again from the tape, not a second turn.+ if (resend_key) |key| if (s.resent.finished(key)) |prior| {+ const tape = Io.Dir.cwd().readFileAlloc(io, s.log_path, arena, .limited(events.max_log_bytes)) catch "";+ var again: Io.Writer.Allocating = .init(arena);+ _ = @import("resend.zig").replayRange(&again.writer, tape, prior.first_seq, prior.last_seq) catch {};+ return req.respond(again.written(), .{ .extra_headers = serveNdjsonHeaders(st) });+ };s.in_flight.store(true, .release);defer s.in_flight.store(false, .release);+ if (resend_key) |key| s.resent.begin(key, s.last_seq + 1);writeChildLine(io, s, line) catch return respondJson(st, req, .bad_gateway, "{\"error\":\"session process is gone\"}");@@ -362,6 +373,7 @@ fn serveMessage(st: *ServeState, req: *std.http.Server.Request, transport: *Io.W}if (events.terminalEvent(trimmed)) {serveClearAnswerState(io, s);+ if (resend_key) |key| s.resent.finish(key, s.last_seq, "");break;}}