Skip to content

armgit / pibot

Public Imported from GitHub
0

Open-source, local-first AI agent team for your desktop: multi-agent group chats, computer use, browser, MCP, routines and approvals. macOS, Windows, Linux + Android. Built on pi.

fix(chat): keep the upstream provider failure reason in the local chat hint (#6)

JQuerydff7db4a7938
diff --git a/apps/desktop/src/renderer/features/chat/chat.module.css b/apps/desktop/src/renderer/features/chat/chat.module.css
index 9469e05..cea34e1 100644
--- a/apps/desktop/src/renderer/features/chat/chat.module.css
+++ b/apps/desktop/src/renderer/features/chat/chat.module.css
@@ -664,6 +664,7 @@
max-width: 100%;
}
.error p {
+ overflow-wrap: anywhere;
color: var(--danger);
margin: 0 0 10px;
}
diff --git a/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx b/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx
index b85e242..ef95599 100644
--- a/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx
+++ b/apps/desktop/src/renderer/features/chat/messages/ChatMessage.tsx
@@ -1,6 +1,7 @@
import {
interruptedMessage,
messageBubbleText,
+ providerFailureText,
silentWake,
type ToolPaths,
} from "@pibot/client-core";
@@ -234,6 +235,7 @@ export const ChatMessage = memo(function ChatMessage({
!Array.isArray(message.usage) &&
message.usage.imageGeneration === true;
const failureCode = messageFailureCode(message);
+ const providerFailure = failureCode && providerFailureText(message, t);
const failed = !!failureCode;
const interrupted = interruptedMessage(message);
const waiting = activity?.approvals.some(
@@ -445,6 +447,7 @@ export const ChatMessage = memo(function ChatMessage({
: `errors.${failureCode ?? "internal"}`,
)}
</p>
+ {providerFailure && <p className={styles.notice}>{providerFailure}</p>}
{agentFacts?.errorDetail && (
<p className={styles.notice}>
{t("externalAgents.errors.agentSaid", {
diff --git a/apps/mobile/src/features/chat/messages/MessageItem.tsx b/apps/mobile/src/features/chat/messages/MessageItem.tsx
index d15e323..b2d81de 100644
--- a/apps/mobile/src/features/chat/messages/MessageItem.tsx
+++ b/apps/mobile/src/features/chat/messages/MessageItem.tsx
@@ -2,6 +2,7 @@ import {
interruptedMessage,
type LiveRunActivity,
messageBubbleText,
+ providerFailureText,
replyCitationText,
routineNoticeText,
silentWake,
@@ -205,6 +206,7 @@ function MessageBody({
}
const failed = message.role === "error" || message.status === "error";
const streaming = message.status === "streaming";
+ const providerFailure = failed && providerFailureText(message, shared);
return (
<BotRow
look={look}
@@ -225,6 +227,11 @@ function MessageBody({
<Text style={[type.body, { color: colors.danger }]}>
{failureText(message.errorCode, t, shared)}
</Text>
+ {providerFailure && (
+ <Text selectable style={[type.small, { color: colors.danger }]}>
+ {providerFailure}
+ </Text>
+ )}
</View>
{onRetry && <Button icon="refresh" title={t("retryFrom")} onPress={onRetry} />}
</>
diff --git a/packages/agent/src/core/errors.ts b/packages/agent/src/core/errors.ts
index 2e91500..25400dd 100644
--- a/packages/agent/src/core/errors.ts
+++ b/packages/agent/src/core/errors.ts
@@ -1,9 +1,11 @@
+import { readProviderError } from "./provider-response-error.ts";
import type { AgentErrorCode } from "./types.ts";
export class AgentError extends Error {
constructor(
readonly code: AgentErrorCode,
readonly httpStatus?: number,
+ readonly providerDetail?: string,
) {
// Never expose raw SDK diagnostics: they can contain keys, headers or response bodies.
super(code);
@@ -28,11 +30,16 @@ export function transientRequestError(
}
export function agentHttpStatus(err: unknown): number | undefined {
+ if (err instanceof AgentError) return err.httpStatus;
const seen = new Set<unknown>();
function extract(value: unknown): number | undefined {
if (typeof value === "string") {
- // pi flattens HTTP errors into messages; retain only the numeric status for diagnostics.
- const match = /\b([45]\d\d)\b/.exec(value);
+ const parsed = readProviderError(value);
+ if (parsed.status !== undefined) return parsed.status;
+ // Fixed Pi Bot errors also carry trailing "HTTP 503"; numbers in arbitrary prose are not statuses.
+ const match = /\b(?:HTTP(?:\/\d(?:\.\d)?)?|status(?: code)?)\s*[:=]?\s*([45]\d\d)\b/i.exec(
+ parsed.message?.split("\n", 1)[0] ?? "",
+ );
return match ? Number(match[1]) : undefined;
}
if (!value || typeof value !== "object" || seen.has(value)) return undefined;
@@ -76,7 +83,7 @@ export function providerModelLimit(
return maxTokens >= 256 && maxTokens < current ? { maxTokens } : undefined;
}
-export function mapAgentError(err: unknown): AgentErrorCode {
+export function mapAgentError(err: unknown, responseStatus?: number): AgentErrorCode {
if (err instanceof AgentError) return err.code;
const seen = new Set<unknown>();
function classify(value: unknown): AgentErrorCode {
@@ -91,7 +98,7 @@ export function mapAgentError(err: unknown): AgentErrorCode {
message?: string;
cause?: unknown;
};
- const status = agentHttpStatus(item);
+ const status = responseStatus ?? agentHttpStatus(item);
const message = typeof item.message === "string" ? item.message : "";
if (message === "subscription_unsupported") return "subscription_unsupported";
if (message.includes("claude_subscription_unsupported"))
@@ -124,7 +131,7 @@ export function mapAgentError(err: unknown): AgentErrorCode {
if (
status === 401 ||
status === 403 ||
- /\b(?:401|403|unauthorized|forbidden)\b|invalid.{0,10}(?:api.?key|authentication)|no api key|authentication failed/i.test(
+ /\b(?:unauthorized|forbidden)\b|invalid.{0,10}(?:api.?key|authentication)|no api key|authentication failed/i.test(
message,
)
)
@@ -138,8 +145,11 @@ export function mapAgentError(err: unknown): AgentErrorCode {
return "quota_exhausted";
const caused = item.cause ? classify(item.cause) : "internal";
if (caused === "quota_exhausted") return caused;
- if (status === 429 || /\b429\b|rate.?limit|too many requests/i.test(message))
- return "rate_limited";
+ if (status === 429 || /rate.?limit|too many requests/i.test(message)) return "rate_limited";
+ if (/context.*(?:length|window|exceed|overflow)|maximum.*tokens/i.test(message))
+ return "context_overflow";
+ // A rejected field can be named "network" or contain "service unavailable".
+ if (status === 400 || status === 404 || status === 422) return "provider_rejected";
if (
/^(?:E(?:CONNREFUSED|CONNRESET|NETUNREACH|HOSTUNREACH|NOTFOUND|AI_AGAIN|TIMEDOUT)|UND_ERR_(?:CONNECT_TIMEOUT|SOCKET))$/.test(
item.code ?? "",
@@ -150,30 +160,19 @@ export function mapAgentError(err: unknown): AgentErrorCode {
)
)
return "network";
- if (/context.*(?:length|window|exceed|overflow)|maximum.*tokens/i.test(message))
- return "context_overflow";
// Split what the user can act on: wait / switch model (overloaded) vs. fix the request
// (rejected); everything else from the provider stays provider_error.
if (
status === 529 ||
status === 503 ||
- /\b(?:529|503)\b|overloaded|over capacity|temporarily unavailable|service unavailable/i.test(
- message,
- )
+ /overloaded|over capacity|temporarily unavailable|service unavailable/i.test(message)
)
return "provider_overloaded";
- if (
- status === 400 ||
- status === 404 ||
- status === 422 ||
- /\b(?:400|404|422)\b|invalid.request|model.*not found|unsupported (?:parameter|model)/i.test(
- message,
- )
- )
+ if (/invalid.request|model.*not found|unsupported (?:parameter|model)/i.test(message))
return "provider_rejected";
if (
(status !== undefined && status >= 400) ||
- /\b(?:[45]\d\d)\b|provider error|context.*(?:length|window|exceed)/i.test(message)
+ /provider error|context.*(?:length|window|exceed)/i.test(message)
)
return "provider_error";
return caused;
diff --git a/packages/agent/src/core/provider-response-error.ts b/packages/agent/src/core/provider-response-error.ts
new file mode 100644
index 0000000..a3e1c73
--- /dev/null
+++ b/packages/agent/src/core/provider-response-error.ts
@@ -0,0 +1,50 @@
+import { z } from "zod";
+
+const bodyError = z.object({
+ message: z.string().optional(),
+ // Validation gateways may return errors per field. Only the explanation is public input
+ // to the redactor; the same object can also contain the rejected field value.
+ detail: z
+ .union([z.string(), z.array(z.object({ msg: z.string() }))])
+ .optional()
+ .catch(undefined),
+ code: z.unknown().optional(),
+});
+const errorBody = z.union([z.object({ error: bodyError }), bodyError]);
+
+/** pi flattens non-2xx responses before the session sees them. Responses may include
+ * the same HTTP status twice, once from pi and once from the OpenAI SDK. */
+export function readProviderError(text: string): { status?: number; message?: string } {
+ const trimmed = text.trim();
+ const provider = /^[^\n({]{1,160}\berror\s*\(([45]\d\d)\)\s*:\s*/i.exec(trimmed);
+ const rest = trimmed.slice(provider?.[0].length ?? 0);
+ const http = /^(?:HTTP(?:\/\d(?:\.\d)?)?\s+([1-5]\d\d)|([45]\d\d))\b[\s:]*/i.exec(rest);
+ const httpCode = http?.[1] ?? http?.[2];
+ const code = provider?.[1] ?? httpCode;
+ const status = code === undefined ? undefined : Number(code);
+ const body = http && code === httpCode ? rest.slice(http[0].length) : rest;
+ if (!body.startsWith("{")) return { status, message: body };
+
+ // OpenRouter can append raw metadata on a new line after a complete JSON body.
+ const firstLine = body.split("\n", 1)[0]?.trimEnd() ?? "";
+ const json = firstLine.endsWith("}") ? firstLine : body;
+ if (json.length > 16_384) return { status };
+ try {
+ const parsed = errorBody.safeParse(JSON.parse(json));
+ if (!parsed.success) return { status };
+ const error = "error" in parsed.data ? parsed.data.error : parsed.data;
+ const code = error.code;
+ return {
+ status:
+ status ??
+ (typeof code === "number" && Number.isInteger(code) && code >= 400 && code <= 599
+ ? code
+ : undefined),
+ message:
+ error.message ?? (typeof error.detail === "string" ? error.detail : error.detail?.[0]?.msg),
+ };
+ } catch {
+ // A truncated JSON body has no reliably separable fields.
+ return { status };
+ }
+}
diff --git a/packages/agent/src/core/types.ts b/packages/agent/src/core/types.ts
index 3adb3e5..2cad140 100644
--- a/packages/agent/src/core/types.ts
+++ b/packages/agent/src/core/types.ts
@@ -29,6 +29,8 @@ export interface ProviderCatalogEntry {
}
export interface OpenSessionOptions {
+ /** Supplied after the host has loaded its registered secrets. */
+ redactProviderDetail?(text: string): string;
retryBoundary?: {
messageId: string;
record(entryId: string, sessionFile: string, messageId?: string): void;
diff --git a/packages/agent/src/runtime/provider-diagnostic.ts b/packages/agent/src/runtime/provider-diagnostic.ts
new file mode 100644
index 0000000..85ebc4c
--- /dev/null
+++ b/packages/agent/src/runtime/provider-diagnostic.ts
@@ -0,0 +1,14 @@
+import { readProviderError } from "../core/provider-response-error.ts";
+
+/** Only the local chat failure hint receives the redacted first line. */
+export function providerDetail(error: unknown, redact: (text: string) => string) {
+ const raw = error instanceof Error ? error.message : error;
+ if (typeof raw !== "string") return;
+ const { message } = readProviderError(raw);
+ if (!message) return;
+ const line = redact(message)
+ .split(/[\r\n\p{Zl}\p{Zp}]/u, 1)[0]
+ ?.trim();
+ if (!line) return;
+ return line.length <= 300 ? line : `${line.slice(0, 299).replace(/[\uD800-\uDBFF]$/u, "")}…`;
+}
diff --git a/packages/agent/src/runtime/retry-stream.ts b/packages/agent/src/runtime/retry-stream.ts
index af5bc2d..b9dfabd 100644
--- a/packages/agent/src/runtime/retry-stream.ts
+++ b/packages/agent/src/runtime/retry-stream.ts
@@ -51,13 +51,17 @@ function keptReply(message: AssistantMessage): AssistantMessage | undefined {
part.type === "text" && part.text.trim() ? [{ type: "text" as const, text: part.text }] : [],
);
if (!content.length) return undefined;
- const { errorMessage: _error, ...rest } = message;
+ const { errorMessage: _error, diagnostics: _diagnostics, ...rest } = message;
return { ...rest, content, stopReason: "length" };
}
-function classified(error: unknown): AgentError {
- const code = mapAgentError(error);
- return new AgentError(code === "internal" ? "provider_error" : code, agentHttpStatus(error));
+function classified(error: unknown, status?: number, detail?: string): AgentError {
+ const code = mapAgentError(error, status);
+ return new AgentError(
+ code === "internal" ? "provider_error" : code,
+ status ?? agentHttpStatus(error),
+ detail,
+ );
}
function failed(model: Model<Api>, error: unknown, partial?: AssistantMessage): AssistantMessage {
@@ -70,6 +74,8 @@ function failed(model: Model<Api>, error: unknown, partial?: AssistantMessage):
: code === "internal"
? "provider_error"
: code;
+ // SDK diagnostic objects can include request bodies and headers even when errorMessage is safe.
+ const { diagnostics: _diagnostics, ...fields } = partial ?? {};
return {
role: "assistant",
content: [],
@@ -85,7 +91,7 @@ function failed(model: Model<Api>, error: unknown, partial?: AssistantMessage):
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
},
timestamp: Date.now(),
- ...partial,
+ ...fields,
stopReason: code === "aborted" ? "aborted" : "error",
// SDK diagnostics can carry credentials; only fixed codes and the HTTP number survive.
errorMessage: `${diagnostic}${status ? ` HTTP ${status}` : ""}`,
@@ -102,6 +108,7 @@ export function retryStream(input: {
hint?: string;
response(response: ProviderResponse): void;
}): ResponseStream | Promise<ResponseStream>;
+ describeFailure?(error: unknown): string | undefined;
onLimit?(limit: { maxTokens: number }): void;
}) {
const output = createAssistantMessageEventStream();
@@ -124,6 +131,7 @@ export function retryStream(input: {
for (;;) {
signal?.throwIfAborted();
const receipt = accounting.begin(model, "response", input.toolSet);
+ let responseStatus: number | undefined;
let observed = false;
let result: AssistantMessage;
let error: unknown;
@@ -131,7 +139,10 @@ export function retryStream(input: {
try {
const stream = await input.open({
hint: recovery.hint,
- response: (response) => recovery.response(response),
+ response: (response) => {
+ responseStatus = response.status;
+ recovery.response(response);
+ },
});
for await (const event of stream) {
// A provider may attach its last usage only to the terminal event, even when result rejects.
@@ -163,17 +174,14 @@ export function retryStream(input: {
result = failed(model, signal?.aborted ? { name: "AbortError" } : caught, partial);
}
observed ||= hasOutput(result);
+ // On a 200 stream, a number from the error body is not the HTTP response status.
+ const attemptError = error === undefined ? undefined : classified(error, responseStatus);
const unbilled = receipt.settle(
result,
- error === undefined
- ? undefined
- : {
- error,
- outputObserved: observed,
- },
+ attemptError && { error: attemptError, outputObserved: observed },
);
const rateLimited =
- mapAgentError(error) === "rate_limited" && agentHttpStatus(error) === 429;
+ attemptError?.code === "rate_limited" && attemptError.httpStatus === 429;
const recoveryRetry =
result.stopReason === "error" && !signal?.aborted && !accounting.blocked
? recovery.next(result, rateLimited && unbilled, accounting.retryAttempts)
@@ -190,7 +198,7 @@ export function retryStream(input: {
!signal?.aborted &&
!accounting.blocked &&
!rateLimited &&
- !!transientRequestError(error ?? result.errorMessage) &&
+ !!transientRequestError(attemptError ?? result.errorMessage) &&
midStreamRetries < MID_STREAM_RETRIES &&
accounting.retryAttempts < CONNECTION_RETRY_DELAYS.length;
const limit =
@@ -215,7 +223,7 @@ export function retryStream(input: {
attempt: accounting.retryAttempts,
maxAttempts: CONNECTION_RETRY_DELAYS.length,
};
- const status = agentHttpStatus(error);
+ const status = attemptError?.httpStatus;
accounting.onReconnect?.({
type: "reconnect",
phase: "start",
@@ -254,14 +262,14 @@ export function retryStream(input: {
if (retry.kind === "connection") accounting.retryAttempts++;
// Why it failed, as a code and HTTP status only (never provider text): without it the
// log shows a run losing a minute to backoff with no cause.
- const status = agentHttpStatus(error);
+ const status = attemptError?.httpStatus;
accounting.onReconnect?.({
type: "reconnect",
phase: "start",
attempt: retry.attempt,
maxAttempts: retry.maxAttempts,
delayMs: retry.delayMs,
- reason: retry.kind === "connection" ? mapAgentError(error) : retry.kind,
+ reason: retry.kind === "connection" ? attemptError?.code : retry.kind,
...(status === undefined ? {} : { status }),
});
await wait(retry.delayMs, undefined, { signal });
@@ -286,9 +294,11 @@ export function retryStream(input: {
if (result.stopReason !== "error" && result.stopReason !== "aborted")
accounting.retryAttempts = 0;
if (result.stopReason === "error" || result.stopReason === "aborted") {
- accounting.responseError = classified(
- signal?.aborted ? { name: "AbortError" } : (error ?? result.errorMessage),
- );
+ const cause = error ?? result.errorMessage;
+ accounting.responseError =
+ signal?.aborted || result.stopReason === "aborted"
+ ? new AgentError("aborted")
+ : classified(cause, responseStatus, input.describeFailure?.(cause));
const final = failed(model, accounting.responseError, result);
output.push({
type: "error",
diff --git a/packages/agent/src/runtime/runtime-parts/runtime-session.ts b/packages/agent/src/runtime/runtime-parts/runtime-session.ts
index e73fad8..6918493 100644
--- a/packages/agent/src/runtime/runtime-parts/runtime-session.ts
+++ b/packages/agent/src/runtime/runtime-parts/runtime-session.ts
@@ -15,6 +15,7 @@ import { storedSessionFile } from "../../session/session-files.ts";
import { CacheDiagnostics } from "../cache-diagnostic.ts";
import { contextBudget, responseMaxTokens } from "../context-budget.ts";
import { historyTokens, referenceTokens, textTokens } from "../context-estimate.ts";
+import { providerDetail } from "../provider-diagnostic.ts";
import { RequestAccounting } from "../request-observer.ts";
import { retryStream } from "../retry-stream.ts";
import type { RuntimeContext } from "../runtime.ts";
@@ -339,6 +340,8 @@ export function createSessionOperations({
model,
signal: requestSignal,
accounting,
+ describeFailure: (error) =>
+ opts.redactProviderDetail && providerDetail(error, opts.redactProviderDetail),
toolSet: extensions.loadout?.snapshot(scopedRequest),
open: async (recovery) => {
const onPayload = options?.onPayload;
diff --git a/packages/agent/src/session/session.ts b/packages/agent/src/session/session.ts
index 6d448c5..f5714e8 100644
--- a/packages/agent/src/session/session.ts
+++ b/packages/agent/src/session/session.ts
@@ -444,14 +444,13 @@ export function wrapSession(
usage: usageInfo(assistant.usage),
};
} catch (error) {
- throw new AgentError(
- eventFailed
- ? "session_event_handler_failed"
- : aborted
- ? "aborted"
- : (programFailure?.() ?? mapAgentError(error)),
- agentHttpStatus(error),
- );
+ const code = eventFailed
+ ? "session_event_handler_failed"
+ : aborted
+ ? "aborted"
+ : (programFailure?.() ?? mapAgentError(error));
+ if (error instanceof AgentError && error.code === code) throw error;
+ throw new AgentError(code, agentHttpStatus(error));
} finally {
emitActivity({ phase: "clear" });
if (additions) {
diff --git a/packages/agent/test/runtime.test.ts b/packages/agent/test/runtime.test.ts
index 5b2c3e7..0517ac6 100644
--- a/packages/agent/test/runtime.test.ts
+++ b/packages/agent/test/runtime.test.ts
@@ -9,6 +9,7 @@ import { dirname, join } from "node:path";
import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
import type { AgentSession, ModelRuntime } from "@earendil-works/pi-coding-agent";
+import { createRedactor } from "@pibot/secrets";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type {
AgentRuntime,
@@ -513,6 +514,41 @@ describe("custom model discovery using fetch stubs", () => {
expect(new Headers(init?.headers).get("X-Literal")).toBe("$OPENAI_API_KEY");
},
);
+ it.each([
+ [
+ 400,
+ "Input tag 'developer' found using 'role' does not match any of the expected tags: 'system', 'user', 'assistant', 'tool'",
+ ],
+ [
+ 200,
+ String.raw`Tool 20 function has invalid 'parameters' schema: '^[^\p{Cc}\p{Cf}]+$' is not a 'regex'. Failed validating 'format' in metaschema. On schema['properties']['items']['items']['properties']['id']['pattern']: '^[^\p{Cc}\p{Cf}]+$'`,
+ ],
+ [200, "Unexpected message role."],
+ [422, "Invalid value for the network field."],
+ ] as const)("preserves the upstream chat explanation for HTTP %i: %s", async (status, detail) => {
+ custom = [local];
+ const error = JSON.stringify({ error: { message: `${detail}\nAdditional gateway context` } });
+ const streaming = status === 200;
+ const fetch = stubFetch(
+ new Response(streaming ? `data: ${error}\n\n` : error, {
+ status,
+ headers: { "content-type": streaming ? "text/event-stream" : "application/json" },
+ }),
+ );
+ const session = await open({
+ ...options(),
+ systemPrompt: "Check each message role: system, user, assistant, tool.",
+ redactProviderDetail: createRedactor().redact,
+ });
+ await expect(session.prompt("hello", () => {})).rejects.toMatchObject({
+ code: streaming ? "provider_error" : "provider_rejected",
+ httpStatus: status,
+ providerDetail: detail,
+ });
+ expect(fetch).toHaveBeenCalledOnce();
+ const transcript = fs.readFileSync(join(dataDir, session.sessionFile), "utf8");
+ expect(transcript).not.toContain(JSON.stringify(detail).slice(1, -1));
+ });
it("uses API-specific authentication and response formats", async () => {
const spy = stubFetch(
new Response(JSON.stringify({ models: [{ name: "models/gemini-test" }] })),
diff --git a/packages/brain/src/brain.test.ts b/packages/brain/src/brain.test.ts
index f99476f..8ee8574 100644
--- a/packages/brain/src/brain.test.ts
+++ b/packages/brain/src/brain.test.ts
@@ -333,6 +333,33 @@ describe("T8 brain", () => {
expect(await readFile(join(dir, "logs", log), "utf8")).not.toContain(testKey);
});
+ it("keeps the upstream reason in the failed chat message and out of log exports", async () => {
+ await configure();
+ const { runId } = await peer.call("chat.send", { botId, text: "Hi" });
+ await waitPrompt();
+ const detail = "Unexpected message role.";
+ reject?.(new AgentError("provider_error", 200, detail));
+ await vi.waitFor(async () =>
+ expect((await history())[1]).toMatchObject({
+ status: "error",
+ errorCode: "provider_error",
+ usage: { providerFailure: { status: 200, detail } },
+ }),
+ );
+ const logsDir = join(dir, "logs");
+ const logs = await Promise.all(
+ (await readdir(logsDir)).map((name) => readFile(join(logsDir, name), "utf8")),
+ );
+ const logText = logs.join("\n");
+ expect(logText).toContain(`Chat ${runId} provider_error status=200`);
+ expect(logText).not.toContain(detail);
+ const snapshot = await peer.call("diagnostics.snapshot", undefined);
+ expect(snapshot.runs).toContainEqual(
+ expect.objectContaining({ runId, errorCode: "provider_error" }),
+ );
+ expect(JSON.stringify(snapshot)).not.toContain(detail);
+ });
+
it("rejects concurrent sends even during async availability preflight", async () => {
await configure();
const original = runtime.listModels;
diff --git a/packages/brain/src/core/privacy.ts b/packages/brain/src/core/privacy.ts
index 113dfe9..c29c72c 100644
--- a/packages/brain/src/core/privacy.ts
+++ b/packages/brain/src/core/privacy.ts
@@ -7,8 +7,31 @@ import {
export type BrainRedactor = NamedRedactor;
-export function createBrainRedactor(): BrainRedactor {
- return withNamedRedaction(createRedactor());
+export function createBrainRedactor() {
+ const shared = withNamedRedaction(createRedactor());
+ // Chat redaction deliberately ignores short anonymous values (e.g. a one-letter
+ // local model key). Provider diagnostics can quote those credentials verbatim.
+ const shortSecrets = new Map<string, RegExp>();
+ return {
+ ...shared,
+ add(value: string) {
+ shared.add(value);
+ if (value.length < 8 && !shortSecrets.has(value)) {
+ const literal = value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ shortSecrets.set(
+ value,
+ new RegExp(`(?<![\\p{L}\\p{N}_])${literal}(?![\\p{L}\\p{N}_])`, "gu"),
+ );
+ }
+ },
+ redactProviderDetail(text: string) {
+ // Match a standalone credential. A one-letter local key can otherwise hide
+ // unrelated explanations from every provider that happens to use that letter.
+ let result = shared.redact(text);
+ for (const token of shortSecrets.values()) result = result.replace(token, "[REDACTED]");
+ return result;
+ },
+ };
}
export function redactValue(value: unknown, redactor: Redactor): unknown {
diff --git a/packages/brain/src/index.ts b/packages/brain/src/index.ts
index 3aba904..4f691e1 100644
--- a/packages/brain/src/index.ts
+++ b/packages/brain/src/index.ts
@@ -656,7 +656,7 @@ export async function startBrain(opts: {
}
// All queue entry points, including unattended runs, share the SDK boundary. Attaching
// the GUI only changes admission; it cannot bypass reconciliation or the terminal seal.
- const contentRuntime = gateAgentContent(sdk, waitForContent, (text) => redactor.redact(text));
+ const contentRuntime = gateAgentContent(sdk, waitForContent, redactor);
const compactHistory = contentRuntime.compactHistory;
const agent: AgentRuntime = {
...contentRuntime,
diff --git a/packages/brain/src/runtime/queue/chat-run.ts b/packages/brain/src/runtime/queue/chat-run.ts
index 7e5d661..44beff1 100644
--- a/packages/brain/src/runtime/queue/chat-run.ts
+++ b/packages/brain/src/runtime/queue/chat-run.ts
@@ -1555,6 +1555,10 @@ export async function generateRun(
: cancelled
? "aborted"
: mapAgentError(error);
+ const providerError =
+ error instanceof AgentError && error.code === code && code !== "aborted" ? error : undefined;
+ const status = providerError?.httpStatus;
+ const detail = providerError?.providerDetail;
// The run's own signal may be the reason it ended; delivery gets a short one of its own.
const delivered = await deliverOutputs(
replies.content,
@@ -1571,6 +1575,9 @@ export async function generateRun(
stopReason: code === "aborted" ? "aborted" : "error",
...runModel(bot, run.session),
...(delivered?.overflow ? { attachmentOverflow: delivered.overflow } : {}),
+ ...(status || detail
+ ? { providerFailure: { ...(status && { status }), ...(detail && { detail }) } }
+ : {}),
},
code,
);
@@ -1591,9 +1598,6 @@ export async function generateRun(
code,
message: code,
});
- // Only the HTTP status survives AgentError (raw SDK text can carry keys or bodies); with the
- // model it tells overload (529/503) from a rejected request (400) when a reply comes back empty.
- const status = error instanceof AgentError ? error.httpStatus : undefined;
deps.logger.warn(
// The budget's own reason (which limit) — one run stopped at 220 tools / 128 requests,
// under both default limits, and the log could not say why.
diff --git a/packages/brain/src/runtime/startup/content-readiness.ts b/packages/brain/src/runtime/startup/content-readiness.ts
index 7daf79d..30d410c 100644
--- a/packages/brain/src/runtime/startup/content-readiness.ts
+++ b/packages/brain/src/runtime/startup/content-readiness.ts
@@ -4,7 +4,10 @@ import type { AgentRuntime } from "@pibot/agent";
export function gateAgentContent(
runtime: AgentRuntime,
ready: (signal?: AbortSignal) => Promise<void>,
- redact: (text: string) => string,
+ {
+ redact,
+ redactProviderDetail,
+ }: { redact(text: string): string; redactProviderDetail(text: string): string },
): AgentRuntime {
const gate =
<Input extends { signal?: AbortSignal }, Output>(
@@ -20,6 +23,7 @@ export function gateAgentContent(
...runtime,
openSession: gate(runtime.openSession, (input) => ({
...input,
+ redactProviderDetail,
systemPrompt:
typeof input.systemPrompt === "string" ? redact(input.systemPrompt) : input.systemPrompt,
})),
diff --git a/packages/client-core/src/chat/provider-failure.ts b/packages/client-core/src/chat/provider-failure.ts
new file mode 100644
index 0000000..72d0624
--- /dev/null
+++ b/packages/client-core/src/chat/provider-failure.ts
@@ -0,0 +1,19 @@
+import type { createTranslator } from "@pibot/i18n";
+import { type Message, messageProviderFailure } from "@pibot/protocol";
+
+export function providerFailureText(
+ message: Pick<Message, "usage">,
+ t: ReturnType<typeof createTranslator>,
+) {
+ const failure = messageProviderFailure(message);
+ if (!failure) return;
+ const { status, detail } = failure;
+ const response = [status && `HTTP ${status}`, detail].filter(Boolean).join(" · ");
+ if (response)
+ return t(
+ status && status >= 200 && status < 300
+ ? "chat.providerStreamFailure"
+ : "chat.providerFailure",
+ { response },
+ );
+}
diff --git a/packages/client-core/src/index.ts b/packages/client-core/src/index.ts
index 2b749d3..88ac1bc 100644
--- a/packages/client-core/src/index.ts
+++ b/packages/client-core/src/index.ts
@@ -24,6 +24,7 @@ export {
export { interruptedMessage } from "./chat/interrupted.ts";
export { readMainBot } from "./chat/main-bot.ts";
export { nextReply } from "./chat/next-reply.ts";
+export { providerFailureText } from "./chat/provider-failure.ts";
export { ChatReadCache, chatReadCache, disposeChatReads } from "./chat/read-cache.ts";
export { replyCitationText } from "./chat/reply-citations.ts";
export { appendReplyDelta, preserveLiveReply } from "./chat/reply-delta.ts";
diff --git a/packages/i18n/src/sections/chat.ts b/packages/i18n/src/sections/chat.ts
index d550cd9..1f0e9e0 100644
--- a/packages/i18n/src/sections/chat.ts
+++ b/packages/i18n/src/sections/chat.ts
@@ -2,6 +2,8 @@
// T11(外壳、侧栏、私聊)往这里加。
export const chatZh = {
+ "chat.providerFailure": "模型服务返回:{response}",
+ "chat.providerStreamFailure": "模型响应流报错:{response}",
"chat.citationsUnread": "引用提示:{count} 个链接未在本轮成功读取,请核对后再使用。",
"chat.citationsIncomplete": "引用提示:本轮来源记录或回复超出核对范围,未能完整核对。",
"chat.citationsScope": "此检查仅核对链接是否读过,不证明页面含有所引数字或结论正确。",
@@ -213,6 +215,8 @@ export const chatZh = {
} as const;
export const chatEn: { [K in keyof typeof chatZh]: string } = {
+ "chat.providerFailure": "Provider response: {response}",
+ "chat.providerStreamFailure": "Model stream failed: {response}",
"chat.citationsUnread":
"Citation note: {count} links were not successfully read in this run. Verify them before use.",
"chat.citationsIncomplete":
diff --git a/packages/protocol-base/src/chat/message-failure.ts b/packages/protocol-base/src/chat/message-failure.ts
index 016be71..9658c06 100644
--- a/packages/protocol-base/src/chat/message-failure.ts
+++ b/packages/protocol-base/src/chat/message-failure.ts
@@ -1,4 +1,4 @@
-import type { z } from "zod";
+import { z } from "zod";
import type { MessageSchema } from "./entities.ts";
type Message = z.infer<typeof MessageSchema>;
@@ -21,3 +21,15 @@ export function messageFailureCode(
return "output_limit";
return undefined;
}
+
+const providerFailure = z.strictObject({
+ status: z.number().int().min(100).max(599).optional(),
+ detail: z.string().max(300).optional(),
+});
+
+export function messageProviderFailure(message: Pick<Message, "usage">) {
+ const usage = message.usage;
+ if (!usage || typeof usage !== "object" || Array.isArray(usage)) return;
+ const parsed = providerFailure.safeParse(usage.providerFailure);
+ return parsed.success ? parsed.data : undefined;
+}