Skip to content

Commit 3f90ffa

Browse files
committed
fix(core): install npm plugins into config directories instead of cache
Plugins declared in config files are now installed into the config directory that declared them (e.g. ~/.config/opencode/ or .opencode/) instead of ~/.cache/opencode/. This prevents plugin data loss on cache version bumps and ensures plugins can reliably locate their data files relative to the config directory. Fixes #12222
1 parent 1dd88ae commit 3f90ffa

3 files changed

Lines changed: 100 additions & 31 deletions

File tree

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

Lines changed: 68 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import { Event } from "../server/event"
3131
import { PackageRegistry } from "@/bun/registry"
3232
import { proxied } from "@/util/proxied"
3333
import { iife } from "@/util/iife"
34+
import { BUILTIN_PLUGINS } from "@/plugin/builtin"
3435

3536
export namespace Config {
3637
const log = Log.create({ service: "config" })
@@ -147,7 +148,21 @@ export namespace Config {
147148

148149
const deps = []
149150

151+
// Collect npm plugins declared in each directory's config so we can
152+
// install them into that directory (instead of ~/.cache/opencode/)
153+
const dirPlugins = new Map<string, string[]>()
154+
155+
// Plugins from global/project configs that were loaded before the directory
156+
// loop get assigned to the global config directory.
157+
// Built-in plugins also get installed in the global config directory.
158+
const preloopPlugins = [
159+
...npmPlugins(result.plugin ?? []),
160+
...(!Flag.OPENCODE_DISABLE_DEFAULT_PLUGINS ? BUILTIN_PLUGINS : []),
161+
]
162+
150163
for (const dir of unique(directories)) {
164+
const pluginsBefore = [...(result.plugin ?? [])]
165+
151166
if (dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR) {
152167
for (const file of ["opencode.jsonc", "opencode.json"]) {
153168
log.debug(`loading config from ${path.join(dir, file)}`)
@@ -159,10 +174,17 @@ export namespace Config {
159174
}
160175
}
161176

177+
// Determine which npm plugins this directory's config added
178+
const added = npmPlugins((result.plugin ?? []).filter((p) => !pluginsBefore.includes(p)))
179+
180+
// First directory (global config) also gets the pre-loop plugins
181+
const plugins = dir === Global.Path.config ? [...preloopPlugins, ...added] : added
182+
if (plugins.length) dirPlugins.set(dir, plugins)
183+
162184
deps.push(
163185
iife(async () => {
164-
const shouldInstall = await needsInstall(dir)
165-
if (shouldInstall) await installDependencies(dir)
186+
const shouldInstall = await needsInstall(dir, dirPlugins.get(dir))
187+
if (shouldInstall) await installDependencies(dir, dirPlugins.get(dir))
166188
}),
167189
)
168190

@@ -247,7 +269,19 @@ export namespace Config {
247269
await Promise.all(deps)
248270
}
249271

250-
export async function installDependencies(dir: string) {
272+
/** Extract npm plugin specifiers (non-file:// plugins) */
273+
function npmPlugins(plugins: string[]): string[] {
274+
return plugins.filter((p) => !p.startsWith("file://"))
275+
}
276+
277+
/** Parse a plugin specifier into package name and version */
278+
function parsePlugin(specifier: string): { pkg: string; version: string } {
279+
const lastAt = specifier.lastIndexOf("@")
280+
if (lastAt > 0) return { pkg: specifier.substring(0, lastAt), version: specifier.substring(lastAt + 1) }
281+
return { pkg: specifier, version: "latest" }
282+
}
283+
284+
export async function installDependencies(dir: string, plugins?: string[]) {
251285
const pkg = path.join(dir, "package.json")
252286
const targetVersion = Installation.isLocal() ? "*" : Installation.VERSION
253287

@@ -258,15 +292,24 @@ export namespace Config {
258292
...json.dependencies,
259293
"@opencode-ai/plugin": targetVersion,
260294
}
295+
296+
// Add declared npm plugins to this directory's package.json
297+
// so they get installed here instead of in ~/.cache/opencode/
298+
if (plugins) {
299+
for (const specifier of plugins) {
300+
const parsed = parsePlugin(specifier)
301+
json.dependencies[parsed.pkg] = parsed.version
302+
}
303+
}
304+
261305
await Bun.write(pkg, JSON.stringify(json, null, 2))
262306
await new Promise((resolve) => setTimeout(resolve, 3000))
263307

264308
const gitignore = path.join(dir, ".gitignore")
265309
const hasGitIgnore = await Bun.file(gitignore).exists()
266310
if (!hasGitIgnore) await Bun.write(gitignore, ["node_modules", "package.json", "bun.lock", ".gitignore"].join("\n"))
267311

268-
// Install any additional dependencies defined in the package.json
269-
// This allows local plugins and custom tools to use external packages
312+
// Install all dependencies (including npm plugins) in this config directory
270313
await BunProc.run(
271314
[
272315
"install",
@@ -286,7 +329,7 @@ export namespace Config {
286329
}
287330
}
288331

289-
async function needsInstall(dir: string) {
332+
async function needsInstall(dir: string, plugins?: string[]) {
290333
// Some config dirs may be read-only.
291334
// Installing deps there will fail; skip installation in that case.
292335
const writable = await isWritable(dir)
@@ -311,15 +354,27 @@ export namespace Config {
311354
const targetVersion = Installation.isLocal() ? "latest" : Installation.VERSION
312355
if (targetVersion === "latest") {
313356
const isOutdated = await PackageRegistry.isOutdated("@opencode-ai/plugin", depVersion, dir)
314-
if (!isOutdated) return false
315-
log.info("Cached version is outdated, proceeding with install", {
316-
pkg: "@opencode-ai/plugin",
317-
cachedVersion: depVersion,
318-
})
357+
if (isOutdated) {
358+
log.info("Cached version is outdated, proceeding with install", {
359+
pkg: "@opencode-ai/plugin",
360+
cachedVersion: depVersion,
361+
})
362+
return true
363+
}
364+
} else if (depVersion !== targetVersion) {
319365
return true
320366
}
321-
if (depVersion === targetVersion) return false
322-
return true
367+
368+
// Check if any declared plugins are missing from the installed dependencies
369+
if (plugins) {
370+
for (const specifier of plugins) {
371+
const parsed = parsePlugin(specifier)
372+
if (!dependencies[parsed.pkg]) return true
373+
if (!existsSync(path.join(nodeModules, ...parsed.pkg.split("/")))) return true
374+
}
375+
}
376+
377+
return false
323378
}
324379

325380
function rel(item: string, patterns: string[]) {
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
/** Built-in npm plugins that are installed by default (unless OPENCODE_DISABLE_DEFAULT_PLUGINS is set) */
2+
export const BUILTIN_PLUGINS = ["[email protected]"]

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

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,33 @@ import { Bus } from "../bus"
44
import { Log } from "../util/log"
55
import { createOpencodeClient } from "@opencode-ai/sdk"
66
import { Server } from "../server/server"
7-
import { BunProc } from "../bun"
87
import { Instance } from "../project/instance"
98
import { Flag } from "../flag/flag"
109
import { CodexAuthPlugin } from "./codex"
1110
import { Session } from "../session"
1211
import { NamedError } from "@opencode-ai/util/error"
1312
import { CopilotAuthPlugin } from "./copilot"
1413
import { gitlabAuthPlugin as GitlabAuthPlugin } from "@gitlab/opencode-gitlab-auth"
14+
import path from "path"
15+
import { existsSync } from "fs"
16+
import { BUILTIN_PLUGINS } from "./builtin"
1517

1618
export namespace Plugin {
1719
const log = Log.create({ service: "plugin" })
1820

19-
const BUILTIN = ["[email protected]"]
21+
export const BUILTIN = BUILTIN_PLUGINS
2022

2123
// Built-in plugins that are directly imported (not installed from npm)
2224
const INTERNAL_PLUGINS: PluginInstance[] = [CodexAuthPlugin, CopilotAuthPlugin, GitlabAuthPlugin]
2325

26+
/** Resolve an npm plugin from the config directories' node_modules */
27+
function resolve(pkg: string, directories: string[]): string | undefined {
28+
for (const dir of directories) {
29+
const mod = path.join(dir, "node_modules", ...pkg.split("/"))
30+
if (existsSync(mod)) return mod
31+
}
32+
}
33+
2434
const state = Instance.state(async () => {
2535
const client = createOpencodeClient({
2636
baseUrl: "http://localhost:4096",
@@ -50,33 +60,35 @@ export namespace Plugin {
5060
plugins.push(...BUILTIN)
5161
}
5262

63+
// Wait for dependencies so npm plugins are installed in their config directories
64+
await Config.waitForDependencies()
65+
const directories = await Config.directories()
66+
5367
for (let plugin of plugins) {
5468
// ignore old codex plugin since it is supported first party now
5569
if (plugin.includes("opencode-openai-codex-auth") || plugin.includes("opencode-copilot-auth")) continue
5670
log.info("loading plugin", { path: plugin })
5771
if (!plugin.startsWith("file://")) {
5872
const lastAtIndex = plugin.lastIndexOf("@")
5973
const pkg = lastAtIndex > 0 ? plugin.substring(0, lastAtIndex) : plugin
60-
const version = lastAtIndex > 0 ? plugin.substring(lastAtIndex + 1) : "latest"
6174
const builtin = BUILTIN.some((x) => x.startsWith(pkg + "@"))
62-
plugin = await BunProc.install(pkg, version).catch((err) => {
63-
if (!builtin) throw err
6475

65-
const message = err instanceof Error ? err.message : String(err)
66-
log.error("failed to install builtin plugin", {
67-
pkg,
68-
version,
69-
error: message,
70-
})
76+
// Resolve the plugin from config directories' node_modules
77+
const resolved = resolve(pkg, directories)
78+
if (!resolved) {
79+
const message = `Plugin ${plugin} not found in any config directory`
80+
if (!builtin) {
81+
log.error("plugin not found", { plugin, directories })
82+
throw new Error(message)
83+
}
84+
85+
log.error("failed to resolve builtin plugin", { plugin })
7186
Bus.publish(Session.Event.Error, {
72-
error: new NamedError.Unknown({
73-
message: `Failed to install built-in plugin ${pkg}@${version}: ${message}`,
74-
}).toObject(),
87+
error: new NamedError.Unknown({ message }).toObject(),
7588
})
76-
77-
return ""
78-
})
79-
if (!plugin) continue
89+
continue
90+
}
91+
plugin = resolved
8092
}
8193
const mod = await import(plugin)
8294
// Prevent duplicate initialization when plugins export the same function

0 commit comments

Comments
 (0)