Skip to content

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

Python

feat(codex): WebSocket transport for the Responses API (gpt-5.5), SSE fallback

justrach0c625fdf7bde
diff --git a/src/agent.zig b/src/agent.zig
index efd48536..48378873 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -109,6 +109,7 @@ pub const Agent = struct {
/// what survives into history (with an "[interrupted]" marker appended).
partial_text: std.ArrayList(u8) = .empty,
stream_quiet: bool = false, // suppress live streaming (compaction summary)
+ ws_off: bool = false, // codex ws transport disabled for this session after a handshake/transport fallback to SSE (#codex-ws)
streamed_text: bool = false, // the last request printed its text live
thinking_open: bool = false, // a live "Thinking" reasoning block is currently streaming (/thinking)
thinking_rows: usize = 0, // on-screen rows the live Thinking block spans (#75 collapse)
@@ -328,6 +329,11 @@ pub const Agent = struct {
pub const toggleThinkingFold = @import("agent_stream.zig").toggleThinkingFold;
pub const postStream = @import("agent_stream.zig").postStream;
pub const printDelta = @import("agent_stream.zig").printDelta;
+ // Codex/gpt-5.5 Responses-over-WebSocket transport (+ its SSE-fallback
+ // wrapper postLive) lives in agent_ws.zig (#codex-ws). Member-aliased.
+ pub const postResponsesWs = @import("agent_ws.zig").postResponsesWs;
+ pub const postLive = @import("agent_ws.zig").postLive;
+ pub const wsEligible = @import("agent_ws.zig").wsEligible;
/// Esc-during-tools cancellation. postStream only watches stdin while an
/// HTTP stream is live, so a long tool join (bash, a subagent fan-out, a
/// whole workflow) used to be Esc-deaf — exactly when turns feel longest.
diff --git a/src/agent_request.zig b/src/agent_request.zig
index b780db42..d9bd2003 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -69,7 +69,7 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
var attempt: usize = 0;
while (true) : (attempt += 1) {
const attempt_body = if (live)
- self.postStream(body)
+ self.postLive(body)
else
postWatched(self.gpa, self.io, self.client, self.provider, body);
if (attempt_body) |ok| break :blk ok else |err| {
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index c2e0a434..b7313527 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -432,7 +432,7 @@ fn readErrIsClose(e: anyerror) bool {
/// close (#134/#135). Precise: matches the `[DONE]` sentinel, a structural
/// `event:` terminator, or a `data:` payload whose PARSED top-level `type` is
/// terminal — never a substring inside a content delta (deltas escape quotes).
-fn isStreamEnd(arena: std.mem.Allocator, kind: anytype, raw_line: []const u8) bool {
+pub fn isStreamEnd(arena: std.mem.Allocator, kind: anytype, raw_line: []const u8) bool {
const line = std.mem.trim(u8, raw_line, " \t\r\n");
if (std.mem.eql(u8, line, "data: [DONE]") or std.mem.eql(u8, line, "data:[DONE]")) return true;
if (std.mem.startsWith(u8, line, "event:")) return switch (kind) {
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
new file mode 100644
index 00000000..2fd5b914
--- /dev/null
+++ b/src/agent_ws.zig
@@ -0,0 +1,184 @@
+//! Codex/gpt-5.5 Responses turn over WebSocket. OpenAI's codex prefers ws and
+//! falls back to SSE; graff mirrors that. The ws frames carry the SAME event
+//! `type`s as the Responses SSE stream (response.output_text.delta,
+//! response.completed, …), so each frame is wrapped as a `data: {json}` line
+//! and handed to the existing parseResponses/isStreamEnd — the reassembly and
+//! completion logic are shared with the SSE path.
+//!
+//! postLive() is the transport selector called by request(): codex root turns
+//! try ws (postResponsesWs); a handshake/transport failure disables ws for the
+//! session and falls back to postStream (SSE) — a genuine Esc/stall propagates.
+//!
+//! Observability (issue #134's ask): every ws lifecycle step is routed to the
+//! tracer ("ws" notes: connecting/connected/completed/stall/fallback/errors),
+//! which lands in harness.trace.jsonl so an agent can debug a ws turn after the
+//! fact; GRAFF_WS_DEBUG=1 additionally dumps the handshake + frames to stderr.
+
+const std = @import("std");
+const Io = std.Io;
+
+const main_mod = @import("main.zig");
+const agent_mod = @import("agent.zig");
+const Agent = agent_mod.Agent;
+
+const ws = @import("ws.zig");
+
+const term = @import("term.zig");
+const tty = term.tty;
+
+const http = @import("http.zig");
+const WatchdogFired = http.WatchdogFired;
+const streamStallTask = http.streamStallTask;
+const watchdogError = http.watchdogError;
+
+const isStreamEnd = @import("agent_stream.zig").isStreamEnd;
+
+const escPressed = Agent.escPressed;
+const rawNonblockStdin = Agent.rawNonblockStdin;
+const drainSteerStdin = Agent.drainSteerStdin;
+
+/// Codex ws applies to root Responses turns when enabled and not already fallen
+/// back this session. Subagents/quiet turns keep the non-streaming SSE path.
+pub fn wsEligible(self: *Agent) bool {
+ return main_mod.g_codex_ws and !self.ws_off and !self.sub and
+ self.provider.kind == .responses and self.out != null and !self.stream_quiet;
+}
+
+/// Transport selector: try ws for eligible codex turns, else SSE (postStream).
+/// A ws transport/handshake failure disables ws for the session and falls back
+/// to SSE; a deliberate Esc/stall propagates unchanged.
+pub fn postLive(self: *Agent, body: []const u8) ![]u8 {
+ if (!wsEligible(self)) return self.postStream(body);
+ return postResponsesWs(self, body) catch |e| {
+ if (e == error.Interrupted or e == error.StreamStalled) return e;
+ self.ws_off = true;
+ if (self.tracer) |tr| tr.note("ws", "transport error — falling back to SSE for this session");
+ return self.postStream(body);
+ };
+}
+
+fn wssUrl(arena: std.mem.Allocator, https_url: []const u8) ![]u8 {
+ if (std.mem.startsWith(u8, https_url, "https://"))
+ return std.fmt.allocPrint(arena, "wss://{s}", .{https_url["https://".len..]});
+ if (std.mem.startsWith(u8, https_url, "http://"))
+ return std.fmt.allocPrint(arena, "ws://{s}", .{https_url["http://".len..]});
+ return arena.dupe(u8, https_url);
+}
+
+fn wsReadTask(client: *ws.WsClient, gpa: std.mem.Allocator, out: *std.ArrayList(u8)) ws.Error!ws.Opcode {
+ return client.readMessage(gpa, out);
+}
+
+/// One Responses turn over ws. Returns the reassembled body as SSE-format
+/// `data:` lines (parseResponses consumes it unchanged). Connect/transport
+/// failures return the ws error so postLive can fall back to SSE.
+pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
+ const gpa = self.gpa;
+ const arena = self.arena;
+ const provider = self.provider;
+
+ // Wrap graff's Responses body ({"model":…}) with the ws envelope.
+ const frame = try std.fmt.allocPrint(gpa, "{{\"type\":\"response.create\",{s}", .{body[1..]});
+ defer gpa.free(frame);
+
+ const bearer = try std.fmt.allocPrint(arena, "Bearer {s}", .{provider.api_key});
+ var rnd: [16]u8 = undefined;
+ self.io.random(&rnd);
+ const hex = std.fmt.bytesToHex(rnd, .lower);
+ const sid = try std.fmt.allocPrint(arena, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] });
+ const headers = [_]ws.Header{
+ .{ .name = "Authorization", .value = bearer },
+ .{ .name = "chatgpt-account-id", .value = provider.account },
+ .{ .name = "OpenAI-Beta", .value = "responses_websockets=2026-02-06" },
+ .{ .name = "originator", .value = "codex_cli_rs" },
+ .{ .name = "session_id", .value = sid },
+ .{ .name = "User-Agent", .value = "codex_cli_rs/0.1 (graff)" },
+ };
+ const url = try wssUrl(arena, provider.url);
+
+ // Esc watching (root TTY), same gate as postStream.
+ const watch_esc = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;
+ const orig_tio: ?tty.RawState = if (watch_esc) rawNonblockStdin() else null;
+ defer if (orig_tio) |o| {
+ _ = drainSteerStdin(true);
+ tty.restore(o);
+ };
+
+ self.spinnerStart();
+ defer self.spinnerStop();
+
+ if (self.tracer) |tr| tr.note("ws", "connecting");
+ var client = ws.WsClient.connect(gpa, self.io, url, false, &headers) catch |e| {
+ if (self.tracer) |tr| tr.note("ws", @errorName(e));
+ return e;
+ };
+ defer client.deinit(gpa);
+ if (self.tracer) |tr| tr.note("ws", "connected");
+ try client.sendText(frame);
+
+ var full: Io.Writer.Allocating = .init(gpa);
+ errdefer full.deinit();
+ var fbuf: std.ArrayList(u8) = .empty;
+ defer fbuf.deinit(gpa);
+
+ stream: while (true) {
+ // Race the frame read against the shared idle-stall watchdog so a dead
+ // ws can't hang the turn — a deadline surfaces as error.StreamStalled
+ // (never a user Esc), handled identically to the SSE path (#134).
+ read: {
+ const ReadDone = union(enum) { msg: ws.Error!ws.Opcode, stall: WatchdogFired };
+ var rd_buf: [2]ReadDone = undefined;
+ var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
+ rsel.concurrent(.msg, wsReadTask, .{ client, gpa, &fbuf }) catch {
+ _ = client.readMessage(gpa, &fbuf) catch |e| return e; // no spare concurrency
+ break :read;
+ };
+ rsel.concurrent(.stall, streamStallTask, .{ self.io, orig_tio != null }) catch {
+ const r = rsel.await() catch |e| {
+ rsel.cancelDiscard();
+ return e;
+ };
+ rsel.cancelDiscard();
+ _ = r.msg catch |e| return e;
+ break :read;
+ };
+ const first = rsel.await() catch |e| {
+ rsel.cancelDiscard();
+ return e;
+ };
+ rsel.cancelDiscard();
+ switch (first) {
+ .msg => |m| _ = m catch |e| return e,
+ .stall => |w| {
+ if (w == .deadline and !main_mod.json_mode) if (self.out) |o| {
+ o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
+ o.flush() catch {};
+ };
+ if (self.tracer) |tr| tr.note("ws", if (w == .esc) "esc" else "stall");
+ return watchdogError(w, error.StreamStalled);
+ },
+ }
+ }
+ if (fbuf.items.len == 0) continue :stream;
+ // Wrap the ws frame as an SSE data: line so parseResponses/isStreamEnd
+ // (shared with the SSE path) handle reassembly + completion.
+ try full.writer.writeAll("data: ");
+ try full.writer.writeAll(fbuf.items);
+ try full.writer.writeByte('\n');
+ const line = try std.fmt.allocPrint(arena, "data: {s}", .{fbuf.items});
+ if (isStreamEnd(arena, self.provider.kind, line)) {
+ if (self.tracer) |tr| tr.note("ws", "completed");
+ break :stream;
+ }
+ if (orig_tio != null and escPressed(true)) return error.Interrupted;
+ }
+ return full.toOwnedSlice();
+}
+
+
+test "wssUrl: https->wss, http->ws" {
+ var a = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer a.deinit();
+ try std.testing.expectEqualStrings("wss://chatgpt.com/backend-api/codex/responses", try wssUrl(a.allocator(), "https://chatgpt.com/backend-api/codex/responses"));
+ try std.testing.expectEqualStrings("ws://localhost:1234/x", try wssUrl(a.allocator(), "http://localhost:1234/x"));
+}
diff --git a/src/main.zig b/src/main.zig
index 019ce45f..57992edd 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -44,6 +44,7 @@ pub var use_color = false; // stdout is a TTY and NO_COLOR unset → enables col
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; // codex/gpt-5.5 uses the WebSocket transport (Responses API over wss) with SSE fallback; GRAFF_CODEX_WS=off|0 forces SSE
pub var max_tool_calls: ?u64 = null; // --max-tool-calls: hard per-turn root tool budget
pub var dedupe_tool_calls = false; // --dedupe-tool-calls: reject duplicate root calls in a turn
pub var plan_mode = false; // /plan: read-only — mutating tools are denied, the model proposes
diff --git a/src/session_run.zig b/src/session_run.zig
index 9b7a6281..4eb116f0 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -29,6 +29,7 @@ const agent_mod = @import("agent.zig");
const approvals_mod = @import("approvals.zig");
const tools_mod = @import("tools.zig");
const http = @import("http.zig");
+const ws = @import("ws.zig");
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
@@ -340,6 +341,12 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
if (secs > 0) http.stream_stall_ms = @min(secs, 86_400) * 1000; // clamp: <=1 day, no u64 overflow
} else |_| {}
}
+ // #codex-ws: GRAFF_CODEX_WS=off|0|false|no forces the SSE transport for
+ // codex; GRAFF_WS_DEBUG=1 dumps the ws handshake + frames to stderr.
+ if (environ_map.get("GRAFF_CODEX_WS")) |v| {
+ main_mod.g_codex_ws = !(std.mem.eql(u8, v, "off") or std.mem.eql(u8, v, "0") or std.mem.eql(u8, v, "false") or std.mem.eql(u8, v, "no"));
+ }
+ ws.g_debug = environ_map.get("GRAFF_WS_DEBUG") != null;
skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connect
anim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choice
anim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme
diff --git a/src/ws.zig b/src/ws.zig
new file mode 100644
index 00000000..0bfffa78
--- /dev/null
+++ b/src/ws.zig
@@ -0,0 +1,317 @@
+//! Minimal WebSocket client (RFC 6455) for the codex/ChatGPT Responses API
+//! over WebSocket (`wss://chatgpt.com/backend-api/codex/responses`) — OpenAI's
+//! codex prefers ws and falls back to SSE, and a persistent ws connection also
+//! sidesteps the keep-alive `HttpConnectionClosing` retries the SSE path hits.
+//! Ported from the mobile-relay daemon's client (src/relay.zig on the
+//! mobile-relay branch), with two additions for this use: custom handshake
+//! headers (Authorization / OpenAI-Beta / chatgpt-account-id / …) and an
+//! upgrade-failure signal (error.UpgradeRequired) so the caller can fall back
+//! to SSE. Just what a request/response turn needs: text frames, client
+//! masking, ping/pong, close, fragmentation reassembly, one message in / one
+//! stream of events out.
+//!
+//! Observability: set `g_debug = true` (GRAFF_WS_DEBUG=1) to trace the
+//! handshake + every frame to stderr; the transport layer additionally routes
+//! structured ws lifecycle events to the tracer (harness.trace.jsonl) so an
+//! agent can debug a ws turn after the fact.
+
+const std = @import("std");
+const Io = std.Io;
+const net = std.Io.net;
+const HostName = net.HostName;
+const Allocator = std.mem.Allocator;
+const tls = std.crypto.tls;
+
+/// GRAFF_WS_DEBUG=1 → dump the handshake + frame headers to stderr.
+pub var g_debug: bool = false;
+
+fn dbg(comptime fmt: []const u8, args: anytype) void {
+ if (g_debug) std.debug.print("[ws] " ++ fmt ++ "\n", args);
+}
+
+pub const Header = struct { name: []const u8, value: []const u8 };
+
+pub const Opcode = enum(u4) {
+ cont = 0x0,
+ text = 0x1,
+ binary = 0x2,
+ close = 0x8,
+ ping = 0x9,
+ pong = 0xA,
+ _,
+};
+
+pub const Error = error{
+ BadUrl,
+ HandshakeFailed,
+ /// Server declined the upgrade (e.g. 426) — the caller should fall back to SSE.
+ UpgradeRequired,
+ PeerClosed,
+ MessageTooLong,
+ StreamTooLong,
+} || Allocator.Error || Io.Reader.Error || Io.Writer.Error;
+
+// Encrypted/raw socket buffers (TLS asserts these are >= tls min_buffer_len).
+const sock_buf_cap = 64 * 1024;
+// Plaintext TLS buffers.
+const tls_buf_cap = 64 * 1024;
+/// Hard cap on one reassembled inbound message (a single Responses event).
+const message_cap = 4 * 1024 * 1024;
+
+comptime {
+ if (sock_buf_cap < tls.max_ciphertext_record_len) @compileError("sock_buf_cap < tls min_buffer_len");
+}
+
+pub const WsClient = struct {
+ io: Io,
+ stream: net.Stream,
+ rd: net.Stream.Reader,
+ wr: net.Stream.Writer,
+ // Active plaintext interfaces: raw stream for ws://, TLS plaintext for wss://.
+ r: *Io.Reader = undefined,
+ w: *Io.Writer = undefined,
+ tls_client: ?tls.Client = null,
+ ca_bundle: std.crypto.Certificate.Bundle = .empty,
+ ca_lock: Io.RwLock = .init,
+ gpa: Allocator,
+ sock_rbuf: [sock_buf_cap]u8 = undefined,
+ sock_wbuf: [sock_buf_cap]u8 = undefined,
+ tls_rbuf: [tls_buf_cap]u8 = undefined,
+ tls_wbuf: [tls_buf_cap]u8 = undefined,
+
+ /// Connect + (for wss) TLS handshake + the HTTP Upgrade handshake, sending
+ /// `headers` as extra request headers. Heap-allocated and stable (the
+ /// Reader/Writer interfaces and the TLS client reference its inline buffers
+ /// and each other).
+ pub fn connect(gpa: Allocator, io: Io, url: []const u8, insecure: bool, headers: []const Header) Error!*WsClient {
+ const u = parseUrl(url) orelse return error.BadUrl;
+ dbg("connect {s} host={s} port={d} path={s} tls={}", .{ url, u.host, u.port, u.path, u.tls });
+
+ // DNS + connect. IpAddress.resolve only parses IP literals, so a
+ // hostname (chatgpt.com) needs HostName.connect, which looks it up.
+ const host_name = HostName.init(u.host) catch |e| {
+ dbg("bad host {s}: {s}", .{ u.host, @errorName(e) });
+ return error.BadUrl;
+ };
+ const stream = host_name.connect(io, u.port, .{ .mode = .stream }) catch |e| {
+ dbg("connect {s}:{d} failed: {s}", .{ u.host, u.port, @errorName(e) });
+ return error.HandshakeFailed;
+ };
+
+ const self = try gpa.create(WsClient);
+ errdefer gpa.destroy(self);
+ self.* = .{ .io = io, .stream = stream, .rd = undefined, .wr = undefined, .gpa = gpa };
+ self.rd = net.Stream.Reader.init(stream, io, &self.sock_rbuf);
+ self.wr = net.Stream.Writer.init(stream, io, &self.sock_wbuf);
+
+ if (u.tls) {
+ var entropy: [tls.Client.Options.entropy_len]u8 = undefined;
+ io.random(&entropy);
+ if (!insecure) self.ca_bundle.rescan(gpa, io, Io.Clock.real.now(io)) catch |e| {
+ dbg("ca rescan failed: {s}", .{@errorName(e)});
+ return error.HandshakeFailed;
+ };
+ self.tls_client = tls.Client.init(&self.rd.interface, &self.wr.interface, .{
+ .host = if (insecure) .no_verification else .{ .explicit = u.host },
+ .ca = if (insecure) .no_verification else .{ .bundle = .{
+ .gpa = gpa,
+ .io = io,
+ .lock = &self.ca_lock,
+ .bundle = &self.ca_bundle,
+ } },
+ .write_buffer = &self.tls_wbuf,
+ .read_buffer = &self.tls_rbuf,
+ .entropy = &entropy,
+ .realtime_now = Io.Clock.real.now(io),
+ }) catch |e| {
+ dbg("tls init failed: {s}", .{@errorName(e)});
+ return error.HandshakeFailed;
+ };
+ self.r = &self.tls_client.?.reader;
+ self.w = &self.tls_client.?.writer;
+ } else {
+ self.r = &self.rd.interface;
+ self.w = &self.wr.interface;
+ }
+
+ try self.handshake(u, headers);
+ return self;
+ }
+
+ pub fn deinit(self: *WsClient, gpa: Allocator) void {
+ self.sendFrame(.close, "") catch {};
+ self.ca_bundle.deinit(gpa);
+ self.stream.close(self.io);
+ gpa.destroy(self);
+ }
+
+ /// Send one text message.
+ pub fn sendText(self: *WsClient, payload: []const u8) Error!void {
+ dbg("send text {d}b", .{payload.len});
+ return self.sendFrame(.text, payload);
+ }
+
+ /// Read one complete (re-assembled) message into `out`. Control frames
+ /// (ping/pong/close) are handled internally; a peer close → error.PeerClosed.
+ /// Returns the message opcode (.text or .binary).
+ pub fn readMessage(self: *WsClient, gpa: Allocator, out: *std.ArrayList(u8)) Error!Opcode {
+ out.clearRetainingCapacity();
+ var msg_op: ?Opcode = null;
+ const r = self.r;
+ while (true) {
+ const h = try r.takeArray(2);
+ const fin = (h[0] & 0x80) != 0;
+ const op: Opcode = @enumFromInt(@as(u4, @truncate(h[0] & 0x0f)));
+ const masked = (h[1] & 0x80) != 0;
+ var len: u64 = @as(u64, h[1] & 0x7f);
+ if (len == 126) {
+ len = std.mem.readInt(u16, try r.takeArray(2), .big);
+ } else if (len == 127) {
+ len = std.mem.readInt(u64, try r.takeArray(8), .big);
+ }
+ var mask: [4]u8 = .{ 0, 0, 0, 0 };
+ if (masked) mask = (try r.takeArray(4)).*;
+
+ switch (op) {
+ .ping => {
+ const p = try r.take(@intCast(len));
+ if (masked) unmask(p, mask);
+ try self.sendFrame(.pong, p);
+ continue;
+ },
+ .pong => {
+ try r.discardAll(@intCast(len));
+ continue;
+ },
+ .close => {
+ try r.discardAll(@intCast(len));
+ self.sendFrame(.close, "") catch {};
+ return error.PeerClosed;
+ },
+ .text, .binary, .cont => {
+ if (out.items.len + len > message_cap) return error.MessageTooLong;
+ const start = out.items.len;
+ try out.resize(gpa, start + @as(usize, @intCast(len)));
+ try r.readSliceAll(out.items[start..]);
+ if (masked) unmask(out.items[start..], mask);
+ if (msg_op == null and op != .cont) msg_op = op;
+ if (fin) {
+ dbg("recv msg {d}b op={s}", .{ out.items.len, @tagName(msg_op orelse .text) });
+ return msg_op orelse .text;
+ }
+ },
+ else => return error.HandshakeFailed, // unknown opcode
+ }
+ }
+ }
+
+ // ── internals ────────────────────────────────────────────────────────────
+
+ fn handshake(self: *WsClient, u: Url, headers: []const Header) Error!void {
+ var key_raw: [16]u8 = undefined;
+ self.io.random(&key_raw);
+ var key_b64: [24]u8 = undefined;
+ _ = std.base64.standard.Encoder.encode(&key_b64, &key_raw);
+
+ try self.w.print(
+ "GET {s} HTTP/1.1\r\nHost: {s}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" ++
+ "Sec-WebSocket-Key: {s}\r\nSec-WebSocket-Version: 13\r\n",
+ .{ u.path, u.host, &key_b64 },
+ );
+ for (headers) |hd| try self.w.print("{s}: {s}\r\n", .{ hd.name, hd.value });
+ try self.w.writeAll("\r\n");
+ try self.flushTransport();
+
+ // status line: expect "HTTP/1.1 101 ..."; anything else is a rejection.
+ const status = try self.r.takeDelimiterInclusive('\n');
+ dbg("handshake <- {s}", .{std.mem.trimEnd(u8, status, "\r\n")});
+ if (std.mem.indexOf(u8, status, " 101 ") == null) {
+ // A 426 (or any non-101) means the server won't upgrade — fall back to SSE.
+ return if (std.mem.indexOf(u8, status, " 426 ") != null) error.UpgradeRequired else error.HandshakeFailed;
+ }
+ // drain headers until the blank line
+ while (true) {
+ const line = try self.r.takeDelimiterInclusive('\n');
+ if (line.len <= 2) break; // "\r\n" or "\n"
+ }
+ }
+
+ fn flushTransport(self: *WsClient) Error!void {
+ try self.w.flush(); // for TLS this encrypts plaintext into the socket writer…
+ if (self.tls_client != null) try self.wr.interface.flush(); // …then push the socket buffer
+ }
+
+ fn sendFrame(self: *WsClient, op: Opcode, payload: []const u8) Error!void {
+ var hdr: [14]u8 = undefined;
+ hdr[0] = 0x80 | @as(u8, @intFromEnum(op)); // FIN + opcode
+ var n: usize = 2;
+ if (payload.len < 126) {
+ hdr[1] = 0x80 | @as(u8, @intCast(payload.len));
+ } else if (payload.len <= 0xffff) {
+ hdr[1] = 0x80 | 126;
+ std.mem.writeInt(u16, hdr[2..4], @intCast(payload.len), .big);
+ n = 4;
+ } else {
+ hdr[1] = 0x80 | 127;
+ std.mem.writeInt(u64, hdr[2..10], payload.len, .big);
+ n = 10;
+ }
+ var mask: [4]u8 = undefined;
+ self.io.random(&mask);
+ @memcpy(hdr[n .. n + 4], &mask);
+ n += 4;
+
+ try self.w.writeAll(hdr[0..n]);
+ var i: usize = 0;
+ var tmp: [4096]u8 = undefined;
+ while (i < payload.len) {
+ const chunk = @min(tmp.len, payload.len - i);
+ for (0..chunk) |j| tmp[j] = payload[i + j] ^ mask[(i + j) & 3];
+ try self.w.writeAll(tmp[0..chunk]);
+ i += chunk;
+ }
+ try self.flushTransport();
+ }
+};
+
+fn unmask(buf: []u8, mask: [4]u8) void {
+ for (buf, 0..) |*b, i| b.* ^= mask[i & 3];
+}
+
+const Url = struct { tls: bool, host: []const u8, port: u16, path: []const u8 };
+
+fn parseUrl(url: []const u8) ?Url {
+ var rest = url;
+ var is_tls = false;
+ if (std.mem.startsWith(u8, rest, "wss://")) {
+ is_tls = true;
+ rest = rest["wss://".len..];
+ } else if (std.mem.startsWith(u8, rest, "ws://")) {
+ rest = rest["ws://".len..];
+ } else return null;
+
+ const slash = std.mem.indexOfScalar(u8, rest, '/');
+ const authority = if (slash) |s| rest[0..s] else rest;
+ const path = if (slash) |s| rest[s..] else "/";
+ if (authority.len == 0) return null;
+
+ var host = authority;
+ var port: u16 = if (is_tls) 443 else 80;
+ if (std.mem.lastIndexOfScalar(u8, authority, ':')) |c| {
+ host = authority[0..c];
+ port = std.fmt.parseInt(u16, authority[c + 1 ..], 10) catch return null;
+ }
+ return .{ .tls = is_tls, .host = host, .port = port, .path = path };
+}
+
+test "parseUrl: wss/ws, default ports, path" {
+ const a = parseUrl("wss://chatgpt.com/backend-api/codex/responses").?;
+ try std.testing.expect(a.tls);
+ try std.testing.expectEqualStrings("chatgpt.com", a.host);
+ try std.testing.expectEqual(@as(u16, 443), a.port);
+ try std.testing.expectEqualStrings("/backend-api/codex/responses", a.path);
+ const b = parseUrl("ws://localhost:8080/x").?;
+ try std.testing.expect(!b.tls);
+ try std.testing.expectEqual(@as(u16, 8080), b.port);
+ try std.testing.expect(parseUrl("https://nope") == null);
+}