Skip to content
Merged
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
69 changes: 69 additions & 0 deletions packages/opencode/src/altimate/server/error-response.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { NodeFileSystem } from "@effect/platform-node"
import { fileLogger } from "@opencode-ai/core/observability/logging"
import { NamedError } from "@opencode-ai/core/util/error"
import { Cause, Effect, Layer, Logger } from "effect"

// 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. The full error is recorded under the same ref (recordUnknownError).

/** 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()
}

const unknownErrorLog = Logger.layer([fileLogger()], { mergeWithExisting: false }).pipe(
Layer.provide(NodeFileSystem.layer),
)

/**
* Record an error no handler recognises under its ref in opencode.log: the file the /api error middleware's refs go
* to, written whether or not --print-logs is on. Only the file, never stderr, which belongs to the TUI when it runs
* the server in-process. A failed write never fails the response.
*/
export function recordUnknownError(service: string, ref: string, error: unknown): Promise<void> {
return Effect.runPromise(
Effect.logError("unexpected error", { ref, cause: Cause.pretty(Cause.die(error)) }).pipe(
Effect.annotateLogs({ service }),
Effect.provide(unknownErrorLog),
),
).catch(() => undefined)
}
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
20 changes: 16 additions & 4 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, recordUnknownError, 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,
})
Comment on lines +17 to 21

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR (bug): the ref this response points to isn't recorded under default settings.

    const ref = errorRef()
    log.error("failed", {
      ref,
      error: err,
    })

The unknown-error response now sends only a fixed message and a ref, and tells the client to look in the server log for it. But log.error goes through shouldLog() → printEnabled() (packages/opencode/src/altimate/util/log.ts:27-44). That is false unless --print-logs / ALTIMATE_PRINT_LOGS / OPENCODE_PRINT_LOGS is set, and the logger has no other sink. Under a plain altimate-code serve, the client gets a ref and the original error is gone. Before this change it was at least in the response body. The capturing-logger test stubs the logger, so it can't see this.

Suggested fix: always write referenced unknown errors to a sink that is kept, for example by bypassing the print gate for this one error line in serve mode while keeping the TUI isolated. Then add a test with the print flags unset that checks the response ref maps to a recorded full error.

This is the same issue as in server.ts onError, here in the shared errorHandler.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same fix in a0d4696: errorHandler and server.ts share recordUnknownError, and the retention test goes through this handler.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified fixed at a0d4696: errorHandler now awaits the shared recordUnknownError, same as server.ts. Resolved.

// altimate_change end
if (err instanceof NamedError) {
let status: ContentfulStatusCode
if (err instanceof NotFoundError) status = 404
Expand All @@ -25,9 +33,13 @@ 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(), {
status: 500,
})
// 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, recorded in full first.
return recordUnknownError("server", ref, err).then(() => 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
23 changes: 19 additions & 4 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, recordUnknownError, 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,
})
Comment on lines +269 to 274

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MAJOR (bug): the ref this response points to isn't recorded under default settings.

        // 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,
        })

The unknown-error response now sends only a fixed message and a ref, and tells the client to look in the server log for it. But log.error goes through shouldLog() → printEnabled() (packages/opencode/src/altimate/util/log.ts:27-44). That is false unless --print-logs / ALTIMATE_PRINT_LOGS / OPENCODE_PRINT_LOGS is set, and the logger has no other sink. Under a plain altimate-code serve, the client gets a ref and the original error is gone. Before this change it was at least in the response body. The capturing-logger test stubs the logger, so it can't see this.

Suggested fix: always write referenced unknown errors to a sink that is kept, for example by bypassing the print gate for this one error line in serve mode while keeping the TUI isolated. Then add a test with the print flags unset that checks the response ref maps to a recorded full error.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in a0d4696. Before answering, both handlers now write the full error under the ref to opencode.log. That is the file the /api middleware's refs already land in, through core's fileLogger, and it's written whatever the print-logs flags say. It never goes to stderr, so the in-process TUI stays clean. A failed write doesn't fail the response. New test: print flags unset, real logger, and the response's ref shows up in opencode.log with the error text (fails on the previous head).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified fixed at a0d4696 by both re-reviewers (gpt-6-astra and gpt-6.1-sol). recordUnknownError writes the full error under the ref to <XDG data>/altimate-code/log/opencode.log whatever the print flags say. It installs only the file logger, so nothing goes to stderr and the TUI stays clean, and a failed write is caught so it doesn't fail the response. server.ts awaits it before answering. The retention test uses the real logger with the flags unset. Resolved.

// 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,20 @@ 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(), {
status: 500,
})
// 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 recordUnknownError("server", ref, err).then(() => 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