Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions agent-langgraph-agui/src/tool_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,7 +292,13 @@ def model_unreachable(error: BaseException) -> bool:

The SDKs' own classes, and httpx's for an SDK that lets them through (Google's). A tool's call
never raises one here: `_call_tool` answers its own transport errors.

Not a connection that broke part way: the OpenAI SDK raises the same `APIConnectionError`
("Connection error.") for a stream reset while it reads, from httpx's `ReadError`, and the
person was told OpenBot couldn't reach a model that had already answered part way.
"""
if dropped_connection(error):
return False
unreached = []
for module, names in (
("openai", ("APIConnectionError",)), # `APITimeoutError` is one.
Expand Down Expand Up @@ -332,6 +338,50 @@ def model_address(error: BaseException) -> str | None:
return None


def dropped_connection(error: BaseException) -> str | None:
"""The code of a connection to the model that broke part way through its answer, or None.

The answer had begun, so somebody was there: not a model nothing answered at, and not a
provider's refusal, since nobody said anything. httpx raises `ReadError` ("[Errno 54] Connection
reset by peer") or `RemoteProtocolError` ("peer closed connection without sending complete
message body") from inside the stream the SDK is reading. Before, the run ended with
`RUN_FAILED`. Found on OpenBot Cloud with the TypeScript engine, 2026-12-03: OpenAI's stream
broke while a Bot was writing a Google Slides deck into a call, and the person read "The Bot
stopped before it finished answering" with no way on.

A tool's call never raises one here: `_call_tool` answers its own transport errors.
"""
cut = []
for module, names in (
("httpx", ("ReadError", "RemoteProtocolError", "WriteError")),
("httpx2", ("ReadError", "RemoteProtocolError", "WriteError")),
):
try:
loaded = __import__(module)
except ImportError:
continue
cut.extend(getattr(loaded, name) for name in names if hasattr(loaded, name))
links = list(_links(error))
broken = next((link for link in links if isinstance(link, tuple(cut))), None)
if broken is None:
return None
reset = any(isinstance(link, ConnectionResetError) for link in links) or (
"reset by peer" in str(broken).lower()
)
return "ECONNRESET" if reset else type(broken).__name__


def dropped_message(code: str, provider: str) -> str:
"""The words a dropped connection ends the run with.

The server reads "Connection dropped" as one (`connection_dropped` in provider-refusal.ts), as it
reads Claude Code's "API Error: Connection dropped (ECONNRESET)", and tells the person the
connection to their model dropped, with Carry on: the turn may already have done work.
"""
who = "your model provider" if provider == "Your model provider" else provider
return f"Connection dropped ({code}) before {who} finished answering."


# What the run ends with when nothing answered at the model's address, coded so the server can put
# the step that fits its edition in place of the second sentence (it reads the address back out of
# the first). The step here is right wherever the model is set.
Expand Down Expand Up @@ -432,6 +482,17 @@ async def run(self, input: RunAgentInput):
message=unreachable_message(address),
code=MODEL_UNREACHABLE,
)
elif dropped := dropped_connection(error):
# Coded as a refusal so the server reads the words, which say the connection
# dropped. Not `server_error`: behind OpenBot's sign-in proxy the server lets that
# category decide, and the person would read that the provider is having problems.
logger.warning("The connection to the model dropped part way: %r", error)
yield RunErrorEvent(
type=EventType.RUN_ERROR,
message=dropped_message(dropped, provider_name()),
code="OPENBOT_MODEL_REFUSED",
metadata={"errorCategory": "unknown"},
)
elif provider_refusal(error):
# Raised, it ended the response stream after RUN_STARTED with no terminal event,
# and the provider's reason never reached anyone. Coded as a refusal, so the server
Expand Down
54 changes: 53 additions & 1 deletion agent-langgraph-agui/tests/test_tool_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

import asyncio
import json
import socket
import struct
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
Expand Down Expand Up @@ -206,7 +208,11 @@ def do_POST(self):
)
if captured.get("text_with_tools"):
parts[0]["content"] = "Using the computer."
for part, reason in [*((part, None) for part in parts), ({}, finish)]:
cut = captured.get("cut")
frames = [*((part, None) for part in parts)]
if not cut:
frames.append(({}, finish))
for part, reason in frames:
chunk = {
"id": "response-proof",
"object": "chat.completion.chunk",
Expand All @@ -215,8 +221,25 @@ def do_POST(self):
"choices": [{"index": 0, "delta": part, "finish_reason": reason}],
}
self.wfile.write(("data: " + json.dumps(chunk) + "\n\n").encode())
if cut:
# The provider's stream breaks part way, after the call's arguments began: a TCP
# reset, as OpenBot Cloud's engine read one (`ECONNRESET`). No finish, no [DONE].
self.wfile.flush()
time.sleep(0.05)
self.connection.setsockopt(
socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)
)
self.connection.close()
self.close_connection = True
return
self.wfile.write(b"data: [DONE]\n\n")

def finish(self):
try:
super().finish()
except OSError:
pass # A connection this handler reset on purpose (`cut`).

def log_message(self, *_args):
pass

Expand Down Expand Up @@ -495,6 +518,35 @@ async def test_a_model_host_that_does_not_exist_is_told_the_same_way(boundary, m
)


@pytest.mark.asyncio
async def test_a_stream_that_breaks_part_way_through_a_call_says_the_connection_dropped(boundary):
"""Found on OpenBot Cloud, 2026-12-03: a Bot said a line and was writing a Google Slides deck
into a call's arguments when the provider's stream broke. The person read "The Bot stopped
before it finished answering. Try again." with no way on. The connection dropped, and the run
says so in the words the server tells as one, with Carry on (provider-refusal.ts)."""
boundary.update(text_with_tools=True, shape="interleaved", cut=True)
events = await run_protocol(
run_input(["GOOGLESLIDES_CREATE_SLIDES_MARKDOWN"]), allow_error=True
)
types = [event["type"] for event in events]
# What the person saw before it broke stays: the line and the call it was making.
assert "TEXT_MESSAGE_CONTENT" in types and "TOOL_CALL_START" in types, types
assert types.count("RUN_ERROR") == 1 and types[-1] == "RUN_ERROR", events[-1]
assert events[-1]["code"] == "OPENBOT_MODEL_REFUSED"
assert events[-1]["metadata"] == {"errorCategory": "unknown"}
# An OpenAI-compatible base URL that is not OpenAI's names nobody.
assert events[-1]["message"] == (
"Connection dropped (ECONNRESET) before your model provider finished answering."
)
# Nothing ran: the call never finished, so it never reached OpenBot.
assert not boundary["callback"]

# Carry on: the next run answers.
boundary["cut"] = False
events = await run_protocol(run_input([]))
assert events[-1]["type"] == "RUN_FINISHED"


def test_a_model_that_never_answers_in_time_is_unreachable_too():
"""A timeout is the third way an address can't be reached, and is told the same way."""
import openai
Expand Down
58 changes: 58 additions & 0 deletions agent-langgraph-ts/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,15 @@ const NOT_CONNECTED = new Set([
"EAI_AGAIN",
]);

/**
* A connection that broke after the model's answer began, by the codes and words Node's and
* undici's fetch give it: undici's "terminated" around a socket's `ECONNRESET`, "other side closed"
* (`UND_ERR_SOCKET`), Node's "socket hang up". The same as the server's `BROKEN_SOCKET`.
*/
const CUT_CODES = new Set(["ECONNRESET", "EPIPE", "UND_ERR_SOCKET"]);
const CUT_WORDS =
/^terminated$|other side closed|socket hang up|socket connection was closed unexpectedly/i;

type Link = Record<string, unknown> & { message?: unknown; name?: unknown };

/** The error and every error it was raised from. */
Expand Down Expand Up @@ -300,6 +309,44 @@ export function unreached(error: unknown): boolean {
});
}

/**
* The code of a connection to the model that broke part way through its answer, or undefined.
*
* FOUND ON OPENBOT CLOUD, 2026-12-03. A Bot on GPT-6.1 Terra had said a line and was writing a
* Google Slides deck into a call's arguments when OpenAI's stream broke 44 seconds in. The model
* gateway's answer broke with it, and this engine's fetch threw undici's `TypeError: terminated`,
* caused by `read ECONNRESET`. That has no status and is not a connection that never opened, so the
* run ended with `RUN_FAILED`, and the person read "The Bot stopped before it finished answering"
* with no way on.
*
* Inside a run the only connection is the model's: OpenBot's tools go back to the caller as
* pending calls, and the one tool answered here (recall) reads memory. A stop the caller asked for
* aborts, and is the caller's, not the connection's.
*/
export function droppedConnection(error: unknown): string | undefined {
const chain = links(error);
if (chain.some((link) => link.name === "AbortError")) return undefined;
for (const link of chain)
if (typeof link.code === "string" && CUT_CODES.has(link.code))
return link.code;
for (const link of chain)
if (typeof link.message === "string" && CUT_WORDS.test(link.message.trim()))
return link.message.trim();
return undefined;
}

/**
* The words a dropped connection ends the run with. The server reads "Connection dropped" as one
* (`connection_dropped` in provider-refusal.ts), as it reads Claude Code's "API Error: Connection
* dropped (ECONNRESET)", and tells the person the connection to their model dropped, with Carry
* on: the turn may already have done work, so it is carried on rather than sent again.
*/
export function droppedMessage(code: string, provider: string): string {
const who =
provider === "Your model provider" ? "your model provider" : provider;
return `Connection dropped (${code}) before ${who} finished answering.`;
}

/**
* Where the model was dialled, as host and port only: a base URL can carry a user and password,
* and some gateways put a key in the path. Nothing for OpenBot's own sign-in proxy, whose address
Expand Down Expand Up @@ -406,5 +453,16 @@ export function runFailure(
};
}

const dropped = droppedConnection(error);
if (dropped) {
return {
message: droppedMessage(dropped, context.provider),
code: MODEL_REFUSED,
// Not `server_error`: behind OpenBot's sign-in proxy the server lets that category decide
// (`PROXY_DECIDES`), and the person would read that the provider is having problems.
category: "unknown",
};
}

return { message: RUN_FAILED };
}
7 changes: 6 additions & 1 deletion agent-langgraph-ts/src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,9 @@ import {
withRecall,
} from "./context-room.ts";
import {
droppedConnection,
MessageTooLongError,
MODEL_REFUSED,
ModelDeclinedError,
runFailure,
} from "./errors.ts";
Expand Down Expand Up @@ -739,7 +741,10 @@ export async function runAgent(
} catch (error) {
if (options.signal?.aborted) return;
const failure = runFailure(error, failureContext(env, choice));
if (failure.code)
// Not a refusal: nobody said anything, and the error is what shows where it broke.
if (droppedConnection(error) && failure.code === MODEL_REFUSED)
log.warn("The connection to the model dropped part way", error);
else if (failure.code)
log.warn(`The model provider refused the run: ${failure.message}`);
else log.error("The run failed before it finished", error);
emit({
Expand Down
41 changes: 41 additions & 0 deletions agent-langgraph-ts/test/errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,44 @@ test("Nothing answering at the model's address says where it was dialled, and no
`OpenBot couldn't reach the AI model at 127.0.0.1:${port}. Check that it's running and the address is right.`,
);
});

/*
* A provider's stream that breaks part way: the answer had begun, a line said and a call's
* arguments under way, and then the connection was reset. Not a refusal and not a model nothing
* answered at: the connection dropped, in the words the server tells as one, with Carry on. Before,
* every wire ended with "The Bot stopped before it finished answering. Try again."
*/
const CUT: { name: string; provider: Provider; who: string }[] = [
// An OpenAI-compatible base URL that is not OpenAI's names nobody.
{
name: "OpenAI Chat Completions",
provider: "openai",
who: "your model provider",
},
{ name: "Anthropic Messages", provider: "anthropic", who: "Anthropic" },
{ name: "Gemini", provider: "google", who: "Google" },
];

for (const each of CUT) {
test(`${each.name}: a connection reset part way through a call ends the run saying the connection dropped`, async () => {
const error = await runError(each.provider, {
text: "I'll make the deck now.",
calls: [
{
id: "call_deck",
name: "get_weather",
args: { city: "A long argument ".repeat(200) },
},
],
cut: true,
});
assert.equal(error.code, "OPENBOT_MODEL_REFUSED");
assert.equal(error.metadata?.errorCategory, "unknown");
assert.match(
error.message,
new RegExp(
`^Connection dropped \\((ECONNRESET|terminated|other side closed|UND_ERR_SOCKET)\\) before ${each.who} finished answering\\.$`,
),
);
});
}
Loading
Loading