Skip to content

Commit 246b0d8

Browse files
committed
fix: handle plugin build/syntax errors gracefully
When a plugin file has a syntax error (e.g., unterminated string literal), catch the build error and display it to the user via the Session.Event.Error bus instead of crashing with a black screen. Fixes anomalyco#13461
1 parent b06afd6 commit 246b0d8

1 file changed

Lines changed: 39 additions & 4 deletions

File tree

‎packages/opencode/src/plugin/index.ts‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,31 @@ import { NamedError } from "@opencode-ai/util/error"
1313
import { CopilotAuthPlugin } from "./copilot"
1414
import { gitlabAuthPlugin as GitlabAuthPlugin } from "@gitlab/opencode-gitlab-auth"
1515

16+
interface BuildMessage {
17+
message: string
18+
position?: {
19+
file?: string
20+
line?: number
21+
column?: number
22+
lineText?: string
23+
}
24+
}
25+
26+
function formatPluginBuildError(e: unknown, plugin: string): string {
27+
if (e instanceof AggregateError && e.errors?.length) {
28+
const buildError = e.errors.find((err): err is BuildMessage => err && typeof err === "object" && "message" in err)
29+
if (buildError) {
30+
const pos = buildError.position
31+
const file = pos?.file ? pos.file.replace(plugin, "").replace(/^\/+/, "") : undefined
32+
const line = pos?.line
33+
const details = file ? `${file}:${line ?? "?"}` : line ? `line ${line}` : undefined
34+
return details ? `${buildError.message} (${details})` : buildError.message
35+
}
36+
}
37+
if (e instanceof Error) return e.message
38+
return String(e)
39+
}
40+
1641
export namespace Plugin {
1742
const log = Log.create({ service: "plugin" })
1843

@@ -79,10 +104,20 @@ export namespace Plugin {
79104
})
80105
if (!plugin) continue
81106
}
82-
const mod = await import(plugin)
83-
// Prevent duplicate initialization when plugins export the same function
84-
// as both a named export and default export (e.g., `export const X` and `export default X`).
85-
// Object.entries(mod) would return both entries pointing to the same function reference.
107+
let mod: Record<string, PluginInstance>
108+
try {
109+
mod = await import(plugin)
110+
} catch (e) {
111+
const name = Config.getPluginName(plugin)
112+
const message = formatPluginBuildError(e, plugin)
113+
log.error("failed to load plugin", { plugin: name, error: message })
114+
Bus.publish(Session.Event.Error, {
115+
error: new NamedError.Unknown({
116+
message: `Failed to load plugin "${name}": ${message}`,
117+
}).toObject(),
118+
})
119+
continue
120+
}
86121
const seen = new Set<PluginInstance>()
87122
for (const [_name, fn] of Object.entries<PluginInstance>(mod)) {
88123
if (seen.has(fn)) continue

0 commit comments

Comments
 (0)