Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/core/src/v1/config/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", {
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
remote: Schema.String,
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
status: Schema.optional(Schema.Number),
reason: Schema.String,
})
// altimate_change end
48 changes: 48 additions & 0 deletions packages/opencode/src/altimate/server/error-response.ts
Original file line number Diff line number Diff line change
@@ -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
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
}

// An indented `at …` line: how V8, JSC and Bun print every stack frame, with or without a source location
// (`at new Promise (<anonymous>)`, `at async Promise.all (index 0)`).
const FRAME = /^\s+at\s/

export const UNEXPECTED = "Unexpected server error. Check server logs for details."
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved

/** 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()
}
9 changes: 9 additions & 0 deletions packages/opencode/src/cli/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
39 changes: 34 additions & 5 deletions packages/opencode/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -332,21 +334,43 @@ export const layer = Layer.effect(
headers: Record<string, string> | 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*<!doctype|^\s*<html/i.test(body)) {
return yield* Effect.die(new RemoteAuthError({ url: loginOrigin, remote: url }))
// altimate_change start — see `shown` above
return yield* Effect.die(new RemoteAuthError({ url: loginOrigin, remote: shown }))
// altimate_change end
}
return yield* Schema.decodeEffect(Schema.fromJsonString(schema))(body).pipe(
Effect.catch((error) => Effect.die(new Error(`failed to decode remote config from ${url}: ${String(error)}`))),
Expand Down Expand Up @@ -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(
Expand Down
18 changes: 16 additions & 2 deletions packages/opencode/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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(),
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
// altimate_change end
})
}),
),
Expand Down
21 changes: 19 additions & 2 deletions packages/opencode/src/server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -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 })
}
Expand All @@ -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) {
Comment thread
ralphstodomingo marked this conversation as resolved.
Resolved
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.
Expand Down
12 changes: 12 additions & 0 deletions packages/opencode/test/cli/error-format.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading