Skip to content

Commit e8295f1

Browse files
feat(opencode): show provider, model and request URL on provider failures (#31)
A failing provider request printed only the response body, e.g. `404 Page not found`, which cannot be told apart from a wrong API key, a wrong model id, or a wrong host. The request URL was already captured on the durable message record (`error.data.metadata.url`) but no surface displayed it. Record the resolved provider and model alongside that URL in `fromError`, so the persisted error is self-describing -- `session.error` events carry no message, so the error itself is the only place a reader can learn where the request went. `--format json` emits the record verbatim and so gains them for free. Render the detail through one shared formatter used by the CLI streaming loop, the CLI interactive scrollback, and the TUI message panel: 404 Page not found provider minimax/MiniMax-M3 request https://api.minimax.chat/v1/messages status 404 Redact URLs before display: userinfo, fragments, and every query value outside a small allowlist are withheld, so an API key embedded in a URL cannot leak. Query redaction is an allowlist rather than a denylist of key-ish names so it fails safe on parameter names we have never seen. Response headers are never displayed. Closes #29 Claude-Session: https://claude.ai/code/session_016rycAgbtqsRQH4qBv8nkE7
1 parent 4aa52d7 commit e8295f1

11 files changed

Lines changed: 372 additions & 3 deletions

File tree

‎.changeset/spotty-pandas-invite.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
"opencode": patch
3+
---
4+
5+
Show the provider, model and request URL on provider transport failures.
6+
7+
A failing provider request used to print only the response body, e.g. `404 Page not found`, which cannot be told apart from a wrong API key, a wrong model id, or a wrong host. The request URL was already recorded on the durable message record but never displayed. It is now shown on both the CLI (`redcode run`, interactive and streaming) and the TUI message panel:
8+
9+
```
10+
404 Page not found
11+
provider minimax/MiniMax-M3
12+
request https://api.minimax.chat/v1/messages
13+
status 404
14+
```
15+
16+
The resolved provider and model are now recorded on the error itself, so `session.error` events and `--format json` carry them too. Request URLs are redacted before display: userinfo, fragments, and all query values outside a small allowlist are withheld, so an API key embedded in a URL cannot leak. Response headers are never displayed.
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
/**
2+
* Renders the diagnostic context Redcode already records for a failed provider
3+
* request — resolved provider, model, request URL and HTTP status — so an opaque
4+
* response body such as "404 Page not found" can be told apart from a wrong API
5+
* key, a wrong model id, and a wrong host.
6+
*
7+
* Every consumer (CLI run loop, CLI scrollback, TUI message panel) goes through
8+
* here so the credential redaction below cannot drift between surfaces.
9+
*/
10+
export namespace ProviderFailure {
11+
/**
12+
* Marker for a value that was withheld. Deliberately free of characters that
13+
* `URL.toString()` would percent-encode, so a redacted URL stays readable.
14+
*/
15+
export const REDACTED = "__REDACTED__"
16+
17+
/**
18+
* Query parameters whose value may be shown. This is an allowlist rather than
19+
* a denylist of key-ish names on purpose: it fails safe when a provider names
20+
* its credential parameter something we have never seen. Only parameters that
21+
* are themselves a diagnosis (Azure's deployment api-version) belong here.
22+
*/
23+
const VISIBLE_QUERY_PARAMS = new Set(["api-version", "api_version", "version"])
24+
25+
/**
26+
* Strips every credential-bearing part of a request URL: userinfo, fragment,
27+
* and any query value not on the allowlist. Scheme, host, port and path
28+
* survive because they are the actual diagnosis.
29+
*/
30+
export function redactURL(input: string): string {
31+
const parsed = URL.parse(input)
32+
if (!parsed) {
33+
// Unparseable input still gets the same guarantee: keep everything before
34+
// the first `?` or `#`, withhold the rest rather than guess at its shape.
35+
const head = input.split(/[?#]/)[0]
36+
if (!head) return REDACTED
37+
return head.length === input.length ? head : `${head}?${REDACTED}`
38+
}
39+
40+
parsed.username = ""
41+
parsed.password = ""
42+
parsed.hash = ""
43+
for (const key of [...parsed.searchParams.keys()]) {
44+
if (VISIBLE_QUERY_PARAMS.has(key.toLowerCase())) continue
45+
// `set` also collapses repeated keys, so a duplicated credential
46+
// parameter cannot survive in a later position.
47+
parsed.searchParams.set(key, REDACTED)
48+
}
49+
return parsed.toString()
50+
}
51+
52+
/**
53+
* Detail rows for a persisted error record. Returns an empty list for errors
54+
* that carry no transport context (aborts, config errors, older records), so
55+
* callers can append unconditionally.
56+
*
57+
* `context` supplies the provider and model for records written before they
58+
* were recorded in the error itself; the error's own metadata wins.
59+
*/
60+
export function detail(error: unknown, context?: { providerID?: string; modelID?: string }): string[] {
61+
const data = isRecord(error) && isRecord(error.data) ? error.data : undefined
62+
if (!data) return []
63+
const metadata = isRecord(data.metadata) ? data.metadata : {}
64+
65+
const provider = string(metadata.providerID) ?? context?.providerID
66+
const model = string(metadata.modelID) ?? context?.modelID
67+
const url = string(metadata.url)
68+
const status = typeof data.statusCode === "number" ? String(data.statusCode) : undefined
69+
70+
return [
71+
...(provider || model ? [row("provider", [provider, model].filter(Boolean).join("/"))] : []),
72+
...(url ? [row("request", redactURL(url))] : []),
73+
...(status ? [row("status", status)] : []),
74+
]
75+
}
76+
77+
/**
78+
* `message` followed by its indented detail rows. Response headers are never
79+
* included — they are where bearer tokens live.
80+
*/
81+
export function describe(
82+
message: string,
83+
error: unknown,
84+
context?: { providerID?: string; modelID?: string },
85+
): string {
86+
const rows = detail(error, context)
87+
if (rows.length === 0) return message
88+
return [message, ...rows.map((entry) => " " + entry)].join("\n")
89+
}
90+
91+
function row(label: string, value: string) {
92+
return `${label.padEnd(8)} ${value}`
93+
}
94+
95+
function string(value: unknown) {
96+
return typeof value === "string" && value ? value : undefined
97+
}
98+
99+
function isRecord(value: unknown): value is Record<string, unknown> {
100+
return typeof value === "object" && value !== null && !Array.isArray(value)
101+
}
102+
}
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import { describe, expect, test } from "bun:test"
2+
import { ProviderFailure } from "../../src/util/provider-failure"
3+
4+
// Verbatim record taken from the `message` table of a real failed session; the
5+
// URL is what revealed the request had gone to an Anthropic path while an
6+
// OpenAI-compatible provider was configured.
7+
const RECORDED = {
8+
name: "APIError",
9+
data: {
10+
message: "404 Page not found",
11+
statusCode: 404,
12+
isRetryable: false,
13+
responseHeaders: {
14+
"minimax-request-id": "fdf4f50a92ec5a88f79125fedaa3ed3b",
15+
authorization: "Bearer sk-live-do-not-print-me",
16+
},
17+
responseBody: "404 page not found",
18+
metadata: {
19+
providerID: "minimax",
20+
modelID: "MiniMax-M3",
21+
url: "https://api.minimax.chat/v1/messages",
22+
},
23+
},
24+
}
25+
26+
describe("ProviderFailure.describe", () => {
27+
test("turns the recorded failure into a diagnosable message", () => {
28+
expect(ProviderFailure.describe("404 Page not found", RECORDED)).toBe(
29+
[
30+
"404 Page not found",
31+
" provider minimax/MiniMax-M3",
32+
" request https://api.minimax.chat/v1/messages",
33+
" status 404",
34+
].join("\n"),
35+
)
36+
})
37+
38+
test("never echoes response headers, where bearer tokens live", () => {
39+
expect(ProviderFailure.describe("404 Page not found", RECORDED)).not.toContain("sk-live-do-not-print-me")
40+
expect(ProviderFailure.describe("404 Page not found", RECORDED)).not.toContain("authorization")
41+
})
42+
43+
test("falls back to the caller's provider and model for records written before they were recorded", () => {
44+
const legacy = { name: "APIError", data: { message: "boom", metadata: { url: "https://api.acme.dev/v1/chat" } } }
45+
expect(ProviderFailure.describe("boom", legacy, { providerID: "acme", modelID: "acme-1" })).toContain(
46+
"provider acme/acme-1",
47+
)
48+
})
49+
50+
test("prefers the recorded provider over the caller's fallback", () => {
51+
expect(ProviderFailure.describe("404 Page not found", RECORDED, { providerID: "wrong", modelID: "wrong" })).toContain(
52+
"provider minimax/MiniMax-M3",
53+
)
54+
})
55+
56+
test("returns the message untouched when there is no transport context", () => {
57+
expect(ProviderFailure.describe("Aborted", { name: "MessageAbortedError", data: { message: "Aborted" } })).toBe(
58+
"Aborted",
59+
)
60+
expect(ProviderFailure.describe("nope", undefined)).toBe("nope")
61+
expect(ProviderFailure.describe("nope", "a string")).toBe("nope")
62+
})
63+
})
64+
65+
describe("ProviderFailure.redactURL", () => {
66+
test("keeps scheme, host, port and path, which are the diagnosis", () => {
67+
expect(ProviderFailure.redactURL("https://api.minimax.chat:8443/v1/messages")).toBe(
68+
"https://api.minimax.chat:8443/v1/messages",
69+
)
70+
})
71+
72+
test("redacts a key passed as a query parameter", () => {
73+
// Google's Generative Language API takes the API key this way.
74+
expect(ProviderFailure.redactURL("https://generativelanguage.googleapis.com/v1/models:generate?key=AIzaSyREAL")).toBe(
75+
`https://generativelanguage.googleapis.com/v1/models:generate?key=${ProviderFailure.REDACTED}`,
76+
)
77+
})
78+
79+
test("redacts query values it has never seen, not just key-shaped names", () => {
80+
const redacted = ProviderFailure.redactURL("https://api.acme.dev/v1?wildcard=SECRET&sig=SECRET&token=SECRET")
81+
expect(redacted).not.toContain("SECRET")
82+
})
83+
84+
test("redacts credentials in userinfo", () => {
85+
expect(ProviderFailure.redactURL("https://admin:[email protected]/v1/chat")).toBe("https://api.acme.dev/v1/chat")
86+
})
87+
88+
test("drops the fragment, which can carry a token", () => {
89+
expect(ProviderFailure.redactURL("https://api.acme.dev/v1/chat#access_token=SECRET")).toBe(
90+
"https://api.acme.dev/v1/chat",
91+
)
92+
})
93+
94+
test("collapses a repeated credential parameter so no copy survives", () => {
95+
expect(ProviderFailure.redactURL("https://api.acme.dev/v1?key=SECRET&key=SECRET2")).not.toContain("SECRET")
96+
})
97+
98+
test("keeps the allowlisted api-version, which is itself a diagnosis", () => {
99+
expect(
100+
ProviderFailure.redactURL("https://acme.openai.azure.com/openai/deployments/gpt/chat?api-version=2024-06-01"),
101+
).toBe("https://acme.openai.azure.com/openai/deployments/gpt/chat?api-version=2024-06-01")
102+
})
103+
104+
test("matches the allowlist case-insensitively", () => {
105+
expect(ProviderFailure.redactURL("https://api.acme.dev/v1?API-Version=2024-06-01")).toContain("2024-06-01")
106+
})
107+
108+
test("withholds the query of an unparseable URL rather than guessing", () => {
109+
expect(ProviderFailure.redactURL("api.acme.dev/v1/chat?key=SECRET")).toBe(
110+
`api.acme.dev/v1/chat?${ProviderFailure.REDACTED}`,
111+
)
112+
expect(ProviderFailure.redactURL("?key=SECRET")).toBe(ProviderFailure.REDACTED)
113+
expect(ProviderFailure.redactURL("")).toBe(ProviderFailure.REDACTED)
114+
})
115+
116+
test("no query value survives for any parameter name a provider might invent", () => {
117+
// The allowlist is the guarantee: an unknown name can never leak its value.
118+
const names = ["key", "api_key", "apikey", "access_token", "sig", "signature", "password", "x-goog-api-key", "zzz"]
119+
for (const name of names) {
120+
expect(ProviderFailure.redactURL(`https://api.acme.dev/v1?${name}=SUPERSECRET`)).not.toContain("SUPERSECRET")
121+
}
122+
})
123+
})

‎packages/opencode/src/cli/cmd/run.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { EOL } from "os"
2424
import { Filesystem } from "@/util/filesystem"
2525
import { createOpencodeClient, type OpencodeClient, type ToolPart } from "@opencode-ai/sdk/v2"
2626
import { FormatError, FormatUnknownError } from "../error"
27+
import { ProviderFailure } from "@opencode-ai/core/util/provider-failure"
2728
import { INTERACTIVE_INPUT_ERROR, resolveInteractiveStdin } from "./run/runtime.stdin"
2829

2930
type ModelInput = Parameters<OpencodeClient["session"]["prompt"]>[0]["model"]
@@ -803,6 +804,7 @@ export const RunCommand = effectCmd({
803804
if ("data" in props.error && props.error.data && "message" in props.error.data) {
804805
err = String(props.error.data.message)
805806
}
807+
err = ProviderFailure.describe(err, props.error)
806808
error = error ? error + EOL + err : err
807809
if (emit("error", { error: props.error })) continue
808810
UI.error(err)

‎packages/opencode/src/cli/cmd/run/session-data.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
import type { Event, Part, PermissionRequest, QuestionRequest, ToolPart } from "@opencode-ai/sdk/v2"
2828
import * as Locale from "@/util/locale"
2929
import { toolView } from "./tool"
30+
import { ProviderFailure } from "@opencode-ai/core/util/provider-failure"
3031
import type { FooterOutput, FooterPatch, FooterView, StreamCommit } from "./types"
3132

3233
const money = new Intl.NumberFormat("en-US", {
@@ -167,6 +168,10 @@ export function formatError(error: {
167168
message?: string
168169
}
169170
}): string {
171+
return ProviderFailure.describe(headline(error), error)
172+
}
173+
174+
function headline(error: { name?: string; message?: string; data?: { message?: string } }) {
170175
if (error.data?.message) {
171176
return error.data.message
172177
}

‎packages/opencode/src/session/message-v2.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -605,8 +605,12 @@ function isAfter(info: Info, other?: Info) {
605605

606606
export function fromError(
607607
e: unknown,
608-
ctx: { providerID: ProviderV2.ID; aborted?: boolean },
608+
ctx: { providerID: ProviderV2.ID; modelID?: string; aborted?: boolean },
609609
): NonNullable<Assistant["error"]> {
610+
// Recorded on every transport failure so the persisted error is self-describing:
611+
// `session.error` events carry no message, so this is the only place a reader
612+
// can learn which provider and model the failed request resolved to.
613+
const transport = { providerID: ctx.providerID, ...(ctx.modelID ? { modelID: ctx.modelID } : {}) }
610614
switch (true) {
611615
case e instanceof DOMException && e.name === "AbortError":
612616
return new AbortedError(
@@ -631,6 +635,7 @@ export function fromError(
631635
message: "Connection reset by server",
632636
isRetryable: true,
633637
metadata: {
638+
...transport,
634639
code: (e as SystemError).code ?? "",
635640
syscall: (e as SystemError).syscall ?? "",
636641
message: (e as SystemError).message ?? "",
@@ -647,6 +652,7 @@ export function fromError(
647652
message: "Response decompression failed",
648653
isRetryable: true,
649654
metadata: {
655+
...transport,
650656
code: (e as FetchDecompressionError).code,
651657
message: e.message,
652658
},
@@ -659,6 +665,7 @@ export function fromError(
659665
message: e.message,
660666
isRetryable: true,
661667
metadata: {
668+
...transport,
662669
code: e.name,
663670
timeoutMs: String(e.ms),
664671
},
@@ -671,6 +678,7 @@ export function fromError(
671678
message: e.message,
672679
isRetryable: true,
673680
metadata: {
681+
...transport,
674682
code: e.name,
675683
},
676684
},
@@ -698,7 +706,7 @@ export function fromError(
698706
isRetryable: parsed.isRetryable,
699707
responseHeaders: parsed.responseHeaders,
700708
responseBody: parsed.responseBody,
701-
metadata: parsed.metadata,
709+
metadata: { ...transport, ...parsed.metadata },
702710
},
703711
{ cause: e },
704712
).toObject()
@@ -722,6 +730,7 @@ export function fromError(
722730
message: parsed.message,
723731
isRetryable: parsed.isRetryable,
724732
responseBody: parsed.responseBody,
733+
metadata: transport,
725734
},
726735
{
727736
cause: e,

‎packages/opencode/src/session/processor.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ const layer = Layer.effect(
117117
const parse = (e: unknown) =>
118118
MessageV2.fromError(e, {
119119
providerID: input.model.providerID,
120+
modelID: input.model.id,
120121
aborted,
121122
})
122123

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1204,6 +1204,7 @@ const layer = Layer.effect(
12041204
if (msg.time.completed) return
12051205
msg.error ??= MessageV2.fromError(new DOMException("Aborted", "AbortError"), {
12061206
providerID: msg.providerID,
1207+
modelID: msg.modelID,
12071208
aborted: true,
12081209
})
12091210
msg.time.completed = Date.now()

0 commit comments

Comments
 (0)