Skip to content

Commit 59f57a9

Browse files
committed
fix(gateway): preserve provider details on chat error events
Expose a closed, bounded errorDetail object from sanitized provider observations. Preserve the observation through direct and deferred terminal ownership, and redact provider error types at the observation boundary. Project before lifecycle publication as well as chat delivery so raw bodies, previews, and hashes stay out of both event streams. Document the additive protocol-v4 field and cover schema bounds, redaction, clean runs, retry cleanup, and lifecycle-to-gateway delivery. Discovery source: NetEase Youdao's LobsterAI patch stack (https://github.com/netease-youdao/LobsterAI). The arbitrary-key payload spreading mechanism was not adopted.
1 parent 2e3cae2 commit 59f57a9

13 files changed

Lines changed: 341 additions & 7 deletions

‎docs/gateway/protocol.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -824,6 +824,17 @@ count.
824824
events. In protocol v4, delta payloads carry `deltaText`; `message` remains
825825
the cumulative assistant snapshot. Non-prefix replacements set
826826
`replace=true` and use `deltaText` as the replacement text.
827+
Failed runs (`state: "error"`) may include `errorDetail` alongside the coarse
828+
`errorKind` and human-readable `errorMessage`. This closed object has seven
829+
optional fields: `provider`, `model`, `failoverReason`,
830+
`providerRuntimeFailureKind`, `providerErrorType`, `httpStatus`, and
831+
`providerErrorMessagePreview`. Strings are capped at 300 characters; `httpStatus`
832+
is an integer from 100 through 599. Details come from the failed attempt's
833+
sanitized provider observation, not from reparsing the user-facing message.
834+
The preview is credential-redacted and may be shorter than the protocol cap.
835+
Raw bodies, raw previews, and diagnostic hashes are never included in
836+
`errorDetail`. Runs without provider observations omit it; successful and
837+
canceled events do not carry it. This is an additive protocol-v4 field.
827838
- `session.message`, `session.operation`, `session.tool`: transcript, in-flight
828839
session operation, and event-stream updates for a subscribed session.
829840
- `session.approval`: sanitized pending and terminal approval truth for an

‎packages/gateway-protocol/src/schema/logs-chat.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,58 @@ describe("ChatStatusEventSchema", () => {
8484
});
8585
});
8686

87+
describe("ChatErrorEventSchema", () => {
88+
const event = { runId: "run-1", sessionKey: "agent:main:main", seq: 1, state: "error" };
89+
const detail = {
90+
provider: "openai",
91+
model: "gpt-5.6-luna",
92+
failoverReason: "server_error",
93+
providerRuntimeFailureKind: "timeout",
94+
providerErrorType: "server_error",
95+
httpStatus: 502,
96+
providerErrorMessagePreview: "Upstream unavailable",
97+
};
98+
99+
it("round-trips optional closed provider error details", () => {
100+
for (const errorDetail of [
101+
undefined,
102+
{},
103+
...Object.entries(detail).map(([key, value]) => ({ [key]: value })),
104+
detail,
105+
]) {
106+
const serialized = JSON.stringify({ ...event, errorDetail });
107+
const wire = JSON.parse(serialized);
108+
expect(Value.Check(ChatEventSchema, wire)).toBe(true);
109+
}
110+
expect(
111+
Value.Check(ChatEventSchema, {
112+
...event,
113+
errorDetail: { ...detail, rawErrorPreview: "raw" },
114+
}),
115+
).toBe(false);
116+
expect(Value.Check(ChatEventSchema, { ...event, state: "final", errorDetail: detail })).toBe(
117+
false,
118+
);
119+
});
120+
121+
it("enforces string and HTTP status bounds", () => {
122+
for (const key of Object.keys(detail).filter((field) => field !== "httpStatus")) {
123+
expect(
124+
Value.Check(ChatEventSchema, { ...event, errorDetail: { [key]: "x".repeat(300) } }),
125+
).toBe(true);
126+
expect(
127+
Value.Check(ChatEventSchema, { ...event, errorDetail: { [key]: "x".repeat(301) } }),
128+
).toBe(false);
129+
}
130+
for (const httpStatus of [100, 599]) {
131+
expect(Value.Check(ChatEventSchema, { ...event, errorDetail: { httpStatus } })).toBe(true);
132+
}
133+
for (const httpStatus of [99, 600, 502.5, "502"]) {
134+
expect(Value.Check(ChatEventSchema, { ...event, errorDetail: { httpStatus } })).toBe(false);
135+
}
136+
});
137+
});
138+
87139
describe("ChatSendParamsSchema", () => {
88140
const send = {
89141
sessionKey: "agent:main:main",

‎packages/gateway-protocol/src/schema/logs-chat.ts‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
// Gateway Protocol schema module defines protocol validation shapes.
2+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
3+
import { truncateUtf16Safe } from "@openclaw/normalization-core/utf16-slice";
24
import type { Static } from "typebox";
35
import { Type } from "typebox";
46
import {
@@ -332,13 +334,61 @@ export const ChatAbortedEventSchema = closedObject({
332334
stopReason: Type.Optional(Type.String()),
333335
});
334336

335-
/** Terminal event for failed chat runs with an optional normalized failure kind. */
337+
const CHAT_ERROR_DETAIL_MAX_CHARS = 300;
338+
const ChatErrorDetailTextSchema = Type.Optional(
339+
Type.String({ maxLength: CHAT_ERROR_DETAIL_MAX_CHARS }),
340+
);
341+
const ChatErrorDetailSchema = closedObject({
342+
provider: ChatErrorDetailTextSchema,
343+
model: ChatErrorDetailTextSchema,
344+
failoverReason: ChatErrorDetailTextSchema,
345+
providerRuntimeFailureKind: ChatErrorDetailTextSchema,
346+
providerErrorType: ChatErrorDetailTextSchema,
347+
httpStatus: Type.Optional(Type.Integer({ minimum: 100, maximum: 599 })),
348+
providerErrorMessagePreview: ChatErrorDetailTextSchema,
349+
});
350+
351+
type ChatErrorDetail = Static<typeof ChatErrorDetailSchema>;
352+
353+
/** Bounds already-redacted provider facts before lifecycle and chat publication. */
354+
export function projectChatErrorDetail(observation: unknown): ChatErrorDetail | undefined {
355+
const source = asOptionalRecord(observation);
356+
if (!source) {
357+
return undefined;
358+
}
359+
const readText = (value: unknown) =>
360+
typeof value === "string" && value.trim()
361+
? truncateUtf16Safe(value.trim(), CHAT_ERROR_DETAIL_MAX_CHARS)
362+
: undefined;
363+
const httpStatus = typeof source.httpStatus === "number" ? source.httpStatus : undefined;
364+
// Only the observation owner's redacted facts cross this boundary; raw previews,
365+
// bodies, and correlation hashes remain outside the closed chat contract.
366+
const detail: ChatErrorDetail = {
367+
provider: readText(source.provider),
368+
model: readText(source.model),
369+
failoverReason: readText(source.failoverReason),
370+
providerRuntimeFailureKind: readText(source.providerRuntimeFailureKind),
371+
providerErrorType: readText(source.providerErrorType),
372+
httpStatus:
373+
httpStatus !== undefined &&
374+
Number.isInteger(httpStatus) &&
375+
httpStatus >= 100 &&
376+
httpStatus <= 599
377+
? httpStatus
378+
: undefined,
379+
providerErrorMessagePreview: readText(source.providerErrorMessagePreview),
380+
};
381+
return Object.values(detail).some((value) => value !== undefined) ? detail : undefined;
382+
}
383+
384+
/** Terminal event for failed chat runs with optional sanitized provider diagnostics. */
336385
export const ChatErrorEventSchema = closedObject({
337386
...ChatEventBaseSchema,
338387
state: Type.Literal("error"),
339388
message: Type.Optional(Type.Unknown()),
340389
errorMessage: Type.Optional(Type.String()),
341390
errorKind: Type.Optional(ChatEventErrorKindSchema),
391+
errorDetail: Type.Optional(ChatErrorDetailSchema),
342392
usage: Type.Optional(Type.Unknown()),
343393
stopReason: Type.Optional(Type.String()),
344394
});

‎src/agents/command/attempt-callbacks.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ describe("createAgentAttemptLifecycleCallbacks", () => {
6363
const state: AgentAttemptLifecycleState = {
6464
currentTurnUserMessagePersisted: true,
6565
lifecycleError: "provider failed",
66+
lifecycleErrorObservation: { provider: "openai", httpStatus: 502 },
6667
lifecycleFinishing: true,
6768
lifecycleEnded: false,
6869
};
@@ -73,6 +74,7 @@ describe("createAgentAttemptLifecycleCallbacks", () => {
7374
expect(state).toEqual({
7475
currentTurnUserMessagePersisted: true,
7576
lifecycleError: undefined,
77+
lifecycleErrorObservation: undefined,
7678
lifecycleFinishing: false,
7779
lifecycleEnded: false,
7880
});

‎src/agents/command/attempt-callbacks.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
/**
22
* Lifecycle callback state helpers for a single agent attempt.
33
*/
4+
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
45
import type { AgentMessage } from "../runtime/index.js";
56

67
/** Mutable lifecycle flags observed while a single agent attempt runs. */
78
export type AgentAttemptLifecycleState = {
89
currentTurnUserMessagePersisted: boolean;
910
lifecycleError?: string;
11+
lifecycleErrorObservation?: Record<string, unknown>;
1012
lifecycleFinishing: boolean;
1113
lifecycleEnded: boolean;
1214
};
@@ -38,12 +40,14 @@ export function createAgentAttemptLifecycleCallbacks(
3840
// A same-candidate retry replaces deferred terminal state from the
3941
// preceding attempt; retaining it would abort a recovered run.
4042
state.lifecycleError = undefined;
43+
state.lifecycleErrorObservation = undefined;
4144
state.lifecycleFinishing = false;
4245
state.lifecycleEnded = false;
4346
return onRuntimeTurnStarted?.();
4447
}
4548
if (typeof evt.data.error === "string" && evt.data.error.trim()) {
4649
state.lifecycleError = evt.data.error;
50+
state.lifecycleErrorObservation = asOptionalRecord(evt.data.errorObservation);
4751
}
4852
// Finishing means output ended but transcript/session persistence may still
4953
// need to run; end/error means the runtime lifecycle is complete.

‎src/agents/command/lifecycle.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ export function createAgentCommandLifecycle(params: {
9494
...(timeoutPhase ? { timeoutPhase } : {}),
9595
...(providerStarted !== undefined ? { providerStarted } : {}),
9696
...(error ? { error: formatErrorMessage(error) } : {}),
97+
...(error && params.state.lifecycleErrorObservation
98+
? { errorObservation: params.state.lifecycleErrorObservation }
99+
: {}),
97100
...(fallbackExhausted ? { fallbackExhaustedFailure: true } : {}),
98101
...(terminalDelivery ? { terminalDelivery } : {}),
99102
...(terminalReceipt ? { terminalReceipt } : {}),
@@ -120,6 +123,9 @@ export function createAgentCommandLifecycle(params: {
120123
startedAt: params.startedAt,
121124
endedAt: Date.now(),
122125
error: formatLifecycleError(error),
126+
...(params.state.lifecycleErrorObservation
127+
? { errorObservation: params.state.lifecycleErrorObservation }
128+
: {}),
123129
...extraData,
124130
},
125131
});

‎src/agents/embedded-agent-error-observation.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,15 @@ describe("buildApiErrorObservationFields", () => {
5353
expect(observed.rawErrorPreview).toContain("Cookie: session=");
5454
});
5555

56+
it("redacts provider error types as well as message previews", () => {
57+
const observed = buildApiErrorObservationFields(
58+
JSON.stringify({
59+
error: { type: `x-api-key: ${OBSERVATION_BEARER_TOKEN}`, message: "Request failed" },
60+
}),
61+
);
62+
expect(observed.providerErrorType).toBe("x-api-key: ***");
63+
});
64+
5665
it("does not let cookie redaction consume unrelated fields on the same line", () => {
5766
const observed = buildApiErrorObservationFields(
5867
`Cookie: session=${OBSERVATION_COOKIE_VALUE} status=503 request_id=req_cookie`,

‎src/agents/embedded-agent-error-observation.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ export function buildApiErrorObservationFields(
171171
},
172172
{ providerPlugin: opts?.providerOwner ?? null },
173173
),
174-
providerErrorType: parsed?.type,
174+
providerErrorType: redactObservationText(parsed?.type),
175175
providerErrorMessagePreview: truncateForObservation(
176176
redactedProviderMessage,
177177
PROVIDER_ERROR_PREVIEW_MAX_CHARS,

‎src/agents/embedded-agent-subscribe.handlers.lifecycle.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -254,20 +254,22 @@ describe("handleAgentEnd", () => {
254254
expect(meta.error).toBe("LLM request failed.");
255255
const userFacingLifecycleText = JSON.stringify(onAgentEvent.mock.calls);
256256
expect(userFacingLifecycleText).not.toContain("SECRET_CANARY_69737");
257+
expect(userFacingLifecycleText).not.toContain("rawError");
257258
expect(userFacingLifecycleText).toContain("LLM request failed.");
258259
expect(onAgentEvent).toHaveBeenCalledWith({
259260
stream: "lifecycle",
260261
data: {
261262
phase: "error",
262263
error: "LLM request failed.",
264+
errorObservation: expect.objectContaining({ providerRuntimeFailureKind: "unclassified" }),
263265
},
264266
});
265267
});
266268

267-
it("suppresses structured provider error messages in user-facing lifecycle events", async () => {
269+
it("publishes only redacted structured provider previews in lifecycle events", async () => {
268270
const onAgentEvent = vi.fn();
269271
const rawError =
270-
'{"type":"error","error":{"type":"server_error","message":"SECRET_CANARY_69737"}}';
272+
'{"type":"error","error":{"type":"server_error","message":"Upstream failed x-api-key: SECRET_CANARY_69737"}}';
271273
const ctx = createContext(
272274
{
273275
role: "assistant",
@@ -287,12 +289,17 @@ describe("handleAgentEnd", () => {
287289
expect(meta.error).toBe(expectedError);
288290
const userFacingLifecycleText = JSON.stringify(onAgentEvent.mock.calls);
289291
expect(userFacingLifecycleText).not.toContain("SECRET_CANARY_69737");
292+
expect(userFacingLifecycleText).not.toContain("rawError");
290293
expect(userFacingLifecycleText).not.toContain("LLM error server_error");
291294
expect(onAgentEvent).toHaveBeenCalledWith({
292295
stream: "lifecycle",
293296
data: {
294297
phase: "error",
295298
error: expectedError,
299+
errorObservation: expect.objectContaining({
300+
providerErrorType: "server_error",
301+
providerErrorMessagePreview: "Upstream failed x-api-key: ***",
302+
}),
296303
},
297304
});
298305
});
@@ -324,6 +331,7 @@ describe("handleAgentEnd", () => {
324331
data: {
325332
phase: "error",
326333
error: "LLM request failed: connection refused by the provider endpoint.",
334+
errorObservation: expect.objectContaining({ providerRuntimeFailureKind: "timeout" }),
327335
livenessState: "blocked",
328336
},
329337
});
@@ -549,6 +557,7 @@ describe("handleAgentEnd", () => {
549557
data: {
550558
phase: "error",
551559
error: "LLM request failed.",
560+
errorObservation: expect.objectContaining({ providerRuntimeFailureKind: "unclassified" }),
552561
},
553562
});
554563
});
@@ -1238,6 +1247,7 @@ describe("handleAgentEnd", () => {
12381247
data: {
12391248
phase: "error",
12401249
error: "LLM request failed: connection refused by the provider endpoint.",
1250+
errorObservation: expect.objectContaining({ providerRuntimeFailureKind: "timeout" }),
12411251
},
12421252
});
12431253
});

‎src/agents/embedded-agent-subscribe.handlers.lifecycle.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* Handles lifecycle and compaction events from subscribed embedded-agent sessions.
33
*/
44
import { isPromiseLike } from "@openclaw/normalization-core/promise-like";
5+
import { projectChatErrorDetail } from "../../packages/gateway-protocol/src/schema/logs-chat.js";
56
import { createInlineCodeState } from "../../packages/markdown-core/src/code-spans.js";
67
import { emitAgentEvent } from "../infra/agent-events.js";
78
import { hasAcceptedSessionSpawn } from "./accepted-session-spawn.js";
@@ -69,6 +70,7 @@ export function handleAgentEnd(
6970
const lastAssistant = ctx.state.lastAssistant;
7071
const isError = isAssistantMessage(lastAssistant) && lastAssistant.stopReason === "error";
7172
let lifecycleErrorText: string | undefined;
73+
let errorObservation: ReturnType<typeof projectChatErrorDetail>;
7274
// Terminal delivery does not depend on streamed text alone: when the streamed
7375
// assistant texts are empty, payload building falls back to the completed
7476
// assistant message's visible text, so such a turn still reaches the user.
@@ -168,6 +170,14 @@ export function handleAgentEnd(
168170
provider: lastAssistant.provider,
169171
}).textPreview ?? GENERIC_ASSISTANT_ERROR_TEXT;
170172
lifecycleErrorText = safeErrorText;
173+
// Lifecycle events also reach clients, so log-only diagnostics must not leave here.
174+
errorObservation = projectChatErrorDetail({
175+
provider: lastAssistant.provider,
176+
model: lastAssistant.model,
177+
failoverReason,
178+
...observedError,
179+
httpStatus: observedError.httpCode ? Number(observedError.httpCode) : undefined,
180+
});
171181
const safeRunId = sanitizeForConsole(ctx.params.runId) ?? "-";
172182
const safeModel = sanitizeForConsole(lastAssistant.model) ?? "unknown";
173183
const safeProvider = sanitizeForConsole(lastAssistant.provider) ?? "unknown";
@@ -209,6 +219,7 @@ export function handleAgentEnd(
209219
? summarizeToolValidationError(ctx.state.lastToolError)
210220
: undefined;
211221
const terminalMeta = {
222+
...(errorObservation ? { errorObservation } : {}),
212223
...(terminalStopReason ? { stopReason: terminalStopReason } : {}),
213224
...(ctx.state.yielded === true ? { yielded: true } : {}),
214225
...(ctx.state.timeoutPhase ? { timeoutPhase: ctx.state.timeoutPhase } : {}),

0 commit comments

Comments
 (0)