From 41b454ede6c56dccf8a1a2f65737cd5997299680 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Thu, 19 Nov 2026 13:38:48 +0800 Subject: [PATCH 1/4] fix: never send a stack trace in a server error response; an unavailable remote config is a 502 - Unknown errors: a fixed message and a ref, logged in full, as the HttpApi middleware does. - Remote config that can't be fetched dies with ConfigRemoteUnavailableError (502 + status). - A failed prompt's session error event carries the message, not the cause's stack. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEmKQx8gR7vd6ettA3mWjP --- packages/core/src/v1/config/error.ts | 9 + .../src/altimate/server/error-response.ts | 37 ++++ packages/opencode/src/cli/error.ts | 9 + packages/opencode/src/config/config.ts | 23 ++- packages/opencode/src/server/middleware.ts | 14 +- .../instance/httpapi/handlers/session.ts | 8 +- packages/opencode/src/server/server.ts | 12 +- .../opencode/test/cli/error-format.test.ts | 12 ++ .../test/server/altimate-error-bodies.test.ts | 166 ++++++++++++++++++ 9 files changed, 282 insertions(+), 8 deletions(-) create mode 100644 packages/opencode/src/altimate/server/error-response.ts create mode 100644 packages/opencode/test/server/altimate-error-bodies.test.ts diff --git a/packages/core/src/v1/config/error.ts b/packages/core/src/v1/config/error.ts index abf3a09276..2a9dad9fa2 100644 --- a/packages/core/src/v1/config/error.ts +++ b/packages/core/src/v1/config/error.ts @@ -37,3 +37,12 @@ export const RemoteAuthError = NamedError.create("ConfigRemoteAuthError", { url: Schema.String, remote: Schema.String, }) + +// altimate_change start — remote config that can't be fetched is the remote's failure: name it and its status, so the +// server answers 502 with a short message instead of a 500 carrying a stack trace. +export const RemoteUnavailableError = NamedError.create("ConfigRemoteUnavailableError", { + remote: Schema.String, + status: Schema.optional(Schema.Number), + reason: Schema.String, +}) +// altimate_change end diff --git a/packages/opencode/src/altimate/server/error-response.ts b/packages/opencode/src/altimate/server/error-response.ts new file mode 100644 index 0000000000..cc2c1e1fa1 --- /dev/null +++ b/packages/opencode/src/altimate/server/error-response.ts @@ -0,0 +1,37 @@ +import { NamedError } from "@opencode-ai/core/util/error" +import type { Log } from "@/util/log" + +// What the server's catch-all error handlers send back. For an error they don't recognise, a fixed message and a +// ref, as the HttpApi error middleware answers (httpapi/middleware/error.ts): never the error's own text, stack or +// file paths. The full error is logged server-side under the same ref. + +/** HTTP status for an error the handlers know by name: a remote the server depends on failed (502). */ +export function upstreamStatus(name: string): 502 | undefined { + return name === "ConfigRemoteUnavailableError" ? 502 : undefined +} + +// An indented `at …` line ending in a source location, as V8, JSC and Bun print stack frames. +const FRAME = /^\s+at\s.*(:\d+:\d+\)?|\(native[^)]*\))\s*$/ + +export const UNEXPECTED = "Unexpected server error. Check server logs for details." + +/** + * An error's message without stack-frame lines (some errors carry frames in the message itself), for a client + * that has to tell a user why their own request failed, such as a session's error event. + */ +export function clientMessage(err: unknown): string { + const raw = err instanceof Error ? err.message : String(err) + const message = raw + .split("\n") + .filter((line) => !FRAME.test(line)) + .join("\n") + .trim() + return message || UNEXPECTED +} + +/** The response body for an error no handler recognises, logged in full under a ref that the body carries. */ +export function unknownErrorBody(log: Log.Logger, err: unknown) { + const ref = `err_${crypto.randomUUID().slice(0, 8)}` + log.error("unexpected error", { ref, error: err }) + return new NamedError.Unknown({ message: UNEXPECTED, ref }).toObject() +} diff --git a/packages/opencode/src/cli/error.ts b/packages/opencode/src/cli/error.ts index 8922169782..075885f3df 100644 --- a/packages/opencode/src/cli/error.ts +++ b/packages/opencode/src/cli/error.ts @@ -105,6 +105,15 @@ export function FormatError(input: unknown): string | undefined { return stringField(configFrontmatter, "message") ?? "" } + // altimate_change start — ConfigRemoteUnavailableError: { remote: string, status?: number, reason: string } + const remoteUnavailable = configData(input, "ConfigRemoteUnavailableError") + if (remoteUnavailable) { + const remote = stringField(remoteUnavailable, "remote") + const reason = stringField(remoteUnavailable, "reason") + return `Failed to load remote config${remote ? ` from ${remote}` : ""}: the remote is unavailable${reason ? ` (${reason})` : ""}.` + } + // altimate_change end + // ConfigRemoteAuthError: { url: string, remote: string } const remoteAuth = configData(input, "ConfigRemoteAuthError") if (remoteAuth) { diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index d49756dc52..cd81ef2b16 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -30,7 +30,9 @@ import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/ import { EffectFlock } from "@opencode-ai/core/util/effect-flock" import { containsPath, type InstanceContext } from "../project/instance-context" import { ConfigV1 } from "@opencode-ai/core/v1/config/config" -import { RemoteAuthError } from "@opencode-ai/core/v1/config/error" +// altimate_change start — typed remote-config failures +import { RemoteAuthError, RemoteUnavailableError } from "@opencode-ai/core/v1/config/error" +// altimate_change end import { ConfigPermissionV1 } from "@opencode-ai/core/v1/config/permission" import { ConfigPluginV1 } from "@opencode-ai/core/v1/config/plugin" import { ConfigAgent } from "./agent" @@ -338,10 +340,25 @@ export const layer = Layer.effect( HttpClientRequest.get(url).pipe(HttpClientRequest.acceptJson, HttpClientRequest.setHeaders(headers ?? {})), ) .pipe( - Effect.catch((error) => Effect.die(new Error(`failed to fetch remote config from ${url}: ${String(error)}`))), + // altimate_change start — an unreachable or failing remote is reported by name and status (HTTP 502), not as + // an untyped defect whose stack the server used to send back in a 500. + Effect.catch((error) => + Effect.die( + new RemoteUnavailableError({ + remote: url, + status: error.reason._tag === "StatusCodeError" ? error.reason.response.status : undefined, + reason: error.reason._tag === "StatusCodeError" ? `HTTP ${error.reason.response.status}` : error.reason._tag, + }), + ), + ), + // altimate_change end ) const body = yield* response.text.pipe( - Effect.catch((error) => Effect.die(new Error(`failed to read remote config from ${url}: ${String(error)}`))), + // altimate_change start — see above + Effect.catch((error) => + Effect.die(new RemoteUnavailableError({ remote: url, status: response.status, reason: error.reason._tag })), + ), + // altimate_change end ) // An auth proxy can answer with an HTML login page at HTTP 200 (passes filterStatusOk); treat it as a re-auth error, not a decode failure. const contentType = (response.headers["content-type"] ?? "").toLowerCase() diff --git a/packages/opencode/src/server/middleware.ts b/packages/opencode/src/server/middleware.ts index 278740c57d..dfd3f37a4a 100644 --- a/packages/opencode/src/server/middleware.ts +++ b/packages/opencode/src/server/middleware.ts @@ -6,6 +6,10 @@ import type { ContentfulStatusCode } from "hono/utils/http-status" import type { ErrorHandler } from "hono" import { HTTPException } from "hono/http-exception" import type { Log } from "../util/log" +// altimate_change start — client-safe error responses +import { NamedError as CoreNamedError } from "@opencode-ai/core/util/error" +import { unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" +// altimate_change end export function errorHandler(log: Log.Logger): ErrorHandler { return (err, c) => { @@ -25,9 +29,15 @@ export function errorHandler(log: Log.Logger): ErrorHandler { return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) } if (err instanceof HTTPException) return err.getResponse() - const message = err instanceof Error && err.stack ? err.stack : err.toString() - return c.json(new NamedError.Unknown({ message }).toObject(), { + // altimate_change start — a NamedError from @opencode-ai/core (config, remote config) isn't an instance of this + // package's NamedError: answer with its own name and fields, never the stack trace below. + if (err instanceof CoreNamedError) { + return c.json(err.toObject(), { status: upstreamStatus(err.name) ?? 500 }) + } + // Never send an error's text or stack to the client: a fixed message and a ref, logged in full. + return c.json(unknownErrorBody(log, err), { status: 500, }) + // altimate_change end } } diff --git a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts index ee405a22b7..6281b7c9d9 100644 --- a/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts +++ b/packages/opencode/src/server/routes/instance/httpapi/handlers/session.ts @@ -23,6 +23,9 @@ import { ModelID, ProviderID } from "@/provider/schema" import type { NotFoundError as StorageNotFoundError } from "@/storage/storage" // altimate_change end import { NamedError } from "@opencode-ai/core/util/error" +// altimate_change start — client-safe error messages +import { clientMessage } from "@/altimate/server/error-response" +// altimate_change end import { Cause, Effect, Option, Schema, Scope } from "effect" import * as Stream from "effect/Stream" import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http" @@ -343,7 +346,10 @@ export const sessionHandlers = HttpApiBuilder.group(InstanceHttpApi, "session", yield* Effect.logError("prompt_async failed", { sessionID: ctx.params.sessionID, cause }) yield* events.publish(Session.Event.Error, { sessionID: ctx.params.sessionID, - error: new NamedError.Unknown({ message: Cause.pretty(cause) }).toObject(), + // altimate_change start — the event goes to clients: the error's message, not the cause's stack trace + // (logged in full just above). + error: new NamedError.Unknown({ message: clientMessage(Cause.squash(cause)) }).toObject(), + // altimate_change end }) }), ), diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index 283c322e07..d58cf986a0 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -10,6 +10,9 @@ import { basicAuth } from "hono/basic-auth" import z from "zod" import { Provider } from "../provider/provider" import { NamedError } from "@opencode-ai/core/util/error" +// altimate_change start — client-safe error responses +import { unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" +// altimate_change end import { LSP } from "../lsp" import { Format } from "../format" import { TuiRoutes } from "./routes/tui" @@ -275,6 +278,9 @@ export namespace Server { // server fault; without this it surfaced from /find as a 500. else if (err.name === "RipgrepInvalidPatternError") status = 400 // altimate_change end + // altimate_change start — a remote the server depends on failed: 502, not a server fault. + else if (upstreamStatus(err.name)) status = 502 + // altimate_change end else status = 500 return c.json(err.toObject(), { status }) } @@ -286,15 +292,17 @@ export namespace Server { // altimate_change start — see above: an invalid search pattern is a client error. else if (err.name === "RipgrepInvalidPatternError") status = 400 // altimate_change end + else if (upstreamStatus(err.name)) status = 502 else status = 500 return c.json(err.toObject(), { status }) } // altimate_change end if (err instanceof HTTPException) return err.getResponse() - const message = err instanceof Error && err.stack ? err.stack : err.toString() - return c.json(new NamedError.Unknown({ message }).toObject(), { + // altimate_change start — never send an error's text or stack to the client: a fixed message and a ref, logged in full. + return c.json(unknownErrorBody(log, err), { status: 500, }) + // altimate_change end }) .use((c, next) => { // Allow CORS preflight requests to succeed without auth. diff --git a/packages/opencode/test/cli/error-format.test.ts b/packages/opencode/test/cli/error-format.test.ts index d7c1b250e1..e271ca45f7 100644 --- a/packages/opencode/test/cli/error-format.test.ts +++ b/packages/opencode/test/cli/error-format.test.ts @@ -36,6 +36,18 @@ describe("FormatError: known error types", () => { expect(result).toContain("anthropic") }) + // altimate_change start — an unavailable remote config names the remote and why + test("Config.RemoteUnavailableError names the remote and the reason", () => { + const err = { + name: "ConfigRemoteUnavailableError", + data: { remote: "https://config.example.com/.well-known/opencode", status: 503, reason: "HTTP 503" }, + } + expect(FormatError(err)).toBe( + "Failed to load remote config from https://config.example.com/.well-known/opencode: the remote is unavailable (HTTP 503).", + ) + }) + // altimate_change end + test("Config.JsonError with message", () => { const err = { name: "ConfigJsonError", data: { path: "/home/user/.config/altimate.json", message: "Unexpected token" } } const result = FormatError(err) diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts new file mode 100644 index 0000000000..209627bcd9 --- /dev/null +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -0,0 +1,166 @@ +// altimate_change - new file +// +// What the server's catch-all error handlers send back: never an error's text, stack or file paths, only a fixed +// message and a ref (the error is logged in full under that ref). A remote config that can't be fetched answers 502 +// with its name and status. Covers server.ts's handler through the full app, middleware.ts's handler directly, and +// the shared helpers. +import { afterEach, describe, expect, test } from "bun:test" +import path from "path" +import { unlink } from "fs/promises" +import { Hono } from "hono" +import { ConfigErrorV1 } from "@opencode-ai/core/v1/config/error" +import { Server } from "../../src/server/server" +import { errorHandler } from "../../src/server/middleware" +import { clientMessage, unknownErrorBody, upstreamStatus, UNEXPECTED } from "../../src/altimate/server/error-response" +import type { Log } from "../../src/util/log" +import { Global } from "@/global" +import { Filesystem } from "@/util/filesystem" +import { disposeAllInstances, tmpdir } from "../fixture/fixture" + +// Stack frames and source paths, as V8, JSC and Bun print them. +const STACKISH = /\n\s+at\s|\.(ts|js):\d+:\d+|node_modules/ + +function capturingLog() { + const calls: Array<{ message: string; extra: Record }> = [] + const log = { + error: (message: string, extra: Record) => calls.push({ message, extra }), + info: () => {}, + warn: () => {}, + debug: () => {}, + } as unknown as Log.Logger + return { log, calls } +} + +describe("clientMessage", () => { + test("drops stack-frame lines and keeps the rest", () => { + const err = new Error( + "failed to load\n at fetch (/srv/app/src/x.ts:10:5)\n at (native:7:39)\nat least one model is required", + ) + expect(clientMessage(err)).toBe("failed to load\nat least one model is required") + }) + + test("falls back to the fixed message when nothing is left", () => { + expect(clientMessage(new Error(""))).toBe(UNEXPECTED) + expect(clientMessage(" at fn (/a.js:1:2)")).toBe(UNEXPECTED) + }) +}) + +test("upstreamStatus is 502 only for an unavailable remote config", () => { + expect(upstreamStatus("ConfigRemoteUnavailableError")).toBe(502) + expect(upstreamStatus("ConfigRemoteAuthError")).toBeUndefined() + expect(upstreamStatus("UnknownError")).toBeUndefined() +}) + +test("unknownErrorBody carries a fixed message and a ref, and logs the error under that ref", () => { + const { log, calls } = capturingLog() + const err = new Error("secret marker") + const body = unknownErrorBody(log, err) as { name: string; data: { message: string; ref: string } } + expect(body.name).toBe("UnknownError") + expect(body.data.message).toBe(UNEXPECTED) + expect(body.data.ref).toMatch(/^err_[0-9a-f-]{8}$/) + expect(JSON.stringify(body)).not.toContain("secret marker") + expect(calls).toEqual([{ message: "unexpected error", extra: { ref: body.data.ref, error: err } }]) +}) + +describe("middleware.ts errorHandler", () => { + function app(thrown: unknown) { + const { log, calls } = capturingLog() + const hono = new Hono().onError(errorHandler(log)).get("/boom", () => { + throw thrown + }) + return { hono, calls } + } + + test("an unknown error answers 500 with a fixed message and a ref, never its text or stack", async () => { + const err = new Error("secret marker") + const { hono, calls } = app(err) + const response = await hono.request("/boom") + const text = await response.text() + expect(response.status).toBe(500) + expect(text).not.toContain("secret marker") + expect(text).not.toMatch(STACKISH) + const body = JSON.parse(text) + expect(body).toMatchObject({ name: "UnknownError", data: { message: UNEXPECTED } }) + expect(calls.some((c) => c.extra.ref === body.data.ref && c.extra.error === err)).toBe(true) + }) + + test("an unavailable remote config answers 502 with its name, remote, status and reason", async () => { + const err = new ConfigErrorV1.RemoteUnavailableError({ + remote: "https://config.example.com/.well-known/opencode", + status: 503, + reason: "HTTP 503", + }) + const response = await app(err).hono.request("/boom") + expect(response.status).toBe(502) + expect(await response.json()).toEqual({ + name: "ConfigRemoteUnavailableError", + data: { remote: "https://config.example.com/.well-known/opencode", status: 503, reason: "HTTP 503" }, + }) + }) + + test("another core config error answers with its own fields, not a stack", async () => { + const err = new ConfigErrorV1.RemoteAuthError({ url: "https://example.com", remote: "https://example.com/c.json" }) + const response = await app(err).hono.request("/boom") + const text = await response.text() + expect(response.status).toBe(500) + expect(text).not.toMatch(STACKISH) + expect(JSON.parse(text)).toEqual({ + name: "ConfigRemoteAuthError", + data: { url: "https://example.com", remote: "https://example.com/c.json" }, + }) + }) +}) + +describe("full server, remote config unavailable", () => { + const authPath = () => path.join(Global.Path.data, "auth.json") + let original: string | undefined + let servers: Array<{ stop: (force?: boolean) => unknown }> = [] + + async function withWellKnown(url: string) { + original = await Filesystem.readText(authPath()).catch(() => undefined) + await Filesystem.write( + authPath(), + JSON.stringify({ [url]: { type: "wellknown", key: "TEST_TOKEN", token: "test-token" } }), + ) + } + + afterEach(async () => { + for (const server of servers) await server.stop(true) + servers = [] + if (original !== undefined) await Filesystem.write(authPath(), original) + else await unlink(authPath()).catch(() => undefined) + original = undefined + await disposeAllInstances() + }) + + test("GET /agent answers 502 naming the remote and its status when the remote answers 500", async () => { + const remote = Bun.serve({ port: 0, fetch: () => new Response("upstream exploded", { status: 500 }) }) + servers.push(remote) + await withWellKnown(remote.url.origin) + await using dir = await tmpdir({ git: true }) + const response = await Server.Default().request("/agent", { headers: { "x-opencode-directory": dir.path } }) + const text = await response.text() + expect(response.status).toBe(502) + expect(text).not.toMatch(STACKISH) + expect(JSON.parse(text)).toEqual({ + name: "ConfigRemoteUnavailableError", + data: { remote: `${remote.url.origin}/.well-known/opencode`, status: 500, reason: "HTTP 500" }, + }) + }) + + test("GET /agent answers 502 with the transport reason when the remote refuses the connection", async () => { + const closed = Bun.serve({ port: 0, fetch: () => new Response("") }) + const origin = closed.url.origin + await closed.stop(true) + await withWellKnown(origin) + await using dir = await tmpdir({ git: true }) + const response = await Server.Default().request("/agent", { headers: { "x-opencode-directory": dir.path } }) + const text = await response.text() + expect(response.status).toBe(502) + expect(text).not.toMatch(STACKISH) + expect(JSON.parse(text)).toEqual({ + name: "ConfigRemoteUnavailableError", + data: { remote: `${origin}/.well-known/opencode`, reason: "TransportError" }, + }) + }) +}) From b378ee07127dd892bd4af9e1ef42ac862499af09 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 20 Nov 2026 10:32:01 +0800 Subject: [PATCH 2/4] fix: drop every stack frame from a session error, with or without a source location MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An indented `at …` line is a frame in V8, JSC and Bun alike; frames such as `at new Promise ()` carry no file:line and slipped through. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEmKQu1Qn99YbrBzhKdtAr --- packages/opencode/src/altimate/server/error-response.ts | 5 +++-- .../opencode/test/server/altimate-error-bodies.test.ts | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/opencode/src/altimate/server/error-response.ts b/packages/opencode/src/altimate/server/error-response.ts index cc2c1e1fa1..371940859b 100644 --- a/packages/opencode/src/altimate/server/error-response.ts +++ b/packages/opencode/src/altimate/server/error-response.ts @@ -10,8 +10,9 @@ export function upstreamStatus(name: string): 502 | undefined { return name === "ConfigRemoteUnavailableError" ? 502 : undefined } -// An indented `at …` line ending in a source location, as V8, JSC and Bun print stack frames. -const FRAME = /^\s+at\s.*(:\d+:\d+\)?|\(native[^)]*\))\s*$/ +// An indented `at …` line: how V8, JSC and Bun print every stack frame, with or without a source location +// (`at new Promise ()`, `at async Promise.all (index 0)`). +const FRAME = /^\s+at\s/ export const UNEXPECTED = "Unexpected server error. Check server logs for details." diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts index 209627bcd9..a80e0b4cfd 100644 --- a/packages/opencode/test/server/altimate-error-bodies.test.ts +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -39,6 +39,14 @@ describe("clientMessage", () => { expect(clientMessage(err)).toBe("failed to load\nat least one model is required") }) + test("drops frames without a source location too", () => { + const err = new Error( + "failed\n at new Promise ()\n at async Promise.all (index 0)\n at forEach ([native code])\n at ", + ) + expect(clientMessage(err)).toBe("failed") + expect(clientMessage(" at new Promise ()")).toBe(UNEXPECTED) + }) + test("falls back to the fixed message when nothing is left", () => { expect(clientMessage(new Error(""))).toBe(UNEXPECTED) expect(clientMessage(" at fn (/a.js:1:2)")).toBe(UNEXPECTED) From 91235eb9da6581b51501d9215849bc5d65efe885 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 20 Nov 2026 11:13:29 +0800 Subject: [PATCH 3/4] fix: keep tokens out of remote-config errors; log once with the ref; busy sessions and NamedError text MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A remote-config error names the remote config by its template (`{env:…}` and all), never the substituted URL that can carry the auth token. This applies to the unavailable error and the HTML-login one. A failed body read no longer reports the 2xx status that preceded it. - Each Hono handler logs an error once, with the ref that an unknown error's response carries. - server.ts answers a busy session 400 with its message, as middleware.ts does, instead of the fixed text. - A session error takes a NamedError's text from `data.message`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEmKQu1Qn99YbrBzhKdtAr --- .../src/altimate/server/error-response.ts | 28 ++++--- packages/opencode/src/config/config.ts | 22 ++++-- packages/opencode/src/server/middleware.ts | 8 +- packages/opencode/src/server/server.ts | 15 +++- .../test/server/altimate-error-bodies.test.ts | 77 ++++++++++++++++--- 5 files changed, 120 insertions(+), 30 deletions(-) diff --git a/packages/opencode/src/altimate/server/error-response.ts b/packages/opencode/src/altimate/server/error-response.ts index 371940859b..dead04989c 100644 --- a/packages/opencode/src/altimate/server/error-response.ts +++ b/packages/opencode/src/altimate/server/error-response.ts @@ -1,9 +1,7 @@ import { NamedError } from "@opencode-ai/core/util/error" -import type { Log } from "@/util/log" -// What the server's catch-all error handlers send back. For an error they don't recognise, a fixed message and a -// ref, as the HttpApi error middleware answers (httpapi/middleware/error.ts): never the error's own text, stack or -// file paths. The full error is logged server-side under the same ref. +// What the server's error handlers send back. For an error they don't recognise, a fixed message and a ref: never +// the error's own text, stack or file paths. Each handler logs the full error once, under the same ref. /** HTTP status for an error the handlers know by name: a remote the server depends on failed (502). */ export function upstreamStatus(name: string): 502 | undefined { @@ -16,12 +14,26 @@ const FRAME = /^\s+at\s/ export const UNEXPECTED = "Unexpected server error. Check server logs for details." +/** A reference for one failure: the handler logs the error under it, and an unknown error's response carries it. */ +export function errorRef(): string { + return `err_${crypto.randomUUID().slice(0, 8)}` +} + +/** A NamedError keeps its text in `data.message`; its own `message` is only its name. */ +function namedErrorMessage(err: unknown): string | undefined { + if (typeof err !== "object" || err === null || !("data" in err)) return undefined + const data = (err as { data?: unknown }).data + if (typeof data !== "object" || data === null) return undefined + const message = (data as { message?: unknown }).message + return typeof message === "string" && message ? message : undefined +} + /** * An error's message without stack-frame lines (some errors carry frames in the message itself), for a client * that has to tell a user why their own request failed, such as a session's error event. */ export function clientMessage(err: unknown): string { - const raw = err instanceof Error ? err.message : String(err) + const raw = namedErrorMessage(err) ?? (err instanceof Error ? err.message : String(err)) const message = raw .split("\n") .filter((line) => !FRAME.test(line)) @@ -30,9 +42,7 @@ export function clientMessage(err: unknown): string { return message || UNEXPECTED } -/** The response body for an error no handler recognises, logged in full under a ref that the body carries. */ -export function unknownErrorBody(log: Log.Logger, err: unknown) { - const ref = `err_${crypto.randomUUID().slice(0, 8)}` - log.error("unexpected error", { ref, error: err }) +/** The response body for an error no handler recognises: the fixed message and the ref it was logged under. */ +export function unknownErrorBody(ref: string) { return new NamedError.Unknown({ message: UNEXPECTED, ref }).toObject() } diff --git a/packages/opencode/src/config/config.ts b/packages/opencode/src/config/config.ts index cd81ef2b16..345a4c2e87 100644 --- a/packages/opencode/src/config/config.ts +++ b/packages/opencode/src/config/config.ts @@ -334,6 +334,9 @@ export const layer = Layer.effect( headers: Record | undefined, schema: S, loginOrigin: string, + // altimate_change start — how errors name the remote: never a URL with a substituted token in it + shown: string = url, + // altimate_change end ) { const response = yield* HttpClient.filterStatusOk(withTransientReadRetry(http)) .execute( @@ -345,9 +348,10 @@ export const layer = Layer.effect( Effect.catch((error) => Effect.die( new RemoteUnavailableError({ - remote: url, + remote: shown, status: error.reason._tag === "StatusCodeError" ? error.reason.response.status : undefined, - reason: error.reason._tag === "StatusCodeError" ? `HTTP ${error.reason.response.status}` : error.reason._tag, + reason: + error.reason._tag === "StatusCodeError" ? `HTTP ${error.reason.response.status}` : error.reason._tag, }), ), ), @@ -356,14 +360,17 @@ export const layer = Layer.effect( const body = yield* response.text.pipe( // altimate_change start — see above Effect.catch((error) => - Effect.die(new RemoteUnavailableError({ remote: url, status: response.status, reason: error.reason._tag })), + // The status passed filterStatusOk, so it says nothing about this failure. + Effect.die(new RemoteUnavailableError({ remote: shown, reason: error.reason._tag })), ), // altimate_change end ) // An auth proxy can answer with an HTML login page at HTTP 200 (passes filterStatusOk); treat it as a re-auth error, not a decode failure. const contentType = (response.headers["content-type"] ?? "").toLowerCase() if (contentType.includes("html") || /^\s* Effect.die(new Error(`failed to decode remote config from ${url}: ${String(error)}`))), @@ -569,7 +576,12 @@ export const layer = Layer.effect( const fetchedConfig = remote ? yield* Effect.gen(function* () { yield* Effect.logDebug("fetching remote config", { url: remote.url }) - const data = yield* fetchRemoteJson(remote.url, remote.headers, Schema.Json, url) + // altimate_change start — errors name the remote by its template (`{env:…}` and all), not the + // substituted URL, which can carry the auth token + const template = isRecord(wellknown.remote_config) ? wellknown.remote_config.url : undefined + const shown = typeof template === "string" ? template : url + const data = yield* fetchRemoteJson(remote.url, remote.headers, Schema.Json, url, shown) + // altimate_change end if (isRecord(data) && isRecord(data.config)) return data.config if (isRecord(data)) return data return yield* Effect.die( diff --git a/packages/opencode/src/server/middleware.ts b/packages/opencode/src/server/middleware.ts index dfd3f37a4a..b36e2a3f8c 100644 --- a/packages/opencode/src/server/middleware.ts +++ b/packages/opencode/src/server/middleware.ts @@ -8,14 +8,18 @@ import { HTTPException } from "hono/http-exception" import type { Log } from "../util/log" // altimate_change start — client-safe error responses import { NamedError as CoreNamedError } from "@opencode-ai/core/util/error" -import { unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" +import { errorRef, unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" // altimate_change end export function errorHandler(log: Log.Logger): ErrorHandler { return (err, c) => { + // altimate_change start — one log line per error, under the ref an unknown error's response carries + const ref = errorRef() log.error("failed", { + ref, error: err, }) + // altimate_change end if (err instanceof NamedError) { let status: ContentfulStatusCode if (err instanceof NotFoundError) status = 404 @@ -35,7 +39,7 @@ export function errorHandler(log: Log.Logger): ErrorHandler { return c.json(err.toObject(), { status: upstreamStatus(err.name) ?? 500 }) } // Never send an error's text or stack to the client: a fixed message and a ref, logged in full. - return c.json(unknownErrorBody(log, err), { + return c.json(unknownErrorBody(ref), { status: 500, }) // altimate_change end diff --git a/packages/opencode/src/server/server.ts b/packages/opencode/src/server/server.ts index d58cf986a0..fac9a96013 100644 --- a/packages/opencode/src/server/server.ts +++ b/packages/opencode/src/server/server.ts @@ -11,7 +11,7 @@ import z from "zod" import { Provider } from "../provider/provider" import { NamedError } from "@opencode-ai/core/util/error" // altimate_change start — client-safe error responses -import { unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" +import { errorRef, unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" // altimate_change end import { LSP } from "../lsp" import { Format } from "../format" @@ -266,9 +266,13 @@ export namespace Server { // altimate_change end return app .onError((err, c) => { + // altimate_change start — one log line per error, under the ref an unknown error's response carries + const ref = errorRef() log.error("failed", { + ref, error: err, }) + // altimate_change end if (err instanceof NamedError) { let status: ContentfulStatusCode if (err instanceof NotFoundError) status = 404 @@ -298,8 +302,13 @@ export namespace Server { } // altimate_change end if (err instanceof HTTPException) return err.getResponse() - // altimate_change start — never send an error's text or stack to the client: a fixed message and a ref, logged in full. - return c.json(unknownErrorBody(log, err), { + // altimate_change start — a busy session answers 400 with its message, as the instance routes' handler does + // (middleware.ts); everything else unrecognised gets a fixed message and the ref it was logged under, never + // the error's text or stack. + if (err instanceof Session.BusyError) { + return c.json(new NamedError.Unknown({ message: err.message }).toObject(), { status: 400 }) + } + return c.json(unknownErrorBody(ref), { status: 500, }) // altimate_change end diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts index a80e0b4cfd..6055141a4d 100644 --- a/packages/opencode/test/server/altimate-error-bodies.test.ts +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -11,7 +11,15 @@ import { Hono } from "hono" import { ConfigErrorV1 } from "@opencode-ai/core/v1/config/error" import { Server } from "../../src/server/server" import { errorHandler } from "../../src/server/middleware" -import { clientMessage, unknownErrorBody, upstreamStatus, UNEXPECTED } from "../../src/altimate/server/error-response" +import { NamedError } from "@opencode-ai/core/util/error" +import { Session } from "../../src/session" +import { + clientMessage, + errorRef, + unknownErrorBody, + upstreamStatus, + UNEXPECTED, +} from "../../src/altimate/server/error-response" import type { Log } from "../../src/util/log" import { Global } from "@/global" import { Filesystem } from "@/util/filesystem" @@ -47,6 +55,12 @@ describe("clientMessage", () => { expect(clientMessage(" at new Promise ()")).toBe(UNEXPECTED) }) + test("reads a NamedError's text from data.message, where it keeps it", () => { + const err = new NamedError.Unknown({ message: "provider refused the key\n at call (/srv/p.ts:3:4)" }) + expect(err.message).toBe("UnknownError") + expect(clientMessage(err)).toBe("provider refused the key") + }) + test("falls back to the fixed message when nothing is left", () => { expect(clientMessage(new Error(""))).toBe(UNEXPECTED) expect(clientMessage(" at fn (/a.js:1:2)")).toBe(UNEXPECTED) @@ -59,15 +73,10 @@ test("upstreamStatus is 502 only for an unavailable remote config", () => { expect(upstreamStatus("UnknownError")).toBeUndefined() }) -test("unknownErrorBody carries a fixed message and a ref, and logs the error under that ref", () => { - const { log, calls } = capturingLog() - const err = new Error("secret marker") - const body = unknownErrorBody(log, err) as { name: string; data: { message: string; ref: string } } - expect(body.name).toBe("UnknownError") - expect(body.data.message).toBe(UNEXPECTED) - expect(body.data.ref).toMatch(/^err_[0-9a-f-]{8}$/) - expect(JSON.stringify(body)).not.toContain("secret marker") - expect(calls).toEqual([{ message: "unexpected error", extra: { ref: body.data.ref, error: err } }]) +test("unknownErrorBody carries only the fixed message and the ref it is given", () => { + const ref = errorRef() + expect(ref).toMatch(/^err_[0-9a-f-]{8}$/) + expect(unknownErrorBody(ref)).toEqual({ name: "UnknownError", data: { message: UNEXPECTED, ref } }) }) describe("middleware.ts errorHandler", () => { @@ -89,7 +98,14 @@ describe("middleware.ts errorHandler", () => { expect(text).not.toMatch(STACKISH) const body = JSON.parse(text) expect(body).toMatchObject({ name: "UnknownError", data: { message: UNEXPECTED } }) - expect(calls.some((c) => c.extra.ref === body.data.ref && c.extra.error === err)).toBe(true) + // One log line, and it names the ref the client got. + expect(calls).toEqual([{ message: "failed", extra: { ref: body.data.ref, error: err } }]) + }) + + test("a busy session answers 400 with its message", async () => { + const response = await app(new Session.BusyError("ses_busy")).hono.request("/boom") + expect(response.status).toBe(400) + expect(await response.json()).toEqual({ name: "UnknownError", data: { message: "Session ses_busy is busy" } }) }) test("an unavailable remote config answers 502 with its name, remote, status and reason", async () => { @@ -156,6 +172,45 @@ describe("full server, remote config unavailable", () => { }) }) + test("an /api route sends no stack either (an empty 500: the instance fails to load before any handler runs)", async () => { + const remote = Bun.serve({ port: 0, fetch: () => new Response("upstream exploded", { status: 500 }) }) + servers.push(remote) + await withWellKnown(remote.url.origin) + await using dir = await tmpdir({ git: true }) + const response = await Server.Default().request("/api/config", { headers: { "x-opencode-directory": dir.path } }) + const text = await response.text() + expect(response.status).toBe(500) + expect(text).not.toMatch(STACKISH) + expect(text).not.toContain("upstream exploded") + }) + + test("a failing remote config URL is named by its template, never with the token filled in", async () => { + const asked: string[] = [] + const remote = Bun.serve({ + port: 0, + fetch: (req) => { + const url = new URL(req.url) + asked.push(url.pathname + url.search) + if (url.pathname === "/.well-known/opencode") { + return Response.json({ remote_config: { url: `${url.origin}/cfg?token={env:TEST_TOKEN}` } }) + } + return new Response("no", { status: 500 }) + }, + }) + servers.push(remote) + await withWellKnown(remote.url.origin) + await using dir = await tmpdir({ git: true }) + const response = await Server.Default().request("/agent", { headers: { "x-opencode-directory": dir.path } }) + const text = await response.text() + expect(asked).toContain("/cfg?token=test-token") + expect(response.status).toBe(502) + expect(text).not.toContain("test-token") + expect(JSON.parse(text)).toEqual({ + name: "ConfigRemoteUnavailableError", + data: { remote: `${remote.url.origin}/cfg?token={env:TEST_TOKEN}`, status: 500, reason: "HTTP 500" }, + }) + }) + test("GET /agent answers 502 with the transport reason when the remote refuses the connection", async () => { const closed = Bun.serve({ port: 0, fetch: () => new Response("") }) const origin = closed.url.origin From 236186bc51dff8f0a61a44b6a14140833d224904 Mon Sep 17 00:00:00 2001 From: "Ralph Sto. Domingo" Date: Fri, 20 Nov 2026 11:26:54 +0800 Subject: [PATCH 4/4] fix: an empty NamedError message falls back to the fixed text Also pin that the /api route's 500 body is empty. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VEmKQu1Qn99YbrBzhKdtAr --- packages/opencode/src/altimate/server/error-response.ts | 2 +- packages/opencode/test/server/altimate-error-bodies.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/opencode/src/altimate/server/error-response.ts b/packages/opencode/src/altimate/server/error-response.ts index dead04989c..a62a6ee73d 100644 --- a/packages/opencode/src/altimate/server/error-response.ts +++ b/packages/opencode/src/altimate/server/error-response.ts @@ -25,7 +25,7 @@ function namedErrorMessage(err: unknown): string | undefined { const data = (err as { data?: unknown }).data if (typeof data !== "object" || data === null) return undefined const message = (data as { message?: unknown }).message - return typeof message === "string" && message ? message : undefined + return typeof message === "string" ? message : undefined } /** diff --git a/packages/opencode/test/server/altimate-error-bodies.test.ts b/packages/opencode/test/server/altimate-error-bodies.test.ts index 6055141a4d..977d80188a 100644 --- a/packages/opencode/test/server/altimate-error-bodies.test.ts +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -59,6 +59,7 @@ describe("clientMessage", () => { const err = new NamedError.Unknown({ message: "provider refused the key\n at call (/srv/p.ts:3:4)" }) expect(err.message).toBe("UnknownError") expect(clientMessage(err)).toBe("provider refused the key") + expect(clientMessage(new NamedError.Unknown({ message: "" }))).toBe(UNEXPECTED) }) test("falls back to the fixed message when nothing is left", () => { @@ -180,8 +181,7 @@ describe("full server, remote config unavailable", () => { const response = await Server.Default().request("/api/config", { headers: { "x-opencode-directory": dir.path } }) const text = await response.text() expect(response.status).toBe(500) - expect(text).not.toMatch(STACKISH) - expect(text).not.toContain("upstream exploded") + expect(text).toBe("") }) test("a failing remote config URL is named by its template, never with the token filled in", async () => {