Skip to content

Commit 79f3a5c

Browse files
committed
fix(opencode): report invalid agent/mode configs instead of crashing or dropping them
An invalid file in agent/ threw ConfigInvalidError and aborted the whole load (no agents loaded); the same file in mode/ was silently dropped with no error. Both loaders now log, publish a session error, and skip just the bad file while loading the rest. Fixes anomalyco#27133
1 parent 549b146 commit 79f3a5c

2 files changed

Lines changed: 123 additions & 22 deletions

File tree

‎packages/opencode/src/config/agent.ts‎

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ import { Glob } from "@opencode-ai/core/util/glob"
99
import { configEntryNameFromPath } from "./entry-name"
1010
import * as ConfigMarkdown from "./markdown"
1111
import { ConfigModelID } from "./model-id"
12-
import { ConfigParse } from "./parse"
1312
import { ConfigPermission } from "./permission"
1413

1514
const log = Log.create({ service: "config" })
@@ -104,6 +103,18 @@ export const Info = AgentSchema.pipe(
104103
).annotate({ identifier: "AgentConfig" })
105104
export type Info = Schema.Schema.Type<typeof Info>
106105

106+
// Surface a config-loading failure to the user and log it, so an invalid file is
107+
// reported instead of crashing the whole load (load) or vanishing silently (loadMode).
108+
// Publishing requires an instance context that isn't always present (e.g. tests), so a
109+
// publish failure is swallowed — the log line is the durable record, the event is best-effort.
110+
async function report(label: string, item: string, message: string, err: unknown) {
111+
log.error(`failed to load ${label}`, { [label]: item, err })
112+
try {
113+
const { Session } = await import("@/session/session")
114+
await Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
115+
} catch {}
116+
}
117+
107118
export async function load(dir: string) {
108119
const result: Record<string, Info> = {}
109120
for (const item of await Glob.scan("{agent,agents}/**/*.md", {
@@ -113,25 +124,24 @@ export async function load(dir: string) {
113124
symlink: true,
114125
})) {
115126
const md = await ConfigMarkdown.parse(item).catch(async (err) => {
116-
const message = ConfigMarkdown.FrontmatterError.isInstance(err)
117-
? err.data.message
118-
: `Failed to parse agent ${item}`
119-
const { Session } = await import("@/session/session")
120-
void Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
121-
log.error("failed to load agent", { agent: item, err })
127+
const message = ConfigMarkdown.FrontmatterError.isInstance(err) ? err.data.message : `Failed to parse agent ${item}`
128+
await report("agent", item, message, err)
122129
return undefined
123130
})
124131
if (!md) continue
125132

126133
const patterns = ["/.opencode/agent/", "/.opencode/agents/", "/agent/", "/agents/"]
127-
const name = configEntryNameFromPath(item, patterns)
128-
129134
const config = {
130-
name,
135+
name: configEntryNameFromPath(item, patterns),
131136
...md.data,
132137
prompt: md.content.trim(),
133138
}
134-
result[config.name] = ConfigParse.schema(Info, config, item)
139+
const parsed = Schema.decodeUnknownExit(Info)(config, { errors: "all", propertyOrder: "original" })
140+
if (Exit.isFailure(parsed)) {
141+
await report("agent", item, `Failed to parse agent ${item}`, parsed.cause)
142+
continue
143+
}
144+
result[config.name] = parsed.value
135145
}
136146
return result
137147
}
@@ -145,12 +155,8 @@ export async function loadMode(dir: string) {
145155
symlink: true,
146156
})) {
147157
const md = await ConfigMarkdown.parse(item).catch(async (err) => {
148-
const message = ConfigMarkdown.FrontmatterError.isInstance(err)
149-
? err.data.message
150-
: `Failed to parse mode ${item}`
151-
const { Session } = await import("@/session/session")
152-
void Bus.publish(Session.Event.Error, { error: new NamedError.Unknown({ message }).toObject() })
153-
log.error("failed to load mode", { mode: item, err })
158+
const message = ConfigMarkdown.FrontmatterError.isInstance(err) ? err.data.message : `Failed to parse mode ${item}`
159+
await report("mode", item, message, err)
154160
return undefined
155161
})
156162
if (!md) continue
@@ -161,11 +167,13 @@ export async function loadMode(dir: string) {
161167
prompt: md.content.trim(),
162168
}
163169
const parsed = Schema.decodeUnknownExit(Info)(config, { errors: "all", propertyOrder: "original" })
164-
if (Exit.isSuccess(parsed)) {
165-
result[config.name] = {
166-
...parsed.value,
167-
mode: "primary" as const,
168-
}
170+
if (Exit.isFailure(parsed)) {
171+
await report("mode", item, `Failed to parse mode ${item}`, parsed.cause)
172+
continue
173+
}
174+
result[config.name] = {
175+
...parsed.value,
176+
mode: "primary" as const,
169177
}
170178
}
171179
return result

‎packages/opencode/test/config/config.test.ts‎

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { test, expect, describe, mock, afterEach, beforeEach } from "bun:test"
22
import { Effect, Layer, Option } from "effect"
33
import { NodeFileSystem, NodePath } from "@effect/platform-node"
4+
import { Bus } from "@/bus"
5+
import { Session } from "@/session/session"
46
import { Config } from "@/config/config"
57
import { ConfigManaged } from "@/config/managed"
68
import { ConfigParse } from "../../src/config/parse"
@@ -81,6 +83,22 @@ const listDirs = () =>
8183
const ready = () =>
8284
Effect.runPromise(Config.Service.use((svc) => svc.waitForDependencies()).pipe(Effect.scoped, Effect.provide(layer)))
8385

86+
// Collect Session.Event.Error messages, and return a promise that resolves as soon
87+
// as the first message containing `pattern` arrives (with a timeout so a missing
88+
// event fails the test instead of hanging it).
89+
function subscribeErrors(pattern: string, timeoutMs = 500) {
90+
const errors: string[] = []
91+
const matched = Promise.withResolvers<void>()
92+
Bus.subscribe(Session.Event.Error, (evt) => {
93+
const data = evt.properties.error?.data
94+
if (!data || !("message" in data) || typeof data.message !== "string") return
95+
errors.push(data.message)
96+
if (data.message.includes(pattern)) matched.resolve()
97+
})
98+
const wait = Promise.race([matched.promise, Bun.sleep(timeoutMs)])
99+
return { errors, wait }
100+
}
101+
84102
// Get managed config directory from environment (set in preload.ts)
85103
const managedConfigDir = process.env.OPENCODE_TEST_MANAGED_CONFIG_DIR!
86104

@@ -891,6 +909,81 @@ Nested agent prompt`,
891909
})
892910
})
893911

912+
test("invalid agent file is reported and does not block valid agents", async () => {
913+
await using tmp = await tmpdir({
914+
init: async (dir) => {
915+
const agentDir = path.join(dir, ".opencode", "agent")
916+
await fs.mkdir(agentDir, { recursive: true })
917+
918+
await Filesystem.write(
919+
path.join(agentDir, "good.md"),
920+
`---
921+
model: test/model
922+
---
923+
Good agent prompt`,
924+
)
925+
926+
await Filesystem.write(
927+
path.join(agentDir, "broken.md"),
928+
`---
929+
temperature: "not a number"
930+
---
931+
Broken agent prompt`,
932+
)
933+
},
934+
})
935+
await WithInstance.provide({
936+
directory: tmp.path,
937+
fn: async () => {
938+
const { errors, wait } = subscribeErrors("broken.md")
939+
const config = await load()
940+
await wait
941+
// The valid agent still loads even though a sibling file is invalid.
942+
expect(config.agent?.["good"]).toMatchObject({ name: "good", model: "test/model" })
943+
expect(config.agent?.["broken"]).toBeUndefined()
944+
// The invalid file is reported rather than crashing the load.
945+
expect(errors.some((m) => m.includes("broken.md"))).toBe(true)
946+
},
947+
})
948+
})
949+
950+
test("invalid mode file is reported instead of being silently dropped", async () => {
951+
await using tmp = await tmpdir({
952+
init: async (dir) => {
953+
const modeDir = path.join(dir, ".opencode", "mode")
954+
await fs.mkdir(modeDir, { recursive: true })
955+
956+
await Filesystem.write(
957+
path.join(modeDir, "good.md"),
958+
`---
959+
model: test/model
960+
---
961+
Good mode prompt`,
962+
)
963+
964+
await Filesystem.write(
965+
path.join(modeDir, "broken.md"),
966+
`---
967+
temperature: "not a number"
968+
---
969+
Broken mode prompt`,
970+
)
971+
},
972+
})
973+
await WithInstance.provide({
974+
directory: tmp.path,
975+
fn: async () => {
976+
const { errors, wait } = subscribeErrors("broken.md")
977+
const config = await load()
978+
await wait
979+
expect(config.agent?.["good"]).toMatchObject({ name: "good", mode: "primary" })
980+
expect(config.agent?.["broken"]).toBeUndefined()
981+
// Previously the invalid mode vanished with no error; now it must be reported.
982+
expect(errors.some((m) => m.includes("broken.md"))).toBe(true)
983+
},
984+
})
985+
})
986+
894987
test("loads commands from .opencode/command (singular)", async () => {
895988
await using tmp = await tmpdir({
896989
init: async (dir) => {

0 commit comments

Comments
 (0)