Skip to content

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

Python

fix(tui): recover poisoned TLS client generations

yxlyxc7a54267b32e
diff --git a/docs/adr/0042-model-http-client-recovery-uses-generations.md b/docs/adr/0042-model-http-client-recovery-uses-generations.md
new file mode 100644
index 00000000..08d19ae2
--- /dev/null
+++ b/docs/adr/0042-model-http-client-recovery-uses-generations.md
@@ -0,0 +1,35 @@
+# 0042. Model HTTP client recovery uses leased generations
+
+Status: accepted 2026-08-31
+
+## Context
+
+Issue #691 captured launch-scoped `TlsInitializationFailed` storms: once
+`std.http.Client.request` failed during TLS construction, six retries and every
+later TUI turn reused the same client and failed until process restart. The
+existing #177 connection poison cannot help because no `Request` exists yet.
+The launch client is also shared with concurrent root, compaction, title,
+recap, and subagent traffic, so deinitializing it in place would race users.
+
+## Decision
+
+Model HTTP constructors lease an active launch-level client generation. A
+request-construction `TlsInitializationFailed` retires that generation and
+publishes a prewarmed replacement under one mutex. Existing requests keep the
+retired generation alive through reference-counted leases; later retries and
+turns resolve the original launch pointer to the replacement. Owned retired
+generations are deinitialized only after their final lease releases.
+
+The original launch client is never reclaimed by the generation manager:
+unrelated launch consumers still holding its pointer remain safe until normal
+shutdown. All managed constructors wait for initial CA prewarm readiness, and
+CA-prewarm plus request-construction failures leave distinct trace evidence.
+Post-construction send/read failures retain #177's per-connection poison.
+
+## Consequences
+
+A recovered network can serve later root, synthetic, compaction, and child
+model trajectories without replacing the process or durable session. Recovery
+adds one mutex operation per model HTTP request and temporarily retains an old
+client while requests from that generation are still in flight. WebSocket
+transport remains independently managed; this record governs HTTP model calls.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index e76f1c51..c2943a4e 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -52,6 +52,7 @@ record only when you need the evidence or the edge cases.
| [0039](0039-local-tools-are-project-scripts.md) | Agent-authored local tools are project scripts under `.graff/tools/`; skills stay instructions. Runtime catalog extras, not `schema.effectiveRootSpecs`. |
| [0040](0040-codedb-stays-when-licensed.md) | Ordinary reads use native `codedb` / `read_file`; codedb-pro is extra search, not the default reader. |
| [0041](0041-tui-is-an-acp-client.md) | The fullscreen TUI is an in-process ACP client: session/prompt in, session/update thought/tool/text out. No child `graff acp`. |
+| [0042](0042-model-http-client-recovery-uses-generations.md) | Model HTTP calls lease a recoverable client generation; request-construction TLS failure rotates safely without deinitializing in-flight users. |
## When to write one
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 3cbf5ae0..8539cf90 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -113,9 +113,9 @@ pub const landing_note =
"results beat dying mid-tool-call.";
pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
- // Startup paints the prompt while CA loading continues. The root turn and
- // title task rendezvous here, then issue their requests concurrently.
+ // Root and title requests rendezvous after launch-time CA loading.
http.waitForClientReady(self.io);
+ if (http.takeCaWarmFailure()) if (self.tracer) |tr| tr.note("ca_prewarm_failed", "CA bundle rescan failed; request will use lazy TLS initialization");
if (self.registry) |reg| {
if (@import("mcp_boot.zig").joinBeforeRequest(reg)) {
self.invalidateRootTools();
@@ -346,6 +346,10 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, 0, body.len, 0, 0, 0, true);
return error.ApiError;
}
+ if (err == error.TlsRequestConstructionFailed or err == error.TlsRequestConstructionCaWarmFailed) if (self.tracer) |tr| tr.note(
+ "tls_request_construction",
+ if (err == error.TlsRequestConstructionCaWarmFailed) "rotated shared HTTP client generation; replacement CA prewarm failed" else "rotated shared HTTP client generation",
+ );
if (attempt < max_attempts) {
if (throttled) {
// #retry-after: prefer the provider's Retry-After
@@ -362,11 +366,8 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
if (self.tracer) |tr| tr.note("retry", what);
self.sleepInterruptible(delay_ms) catch return error.Interrupted;
} else {
- // Transport flake (HttpConnectionClosing, a reset,
- // a truncated TLS read): back off before a fresh
- // connection. Rapid-fire retries against a
- // just-closed keep-alive almost always re-fail
- // (#86). 250ms·2ⁿ, capped at 4s over 6 tries; Esc cancels.
+ // Transport flakes back off; rapid retries against a
+ // just-closed keep-alive re-fail (#86). Cap: 4s/6 tries.
const delay_ms = RetryPlan.delayMs(throttled, attempt);
@import("turn_chrome.zig").emitRetryNotice(self.io, @errorName(err), attempt + 1, max_attempts);
if (showRecoveredTransportRetry(self.call_kind))
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 7335450c..03533704 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -24,6 +24,7 @@ const reasoningDelta = @import("title.zig").reasoningDelta;
const stream_tests = @import("agent_stream_tests.zig");
const http = @import("http.zig");
+const http_client = @import("http_client.zig");
const http_headers = @import("http_headers.zig");
const providerUserAgent = http.providerUserAgent;
const capture5xxBodyStream = http.capture5xxBodyStream;
@@ -52,6 +53,11 @@ pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
/// keep-alive cannot poison the WS→SSE handoff and every fallback retry dials
/// from a clean pool.
pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []const u8) ![]u8 {
+ http_client.waitForReady(client.io);
+ var lease = http_client.acquire(client);
+ defer lease.release();
+ if (http_client.injectedConstructionTls(&lease)) |err| return err;
+ const transport = lease.client;
const sink = engine_sink.forAgent(self);
sink.emit(self.io, .stream_begin);
// Every exit path — success, interrupt, transport error — tears down the
@@ -109,14 +115,17 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
_ = drainSteerStdin(true);
restoreStdin(o);
};
- var req = try client.request(.POST, try std.Uri.parse(provider.url), .{
+ var req = transport.request(.POST, try std.Uri.parse(provider.url), .{
.redirect_behavior = .unhandled,
.headers = .{
.content_type = .{ .override = "application/json" },
.user_agent = providerUserAgent(provider),
},
.extra_headers = extra,
- });
+ }) catch |err| {
+ if (err == error.TlsInitializationFailed) return http_client.constructionTlsError(transport);
+ return err;
+ };
defer req.deinit();
// A failed SEND leaves reader.state == .ready, which Request.deinit
// reads as "connection still clean" and returns it to the keep-alive
diff --git a/src/http.zig b/src/http.zig
index 2aa9ac13..9794d27d 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -16,15 +16,9 @@ const Provider = provider_mod.Provider;
const Agent = agent_mod.Agent;
const headers = @import("http_headers.zig");
const stall = @import("http_stall.zig"); // #56: the watchdogs' pure budget arithmetic
-
-/// Launch-scoped gate installed while the shared client's CA bundle warms in
-/// the background. Null in unit tests and standalone pre-client subcommands.
-pub var g_client_ready: ?*Io.Event = null;
-
-pub fn waitForClientReady(io: Io) void {
- if (g_client_ready) |ready| ready.waitUncancelable(io);
-}
-
+const http_client = @import("http_client.zig");
+pub const waitForClientReady = http_client.waitForReady;
+pub const takeCaWarmFailure = http_client.takeCaWarmFailure;
pub const providerUserAgent = headers.userAgent;
pub const providerHeaders = headers.providerHeaders;
/// Test/call-site seam: the !live request path's POST, with an explicit conv id.
@@ -113,15 +107,15 @@ test "retryAfterMs: seconds, ms preferred, cap, HTTP-date/none -> 0 (#retry-afte
/// POST the request body; returns the raw response body (caller frees).
/// Built on client.request, NOT client.fetch: fetch never exposes the
-/// Request, so a failed body send could not be poisoned — std re-pooled the
-/// dead connection (a failed SEND leaves reader.state == .ready, which
-/// Request.deinit reads as "still clean") and findConnection handed the same
-/// corpse to every retry and every later same-host request, so one
-/// WriteFailed became a whole-session storm across compaction, [title], and
-/// subagents (#177). Mirrors postStream's errdefer poison (agent_stream.zig).
-/// The client and its connection pool stay shared across pool threads —
-/// client.request is what fetch wraps and is equally thread-safe.
+/// Request, so a failed body send could not be poisoned and std re-pooled the
+/// dead connection across later retries, compaction, titles, and subagents
+/// (#177). Mirrors postStream's errdefer poison (agent_stream.zig).
fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []const u8, conv_id: ?[]const u8) ![]u8 {
+ http_client.waitForReady(client.io);
+ var lease = http_client.acquire(client);
+ defer lease.release();
+ if (http_client.injectedConstructionTls(&lease)) |err| return err;
+ const transport = lease.client;
var aw: Io.Writer.Allocating = .init(gpa);
errdefer aw.deinit();
@@ -132,16 +126,19 @@ fn post(gpa: Allocator, client: *std.http.Client, provider: Provider, body: []co
defer if (bearer.len > 0) gpa.free(bearer);
var headers_buf: [12]std.http.Header = undefined;
- const extra = headers.providerHeadersWithConv(client.io, provider, bearer, &headers_buf, conv_id);
+ const extra = headers.providerHeadersWithConv(transport.io, provider, bearer, &headers_buf, conv_id);
- var req = try client.request(.POST, try std.Uri.parse(provider.url), .{
+ var req = transport.request(.POST, try std.Uri.parse(provider.url), .{
.redirect_behavior = .unhandled,
.headers = .{
.content_type = .{ .override = "application/json" },
.user_agent = providerUserAgent(provider),
},
.extra_headers = extra,
- });
+ }) catch |err| {
+ if (err == error.TlsInitializationFailed) return http_client.constructionTlsError(transport);
+ return err;
+ };
defer req.deinit();
// The #177 poison: on ANY error make deinit discard this connection
// instead of returning it to the keep-alive pool, so the retry (and
diff --git a/src/http_client.zig b/src/http_client.zig
new file mode 100644
index 00000000..016d7a38
--- /dev/null
+++ b/src/http_client.zig
@@ -0,0 +1,275 @@
+//! Launch-level HTTP client generations for model traffic.
+//!
+//! A `TlsInitializationFailed` raised by `Client.request` occurs before a
+//! Request exists, so the connection-poison cleanup in http.zig cannot touch
+//! it. Model calls lease the active generation through this module. On that
+//! construction error, one caller rotates the generation; in-flight callers
+//! keep their old lease, and owned retired clients are reclaimed only after
+//! their final lease is released.
+
+const std = @import("std");
+const builtin = @import("builtin");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const warm = @import("http_warm.zig");
+
+const Generation = struct {
+ client: *std.http.Client,
+ id: u64,
+ refs: usize = 0,
+ retired: bool = false,
+ owned: bool,
+ next: ?*Generation = null,
+};
+
+pub const RecoveryOutcome = enum {
+ unavailable,
+ rotated,
+ rotated_ca_warm_failed,
+ already_rotated,
+};
+
+pub const Recovery = struct {
+ gpa: Allocator,
+ io: Io,
+ mutex: Io.Mutex = .init,
+ original: Generation,
+ active: *Generation,
+ retired: ?*Generation = null,
+ next_id: u64 = 1,
+ warm_replacements: bool,
+
+ pub fn init(self: *Recovery, gpa: Allocator, io: Io, original: *std.http.Client, warm_replacements: bool) void {
+ self.* = .{
+ .gpa = gpa,
+ .io = io,
+ .original = .{ .client = original, .id = 0, .owned = false },
+ .active = undefined,
+ .warm_replacements = warm_replacements,
+ };
+ self.active = &self.original;
+ }
+
+ pub fn deinit(self: *Recovery) void {
+ std.debug.assert(self.active.refs == 0);
+ if (self.active.owned) self.destroyOwned(self.active);
+ var cursor = self.retired;
+ while (cursor) |generation| {
+ const next = generation.next;
+ std.debug.assert(generation.refs == 0);
+ if (generation.owned) self.destroyOwned(generation);
+ cursor = next;
+ }
+ self.retired = null;
+ }
+
+ pub fn acquire(self: *Recovery, requested: *std.http.Client) Lease {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (requested != self.original.client and requested != self.active.client)
+ return .{ .client = requested };
+ self.active.refs += 1;
+ return .{ .client = self.active.client, .owner = self, .generation = self.active, .generation_id = self.active.id };
+ }
+
+ /// Retire the generation that failed while constructing a request. If a
+ /// concurrent caller already rotated it, this is a successful no-op: the
+ /// next retry will acquire that newer generation.
+ pub fn recoverConstructionTls(self: *Recovery, failed: *std.http.Client) RecoveryOutcome {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ if (failed != self.active.client)
+ return if (failed == self.original.client or self.isRetired(failed)) .already_rotated else .unavailable;
+
+ const client = self.gpa.create(std.http.Client) catch return .unavailable;
+ client.* = .{ .allocator = self.gpa, .io = self.io };
+ var ca_warm_failed = false;
+ if (self.warm_replacements) warm.prewarmCaBundle(client, self.gpa, self.io) catch {
+ ca_warm_failed = true;
+ };
+ const generation = self.gpa.create(Generation) catch {
+ client.deinit();
+ self.gpa.destroy(client);
+ return .unavailable;
+ };
+ generation.* = .{ .client = client, .id = self.next_id, .owned = true };
+ self.next_id += 1;
+
+ const old = self.active;
+ old.retired = true;
+ old.next = self.retired;
+ self.retired = old;
+ self.active = generation;
+ if (old.refs == 0) self.reclaim(old);
+ return if (ca_warm_failed) .rotated_ca_warm_failed else .rotated;
+ }
+
+ fn release(self: *Recovery, generation: *Generation) void {
+ self.mutex.lockUncancelable(self.io);
+ defer self.mutex.unlock(self.io);
+ std.debug.assert(generation.refs > 0);
+ generation.refs -= 1;
+ if (generation.retired and generation.refs == 0) self.reclaim(generation);
+ }
+
+ fn isRetired(self: *Recovery, client: *std.http.Client) bool {
+ var cursor = self.retired;
+ while (cursor) |generation| : (cursor = generation.next) {
+ if (generation.client == client) return true;
+ }
+ return false;
+ }
+
+ fn reclaim(self: *Recovery, target: *Generation) void {
+ var link = &self.retired;
+ while (link.*) |generation| {
+ if (generation == target) {
+ link.* = generation.next;
+ generation.next = null;
+ generation.retired = false;
+ if (generation.owned) self.destroyOwned(generation);
+ return;
+ }
+ link = &generation.next;
+ }
+ }
+
+ fn destroyOwned(self: *Recovery, generation: *Generation) void {
+ generation.client.deinit();
+ self.gpa.destroy(generation.client);
+ self.gpa.destroy(generation);
+ }
+};
+
+pub const Lease = struct {
+ client: *std.http.Client,
+ owner: ?*Recovery = null,
+ generation: ?*Generation = null,
+ generation_id: u64 = 0,
+
+ pub fn release(self: *Lease) void {
+ if (self.owner) |owner| owner.release(self.generation.?);
+ self.* = .{ .client = self.client };
+ }
+};
+
+var g_recovery: ?*Recovery = null;
+var g_client_ready: ?*Io.Event = null;
+var g_ca_warm_failed: std.atomic.Value(bool) = .init(false);
+const no_test_failure = std.math.maxInt(u64);
+var g_test_fail_generation: std.atomic.Value(u64) = .init(no_test_failure);
+
+pub fn acquire(requested: *std.http.Client) Lease {
+ if (g_recovery) |recovery| return recovery.acquire(requested);
+ return .{ .client = requested };
+}
+
+pub fn constructionTlsError(failed: *std.http.Client) anyerror {
+ const outcome = if (g_recovery) |recovery| recovery.recoverConstructionTls(failed) else .unavailable;
+ return switch (outcome) {
+ .unavailable => error.TlsInitializationFailed,
+ .rotated_ca_warm_failed => error.TlsRequestConstructionCaWarmFailed,
+ .rotated, .already_rotated => error.TlsRequestConstructionFailed,
+ };
+}
+
+pub fn injectConstructionTlsForTest(generation: u64) void {
+ if (builtin.is_test) g_test_fail_generation.store(generation, .release);
+}
+
+pub fn injectedConstructionTls(lease: *const Lease) ?anyerror {
+ if (!builtin.is_test) return null;
+ if (g_test_fail_generation.cmpxchgStrong(lease.generation_id, no_test_failure, .acq_rel, .acquire) == null)
+ return constructionTlsError(lease.client);
+ return null;
+}
+
+pub fn waitForReady(io: Io) void {
+ if (g_client_ready) |ready| ready.waitUncancelable(io);
+}
+
+pub fn takeCaWarmFailure() bool {
+ return g_ca_warm_failed.swap(false, .acq_rel);
+}
+
+pub const Runtime = struct {
+ gpa: Allocator,
+ io: Io,
+ client: std.http.Client,
+ ready: Io.Event,
+ warm_future: Io.Future(void),
+ recovery: Recovery,
+
+ pub fn init(self: *Runtime, gpa: Allocator, io: Io) void {
+ self.gpa = gpa;
+ self.io = io;
+ self.client = .{ .allocator = gpa, .io = io };
+ self.ready = .unset;
+ self.recovery.init(gpa, io, &self.client, true);
+ g_recovery = &self.recovery;
+ g_client_ready = &self.ready;
+ g_ca_warm_failed.store(false, .release);
+ self.warm_future = io.async(warm.prewarmCaBundleTask, .{ &self.client, gpa, io, &self.ready, &g_ca_warm_failed });
+ }
+
+ pub fn deinit(self: *Runtime, await_io: Io) void {
+ _ = self.warm_future.await(await_io);
+ g_client_ready = null;
+ g_recovery = null;
+ self.recovery.deinit();
+ self.client.deinit();
+ }
+};
+
+test "request-construction TLS recovery reaches later root and child trajectories" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var original: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer original.deinit();
+ var recovery: Recovery = undefined;
+ recovery.init(gpa, io, &original, false);
+ defer recovery.deinit();
+
+ var failed_root = recovery.acquire(&original);
+ try std.testing.expectEqual(@as(u64, 0), failed_root.generation_id);
+ try std.testing.expectEqual(RecoveryOutcome.rotated, recovery.recoverConstructionTls(failed_root.client));
+
+ var later_root = recovery.acquire(&original);
+ defer later_root.release();
+ var child = recovery.acquire(&original);
+ defer child.release();
+ try std.testing.expectEqual(@as(u64, 1), later_root.generation_id);
+ try std.testing.expectEqual(later_root.generation_id, child.generation_id);
+ try std.testing.expect(later_root.client == child.client);
+ try std.testing.expect(later_root.client != failed_root.client);
+ failed_root.release();
+}
+
+fn recoverTask(recovery: *Recovery, client: *std.http.Client) RecoveryOutcome {
+ return recovery.recoverConstructionTls(client);
+}
+
+test "concurrent stale TLS reports rotate a generation only once" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var original: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer original.deinit();
+ var recovery: Recovery = undefined;
+ recovery.init(gpa, io, &original, false);
+ defer recovery.deinit();
+
+ var first = recovery.acquire(&original);
+ var concurrent = recovery.acquire(&original);
+ var first_fut = io.async(recoverTask, .{ &recovery, first.client });
+ var second_fut = io.async(recoverTask, .{ &recovery, concurrent.client });
+ const first_result = first_fut.await(io);
+ const second_result = second_fut.await(io);
+ try std.testing.expect(first_result != .unavailable);
+ try std.testing.expect(second_result != .unavailable);
+ try std.testing.expect(first_result != second_result);
+ var after = recovery.acquire(&original);
+ defer after.release();
+ try std.testing.expectEqual(@as(u64, 1), after.generation_id);
+ first.release();
+ concurrent.release();
+}
diff --git a/src/http_client_integration_tests.zig b/src/http_client_integration_tests.zig
new file mode 100644
index 00000000..7b5f92a7
--- /dev/null
+++ b/src/http_client_integration_tests.zig
@@ -0,0 +1,67 @@
+//! End-to-end model-POST regression for request-construction TLS recovery.
+
+const std = @import("std");
+const Io = std.Io;
+const http = @import("http.zig");
+const http_client = @import("http_client.zig");
+const Provider = @import("provider.zig").Provider;
+
+fn serveOk(io: Io, server: *std.Io.net.Server) void {
+ for (0..2) |_| {
+ const conn = server.accept(io) catch return;
+ defer conn.close(io);
+ var read_buf: [4096]u8 = undefined;
+ var reader = std.Io.net.Stream.Reader.init(conn, io, &read_buf);
+ while (true) {
+ const line = (reader.interface.takeDelimiter('\n') catch return) orelse return;
+ if (line.len == 0 or (line.len == 1 and line[0] == '\r')) break;
+ }
+ _ = reader.interface.take(2) catch return;
+ var write_buf: [256]u8 = undefined;
+ var writer = std.Io.net.Stream.Writer.init(conn, io, &write_buf);
+ writer.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nok") catch return;
+ writer.interface.flush() catch return;
+ }
+}
+
+test "one TLS-broken generation recovers later ordinary and child model POSTs" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var runtime: http_client.Runtime = undefined;
+ runtime.init(gpa, io);
+ defer runtime.deinit(io);
+ http.waitForClientReady(io);
+
+ var address = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try std.Io.net.IpAddress.listen(&address, io, .{});
+ defer server.deinit(io);
+ var server_future = io.async(serveOk, .{ io, &server });
+ defer server_future.await(io);
+
+ const bound = server.socket.address;
+ var url_buf: [64]u8 = undefined;
+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/v1/test", .{bound.getPort()});
+ const provider: Provider = .{
+ .id = "test",
+ .kind = .openai,
+ .auth = .x_api_key,
+ .url = url,
+ .api_key = "test",
+ .model = "test",
+ .context = 0,
+ };
+
+ http_client.injectConstructionTlsForTest(0);
+ try std.testing.expectError(
+ error.TlsRequestConstructionFailed,
+ http.postWithConv(gpa, &runtime.client, provider, "{}", "tui-root-failed"),
+ );
+
+ const ordinary = try http.postWithConv(gpa, &runtime.client, provider, "{}", "tui-root-later");
+ defer gpa.free(ordinary);
+ try std.testing.expectEqualStrings("ok", ordinary);
+
+ const child = try http.postWithConv(gpa, &runtime.client, provider, "{}", "tui-child-later");
+ defer gpa.free(child);
+ try std.testing.expectEqualStrings("ok", child);
+}
diff --git a/src/http_warm.zig b/src/http_warm.zig
index ff5c88cf..d95d744b 100644
--- a/src/http_warm.zig
+++ b/src/http_warm.zig
@@ -5,15 +5,15 @@ const Io = std.Io;
/// Pre-load the shared HTTP client's CA bundle single-threaded so concurrent
/// agents never race Zig's lazy first-connect rescan.
-pub fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) void {
+pub fn prewarmCaBundle(client: *std.http.Client, gpa: std.mem.Allocator, io: Io) !void {
const now = Io.Clock.real.now(io);
- client.ca_bundle.rescan(gpa, io, now) catch return;
+ try client.ca_bundle.rescan(gpa, io, now);
client.now = now;
}
/// Warm off the launch critical path. Outbound users wait on
/// `http.g_client_ready`, so prompt painting can overlap the scan safely.
-pub fn prewarmCaBundleTask(client: *std.http.Client, gpa: std.mem.Allocator, io: Io, ready: *Io.Event) void {
+pub fn prewarmCaBundleTask(client: *std.http.Client, gpa: std.mem.Allocator, io: Io, ready: *Io.Event, failed: *std.atomic.Value(bool)) void {
defer ready.set(io);
- prewarmCaBundle(client, gpa, io);
+ prewarmCaBundle(client, gpa, io) catch failed.store(true, .release);
}
diff --git a/src/main.zig b/src/main.zig
index e6f5c174..48367233 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -4,9 +4,7 @@
const std = @import("std");
pub const panic = @import("tui").restore.Panic; // leave the alt screen BEFORE std prints a panic, or the restore sequence erases the trace (#535)
const Io = std.Io;
-const http_warm = @import("http_warm.zig");
-pub const prewarmCaBundle = http_warm.prewarmCaBundle;
-const prewarmCaBundleTask = http_warm.prewarmCaBundleTask;
+const http_client = @import("http_client.zig");
const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const mcp = @import("mcp.zig");
@@ -292,16 +290,11 @@ pub fn main(init: std.process.Init) !void {
const stale_saved_model = resolved_keys.stale_saved_model;
const preferred_provider = resolved_keys.preferred_provider;
const codex_account = resolved_keys.codex_account;
- var client: std.http.Client = .{ .allocator = gpa, .io = io };
- defer client.deinit();
- var client_ready: Io.Event = .unset;
- http.g_client_ready = &client_ready;
- var client_warm_fut = io.async(prewarmCaBundleTask, .{ &client, gpa, io, &client_ready });
+ var client_runtime: http_client.Runtime = undefined;
+ client_runtime.init(gpa, io);
+ defer client_runtime.deinit(startup_timing.shutdown_trace.at(io, "ca-warm-await"));
+ const client = &client_runtime.client;
boot.mark(io, "CA warm scheduled");
- defer {
- _ = client_warm_fut.await(startup_timing.shutdown_trace.at(io, "ca-warm-await"));
- http.g_client_ready = null;
- }
var stdin_buf: [64 * 1024]u8 = undefined;
var stdin_reader = Io.File.stdin().reader(io, &stdin_buf);
const in = &stdin_reader.interface;
@@ -309,7 +302,7 @@ pub fn main(init: std.process.Init) !void {
var stdout_writer = Io.File.stdout().writer(io, &stdout_buf);
const out = &stdout_writer.interface;
g_out = out;
- if (try session_start.runTitleCommand(io, gpa, arena, &client, default_provider, out, flags, &invocation_budget)) return;
+ if (try session_start.runTitleCommand(io, gpa, arena, client, default_provider, out, flags, &invocation_budget)) return;
// Generate identity before opening either JSONL. The score channel and both
// files share this run id; session_id is a separate runtime correlation id.
session_start.initScoreRunId(io);
@@ -359,7 +352,7 @@ pub fn main(init: std.process.Init) !void {
}
traj.node(.{ .kind = "session", .version = harness_version, .unix_ms = unixMs(io) });
- var telem = session_start.initTelemetry(io, gpa, &client, init.environ_map, flags, default_telemetry_endpoint);
+ var telem = session_start.initTelemetry(io, gpa, client, init.environ_map, flags, default_telemetry_endpoint);
telemetry.g_telem = &telem;
if (init.environ_map.get("GRAFF_FLEET")) |fv| {
g_fleet = !(std.ascii.eqlIgnoreCase(fv, "off") or std.mem.eql(u8, fv, "0") or std.ascii.eqlIgnoreCase(fv, "false") or std.ascii.eqlIgnoreCase(fv, "no"));
@@ -425,7 +418,7 @@ pub fn main(init: std.process.Init) !void {
// Root Agent construction + post-construction config (session name, persisted thinking/goal/eval settings, session-start trace note) + the
// backgrounded fleet-champion pull live in session_start.zig. `root`'s pointer fields (snapshots/client/tracer/approvals/registry) all reference
// already-stable main()-owned storage passed in by address, so returning the constructed Agent by value here is safe.
- var root = try session_run.buildRootAgent(gpa, arena, io, &client, default_provider, subagent_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, &snaps, flags, telem.endpoint);
+ var root = try session_run.buildRootAgent(gpa, arena, io, client, default_provider, subagent_provider, init.environ_map, out, in, registry, &approvals, &tracer, sys_normal, &snaps, flags, telem.endpoint);
root.run_budget = &invocation_budget;
root.model_catalog = resolved_keys.model_catalog;
root.stored_keys_loaded = resolved_keys.stored_keys_loaded;
@@ -439,7 +432,7 @@ pub fn main(init: std.process.Init) !void {
// JSONL and the privacy-projected upload are independent sinks; the Boot
// owns both, wired and torn down in LIFO order (behavior_trace.zig).
var behavior_buf: [8 * 1024]u8 = undefined;
- var behavior_boot = behavior_trace.boot(io, gpa, &client, init.environ_map, telem.endpoint, telem.auth_key, telem.install_id, telem.client_name, harness_version, &behavior_buf);
+ var behavior_boot = behavior_trace.boot(io, gpa, client, init.environ_map, telem.endpoint, telem.auth_key, telem.install_id, telem.client_name, harness_version, &behavior_buf);
behavior_boot.link(&tracer);
// A dead local sink must not be silent: the collision that disabled local
// capture in every session shipped invisibly because every failure path
@@ -484,7 +477,7 @@ pub fn main(init: std.process.Init) !void {
// `graff` is the default session. TTY `graff repl` / `graff tui` open the Grok-style pager.
// `graff acp` (acp.zig) is the same idea over Zed's stdio Agent Client Protocol. Both self-contained — each exits after.
- if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, in, out, arena, flags) or try @import("acp.zig").runAcpCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, in, out, arena, flags) or try @import("tui_launch.zig").maybeRun(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, arena, flags, json_mode, g_cwd_display)) return;
+ if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), client, in, out, arena, flags) or try @import("acp.zig").runAcpCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), client, in, out, arena, flags) or try @import("tui_launch.zig").maybeRun(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), client, arena, flags, json_mode, g_cwd_display)) return;
// One-shot print mode: run the single prompt to completion, print the final text to stdout, exit.
if (flags.oneshot_prompt) |prompt_text| {
try session_run.runOneshotPrompt(gpa, io, arena, &root, @import("bench_priors.zig").noteKeys(&keys), &tracer, out, prompt_text); // one-shot exits before loop_ctx below — capture keys for sub-first routing here too
@@ -584,6 +577,8 @@ test { // pull in tests from imported modules (mcp.zig)
_ = @import("mcp.zig");
_ = @import("mcp_rpc.zig");
_ = @import("main_test.zig");
+ _ = @import("http_client.zig");
+ _ = @import("http_client_integration_tests.zig");
// A module whose tests must run needs an explicit reference here (a plain @import elsewhere compiles to nothing); scripts/eval-tier1.sh --only reach catches one.
_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped
_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests