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..a62a6ee73d --- /dev/null +++ b/packages/opencode/src/altimate/server/error-response.ts @@ -0,0 +1,48 @@ +import { NamedError } from "@opencode-ai/core/util/error" + +// 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 { + return name === "ConfigRemoteUnavailableError" ? 502 : undefined +} + +// 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." + +/** 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 : 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 = namedErrorMessage(err) ?? (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: 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/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..345a4c2e87 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" @@ -332,21 +334,43 @@ 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( 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: shown, + 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) => + // 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)}`))), @@ -552,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 278740c57d..b36e2a3f8c 100644 --- a/packages/opencode/src/server/middleware.ts +++ b/packages/opencode/src/server/middleware.ts @@ -6,12 +6,20 @@ 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 { 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 @@ -25,9 +33,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(ref), { 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..fac9a96013 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 { errorRef, unknownErrorBody, upstreamStatus } from "../altimate/server/error-response" +// altimate_change end import { LSP } from "../lsp" import { Format } from "../format" import { TuiRoutes } from "./routes/tui" @@ -263,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 @@ -275,6 +282,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 +296,22 @@ 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 — 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 }) .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..977d80188a --- /dev/null +++ b/packages/opencode/test/server/altimate-error-bodies.test.ts @@ -0,0 +1,229 @@ +// 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 { 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" +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("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("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") + expect(clientMessage(new NamedError.Unknown({ message: "" }))).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) + }) +}) + +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 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", () => { + 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 } }) + // 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 () => { + 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("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).toBe("") + }) + + 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 + 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" }, + }) + }) +})