Skip to content

Commit 324e97b

Browse files
committed
fix(agents): preserve provider ownership in error diagnostics
1 parent 4feff03 commit 324e97b

12 files changed

Lines changed: 185 additions & 44 deletions

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

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -162,11 +162,14 @@ export function buildApiErrorObservationFields(
162162
? redactIdentifier(rawFingerprint, { len: 12 })
163163
: undefined,
164164
httpCode: parsed?.httpCode,
165-
providerRuntimeFailureKind: classifyProviderRuntimeFailureKind({
166-
status: parsed?.httpCode ? Number(parsed.httpCode) : undefined,
167-
message: trimmed,
168-
provider: opts?.provider,
169-
}),
165+
providerRuntimeFailureKind: classifyProviderRuntimeFailureKind(
166+
{
167+
status: parsed?.httpCode ? Number(parsed.httpCode) : undefined,
168+
message: trimmed,
169+
provider: opts?.provider,
170+
},
171+
{ providerPlugin: null },
172+
),
170173
providerErrorType: parsed?.type,
171174
providerErrorMessagePreview: truncateForObservation(
172175
redactedProviderMessage,

‎src/agents/embedded-agent-helpers.formatassistanterrortext.test.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { sanitizeUserFacingText } from "./embedded-agent-helpers/sanitize-user-f
1414
import { renderUserFacingText } from "./embedded-agent-helpers/user-facing-text.js";
1515
import { isRawApiErrorPayload } from "./failover/user-copy.js";
1616
import { makeAssistantMessageFixture } from "./test-helpers/assistant-message-fixtures.js";
17+
import { withPreparedFailoverProviders } from "./test-helpers/provider-failover-generation.js";
1718

1819
describe("formatAssistantErrorText", () => {
1920
const BILLING_ERROR_USER_MESSAGE =
@@ -178,14 +179,16 @@ describe("formatAssistantErrorText", () => {
178179
errorType: "upstream_error",
179180
});
180181

181-
expect(classifyAssistantFailoverReason(msg, { provider: "openai" })).toBe("server_error");
182-
expect(
183-
classifyAssistantFailoverReason(
184-
makeAssistantError(
185-
'{"error":{"message":"Upstream request failed","type":"upstream_error","param":"","code":null}}',
182+
withPreparedFailoverProviders(["openai"], () => {
183+
expect(classifyAssistantFailoverReason(msg, { provider: "openai" })).toBe("server_error");
184+
expect(
185+
classifyAssistantFailoverReason(
186+
makeAssistantError(
187+
'{"error":{"message":"Upstream request failed","type":"upstream_error","param":"","code":null}}',
188+
),
186189
),
187-
),
188-
).toBe("server_error");
190+
).toBe("server_error");
191+
});
189192
});
190193
it("uses generic user-facing copy for escaped structured provider messages", () => {
191194
// The internal formatter keeps detail for logs, while user-facing text must
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import { classifyProviderFailoverSignalWithPlugin } from "../../plugins/provider-failover.js";
3+
import { buildApiErrorObservationFields } from "../embedded-agent-error-observation.js";
4+
import { classifyFailoverSignal, isContextOverflowError } from "../failover/classify.js";
5+
import { PROVIDER_SCHEMA_REJECTION_USER_TEXT } from "../failover/user-copy.js";
6+
import { makeAssistantMessageFixture } from "../test-helpers/assistant-message-fixtures.js";
7+
import { formatAssistantErrorText } from "./error-text.js";
8+
import { classifyProviderRuntimeFailureKind } from "./provider-runtime-failure.js";
9+
10+
vi.mock("../../plugins/provider-failover.js", () => ({
11+
classifyProviderFailoverSignalWithPlugin: vi.fn(),
12+
}));
13+
14+
describe("assistant diagnostic provider ownership", () => {
15+
beforeEach(() => {
16+
vi.mocked(classifyProviderFailoverSignalWithPlugin)
17+
.mockReset()
18+
.mockReturnValue("model_not_found");
19+
});
20+
21+
it.each(["provider sent an opaque failure", "prompt reached the tenant maximum"])(
22+
"renders %j without discovering provider policy",
23+
(errorMessage) => {
24+
expect(formatAssistantErrorText(makeAssistantMessageFixture({ errorMessage }))).toBe(
25+
errorMessage,
26+
);
27+
expect(classifyProviderFailoverSignalWithPlugin).not.toHaveBeenCalled();
28+
},
29+
);
30+
31+
it("keeps the prepared owner through schema diagnostics", () => {
32+
const classifyFailoverReason = vi.fn(() => "format" as const);
33+
expect(
34+
formatAssistantErrorText(
35+
makeAssistantMessageFixture({ errorMessage: "provider rejected this payload" }),
36+
{ providerOwner: { id: "synthetic-owner", classifyFailoverReason } },
37+
),
38+
).toBe(PROVIDER_SCHEMA_REJECTION_USER_TEXT);
39+
expect(classifyFailoverReason).toHaveBeenCalledWith(
40+
expect.objectContaining({ provider: "synthetic-owner" }),
41+
);
42+
expect(classifyProviderFailoverSignalWithPlugin).not.toHaveBeenCalled();
43+
});
44+
45+
it("keeps the prepared owner through context diagnostics", () => {
46+
expect(
47+
formatAssistantErrorText(
48+
makeAssistantMessageFixture({ errorMessage: "prompt reached the tenant maximum" }),
49+
{
50+
providerOwner: {
51+
id: "synthetic-owner",
52+
matchesContextOverflowError: () => true,
53+
},
54+
},
55+
),
56+
).toContain("Context overflow: prompt too large for the model.");
57+
expect(classifyProviderFailoverSignalWithPlugin).not.toHaveBeenCalled();
58+
});
59+
60+
it("records diagnostics without discovering provider policy", () => {
61+
expect(
62+
buildApiErrorObservationFields("provider sent an opaque failure", { provider: "openai" }),
63+
).toMatchObject({ providerRuntimeFailureKind: "unclassified" });
64+
expect(classifyProviderFailoverSignalWithPlugin).not.toHaveBeenCalled();
65+
});
66+
67+
it("preserves runtime discovery when no prepared owner is supplied", () => {
68+
expect(
69+
classifyFailoverSignal({ provider: "synthetic-owner", message: "opaque runtime failure" }),
70+
).toEqual({ kind: "reason", reason: "model_not_found" });
71+
expect(classifyProviderRuntimeFailureKind("opaque runtime failure")).toBe("model_not_found");
72+
vi.mocked(classifyProviderFailoverSignalWithPlugin).mockReturnValue("context_overflow");
73+
expect(isContextOverflowError("prompt reached the tenant maximum")).toBe(true);
74+
expect(classifyProviderFailoverSignalWithPlugin).toHaveBeenCalledTimes(3);
75+
});
76+
});

‎src/agents/embedded-agent-helpers/error-text.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,12 @@ export function formatAssistantErrorText(
8181
return formatCopy;
8282
}
8383
const providerOwner = opts?.providerOwner?.id ?? opts?.provider;
84-
const providerRuntimeFailureKind = classifyProviderRuntimeFailureKind({
85-
...buildAssistantFailoverSignal(msg, { provider: providerOwner }),
86-
message: raw,
87-
});
84+
// Rendering can reuse a prepared owner, but must not discover runtime plugins.
85+
const providerPlugin = opts?.providerOwner ?? null;
86+
const providerRuntimeFailureKind = classifyProviderRuntimeFailureKind(
87+
{ ...buildAssistantFailoverSignal(msg, { provider: providerOwner }), message: raw },
88+
{ providerPlugin },
89+
);
8890
const unknownTool =
8991
raw.match(/unknown tool[:\s]+["']?([a-z0-9_-]+)["']?/i) ??
9092
raw.match(/tool\s+["']?([a-z0-9_-]+)["']?\s+(?:not found|is not available)/i);
@@ -169,7 +171,7 @@ export function formatAssistantErrorText(
169171
if (providerRuntimeFailureKind === "model_not_found") {
170172
return MODEL_NOT_FOUND_USER_TEXT;
171173
}
172-
if (isContextOverflowError(raw)) {
174+
if (isContextOverflowError(raw, { providerPlugin })) {
173175
return (
174176
"Context overflow: prompt too large for the model. " +
175177
"Try /reset (or /new) to start a fresh session, or use a larger-context model."
@@ -224,7 +226,7 @@ export function formatAssistantErrorText(
224226

225227
const failoverReason = classifyFailoverReason(raw, {
226228
provider: providerOwner,
227-
providerPlugin: opts?.providerOwner,
229+
providerPlugin,
228230
});
229231
if (failoverReason === "billing") {
230232
return formatBillingErrorMessage(opts?.provider, opts?.model ?? msg.model, opts?.authMode);

‎src/agents/embedded-agent-helpers/provider-runtime-failure.test.ts‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,17 @@
1-
import { describe, expect, it, vi } from "vitest";
2-
// Classification fixtures here exercise message/status tables. Provider-attributed
3-
// structured signals otherwise cross the plugin-consult gate and cold-materialize
4-
// the full bundled provider runtime, timing the unit test out under CI load
5-
// (src/agents/CLAUDE.md: no full-runtime cold loads for table coverage).
6-
vi.mock("../../plugins/provider-hook-runtime.js", async (importOriginal) => {
7-
const actual = await importOriginal<typeof import("../../plugins/provider-hook-runtime.js")>();
8-
return {
9-
...actual,
10-
resolveProviderHookPlugin: () => undefined,
11-
resolveProviderPluginsForHooks: () => [],
12-
};
13-
});
14-
1+
import { aroundEach, describe, expect, it } from "vitest";
152
import {
163
classifyFailoverReason,
174
isFailoverErrorMessage,
185
isTimeoutErrorMessage,
196
} from "../failover/classify.js";
7+
import { withPreparedFailoverProviders } from "../test-helpers/provider-failover-generation.js";
208
import { classifyProviderRuntimeFailureKind } from "./provider-runtime-failure.js";
219

2210
describe("classifyProviderRuntimeFailureKind", () => {
11+
aroundEach((runTest) =>
12+
withPreparedFailoverProviders(["openai", "google", "anthropic"], runTest),
13+
);
14+
2315
it("classifies complete HTML after an HTTP reason phrase as upstream_html", () => {
2416
const raw = "HTTP 502 Bad Gateway\n\n<!doctype html><html><body>down</body></html>";
2517

‎src/agents/embedded-agent-helpers/provider-runtime-failure.ts‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
import { classifyFailoverReason, classifyFailoverSignal } from "../failover/classify.js";
1111
import { isContextOverflowErrorFromTables } from "../failover/context-overflow.js";
1212
import { matchesFormatErrorPattern, isTimeoutErrorMessage } from "../failover/message-patterns.js";
13+
import type { PreparedProviderFailoverOwner } from "../failover/provider-patterns.js";
1314
import type { FailoverSignal } from "../failover/signal.js";
1415
export type ProviderRuntimeFailureKind =
1516
| "auth_scope"
@@ -130,11 +131,15 @@ function isThinkingSignatureReplayInvalidErrorMessage(raw: string): boolean {
130131
function isSandboxBlockedErrorMessage(raw: string): boolean {
131132
return Boolean(formatExecDeniedUserMessage(raw)) || SANDBOX_BLOCKED_RE.test(raw);
132133
}
133-
function isSchemaErrorMessage(raw: string): boolean {
134+
function isSchemaErrorMessage(
135+
raw: string,
136+
opts?: { provider?: string; providerPlugin?: PreparedProviderFailoverOwner | null },
137+
): boolean {
134138
if (!raw || isReplayInvalidErrorMessage(raw) || isContextOverflowErrorFromTables(raw)) {
135139
return false;
136140
}
137-
return classifyFailoverReason(raw) === "format" || matchesFormatErrorPattern(raw);
141+
// Schema copy requires message evidence, not a generic HTTP 400 classification.
142+
return classifyFailoverReason(raw, opts) === "format" || matchesFormatErrorPattern(raw);
138143
}
139144
function isTimeoutTransportErrorMessage(raw: string, status?: number): boolean {
140145
if (!raw) {
@@ -169,6 +174,7 @@ function isOAuthCallbackValidationMessage(raw: string): boolean {
169174
}
170175
export function classifyProviderRuntimeFailureKind(
171176
signal: FailoverSignal | string,
177+
opts?: { providerPlugin?: PreparedProviderFailoverOwner | null },
172178
): ProviderRuntimeFailureKind {
173179
const normalizedSignal = typeof signal === "string" ? { message: signal } : signal;
174180
const message = normalizedSignal.message?.trim() ?? "";
@@ -211,11 +217,10 @@ export function classifyProviderRuntimeFailureKind(
211217
}
212218
return status === 401 || status === 403 ? "auth_html" : "upstream_html";
213219
}
214-
const failoverClassification = classifyFailoverSignal({
215-
...normalizedSignal,
216-
status,
217-
message: message || undefined,
218-
});
220+
const failoverClassification = classifyFailoverSignal(
221+
{ ...normalizedSignal, status, message: message || undefined },
222+
opts,
223+
);
219224
const failoverReason =
220225
failoverClassification?.kind === "reason" ? failoverClassification.reason : undefined;
221226
switch (failoverReason) {
@@ -235,7 +240,7 @@ export function classifyProviderRuntimeFailureKind(
235240
if (message && isReplayInvalidErrorMessage(message)) {
236241
return "replay_invalid";
237242
}
238-
if (message && isSchemaErrorMessage(message)) {
243+
if (message && isSchemaErrorMessage(message, { ...opts, provider: normalizedSignal.provider })) {
239244
return "schema";
240245
}
241246
// Plain HTTP 401 / invalid-token replies should be safe chat copy, but the

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,7 @@ export function handleAgentEnd(
150150
const rawError = lastAssistant.errorMessage?.trim();
151151
const failoverReason = classifyFailoverReason(rawError ?? "", {
152152
provider: lastAssistant.provider,
153+
providerPlugin: null,
153154
});
154155
const errorText = formatUserFacingAssistantErrorText(lastAssistant, {
155156
cfg: ctx.params.config,

‎src/agents/failover/context-overflow.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import {
88
import {
99
classifyProviderPluginError,
1010
looksLikeProviderContextOverflowCandidate,
11+
type PreparedProviderFailoverOwner,
1112
} from "./provider-patterns.js";
1213

1314
export function isReasoningConstraintErrorMessage(raw: string): boolean {
@@ -49,14 +50,18 @@ export function isContextOverflowErrorFromTables(errorMessage?: string): boolean
4950
);
5051
}
5152

52-
export function isContextOverflowError(errorMessage?: string): boolean {
53+
export function isContextOverflowError(
54+
errorMessage?: string,
55+
opts?: { providerPlugin?: PreparedProviderFailoverOwner | null },
56+
): boolean {
5357
if (!errorMessage) {
5458
return false;
5559
}
5660
return (
5761
isContextOverflowErrorFromTables(errorMessage) ||
5862
(looksLikeProviderContextOverflowCandidate(errorMessage) &&
59-
classifyProviderPluginError({ errorMessage }) === "context_overflow")
63+
classifyProviderPluginError({ errorMessage, providerPlugin: opts?.providerPlugin }) ===
64+
"context_overflow")
6065
);
6166
}
6267

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import {
2+
createPluginMetadataSnapshot,
3+
makeRegistry,
4+
} from "../../config/plugin-auto-enable.test-helpers.js";
5+
import { createEmptyPluginRegistry } from "../../plugins/registry-empty.js";
6+
import { withPluginRuntimeGenerationScope } from "../../plugins/runtime/generation-scope.js";
7+
8+
/** Runs core classifier fixtures with the provider generation prepared by agent runs. */
9+
export function withPreparedFailoverProviders<T>(providerIds: string[], run: () => T): T {
10+
const pluginRegistry = createEmptyPluginRegistry();
11+
for (const id of providerIds) {
12+
pluginRegistry.providers.push({
13+
pluginId: id,
14+
source: "test",
15+
provider: { id, label: id, auth: [], classifyFailoverReason: () => undefined },
16+
});
17+
}
18+
return withPluginRuntimeGenerationScope(
19+
{
20+
config: {},
21+
metadataSnapshot: createPluginMetadataSnapshot({
22+
manifestRegistry: makeRegistry(
23+
providerIds.map((id) => ({ id, channels: [], providers: [id] })),
24+
),
25+
}),
26+
pluginRegistry,
27+
},
28+
run,
29+
);
30+
}

‎src/gateway/chat-display-projection.core.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,10 @@ function isContextOverflowErrorSignal(value: unknown): boolean {
118118
if (typeof value !== "string") {
119119
return false;
120120
}
121-
return normalizeErrorSignal(value) === "context_overflow" || isContextOverflowError(value);
121+
return (
122+
normalizeErrorSignal(value) === "context_overflow" ||
123+
isContextOverflowError(value, { providerPlugin: null })
124+
);
122125
}
123126

124127
function isContextOverflowAssistantError(message: Record<string, unknown>): boolean {

0 commit comments

Comments
 (0)