Skip to content

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

Python

HTTPS SSE over HTTP/2 with 1.1 fallback.

justrach26ee8e701403
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 49ee8a22..ea55813d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ current is part of cutting a release.
- Task workspace housekeeping: `graff worktree update` merges the remote base; `gc` drops dead session trees and clean trees whose GitHub PR is MERGED (dirty trees stay). Desktop: Update from main, Clear unused trees. Asking to free space unfolds `workspace` so `action=gc` is callable this turn.
- xAI Responses WS chains `previous_response_id` on the held socket (store:false in-memory cache) and `generate:false` prewarms a fresh socket. A stalled first handshake or 426 latches HTTPS SSE for the session; chrome shows a dim `using HTTPS SSE` notice. `GRAFF_XAI_WS_CHAIN=0` opts out.
+- HTTPS SSE prefers HTTP/2 (`justrach/http-zig`): connection reuse, ALPN `h2`, first-failure HTTP/1.1 latch. `GRAFF_HTTP2=0` forces 1.1.
## v0.0.302.3
diff --git a/build.zig b/build.zig
index 8d4d141e..bb65a960 100644
--- a/build.zig
+++ b/build.zig
@@ -56,6 +56,9 @@ pub fn build(b: *std.Build) void {
const accord_dep = b.dependency("accord", .{ .target = target, .optimize = optimize });
const accord_mod = accord_dep.module("accord");
exe.root_module.addImport("accord", accord_mod);
+ const http_zig_dep = b.dependency("http_zig", .{ .target = target, .optimize = optimize });
+ const http_zig_mod = http_zig_dep.module("http_zig");
+ exe.root_module.addImport("http_zig", http_zig_mod);
// Shared by the line-REPL picker and the TUI overlay so they cannot
// drift: a file import from both modules is illegal in Zig 0.17.
const models_rank_mod = b.createModule(.{
@@ -102,6 +105,7 @@ pub fn build(b: *std.Build) void {
});
unit_tests.root_module.addOptions("build_options", opts);
unit_tests.root_module.addImport("accord", accord_mod);
+ unit_tests.root_module.addImport("http_zig", http_zig_mod);
unit_tests.root_module.addImport("models_rank", models_rank_mod);
unit_tests.root_module.addImport("tui", tui_mod);
// spec/ fixtures live outside src/; importing them here makes @embedFile
diff --git a/build.zig.zon b/build.zig.zon
index 66c3b4c2..8792aba6 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -7,7 +7,11 @@
.url = "git+https://github.com/justrach/accord#c053e17295cb7ad8c0fb284d7d7748aad4aeeeea",
.hash = "accord-0.0.0-aQy1J3iBAgADDHWM0hIAXhISKtQ0zasFN7TyLhI_tkI8",
},
+ .http_zig = .{
+ .url = "git+https://github.com/justrach/http-zig#1d734eee07d3add6638b171adcc0da9f933d7902",
+ .hash = "http_zig-0.1.0-2CB7E-I9AgAXrxfMjTCoG9Q9RRwh3QhfEY4OXfhHWCiX",
+ },
},
- .paths = .{ "" },
+ .paths = .{""},
.fingerprint = 0x99ab87d62eef2520,
}
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index cfc105d5..92813fac 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -103,6 +103,8 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
self.md_table.clearRetainingCapacity();
self.partial_text.clearRetainingCapacity(); // fresh Esc-interrupt capture
+ if (try @import("agent_stream_h2.zig").postStream(self, body)) |full| return full;
+
// Esc-interrupt: while the root's request is on a TTY, stdin sits in raw
// non-blocking no-echo mode — from *before* the connect, so Esc pressed
// during a slow time-to-first-token wait neither echoes ^[ nor leaks into
diff --git a/src/agent_stream_h2.zig b/src/agent_stream_h2.zig
new file mode 100644
index 00000000..398c632a
--- /dev/null
+++ b/src/agent_stream_h2.zig
@@ -0,0 +1,161 @@
+//! HTTPS SSE over http-zig. Returns null to keep the std.http/1.1 path.
+
+const std = @import("std");
+const Io = std.Io;
+const Agent = @import("agent.zig").Agent;
+const main_mod = @import("main.zig");
+const http = @import("http.zig");
+const http_headers = @import("http_headers.zig");
+const http_stall = @import("http_stall.zig");
+const http2_pool = @import("http2_pool.zig");
+const engine_sink = @import("engine_sink.zig");
+const http_zig = @import("http_zig");
+const WatchdogFired = http.WatchdogFired;
+const watchdogError = http.watchdogError;
+const deadlineStallTask = @import("http.zig").deadlineStallTask;
+
+const ssePayload = Agent.ssePayload;
+const isStreamEnd = @import("agent_stream.zig").isStreamEnd;
+
+pub fn postStream(self: *Agent, body: []const u8) !?[]u8 {
+ if (!http2_pool.want(self.provider.url)) return null;
+ const origin = http2_pool.parseOrigin(self.provider.url) catch return null;
+ const gpa = self.gpa;
+ const provider = self.provider;
+ const bearer = switch (provider.auth) {
+ .x_api_key, .goog_api_key => "",
+ .bearer => try std.fmt.allocPrint(gpa, "Bearer {s}", .{provider.api_key}),
+ };
+ defer if (bearer.len > 0) gpa.free(bearer);
+ var headers_buf: [12]std.http.Header = undefined;
+ var conv_buf: [96]u8 = undefined;
+ const conv = http_headers.requestCacheKey(self.io, self.label, self, provider.id, &conv_buf);
+ const extra = http_headers.providerHeadersWithConv(self.io, provider, bearer, &headers_buf, conv);
+
+ var name_store: [16][64]u8 = undefined;
+ var extras: [20]http_zig.Header = undefined;
+ var n: usize = 0;
+ extras[n] = .{ .name = "content-type", .value = "application/json" };
+ n += 1;
+ if (std.mem.eql(u8, provider.id, "kimi")) {
+ extras[n] = .{ .name = "user-agent", .value = main_mod.kimi_user_agent };
+ n += 1;
+ }
+ for (extra, 0..) |h, i| {
+ if (i >= name_store.len or n >= extras.len) break;
+ extras[n] = .{ .name = std.ascii.lowerString(&name_store[i], h.name), .value = h.value };
+ n += 1;
+ }
+
+ const sess = http2_pool.sessionFor(gpa, self.io, origin.host, origin.port) catch return null;
+ var lines = sess.startLines(.{
+ .method = "POST",
+ .scheme = "https",
+ .authority = origin.host,
+ .path = origin.path,
+ .extra = extras[0..n],
+ .body = body,
+ }) catch return null;
+ defer lines.deinit();
+
+ const status = lines.waitStatus() catch return null;
+ if (status == 429) return error.RateLimited;
+ if (status >= 500) return error.ServerError;
+ if (status == 404 and std.mem.startsWith(u8, provider.id, "openai")) return error.OpenAiFlaky404;
+ if (status < 200 or status >= 300) return null;
+
+ const sink = engine_sink.forAgent(self);
+ var full: Io.Writer.Allocating = .init(gpa);
+ errdefer full.deinit();
+ var line: std.ArrayList(u8) = .empty;
+ defer line.deinit(gpa);
+ var loop_guard: @import("agent_model_loop.zig").Stream = .{};
+ var got_body = false;
+ var saw_done = false;
+
+ while (true) {
+ const stall_budget = http_stall.interFrameBudgetMs(http.stream_stall_ms, got_body, self.partial_text.items.len != 0, self.stall.widen);
+ read: {
+ const ReadDone = union(enum) { line: anyerror!bool, stall: WatchdogFired };
+ var rd_buf: [2]ReadDone = undefined;
+ var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
+ rsel.concurrent(.line, lineTask, .{ &lines, &line, gpa }) catch {
+ if (saw_done) break;
+ self.stall.tripped_ms = stall_budget;
+ sink.emit(self.io, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = false } });
+ return error.StreamStalled;
+ };
+ rsel.concurrent(.stall, deadlineStallTask, .{ self.io, false, stall_budget }) catch {
+ const r = rsel.await() catch |e| {
+ rsel.cancelDiscard();
+ return e;
+ };
+ rsel.cancelDiscard();
+ const more = r.line catch |e| {
+ if (saw_done) break;
+ if (got_body) {
+ sink.emit(self.io, .{ .stream_aborted = .dropped });
+ return error.StreamDropped;
+ }
+ return e;
+ };
+ if (!more) break;
+ break :read;
+ };
+ const first = rsel.await() catch |e| {
+ rsel.cancelDiscard();
+ return e;
+ };
+ rsel.cancelDiscard();
+ switch (first) {
+ .line => |r| {
+ const more = r catch |e| {
+ if (saw_done) break;
+ if (got_body) {
+ sink.emit(self.io, .{ .stream_aborted = .dropped });
+ return error.StreamDropped;
+ }
+ return e;
+ };
+ if (!more) break;
+ },
+ .stall => |w| {
+ if (w == .deadline) self.stall.tripped_ms = stall_budget;
+ if (w == .deadline) sink.emit(self.io, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = false } }) else sink.emit(self.io, .{ .stream_aborted = .interrupted });
+ return watchdogError(w, error.StreamStalled);
+ },
+ }
+ }
+ if (ssePayload(line.items)) |payload|
+ try loop_guard.event(self, payload, true);
+ try full.writer.writeAll(line.items);
+ try full.writer.writeByte('\n');
+ got_body = true;
+ self.printDelta(line.items);
+ if (main_mod.g_thinking_fold_request) {
+ main_mod.g_thinking_fold_request = false;
+ sink.emit(self.io, .thinking_fold_toggle);
+ }
+ if (self.provider.kind == .openai and openaiComplete(line.items)) saw_done = true;
+ if (isStreamEnd(self.scratchAlloc(), self.provider.kind, line.items)) {
+ saw_done = true;
+ break;
+ }
+ if (self.sub and Agent.esc_cancel.load(.acquire)) {
+ sink.emit(self.io, .{ .stream_aborted = .interrupted });
+ return error.Interrupted;
+ }
+ }
+ sink.emit(self.io, .{ .stream_complete = .{ .streamed_text = self.streamed_text } });
+ return try full.toOwnedSlice();
+}
+
+fn lineTask(ls: *http_zig.conn.LineStream, dest: *std.ArrayList(u8), gpa: std.mem.Allocator) !bool {
+ _ = gpa;
+ return ls.readLine(dest);
+}
+
+fn openaiComplete(raw_line: []const u8) bool {
+ const payload = ssePayload(raw_line) orelse return false;
+ return std.mem.indexOf(u8, payload, "\"finish_reason\":\"") != null;
+}
diff --git a/src/http2_pool.zig b/src/http2_pool.zig
new file mode 100644
index 00000000..09b146d5
--- /dev/null
+++ b/src/http2_pool.zig
@@ -0,0 +1,60 @@
+//! Process-wide HTTP/2 session for HTTPS SSE (http-zig). GRAFF_HTTP2=0|off
+//! latches HTTP/1.1. One session per origin; peer close redials inside Session.
+
+const std = @import("std");
+const Io = std.Io;
+const http_zig = @import("http_zig");
+const main_mod = @import("main.zig");
+
+var mu: Io.Mutex = .init;
+var session: ?*http_zig.Session = null;
+var host_buf: [256]u8 = undefined;
+var host_len: usize = 0;
+var port: u16 = 0;
+
+pub fn enabled() bool {
+ return main_mod.g_http2;
+}
+
+pub fn want(url: []const u8) bool {
+ return enabled() and std.mem.startsWith(u8, url, "https://");
+}
+
+pub const Origin = struct {
+ host: []const u8,
+ port: u16,
+ path: []const u8,
+};
+
+pub fn parseOrigin(url: []const u8) !Origin {
+ const u = try http_zig.https.parseHttpsUrl(url);
+ return .{ .host = u.host, .port = u.port, .path = u.path };
+}
+
+pub fn sessionFor(gpa: std.mem.Allocator, io: Io, host: []const u8, p: u16) !*http_zig.Session {
+ mu.lockUncancelable(io);
+ defer mu.unlock(io);
+ if (session) |s| {
+ if (p == port and host_len == host.len and std.mem.eql(u8, host_buf[0..host_len], host))
+ return s;
+ s.close();
+ session = null;
+ }
+ if (host.len > host_buf.len) return error.NameTooLong;
+ @memcpy(host_buf[0..host.len], host);
+ host_len = host.len;
+ port = p;
+ const s = try http_zig.Session.open(gpa, io, host, p);
+ session = s;
+ return s;
+}
+
+test "want is https-only" {
+ const saved = main_mod.g_http2;
+ defer main_mod.g_http2 = saved;
+ main_mod.g_http2 = true;
+ try std.testing.expect(want("https://api.x.ai/v1/responses"));
+ try std.testing.expect(!want("http://127.0.0.1/"));
+ main_mod.g_http2 = false;
+ try std.testing.expect(!want("https://api.x.ai/v1/responses"));
+}
diff --git a/src/main.zig b/src/main.zig
index bde415d3..27ad956f 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -31,6 +31,7 @@ pub var show_timing = false;
pub var show_cost = false;
pub var json_mode = false; // --json: structured JSONL events on stdout instead of human text
pub var g_codex_ws = true; // root Codex turns use the WebSocket transport (Responses API over wss) with SSE fallback; GRAFF_CODEX_WS=off|0 forces SSE
+pub var g_http2 = true; // HTTPS SSE prefers http-zig HTTP/2; GRAFF_HTTP2=off|0 forces HTTP/1.1
pub var g_clock_sleep: bool = false; // #225: root-only clock_sleep meta tool, off by default; --clock-sleep / GRAFF_CLOCK_SLEEP=1 turns it on (gates advertising in renderRootTools, mirrors g_codex_ws)
pub var g_force_stall_once: bool = false; // #134 test seam (GRAFF_FORCE_STALL_ONCE=1): the next live turn returns error.StreamStalled — proves the stall path is never labeled a user Esc
pub var g_force_drop_once: bool = false; // #132/#133 test seam (GRAFF_FORCE_DROP_ONCE=1): the next live turn returns error.StreamDropped
@@ -581,6 +582,8 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("agent_ws_steer.zig");
_ = @import("agent_ws_signal.zig");
_ = @import("agent_ws_prewarm.zig");
+ _ = @import("http2_pool.zig");
+ _ = @import("agent_stream_h2.zig");
_ = @import("tui_acp_updates.zig");
_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root
_ = @import("task_outcome.zig"); // goal-outcome telemetry events
diff --git a/src/session_settings.zig b/src/session_settings.zig
index 4dcce00e..c94b14f1 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -108,6 +108,9 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
if (environ_map.get("GRAFF_CODEX_WS")) |v| {
main_mod.g_codex_ws = !(std.ascii.eqlIgnoreCase(v, "off") or std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
}
+ if (environ_map.get("GRAFF_HTTP2")) |v| {
+ main_mod.g_http2 = !(std.ascii.eqlIgnoreCase(v, "off") or std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "no"));
+ }
// #225 GRAFF_CLOCK_SLEEP (root-only clock_sleep meta tool) and #330
// GRAFF_NO_LOCAL_TOOLS (the hard local-execution gate): both are
// affirmative-only (1|true|on|yes), like GRAFF_WS_FORCE_FAIL_ONCE below,