diff --git a/packages/core/src/plugin/supervisor.ts b/packages/core/src/plugin/supervisor.ts index 75c5f7d86ab..9173dc2bafe 100644 --- a/packages/core/src/plugin/supervisor.ts +++ b/packages/core/src/plugin/supervisor.ts @@ -136,8 +136,8 @@ export const layer = Layer.effectDiscard( let running = new Map() let outdated = new Set() const updating = new Set() - // The check interval in which each `@latest` plugin last updated on its own. One attempt per interval, so an update - // that doesn't take, or a new version that fails to load, isn't retried on every reload. + // The check interval in which each outdated plugin was last considered for updating on its own. Once per interval, + // so an update that doesn't take, or a new version that fails to load, isn't retried on every reload. const attempted = new Map() let cycle = 0 let generation = 0 @@ -206,18 +206,15 @@ export const layer = Layer.effectDiscard( Effect.flatMap((checked) => Effect.gen(function* () { if (current !== generation) return - // Only a plugin written as `name@latest` updates on its own; the update reloads it. + // Only plugins that name what to follow (`@latest`, a range or a Git branch) update on their own; the + // update reloads them. yield* Effect.forEach( - checked.filter( - ([target, available]) => - available && - target.endsWith("@latest") && - attempted.get(target) !== cycle, - ), + checked.filter(([target, available]) => available && attempted.get(target) !== cycle), ([target]) => // Recorded first: the update itself triggers reloads, which check again while it runs. Effect.sync(() => attempted.set(target, cycle)).pipe( - Effect.andThen(updates.update(target)), + Effect.andThen(npm.follows(target)), + Effect.flatMap((follows) => (follows ? updates.update(target) : Effect.void)), Effect.catchCause((cause) => Effect.logWarning("failed to update plugin", { target, cause })), ), { concurrency: "unbounded", discard: true }, diff --git a/packages/core/test/npm.test.ts b/packages/core/test/npm.test.ts index 3bd82d27513..cf4d26baeb3 100644 --- a/packages/core/test/npm.test.ts +++ b/packages/core/test/npm.test.ts @@ -57,7 +57,7 @@ async function createGitFixture(directory: string) { async function createRegistryFixture(directory: string) { const tarballs = new Map() - for (const version of ["1.0.0", "1.1.0"]) { + for (const version of ["1.0.0", "1.1.0", "2.0.0"]) { const root = path.join(directory, version) await fs.mkdir(path.join(root, "package"), { recursive: true }) await writePackage(path.join(root, "package"), { @@ -165,6 +165,43 @@ describe("Npm.cacheKey", () => { }) }) +describe("Npm.follows", () => { + test("follows only @latest, ranges and Git branches", async () => { + await using tmp = await tmpdir() + const fixture = await createGitFixture(tmp.path) + await Bun.$`git -C ${fixture.repository} tag fixture-tag` + const repository = `git+${pathToFileURL(fixture.repository).href}` + const commit = "0123456789abcdef0123456789abcdef01234567" + const specs = { + plugin: false, + "plugin@latest": true, + "@acme/plugin@latest": true, + "plugin@next": false, + "plugin@^1.2.0": true, + "plugin@~1.2.0": true, + "plugin@1.x": true, + "plugin@>=1.2.0 <2": true, + "plugin@1.2.0": false, + "github:acme/plugin": false, + "github:acme/plugins#::path:packages/plugin": false, + [`github:acme/plugin#${commit}`]: false, + "github:acme/plugin#semver:^1.2.0": true, + [`${repository}#fixture-branch`]: true, + [`${repository}#fixture-branch::path:packages/subdirectory-plugin`]: true, + [`${repository}#fixture-tag`]: false, + [`${repository}#${fixture.commit.slice(0, 7)}`]: false, + "./plugin": false, + } + const followed = await Effect.gen(function* () { + const npm = yield* Npm.Service + return yield* Effect.forEach(Object.keys(specs), (spec) => + npm.follows(spec).pipe(Effect.map((value) => [spec, value])), + ) + }).pipe(Effect.scoped, Effect.provide(npmLayer(path.join(tmp.path, "cache"))), Effect.runPromise) + expect(Object.fromEntries(followed)).toEqual(specs) + }) +}) + describe("Npm.add", () => { test("locates cached scoped package specs without reifying", async () => { await using tmp = await tmpdir() @@ -470,6 +507,25 @@ describe("Npm.check and Npm.update", () => { expect(result.updated).toBeFalse() }) + test("updates a range only within it", async () => { + await using tmp = await tmpdir() + await using registry = await createRegistryFixture(tmp.path) + const cache = path.join(tmp.path, "cache") + const range = "@fixture/registry-plugin@^1.0.0" + await registry.configure(cache, range) + + const result = await Effect.gen(function* () { + const npm = yield* Npm.Service + const installed = yield* npm.add(range) + registry.state.latest = "2.0.0" + const outdated = yield* npm.check(range) + const updated = yield* npm.update(range) + return { installed: installed.version, outdated, updated: updated.version, current: yield* npm.check(range) } + }).pipe(Effect.scoped, Effect.provide(npmLayer(cache)), Effect.runPromise) + + expect(result).toEqual({ installed: "1.0.0", outdated: true, updated: "1.1.0", current: false }) + }) + test("never reports a pinned registry target as outdated", async () => { await using tmp = await tmpdir() await using registry = await createRegistryFixture(tmp.path) diff --git a/packages/core/test/plugin/fixture.ts b/packages/core/test/plugin/fixture.ts index b36f482f9d6..a6c84377ec8 100644 --- a/packages/core/test/plugin/fixture.ts +++ b/packages/core/test/plugin/fixture.ts @@ -60,6 +60,7 @@ const npmLayer = Layer.succeed( resolve: (name) => Effect.succeed({ directory: "", name }), check: () => Effect.succeed(false), update: (name) => Effect.succeed({ directory: "", name }), + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }), diff --git a/packages/core/test/plugin/home-memory.test.ts b/packages/core/test/plugin/home-memory.test.ts index 86904b9039a..e98a87ecff6 100644 --- a/packages/core/test/plugin/home-memory.test.ts +++ b/packages/core/test/plugin/home-memory.test.ts @@ -51,6 +51,7 @@ const instances = Layer.effect( resolve: (name) => Effect.succeed({ directory: "", name }), check: () => Effect.succeed(false), update: unexpected, + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }), diff --git a/packages/core/test/plugin/internal-flag.test.ts b/packages/core/test/plugin/internal-flag.test.ts index 64368de6977..f9a45c8c42c 100644 --- a/packages/core/test/plugin/internal-flag.test.ts +++ b/packages/core/test/plugin/internal-flag.test.ts @@ -51,6 +51,7 @@ const instances = Layer.effect( resolve: (name) => Effect.succeed({ directory: "", name }), check: () => Effect.succeed(false), update: unexpected, + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }), diff --git a/packages/core/test/plugin/provider-dynamic.test.ts b/packages/core/test/plugin/provider-dynamic.test.ts index ec85c6f09ec..afee4d2de3b 100644 --- a/packages/core/test/plugin/provider-dynamic.test.ts +++ b/packages/core/test/plugin/provider-dynamic.test.ts @@ -24,6 +24,7 @@ function npmPackage(directory = "") { resolve: (name) => Effect.succeed({ directory, name }), check: () => Effect.succeed(false), update: (name) => Effect.succeed({ directory, name }), + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }) diff --git a/packages/core/test/plugin/provider-sap-ai-core.test.ts b/packages/core/test/plugin/provider-sap-ai-core.test.ts index f7aaccfb4da..811c82a2f65 100644 --- a/packages/core/test/plugin/provider-sap-ai-core.test.ts +++ b/packages/core/test/plugin/provider-sap-ai-core.test.ts @@ -18,6 +18,7 @@ const npm = Npm.Service.of({ resolve: (name) => Effect.succeed({ directory: "", name }), check: () => Effect.succeed(false), update: (name) => Effect.succeed({ directory: "", name }), + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }) diff --git a/packages/core/test/plugin/supervisor-reload.test.ts b/packages/core/test/plugin/supervisor-reload.test.ts index 05279a0b664..5245aabb9a9 100644 --- a/packages/core/test/plugin/supervisor-reload.test.ts +++ b/packages/core/test/plugin/supervisor-reload.test.ts @@ -54,6 +54,7 @@ const npmLayer = Layer.succeed( }), check: () => Effect.succeed(false), update: (name) => Effect.succeed({ directory: npm.directory, name }), + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }), diff --git a/packages/core/test/plugin/supervisor.test.ts b/packages/core/test/plugin/supervisor.test.ts index 8ac494c368f..29a55fed09a 100644 --- a/packages/core/test/plugin/supervisor.test.ts +++ b/packages/core/test/plugin/supervisor.test.ts @@ -51,8 +51,9 @@ const sourceLayer = Layer.succeed( }), ) -// Package checks report `available` after `delay`; updates are recorded instead of installed. -const packages = { available: false, delay: Duration.zero, checks: 0, updated: [] as string[] } +// Package checks report `available` after `delay`, and packages in `stays` don't follow updates; updates are recorded +// instead of installed. +const packages = { available: false, delay: Duration.zero, checks: 0, stays: [] as string[], updated: [] as string[] } const instances = Layer.effect( LocationServiceMap.Service, @@ -97,6 +98,7 @@ const instances = Layer.effect( cause: new Error(`Unexpected Npm.update(${pkg})`), }), ), + follows: (pkg) => Effect.succeed(!packages.stays.includes(pkg)), reject: () => Effect.succeed(false), which: () => Effect.undefined, }), @@ -206,18 +208,29 @@ describe("PluginSupervisor", () => { }), ) - it.effect("updates only packages written as name@latest when a newer version is out", () => + it.effect("updates only packages that follow updates, once per check interval", () => Effect.gen(function* () { - source.operations = ["latest-plugin@latest", "plain-plugin", "ranged-plugin@^1.0.0", "next-plugin@next"].map( - (target) => ({ type: "add" as const, target, options: {} }), - ) + const follows = ["latest-plugin@latest", "ranged-plugin@^1.0.0", "github:acme/branch-plugin#dev"] + packages.stays = ["plain-plugin", "next-plugin@next", "github:acme/default-plugin"] + source.operations = [...follows, ...packages.stays].map((target) => ({ + type: "add" as const, + target, + options: {}, + })) packages.available = true packages.updated = [] const directory = yield* tmpdirScoped() const locations = yield* LocationServiceMap.Service yield* Effect.gen(function* () { yield* Plugin.Service - yield* advance(() => packages.updated.length > 0) + yield* advance(() => packages.updated.length >= follows.length) + // Each update reloads and checks again; the newer version is still reported but isn't installed twice. + yield* drain + expect(packages.updated.toSorted()).toEqual(follows.toSorted()) + // The next interval's scheduled check installs again. + yield* TestClock.adjust(PluginUpdate.interval) + yield* advance(() => packages.updated.length >= follows.length * 2) + yield* drain }).pipe( Effect.scoped, Effect.provide(locations.get(Location.Ref.make({ directory: AbsolutePath.make(directory.path) }))), @@ -225,10 +238,11 @@ describe("PluginSupervisor", () => { Effect.sync(() => { source.operations = [] packages.available = false + packages.stays = [] }), ), ) - expect(packages.updated).toEqual(["latest-plugin@latest"]) + expect(packages.updated.toSorted()).toEqual([...follows, ...follows].toSorted()) }), ) diff --git a/packages/server/src/workerd.ts b/packages/server/src/workerd.ts index 638180a5f10..c2edfa9dd99 100644 --- a/packages/server/src/workerd.ts +++ b/packages/server/src/workerd.ts @@ -118,6 +118,7 @@ const npmLayer = Layer.succeed( resolve: (name) => Effect.succeed({ directory: "", name }), check: () => Effect.succeed(false), update: (pkg) => npmUnavailable("Npm.update", pkg), + follows: () => Effect.succeed(false), reject: () => Effect.succeed(false), which: () => Effect.undefined, }), diff --git a/packages/util/src/npm.ts b/packages/util/src/npm.ts index 3004762004b..ca3b9f35180 100644 --- a/packages/util/src/npm.ts +++ b/packages/util/src/npm.ts @@ -37,6 +37,12 @@ export interface Interface { readonly resolve: (pkg: string) => Effect.Effect readonly check: (pkg: string) => Effect.Effect readonly update: (pkg: string) => Effect.Effect + /** + * Whether newer versions should install on their own because the package names what to follow: `name@latest`, a + * version range, a Git `semver:` range, or a Git ref the remote lists as a branch. A bare name or repository, other + * dist-tags, Git tags and commits stay on what's installed. + */ + readonly follows: (pkg: string) => Effect.Effect /** * Stop using the newest installed version when it is `version`, so the previous one is current again. Its files stay * until they expire, for anything still running it. False when it isn't the newest or there is no previous one. @@ -67,19 +73,36 @@ export async function cacheKey(pkg: string) { } type Target = - | { readonly type: "registry"; readonly name: string; readonly spec: string; readonly mutable: boolean } - | { readonly type: "git"; readonly name?: string; readonly slug: string; readonly mutable: boolean } + | { + readonly type: "registry" + readonly name: string + readonly spec: string + readonly mutable: boolean + readonly follows: boolean + } + | { + readonly type: "git" + readonly name?: string + readonly slug: string + readonly mutable: boolean + readonly follows: boolean + /** A named ref that may be a branch or a tag. */ + readonly ref?: string + } async function parse(pkg: string): Promise { const { default: npa } = await import("npm-package-arg") try { const result = npa(pkg) if (result.type === "git") { + const mutable = !isCommit(result.gitCommittish) return { type: "git", ...(result.name ? { name: result.name } : {}), slug: gitSlug(pkg), - mutable: !isCommit(result.gitCommittish), + mutable, + follows: Boolean(result.gitRange), + ...(mutable && result.gitCommittish ? { ref: result.gitCommittish } : {}), } } if (!result.name || !["version", "range", "tag"].includes(result.type)) return @@ -88,6 +111,10 @@ async function parse(pkg: string): Promise { name: result.name, spec: result.raw === result.name ? "latest" : result.rawSpec, mutable: result.type !== "version", + // npm parses a bare name as the range `*`; only a written `@latest` or range follows. + follows: + result.raw !== result.name && + (result.type === "range" || (result.type === "tag" && result.rawSpec === "latest")), } } catch { return @@ -417,6 +444,26 @@ const layer = Layer.effect( return installed }, Effect.scoped) + const follows = Effect.fn("Npm.follows")(function* (pkg: string) { + const target = yield* Effect.promise(() => parse(pkg)) + if (target?.type !== "git" || !target.ref) return target?.follows ?? false + const root = directory(pkg, target) + // Only the remote knows whether a ref is a branch or a tag. pacote keeps the ref it resolved, and Git reuses the + // refs the update check just listed for a few minutes, so this usually doesn't ask the remote again. + const { GitFetcher } = (yield* Effect.promise(() => import("pacote"))) as unknown as { + GitFetcher: new ( + spec: string, + options: Record, + ) => { resolve(): Promise; resolvedRef: { readonly type: string } | null } + } + const fetcher = new GitFetcher(pkg, { ...(yield* NpmConfig.load(root)), ignoreScripts: true, windowsHide: true }) + yield* Effect.tryPromise({ + try: () => fetcher.resolve(), + catch: (cause) => new InstallFailedError({ dir: root, cause }), + }) + return fetcher.resolvedRef?.type === "branch" + }) + const reject = Effect.fn("Npm.reject")(function* (pkg: string, version: string) { const target = yield* Effect.promise(() => parse(pkg)) const dir = directory(pkg, target) @@ -488,6 +535,7 @@ const layer = Layer.effect( resolve, check, update, + follows, reject, which, }) diff --git a/services/site/src/docs/content/plugins.mdx b/services/site/src/docs/content/plugins.mdx index 3e22f2126a5..bcbe9e1c97c 100644 --- a/services/site/src/docs/content/plugins.mdx +++ b/services/site/src/docs/content/plugins.mdx @@ -107,8 +107,14 @@ opencode plugin remove opencode-acme-plugin@1.2.0 pass a configured package target to check or update only that package. Local plugins and exact package revisions are skipped. -A package written as `name@latest` updates itself: OpenCode checks it on startup and every 24 hours, installs a newer -version, and reloads it. If the new version fails to load, the previous one keeps running and stays installed. +A package updates itself when it names what to follow: `name@latest`, a version range such as `name@^1.2.0`, +`name@~1.2.0`, `name@1.x` or `name@>=1.2.0 <2`, a Git branch such as `github:acme/plugin#main`, or a Git `semver:` range. +OpenCode checks it on startup and every 24 hours, installs a newer version, and reloads it. A range only moves to versions +inside it. If the new version fails to load, the previous one keeps running and stays installed. + +A bare name (`name`) or repository (`github:acme/plugin`) stays on the version it installed. So do other npm tags such as +`name@next` and Git tags. `plugin check` still reports their updates and `plugin update` installs them. Exact versions and +commit hashes are pinned. Package installation accepts npm names with versions, tags, or ranges, plus npm-compatible Git package specifications. Git repositories can use hosted shortcuts, HTTPS, or SSH, including private repositories available through your existing @@ -127,8 +133,8 @@ local paths directly; tarball and npm alias targets are not accepted by `plugin ## Reload Changes under watched config directories reload automatically. Server startup loads cached package plugins immediately, -installs missing packages in the background, and checks unpinned npm and Git plugins for updates without changing the -installed package. Exact npm versions and full Git commit hashes stay pinned. Changes to unwatched local dependencies +installs missing packages in the background, and checks unpinned npm and Git plugins for updates. Exact npm versions and +full Git commit hashes stay pinned. Changes to unwatched local dependencies may still require restarting OpenCode. ```sh