Skip to content

Commit a8c8c82

Browse files
authored
fix(gateway): honor recorded HTTP run failures (#133275)
1 parent 6475a19 commit a8c8c82

7 files changed

Lines changed: 106 additions & 43 deletions

File tree

‎docs/gateway/openai-http-api.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,8 @@ Set `stream: true` to receive Server-Sent Events:
219219
- Each event line is `data: <json>`
220220
- Stream ends with `data: [DONE]`
221221

222+
Failed agent runs, including whole-agent timeouts, return an error instead of a successful completion. A streaming failure emits an `error` object followed by `[DONE]`; partial content may already have reached the client. Timeout settings follow the [agent loop](/concepts/agent-loop#timeouts).
223+
222224
## Open WebUI quick setup
223225

224226
- Base URL: `http://127.0.0.1:18789/v1`

‎docs/gateway/openresponses-http-api.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,8 @@ Set `stream: true` to receive Server-Sent Events:
225225

226226
Event types currently emitted: `response.created`, `response.in_progress`, `response.output_item.added`, `response.content_part.added`, `response.output_text.delta`, `response.output_text.done`, `response.content_part.done`, `response.output_item.done`, `response.completed`, `response.failed` (on error).
227227

228+
Failed agent runs, including whole-agent timeouts, return a failed response. Streaming failures emit `response.failed` followed by `[DONE]`; partial content may already have reached the client. Timeout settings follow the [agent loop](/concepts/agent-loop#timeouts).
229+
228230
## Usage
229231

230232
`usage` is populated when the underlying provider reports token counts. OpenClaw normalizes common OpenAI-style aliases before those counters reach downstream status/session surfaces, including `input_tokens` / `output_tokens` and `prompt_tokens` / `completion_tokens`.

‎src/gateway/openai-compat-errors.ts‎

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
21
import { describeFailoverError, resolveFailoverStatus } from "../agents/failover-error.js";
32
// OpenAI-compatible error helpers.
43
// Converts OpenClaw failover/sampling errors to OpenAI-style HTTP responses.
@@ -32,12 +31,6 @@ const ERROR_TYPE_BY_REASON = {
3231
unknown: undefined,
3332
} satisfies Record<FailoverReason, string | undefined>;
3433

35-
/** Resolved agent failures must not become successful OpenAI HTTP responses. */
36-
export function isFailedOpenAiAgentRun(result: unknown): boolean {
37-
const metadata = asOptionalRecord(asOptionalRecord(result)?.meta);
38-
return Boolean(metadata?.error) || metadata?.stopReason === "error";
39-
}
40-
4134
function statusForReason(reason: FailoverReason, status: number | undefined): number {
4235
if (reason === "server_error") {
4336
return status && status >= 400 && status < 500 ? status : 502;

‎src/gateway/openai-http.test.ts‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { subscribeEmbeddedAgentSession } from "../agents/embedded-agent-subscrib
2020
import { FailoverError } from "../agents/failover-error.js";
2121
import { HISTORY_CONTEXT_MARKER } from "../auto-reply/reply/history.js";
2222
import { CURRENT_MESSAGE_MARKER } from "../auto-reply/reply/mentions.js";
23+
import { recordAgentRunTerminalOutcome } from "../channels/turn/agent-run-terminal-outcome.js";
2324
import { resetConfigRuntimeState } from "../config/config.js";
2425
import { upsertSessionEntryCore } from "../config/sessions/session-accessor.js";
2526
import {
@@ -2049,10 +2050,15 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
20492050
it("rejects resolved terminal agent failures without exposing provider details", async () => {
20502051
const privateDetail = "raw provider detail should stay private";
20512052
agentCommandMock.mockClear();
2052-
agentCommandMock.mockResolvedValueOnce({
2053-
payloads: [{ text: "Command may have changed state", isError: true }],
2054-
meta: { error: { kind: "incomplete_turn", message: privateDetail } },
2055-
} as never);
2053+
agentCommandMock.mockResolvedValueOnce(
2054+
recordAgentRunTerminalOutcome(
2055+
{
2056+
payloads: [{ text: "Command may have changed state", isError: true }],
2057+
meta: { error: { kind: "incomplete_turn", message: privateDetail } },
2058+
},
2059+
"failed",
2060+
) as never,
2061+
);
20562062

20572063
const res = await postChatCompletions(enabledPort, {
20582064
model: "openclaw",
@@ -2066,18 +2072,30 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
20662072
expect(body).not.toContain(privateDetail);
20672073
});
20682074

2069-
it("rejects resolved error stop reasons", async () => {
2075+
it.each([
2076+
{ name: "error stop", meta: { stopReason: "error" }, outcome: "failed", status: 500 },
2077+
{
2078+
name: "run-budget timeout without error metadata",
2079+
meta: { aborted: false, timeoutPhase: "provider", providerStarted: true },
2080+
outcome: "failed",
2081+
status: 500,
2082+
},
2083+
{ name: "completed run with an error payload", meta: {}, outcome: "completed", status: 200 },
2084+
] as const)("uses the recorded outcome for $name", async ({ meta, outcome, status }) => {
20702085
agentCommandMock.mockClear();
2071-
agentCommandMock.mockResolvedValueOnce({
2072-
payloads: [{ text: "Command may have changed state", isError: true }],
2073-
meta: { stopReason: "error" },
2074-
} as never);
2086+
agentCommandMock.mockResolvedValueOnce(
2087+
recordAgentRunTerminalOutcome(
2088+
{ payloads: [{ text: "Command may have changed state", isError: true }], meta },
2089+
outcome,
2090+
) as never,
2091+
);
20752092

20762093
const res = await postChatCompletions(enabledPort, {
20772094
model: "openclaw",
20782095
messages: [{ role: "user", content: "hi" }],
20792096
});
2080-
expect(res.status).toBe(500);
2097+
expect(res.status).toBe(status);
2098+
await res.text();
20812099
});
20822100

20832101
it.each(
@@ -2092,6 +2110,11 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
20922110
meta: { stopReason: "error" },
20932111
expectedPhase: "end" as const,
20942112
},
2113+
{
2114+
label: "a run-budget timeout without error metadata",
2115+
meta: { aborted: false, timeoutPhase: "provider" as const, providerStarted: true },
2116+
expectedPhase: "end" as const,
2117+
},
20952118
].flatMap((failure) =>
20962119
[false, true].map((producerTerminal) => ({
20972120
meta: failure.meta,
@@ -2123,6 +2146,7 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
21232146
if (!runId) {
21242147
throw new Error("expected a streaming chat-completion run ID");
21252148
}
2149+
emitAgentEvent({ runId, stream: "assistant", data: { delta: "partial answer" } });
21262150
const result = {
21272151
payloads: [{ text: "Command may have changed state", isError: true }],
21282152
meta: { durationMs: 0, ...meta },
@@ -2140,15 +2164,19 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
21402164
});
21412165
const terminal = {
21422166
metadata: {},
2143-
outcome: buildAgentRunTerminalOutcome({ status: "error", stopReason: "error" }),
2167+
outcome: buildAgentRunTerminalOutcome({
2168+
status: meta.timeoutPhase ? "timeout" : "error",
2169+
stopReason: meta.timeoutPhase ? undefined : "error",
2170+
timeoutPhase: meta.timeoutPhase,
2171+
}),
21442172
};
21452173
if (lifecycle.resolveResultError(result, false)) {
21462174
lifecycle.emitResultError(result, false, terminal);
21472175
} else {
21482176
lifecycle.emitEnd(terminal);
21492177
}
21502178
}
2151-
return result;
2179+
return recordAgentRunTerminalOutcome(result, "failed");
21522180
}) as never);
21532181

21542182
try {
@@ -2158,16 +2186,22 @@ describe("OpenAI-compatible HTTP API (e2e)", () => {
21582186
stream: true,
21592187
});
21602188
const finishReasons: Array<string | null> = [];
2189+
const content: string[] = [];
21612190
await expect(async () => {
21622191
for await (const chunk of stream) {
21632192
finishReasons.push(...chunk.choices.map((choice) => choice.finish_reason));
2193+
content.push(...chunk.choices.map((choice) => choice.delta.content ?? ""));
21642194
}
21652195
}).rejects.toMatchObject({
21662196
error: { message: "internal error", type: "api_error" },
21672197
});
21682198
expect(finishReasons).not.toContain("stop");
2199+
expect(content.join("")).toBe("partial answer");
21692200
expect(terminals).toEqual([
2170-
{ phase: producerTerminal ? expectedPhase : "error", status: "error" },
2201+
{
2202+
phase: producerTerminal ? expectedPhase : "error",
2203+
status: producerTerminal && meta.timeoutPhase ? "timeout" : "error",
2204+
},
21712205
]);
21722206
} finally {
21732207
unsubscribe();

‎src/gateway/openai-http.ts‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import type { AgentStreamParams, ClientToolDefinition } from "../agents/command/
1616
import type { ImageContent } from "../agents/command/types.js";
1717
import { STREAM_ERROR_FALLBACK_TEXT } from "../agents/stream-message-shared.js";
1818
import { toOpenAiChatCompletionsUsage, type OpenAiChatCompletionsUsage } from "../agents/usage.js";
19+
import { readAgentRunTerminalOutcome } from "../channels/turn/agent-run-terminal-outcome.js";
1920
import { createDefaultDeps } from "../cli/deps.js";
2021
import { agentCommandFromGatewayIngress } from "../commands/agent.js";
2122
import { getRuntimeConfig } from "../config/io.js";
@@ -74,11 +75,7 @@ import {
7475
} from "./http-utils.js";
7576
import { normalizeInputHostnameAllowlist } from "./input-allowlist.js";
7677
import { resolveAgentRunUsage } from "./openai-agent-run-usage.js";
77-
import {
78-
isFailedOpenAiAgentRun,
79-
resolveOpenAiCompatError,
80-
validateOpenAiSamplingParams,
81-
} from "./openai-compat-errors.js";
78+
import { resolveOpenAiCompatError, validateOpenAiSamplingParams } from "./openai-compat-errors.js";
8279
import {
8380
isToolChoiceConstraintSatisfied,
8481
resolveUnsatisfiedToolChoiceMessage,
@@ -1080,7 +1077,7 @@ export async function handleOpenAiHttpRequest(
10801077
}
10811078

10821079
const meta = (result as { meta?: { error?: unknown; stopReason?: unknown } } | null)?.meta;
1083-
if (isFailedOpenAiAgentRun(result)) {
1080+
if (readAgentRunTerminalOutcome(result) === "failed") {
10841081
throw new Error("agent run failed");
10851082
}
10861083
const usage = resolveChatCompletionUsage(result);
@@ -1358,7 +1355,7 @@ export async function handleOpenAiHttpRequest(
13581355
return;
13591356
}
13601357

1361-
if (isFailedOpenAiAgentRun(result)) {
1358+
if (readAgentRunTerminalOutcome(result) === "failed") {
13621359
terminalLifecyclePhase = "error";
13631360
finishStreamWithError({ message: "internal error", type: "api_error" });
13641361
return;

‎src/gateway/openresponses-http.test.ts‎

Lines changed: 47 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { createAgentCommandLifecycle } from "../agents/command/lifecycle.js";
1515
import { FailoverError } from "../agents/failover-error.js";
1616
import { HISTORY_CONTEXT_MARKER } from "../auto-reply/reply/history.js";
1717
import { CURRENT_MESSAGE_MARKER } from "../auto-reply/reply/mentions.js";
18+
import { recordAgentRunTerminalOutcome } from "../channels/turn/agent-run-terminal-outcome.js";
1819
import { resetConfigRuntimeState } from "../config/config.js";
1920
import { upsertSessionEntryCore } from "../config/sessions/session-accessor.js";
2021
import {
@@ -1923,10 +1924,15 @@ describe("OpenResponses HTTP API (e2e)", () => {
19231924
it("rejects resolved terminal agent failures without exposing provider details", async () => {
19241925
const privateDetail = "raw provider detail should stay private";
19251926
agentCommandMock.mockClear();
1926-
agentCommandMock.mockResolvedValueOnce({
1927-
payloads: [{ text: "Command may have changed state", isError: true }],
1928-
meta: { error: { kind: "incomplete_turn", message: privateDetail } },
1929-
} as never);
1927+
agentCommandMock.mockResolvedValueOnce(
1928+
recordAgentRunTerminalOutcome(
1929+
{
1930+
payloads: [{ text: "Command may have changed state", isError: true }],
1931+
meta: { error: { kind: "incomplete_turn", message: privateDetail } },
1932+
},
1933+
"failed",
1934+
) as never,
1935+
);
19301936

19311937
const res = await postResponses(enabledPort, { model: "openclaw", input: "hi" });
19321938
const body = await res.text();
@@ -1939,15 +1945,27 @@ describe("OpenResponses HTTP API (e2e)", () => {
19391945
expect(body).not.toContain(privateDetail);
19401946
});
19411947

1942-
it("rejects resolved error stop reasons", async () => {
1948+
it.each([
1949+
{ name: "error stop", meta: { stopReason: "error" }, outcome: "failed", status: 500 },
1950+
{
1951+
name: "run-budget timeout without error metadata",
1952+
meta: { aborted: false, timeoutPhase: "provider", providerStarted: true },
1953+
outcome: "failed",
1954+
status: 500,
1955+
},
1956+
{ name: "completed run with an error payload", meta: {}, outcome: "completed", status: 200 },
1957+
] as const)("uses the recorded outcome for $name", async ({ meta, outcome, status }) => {
19431958
agentCommandMock.mockClear();
1944-
agentCommandMock.mockResolvedValueOnce({
1945-
payloads: [{ text: "Command may have changed state", isError: true }],
1946-
meta: { stopReason: "error" },
1947-
} as never);
1959+
agentCommandMock.mockResolvedValueOnce(
1960+
recordAgentRunTerminalOutcome(
1961+
{ payloads: [{ text: "Command may have changed state", isError: true }], meta },
1962+
outcome,
1963+
) as never,
1964+
);
19481965

19491966
const res = await postResponses(enabledPort, { model: "openclaw", input: "hi" });
1950-
expect(res.status).toBe(500);
1967+
expect(res.status).toBe(status);
1968+
await res.text();
19511969
});
19521970

19531971
it.each(
@@ -1962,6 +1980,11 @@ describe("OpenResponses HTTP API (e2e)", () => {
19621980
meta: { stopReason: "error" },
19631981
expectedPhase: "end" as const,
19641982
},
1983+
{
1984+
label: "a run-budget timeout without error metadata",
1985+
meta: { aborted: false, timeoutPhase: "provider" as const, providerStarted: true },
1986+
expectedPhase: "end" as const,
1987+
},
19651988
].flatMap((failure) =>
19661989
[false, true].map((producerTerminal) => ({
19671990
meta: failure.meta,
@@ -1993,6 +2016,7 @@ describe("OpenResponses HTTP API (e2e)", () => {
19932016
if (!runId) {
19942017
throw new Error("expected a streaming response run ID");
19952018
}
2019+
emitAgentEvent({ runId, stream: "assistant", data: { delta: "partial answer" } });
19962020
const result = {
19972021
payloads: [{ text: "Command may have changed state", isError: true }],
19982022
meta: {
@@ -2019,15 +2043,19 @@ describe("OpenResponses HTTP API (e2e)", () => {
20192043
});
20202044
const terminal = {
20212045
metadata: {},
2022-
outcome: buildAgentRunTerminalOutcome({ status: "error", stopReason: "error" }),
2046+
outcome: buildAgentRunTerminalOutcome({
2047+
status: meta.timeoutPhase ? "timeout" : "error",
2048+
stopReason: meta.timeoutPhase ? undefined : "error",
2049+
timeoutPhase: meta.timeoutPhase,
2050+
}),
20232051
};
20242052
if (lifecycle.resolveResultError(result, false)) {
20252053
lifecycle.emitResultError(result, false, terminal);
20262054
} else {
20272055
lifecycle.emitEnd(terminal);
20282056
}
20292057
}
2030-
return result;
2058+
return recordAgentRunTerminalOutcome(result, "failed");
20312059
}) as never);
20322060

20332061
try {
@@ -2039,6 +2067,8 @@ describe("OpenResponses HTTP API (e2e)", () => {
20392067
});
20402068
const stream = client.responses.stream({ model: "openclaw", input: "hi" });
20412069
const terminalEvents: string[] = [];
2070+
const content: string[] = [];
2071+
stream.on("response.output_text.delta", (event) => content.push(event.delta));
20422072
stream.on("response.completed", () => terminalEvents.push("response.completed"));
20432073
stream.on("response.failed", () => terminalEvents.push("response.failed"));
20442074

@@ -2051,8 +2081,12 @@ describe("OpenResponses HTTP API (e2e)", () => {
20512081
total_tokens: 18,
20522082
});
20532083
expect(terminalEvents).toEqual(["response.failed"]);
2084+
expect(content.join("")).toBe("partial answer");
20542085
expect(terminals).toEqual([
2055-
{ phase: producerTerminal ? expectedPhase : "error", status: "error" },
2086+
{
2087+
phase: producerTerminal ? expectedPhase : "error",
2088+
status: producerTerminal && meta.timeoutPhase ? "timeout" : "error",
2089+
},
20562090
]);
20572091
} finally {
20582092
unsubscribe();

‎src/gateway/openresponses-http.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { isClientToolNameConflictError } from "../agents/agent-tool-definition-a
1414
import type { ImageContent } from "../agents/command/types.js";
1515
import type { ClientToolDefinition } from "../agents/embedded-agent-runner/run/params.js";
1616
import { toOpenAiResponsesUsage } from "../agents/usage.js";
17+
import { readAgentRunTerminalOutcome } from "../channels/turn/agent-run-terminal-outcome.js";
1718
import { createDefaultDeps } from "../cli/deps.js";
1819
import type { CliDeps } from "../cli/deps.types.js";
1920
import { agentCommandFromGatewayIngress } from "../commands/agent.js";
@@ -82,7 +83,7 @@ import {
8283
type Usage,
8384
} from "./open-responses.schema.js";
8485
import { resolveAgentRunUsage } from "./openai-agent-run-usage.js";
85-
import { isFailedOpenAiAgentRun, resolveOpenAiCompatError } from "./openai-compat-errors.js";
86+
import { resolveOpenAiCompatError } from "./openai-compat-errors.js";
8687
import {
8788
isToolChoiceConstraintSatisfied,
8889
resolveUnsatisfiedToolChoiceMessage,
@@ -753,7 +754,7 @@ export async function handleOpenResponsesHttpRequest(
753754
}
754755

755756
const meta = (result as { meta?: { error?: unknown; stopReason?: unknown } } | null)?.meta;
756-
if (isFailedOpenAiAgentRun(result)) {
757+
if (readAgentRunTerminalOutcome(result) === "failed") {
757758
throw new Error("agent run failed");
758759
}
759760
const assistantText = resolveResponsePayloadText(result);
@@ -1182,7 +1183,7 @@ export async function handleOpenResponsesHttpRequest(
11821183
return;
11831184
}
11841185

1185-
if (isFailedOpenAiAgentRun(result)) {
1186+
if (readAgentRunTerminalOutcome(result) === "failed") {
11861187
terminalLifecyclePhase = "error";
11871188
rememberResponseSession();
11881189
finalizeFailedResponse(

0 commit comments

Comments
 (0)