Skip to content

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

Python

Surface error-only SSE bodies on every streaming wire

Rach Pradhandfe5b0c12662
diff --git a/src/agent_request.zig b/src/agent_request.zig
index ede0d7cf..d7c92465 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -480,7 +480,7 @@ pub fn request(self: *Agent, tools_in: ?[]const u8) !std.json.ObjectMap {
// Codex Responses reports capacity failures through this
// response.failed arm too. Keep it on the same bounded
// overload retry path as SSE and JSON error envelopes.
- if (try policy.afterServerErrorOrParseReject(self, "", failure.code, msg, &server_retries, &gw_retry)) continue :rebuild;
+ if (try policy.afterServerErrorOrParseReject(self, failure.etype, failure.code, msg, &server_retries, &gw_retry)) continue :rebuild; // #748: the class keeps invalid requests off the flake ladder
self.last_api_reauth = @import("auth_recovery.zig").forFailure(self.provider, failure.code, msg);
if (self.tracer) |tr| tr.api(self.label, self.sub, self.provider.model, ms, body.len, resp_body.len, 0, 0, true);
try self.sayApiError("{s}", .{diagnostic});
diff --git a/src/agent_responses.zig b/src/agent_responses.zig
index 0237604a..c815063e 100644
--- a/src/agent_responses.zig
+++ b/src/agent_responses.zig
@@ -7,11 +7,16 @@ const Agent = @import("agent.zig").Agent;
const policy = @import("agent_request_policy.zig");
const errorCode = policy.errorCode;
const util = @import("util.zig");
+const sse_error = @import("sse_error_event.zig");
pub const ResponsesFailure = struct {
message: []const u8,
code: ?[]const u8 = null,
request_id: ?[]const u8 = null,
+ /// The provider's error class (`error.type`, e.g. invalid_request_error),
+ /// so the retry classifiers can tell a deterministic rejection from a
+ /// transient one (#748). Empty when the provider sent none.
+ etype: []const u8 = "",
/// The text to test for an auth failure. The ChatGPT plan route's
/// subscription_sharing_invalid_user 401 names it only in the code.
@@ -48,21 +53,43 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
var err_msg: ?[]const u8 = null;
var err_code: ?[]const u8 = null;
var err_rid: ?[]const u8 = null;
+ var err_type: []const u8 = "";
+ var named_error = false; // the data lines follow an `event: error` name
var it = std.mem.tokenizeScalar(u8, body, '\n');
while (it.next()) |raw_line| {
const line = std.mem.trim(u8, raw_line, " \r");
- if (!std.mem.startsWith(u8, line, "data:")) continue;
+ if (!std.mem.startsWith(u8, line, "data:")) {
+ named_error = sse_error.namesError(line, named_error);
+ continue;
+ }
const payload = std.mem.trim(u8, line["data:".len..], " ");
if (payload.len == 0 or std.mem.eql(u8, payload, "[DONE]")) continue;
const v = std.json.parseFromSliceLeaky(Value, scratch, payload, .{ .allocate = .alloc_always }) catch continue;
if (v != .object) continue;
- const t = v.object.get("type") orelse continue;
- if (t != .string) continue;
- if (std.mem.eql(u8, t.string, "response.output_item.done")) {
+ const named = named_error;
+ named_error = false;
+ const tname: []const u8 = if (v.object.get("type")) |tv| (if (tv == .string) tv.string else "") else "";
+ // #748: `response.failed`, a typed `error` event, an untyped
+ // `{"error":…}` frame, or a bare frame under `event: error` all end
+ // the stream as a failure carrying the provider's type and message.
+ // Before, the last two parsed as nothing and the body as Unparseable.
+ if (std.mem.eql(u8, tname, "response.failed") or std.mem.eql(u8, tname, "error") or named or
+ (tname.len == 0 and sse_error.isErrorEvent(v.object, false)))
+ {
+ err_msg = if (errorMessage(v.object)) |m|
+ result_arena.dupe(u8, m) catch "codex stream reported a failure"
+ else
+ "codex stream reported a failure";
+ if (errorCode(v.object)) |code| err_code = result_arena.dupe(u8, code) catch null;
+ if (errorRequestId(v.object)) |id| err_rid = result_arena.dupe(u8, id) catch null;
+ err_type = result_arena.dupe(u8, errorType(v.object)) catch "";
+ continue;
+ }
+ if (std.mem.eql(u8, tname, "response.output_item.done")) {
if (v.object.get("item")) |item| try items.append(try util.dupeJsonValue(result_arena, item));
- } else if (std.mem.eql(u8, t.string, "response.completed") or std.mem.eql(u8, t.string, "response.incomplete")) {
- saw_completed = std.mem.eql(u8, t.string, "response.completed");
- saw_incomplete = std.mem.eql(u8, t.string, "response.incomplete");
+ } else if (std.mem.eql(u8, tname, "response.completed") or std.mem.eql(u8, tname, "response.incomplete")) {
+ saw_completed = std.mem.eql(u8, tname, "response.completed");
+ saw_incomplete = std.mem.eql(u8, tname, "response.incomplete");
if (v.object.get("response")) |r| if (r == .object) {
try terminal.record(result_arena, r.object);
if (r.object.get("usage")) |u| {
@@ -73,24 +100,17 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
resp_id = try result_arena.dupe(u8, idv.string);
};
};
- } else if (std.mem.eql(u8, t.string, @import("agent_ws_steer.zig").applied_type)) {
+ } else if (std.mem.eql(u8, tname, @import("agent_ws_steer.zig").applied_type)) {
// A steer the server applied here: the user's words where the model read them.
if (v.object.get("text")) |txt| if (txt == .string)
try items.append(try @import("session_wake.zig").message(result_arena, txt.string));
- } else if (std.mem.eql(u8, t.string, "response.failed") or std.mem.eql(u8, t.string, "error")) {
- err_msg = if (errorMessage(v.object)) |m|
- result_arena.dupe(u8, m) catch "codex stream reported a failure"
- else
- "codex stream reported a failure";
- if (errorCode(v.object)) |code| err_code = result_arena.dupe(u8, code) catch null;
- if (errorRequestId(v.object)) |id| err_rid = result_arena.dupe(u8, id) catch null;
}
}
// A terminal failure wins even if the stream produced partial completed
// items first. Committing those items as a successful compaction summary
// would replace live history with a response the provider explicitly
// rejected.
- if (err_msg) |m| return .{ .err = .{ .message = m, .code = err_code, .request_id = err_rid } };
+ if (err_msg) |m| return .{ .err = .{ .message = m, .code = err_code, .request_id = err_rid, .etype = err_type } };
if (saw_completed or saw_incomplete or items.items.len > 0) {
var resp: std.json.ObjectMap = .empty;
try resp.put(result_arena, "output", .{ .array = items });
@@ -120,6 +140,7 @@ pub fn parseResponses(self: *Agent, body: []const u8) !ResponsesResult {
.message = result_arena.dupe(u8, m) catch "unparseable provider error",
.code = code,
.request_id = rid,
+ .etype = result_arena.dupe(u8, errorType(v.object)) catch "",
} };
}
}
@@ -335,6 +356,56 @@ pub fn errorMessage(obj: std.json.ObjectMap) ?[]const u8 {
return null;
}
+/// The error class from `error.type` or `response.error.type`; the frame's
+/// own top-level `type` is the event name, never the class.
+fn errorType(obj: std.json.ObjectMap) []const u8 {
+ const holder = if (obj.get("response")) |r| (if (r == .object and obj.get("error") == null) r.object else obj) else obj;
+ const e = holder.get("error") orelse return "";
+ if (e != .object) return "";
+ const t = e.object.get("type") orelse return "";
+ return if (t == .string) t.string else "";
+}
+
+test "#748: error-only Responses SSE is a typed failure, never Unparseable" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var agent: Agent = undefined;
+ agent.arena = arena_state.allocator();
+ agent.scratch_arena = null;
+ agent.message_mutation_arena = null;
+ const bodies = [_][]const u8{
+ // Typed error event (already handled): the class now survives.
+ "event: error\ndata: {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"code\":\"invalid_value\",\"message\":\"Invalid tool schema\"}}\n\n",
+ // response.failed carries the class under response.error.
+ "event: response.failed\ndata: {\"type\":\"response.failed\",\"response\":{\"status\":\"failed\",\"error\":{\"type\":\"invalid_request_error\",\"code\":\"invalid_value\",\"message\":\"Invalid tool schema\"}}}\n\n",
+ // An untyped frame from a proxy used to be skipped, leaving the body Unparseable.
+ "event: error\ndata: {\"error\":{\"type\":\"invalid_request_error\",\"code\":\"invalid_value\",\"message\":\"Invalid tool schema\"}}\n\n",
+ };
+ for (bodies) |body| switch (try parseResponses(&agent, body)) {
+ .err => |failure| {
+ try std.testing.expectEqualStrings("Invalid tool schema", failure.message);
+ try std.testing.expectEqualStrings("invalid_value", failure.code.?);
+ try std.testing.expectEqualStrings("invalid_request_error", failure.etype);
+ },
+ .ok => return error.TestUnexpectedResult,
+ };
+ // A bare frame is a failure only because the SSE event named it one.
+ switch (try parseResponses(&agent, "event: error\ndata: {\"message\":\"Upstream rejected the request\",\"code\":\"bad_request\"}\n\n")) {
+ .err => |failure| {
+ try std.testing.expectEqualStrings("Upstream rejected the request", failure.message);
+ try std.testing.expectEqualStrings("bad_request", failure.code.?);
+ },
+ .ok => return error.TestUnexpectedResult,
+ }
+ // The class decides the retry: an invalid request is deterministic, an
+ // overload stays on the transient ladder.
+ const gw = @import("agent_gateway_retry.zig");
+ try std.testing.expect(!gw.isTransientServerError("invalid_request_error", "invalid_value", "Invalid tool schema"));
+ try std.testing.expect(!gw.isShortGatewayFlake("invalid_request_error", null, "An error occurred while processing your request."));
+ try std.testing.expect(gw.isShortGatewayFlake("", null, "An error occurred while processing your request."));
+ try std.testing.expect(gw.isTransientServerError("server_error", null, "The server is overloaded"));
+}
+
test "parseResponses reads the ChatGPT plan route's expired-token envelope" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/agent_steps.zig b/src/agent_steps.zig
index 2676afd2..2c8e420c 100644
--- a/src/agent_steps.zig
+++ b/src/agent_steps.zig
@@ -283,6 +283,7 @@ pub fn assembleStream(self: *Agent, body: []const u8) !?std.json.ObjectMap {
pub const assembleAnthropic = @import("anthropic_assemble.zig").assembleAnthropic;
const chat_tool_calls = @import("chat_tool_calls.zig");
+const sse_error = @import("sse_error_event.zig");
pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
const result_arena = self.messageMutationAlloc();
@@ -298,10 +299,12 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
var extra_content: ?Value = null;
var saw_chunk = false;
var saw_done = false; // `data: [DONE]`: the stream ended on purpose even without a finish_reason
+ var named_error = false; // the data lines follow an `event: error` name
var it = std.mem.tokenizeScalar(u8, body, '\n');
while (it.next()) |raw_line| {
const payload = ssePayload(raw_line) orelse {
saw_done = saw_done or std.mem.eql(u8, std.mem.trim(u8, raw_line, " \r"), "data: [DONE]");
+ named_error = sse_error.namesError(raw_line, named_error);
continue;
};
const v = std.json.parseFromSliceLeaky(Value, self.scratchAlloc(), payload, .{ .allocate = .alloc_always }) catch continue; // #124: per-event parse tree is transient (deltas are appendSlice'd into session accumulators)
@@ -309,15 +312,8 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
// Error-only SSE (`event: error` / `data: {"error":…}`) has no
// choices chunk. Hand the envelope back so request() reports it
// instead of falling through to the truncated-body retry (#748).
- if (v.object.get("error")) |err| if (err != .null) {
- var env: std.json.ObjectMap = .empty;
- try env.put(result_arena, "type", .{ .string = "error" });
- try env.put(result_arena, "error", try util.dupeJsonValue(result_arena, err));
- return env;
- };
- if (v.object.get("type")) |t| if (t == .string and std.mem.eql(u8, t.string, "error")) {
- return (try util.dupeJsonValue(result_arena, v)).object;
- };
+ if (try sse_error.envelope(result_arena, v.object, named_error)) |env| return env;
+ named_error = false;
// The final usage chunk (stream_options.include_usage) may have
// an empty choices array.
if (v.object.get("usage")) |u| if (u == .object) {
@@ -429,4 +425,5 @@ pub fn assembleOpenAI(self: *Agent, body: []const u8) !?std.json.ObjectMap {
test {
_ = @import("agent_steps_tests.zig");
_ = @import("anthropic_assemble.zig");
+ _ = @import("sse_error_event.zig");
}
diff --git a/src/anthropic_assemble.zig b/src/anthropic_assemble.zig
index 5940c7d7..3afcb594 100644
--- a/src/anthropic_assemble.zig
+++ b/src/anthropic_assemble.zig
@@ -8,6 +8,7 @@ const Value = std.json.Value;
const Agent = @import("agent.zig").Agent;
const util = @import("util.zig");
const tool_call_args = @import("tool_call_args.zig");
+const sse_error = @import("sse_error_event.zig");
const ssePayload = Agent.ssePayload;
const sseIndex = Agent.sseIndex;
@@ -47,11 +48,22 @@ pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
var stop_details: ?Value = null; // a refusal's category (ADR 0219)
var usage_delta: ?Value = null;
var saw_block_stop = false;
+ var named_error = false; // the data lines follow an `event: error` name
var it = std.mem.tokenizeScalar(u8, body, '\n');
while (it.next()) |raw_line| {
- const payload = ssePayload(raw_line) orelse continue;
+ const payload = ssePayload(raw_line) orelse {
+ named_error = sse_error.namesError(raw_line, named_error);
+ continue;
+ };
const v = std.json.parseFromSliceLeaky(Value, scratch, payload, .{ .allocate = .alloc_always }) catch continue;
if (v != .object) continue;
+ // An error event (typed, untyped from a proxy, or a bare frame under
+ // `event: error`) becomes the root: request()'s type=="error" check
+ // reports it with the provider's type and message (#748). Detached
+ // from scratch: the rebuild loop can reset the scratch arena before
+ // the message is done being read.
+ if (try sse_error.envelope(result_arena, v.object, named_error)) |env| return env;
+ named_error = false;
const t = v.object.get("type") orelse continue;
if (t != .string) continue;
if (std.mem.eql(u8, t.string, "message_start")) {
@@ -90,12 +102,6 @@ pub fn assembleAnthropic(self: *Agent, body: []const u8) !?std.json.ObjectMap {
if (v.object.get("usage")) |u| if (u == .object) {
usage_delta = u;
};
- } else if (std.mem.eql(u8, t.string, "error")) {
- // Hand the envelope back as the root: request()'s existing
- // type=="error" check reports it. Detached from scratch — the
- // rebuild loop can reset the scratch arena before the message
- // is done being read.
- return (try util.dupeJsonValue(result_arena, v)).object;
}
}
var r = root orelse return null;
diff --git a/src/interactions_stream.zig b/src/interactions_stream.zig
index 843f1e77..5ae38321 100644
--- a/src/interactions_stream.zig
+++ b/src/interactions_stream.zig
@@ -21,6 +21,7 @@ const std = @import("std");
const Value = std.json.Value;
const Agent = @import("agent.zig").Agent;
+const sse_error = @import("sse_error_event.zig");
/// One in-flight step. `text` and `args` accumulate across deltas.
const StepAcc = struct {
@@ -49,10 +50,14 @@ pub fn assemble(self: *Agent, body: []const u8) !?std.json.ObjectMap {
var status: []const u8 = "";
var interaction_id: []const u8 = "";
var saw_event = false;
+ var named_error = false; // the data lines follow an `event: error` name
var it = std.mem.tokenizeScalar(u8, body, '\n');
while (it.next()) |raw_line| {
- const payload = ssePayload(raw_line) orelse continue;
+ const payload = ssePayload(raw_line) orelse {
+ named_error = sse_error.namesError(raw_line, named_error);
+ continue;
+ };
if (std.mem.eql(u8, payload, "[DONE]")) {
saw_event = true;
continue;
@@ -62,8 +67,14 @@ pub fn assemble(self: *Agent, body: []const u8) !?std.json.ObjectMap {
const v = std.json.parseFromSliceLeaky(Value, self.scratchAlloc(), payload, .{ .allocate = .alloc_always }) catch continue;
if (v != .object) continue;
saw_event = true;
+ // An error event used to reassemble as an empty interaction: a silent
+ // empty turn. Hand it back as the error root request() reports (#748),
+ // whether it arrives on its own or inside a failed interaction.
+ if (try sse_error.envelope(arena, v.object, named_error)) |env| return env;
+ named_error = false;
if (v.object.get("interaction")) |ix| if (ix == .object) {
+ if (try sse_error.envelope(arena, ix.object, false)) |env| return env;
if (str(ix.object, "id").len > 0) interaction_id = try arena.dupe(u8, str(ix.object, "id"));
if (str(ix.object, "status").len > 0) status = try arena.dupe(u8, str(ix.object, "status"));
if (ix.object.get("usage")) |u| usage = try @import("util.zig").dupeJsonValue(arena, u);
diff --git a/src/sse_error_event.zig b/src/sse_error_event.zig
new file mode 100644
index 00000000..693acf21
--- /dev/null
+++ b/src/sse_error_event.zig
@@ -0,0 +1,191 @@
+//! Explicit error events inside a streamed body (#748).
+//!
+//! A provider that refuses a streamed request often answers with an SSE body
+//! that holds nothing but an error event: `event: error` plus
+//! `data: {"type":"error","error":{…}}` on Anthropic Messages, a
+//! `{"error":{…}}` chunk on chat-completions, Google's
+//! `{"error":{"code":400,"status":"INVALID_ARGUMENT",…}}` on Interactions, or a
+//! bare `{"message":…}` frame after `event: error` from a proxy. Each stream
+//! assembler asks `envelope` about every payload it parses and hands a match
+//! back as the `{"type":"error","error":{…}}` root that request() already
+//! reports, so the provider's type and message reach the api-error path and
+//! its retry policy instead of the body failing reassembly and looking like a
+//! truncated response.
+
+const std = @import("std");
+const Value = std.json.Value;
+const ObjectMap = std.json.ObjectMap;
+
+const util = @import("util.zig");
+
+/// Track the SSE `event:` name for the data lines that follow it. Call with
+/// every line the assembler's `ssePayload` rejected; returns the new flag.
+/// `event: error` sets it, any other event name clears it, other lines keep it.
+pub fn namesError(raw_line: []const u8, prev: bool) bool {
+ const line = std.mem.trim(u8, raw_line, " \t\r");
+ if (!std.mem.startsWith(u8, line, "event:")) return prev;
+ return std.mem.eql(u8, std.mem.trim(u8, line["event:".len..], " \t"), "error");
+}
+
+fn isError(v: ?Value) bool {
+ const t = v orelse return false;
+ return t == .string and std.mem.eql(u8, t.string, "error");
+}
+
+/// The `error` member when it carries anything (`"error": null` is a normal
+/// chat-completions chunk on some providers).
+fn errorField(obj: ObjectMap) ?Value {
+ const e = obj.get("error") orelse return null;
+ return switch (e) {
+ .object, .string => e,
+ else => null,
+ };
+}
+
+/// True when this parsed payload is an explicit error event: it is typed
+/// `error` (`type` or Interactions' `event_type`), carries a non-null `error`
+/// member, or arrived under an `event: error` name.
+pub fn isErrorEvent(obj: ObjectMap, named_error: bool) bool {
+ return named_error or isError(obj.get("type")) or isError(obj.get("event_type")) or errorField(obj) != null;
+}
+
+/// The `{"type":"error","error":{type,message,code,…}}` envelope for an error
+/// event, deep-copied onto `arena`, or null when `obj` is an ordinary event.
+/// Nested `error` fields win; top-level `message`/`code` (Responses-style and
+/// bare proxy frames) fill gaps; Google's `status` stands in for a missing
+/// `type` so deterministic classes like INVALID_ARGUMENT stay recognizable.
+pub fn envelope(arena: std.mem.Allocator, obj: ObjectMap, named_error: bool) !?ObjectMap {
+ if (!isErrorEvent(obj, named_error)) return null;
+ var inner: ObjectMap = .empty;
+ if (errorField(obj)) |e| switch (e) {
+ .object => inner = (try util.dupeJsonValue(arena, e)).object,
+ .string => |s| try inner.put(arena, "message", .{ .string = try arena.dupe(u8, s) }),
+ else => {},
+ };
+ for ([_][]const u8{ "message", "code" }) |k| if (inner.get(k) == null) if (obj.get(k)) |v| switch (v) {
+ .string, .integer => try inner.put(arena, k, try util.dupeJsonValue(arena, v)),
+ else => {},
+ };
+ if (inner.get("type") == null) if (inner.get("status")) |s| if (s == .string) try inner.put(arena, "type", s);
+ var env: ObjectMap = .empty;
+ try env.put(arena, "type", .{ .string = "error" });
+ try env.put(arena, "error", .{ .object = inner });
+ if (obj.get("request_id")) |r| if (r == .string) try env.put(arena, "request_id", .{ .string = try arena.dupe(u8, r.string) });
+ return env;
+}
+
+/// `error.type` from an envelope, or "" — the class name request() and the
+/// retry classifiers read.
+pub fn errorType(env: ObjectMap) []const u8 {
+ const e = env.get("error") orelse return "";
+ if (e != .object) return "";
+ const t = e.object.get("type") orelse return "";
+ return if (t == .string) t.string else "";
+}
+
+fn parse(arena: std.mem.Allocator, payload: []const u8) !ObjectMap {
+ return (try std.json.parseFromSliceLeaky(Value, arena, payload, .{})).object;
+}
+
+test "#748: envelope recognizes each error event shape and preserves type and message" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+
+ const anth = (try envelope(a, try parse(a, "{\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"bad tool schema\"},\"request_id\":\"req_1\"}"), false)).?;
+ try std.testing.expectEqualStrings("invalid_request_error", errorType(anth));
+ try std.testing.expectEqualStrings("bad tool schema", anth.get("error").?.object.get("message").?.string);
+ try std.testing.expectEqualStrings("req_1", anth.get("request_id").?.string);
+
+ const google = (try envelope(a, try parse(a, "{\"error\":{\"code\":400,\"message\":\"Request contains an invalid argument.\",\"status\":\"INVALID_ARGUMENT\"}}"), false)).?;
+ try std.testing.expectEqualStrings("INVALID_ARGUMENT", errorType(google));
+
+ const string_err = (try envelope(a, try parse(a, "{\"error\":\"model not allowed\"}"), false)).?;
+ try std.testing.expectEqualStrings("model not allowed", string_err.get("error").?.object.get("message").?.string);
+
+ // A bare frame is an error only because the SSE event named it one.
+ const bare = "{\"message\":\"Overloaded\",\"code\":\"overloaded\"}";
+ try std.testing.expect((try envelope(a, try parse(a, bare), false)) == null);
+ const named = (try envelope(a, try parse(a, bare), true)).?;
+ try std.testing.expectEqualStrings("Overloaded", named.get("error").?.object.get("message").?.string);
+ try std.testing.expectEqualStrings("overloaded", named.get("error").?.object.get("code").?.string);
+
+ // Ordinary events stay ordinary.
+ try std.testing.expect((try envelope(a, try parse(a, "{\"choices\":[],\"error\":null}"), false)) == null);
+ try std.testing.expect((try envelope(a, try parse(a, "{\"type\":\"message_start\",\"message\":{}}"), false)) == null);
+}
+
+test "#748: namesError follows the SSE event name" {
+ try std.testing.expect(namesError("event: error\r", false));
+ try std.testing.expect(namesError("event:error", false));
+ try std.testing.expect(!namesError("event: message_start", true));
+ try std.testing.expect(namesError(": keep-alive", true));
+ try std.testing.expect(!namesError("id: 7", false));
+}
+
+const Agent = @import("agent.zig").Agent;
+
+fn testAgent(arena: std.mem.Allocator) Agent {
+ return .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = null,
+ };
+}
+
+test "#748: error-only Anthropic SSE becomes an error root on every frame shape" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var agent = testAgent(arena_state.allocator());
+ const assemble = @import("anthropic_assemble.zig").assembleAnthropic;
+ const typed = (try assemble(&agent, "event: error\n" ++
+ "data: {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"tools.0: name too long\"}}\n\n")).?;
+ try std.testing.expectEqualStrings("invalid_request_error", errorType(typed));
+ try std.testing.expectEqualStrings("tools.0: name too long", typed.get("error").?.object.get("message").?.string);
+
+ // A compatible proxy that drops `type` used to reassemble to null and fall
+ // through to the unparseable/truncated-body path.
+ const untyped = (try assemble(&agent, "event: error\n" ++
+ "data: {\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n")).?;
+ try std.testing.expectEqualStrings("error", untyped.get("type").?.string);
+ try std.testing.expectEqualStrings("overloaded_error", errorType(untyped));
+
+ const bare = (try assemble(&agent, "event: error\ndata: {\"message\":\"upstream rejected the request\"}\n\n")).?;
+ try std.testing.expectEqualStrings("upstream rejected the request", bare.get("error").?.object.get("message").?.string);
+}
+
+test "#748: error-only Interactions SSE is an error root, not an empty interaction" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var agent = testAgent(arena_state.allocator());
+ const assemble = @import("interactions_stream.zig").assemble;
+ const root = (try assemble(&agent, "event: error\n" ++
+ "data: {\"event_type\":\"error\",\"error\":{\"code\":400,\"message\":\"Request contains an invalid argument.\",\"status\":\"INVALID_ARGUMENT\"}}\n\n" ++
+ "data: [DONE]\n")).?;
+ try std.testing.expectEqualStrings("error", root.get("type").?.string);
+ try std.testing.expectEqualStrings("INVALID_ARGUMENT", errorType(root));
+ try std.testing.expectEqualStrings("Request contains an invalid argument.", root.get("error").?.object.get("message").?.string);
+ try std.testing.expect(root.get("steps") == null);
+
+ // A failed interaction carries its error inside the interaction object.
+ const failed = (try assemble(&agent, "event: interaction.completed\n" ++
+ "data: {\"event_type\":\"interaction.completed\",\"interaction\":{\"id\":\"v1_x\",\"status\":\"failed\",\"error\":{\"code\":503,\"message\":\"The model is overloaded.\",\"status\":\"UNAVAILABLE\"}}}\n\n")).?;
+ try std.testing.expectEqualStrings("UNAVAILABLE", errorType(failed));
+ try std.testing.expectEqualStrings("The model is overloaded.", failed.get("error").?.object.get("message").?.string);
+}
+
+test "#748: error-only chat-completions SSE keeps a string error and a bare named frame" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var agent = testAgent(arena_state.allocator());
+ const str_err = (try agent.assembleOpenAI("data: {\"error\":\"tool_choice must be auto\"}\n\ndata: [DONE]\n")).?;
+ try std.testing.expectEqualStrings("tool_choice must be auto", str_err.get("error").?.object.get("message").?.string);
+ const named = (try agent.assembleOpenAI("event: error\ndata: {\"message\":\"Provider returned error\",\"code\":502}\n\n")).?;
+ try std.testing.expectEqualStrings("Provider returned error", named.get("error").?.object.get("message").?.string);
+}