From f330f3e02b7a53abc9fae116d5b9619758bfb8f3 Mon Sep 17 00:00:00 2001 From: Dax Raad Date: Tue, 1 Sep 2026 10:46:34 -0400 Subject: [PATCH] feat(cli): check and update plugins with flat inventory --- packages/cli/src/commands/commands.ts | 18 +++ .../cli/src/commands/handlers/plugin/check.ts | 14 ++ .../src/commands/handlers/plugin/inventory.ts | 101 ++++++++++++++ .../cli/src/commands/handlers/plugin/list.ts | 95 ++++++++----- .../src/commands/handlers/plugin/update.ts | 44 ++++++ packages/cli/src/index.ts | 2 + packages/cli/test/plugin-check.test.ts | 18 +++ packages/cli/test/plugin-list.test.ts | 63 ++++++--- packages/client/src/effect/api/api.ts | 8 ++ .../client/src/effect/generated/client.ts | 10 ++ .../client/src/promise/generated/client.ts | 15 +++ .../client/src/promise/generated/types.ts | 12 ++ packages/core/src/plugin/supervisor.ts | 6 +- packages/core/src/plugin/update.ts | 13 +- packages/core/test/plugin/update.test.ts | 2 +- packages/protocol/openapi.json | 126 ++++++++++++++++++ packages/protocol/src/groups/plugin.ts | 16 +++ packages/server/src/handlers/plugin.ts | 42 ++++++ packages/server/test/plugin-update.test.ts | 19 ++- packages/www/openapi.json | 126 ++++++++++++++++++ packages/www/public/openapi.json | 126 ++++++++++++++++++ packages/www/src/docs/content/plugins.mdx | 6 + 22 files changed, 815 insertions(+), 67 deletions(-) create mode 100644 packages/cli/src/commands/handlers/plugin/check.ts create mode 100644 packages/cli/src/commands/handlers/plugin/inventory.ts create mode 100644 packages/cli/src/commands/handlers/plugin/update.ts create mode 100644 packages/cli/test/plugin-check.test.ts diff --git a/packages/cli/src/commands/commands.ts b/packages/cli/src/commands/commands.ts index 3ebaf9f49bc..f819454bce2 100644 --- a/packages/cli/src/commands/commands.ts +++ b/packages/cli/src/commands/commands.ts @@ -199,6 +199,24 @@ const Root = Spec.make(typeof OPENCODE_CLI_NAME === "string" ? OPENCODE_CLI_NAME package: Argument.string("package").pipe(Argument.withDescription("npm registry or Git package specifier")), }, }), + Spec.make("check", { + description: "Check package plugins for updates", + params: { + target: Argument.string("target").pipe( + Argument.withDescription("Configured package target"), + Argument.optional, + ), + }, + }), + Spec.make("update", { + description: "Update package plugins", + params: { + target: Argument.string("target").pipe( + Argument.withDescription("Configured package target; omit to update all outdated plugins"), + Argument.optional, + ), + }, + }), Spec.make("remove", { description: "Remove a plugin from global configuration", params: { diff --git a/packages/cli/src/commands/handlers/plugin/check.ts b/packages/cli/src/commands/handlers/plugin/check.ts new file mode 100644 index 00000000000..9e550494aa4 --- /dev/null +++ b/packages/cli/src/commands/handlers/plugin/check.ts @@ -0,0 +1,14 @@ +import { EOL } from "node:os" +import { Effect, Option } from "effect" +import { Commands } from "../../commands" +import { Runtime } from "../../../framework/runtime" +import { format, inspect } from "./inventory" + +export default Runtime.handler( + Commands.commands.plugin.commands.check, + Effect.fn("cli.plugin.check")(function* (input) { + const result = yield* inspect(Option.getOrUndefined(input.target)) + process.stdout.write((format(result.items) || "No package plugins found") + EOL) + if (result.items.some((item) => item.error)) process.exitCode = 1 + }), +) diff --git a/packages/cli/src/commands/handlers/plugin/inventory.ts b/packages/cli/src/commands/handlers/plugin/inventory.ts new file mode 100644 index 00000000000..d42c86f7e5d --- /dev/null +++ b/packages/cli/src/commands/handlers/plugin/inventory.ts @@ -0,0 +1,101 @@ +import { EOL } from "node:os" +import { Cause, Effect, Exit } from "effect" +import { OpenCode, type PluginInfo } from "@opencode-ai/client" +import { Service } from "@opencode-ai/client/effect/service" +import { Npm } from "@opencode-ai/util/npm" +import { Config } from "../../../config" +import { ServiceConfig } from "../../../services/service-config" + +export interface Item { + readonly runtime: "Server" | "TUI" + readonly target: string + readonly name: string + readonly version?: string + readonly outdated: boolean + readonly error?: string +} + +export const inspect = Effect.fn("cli.plugin.inspect")(function* (selected?: string) { + const endpoint = yield* Service.ensure(yield* ServiceConfig.options()) + const client = OpenCode.make({ baseUrl: endpoint.url, headers: Service.headers(endpoint) }) + const location = { directory: process.cwd() } + const listed = yield* Effect.promise(() => client.plugin.list({ location })) + const serverTargets = new Set( + listed.data.flatMap((plugin) => (plugin.source.type === "package" ? [plugin.source.target] : [])), + ) + const server = + selected === undefined || serverTargets.has(selected) + ? yield* Effect.promise(() => client.plugin.check({ location, ...(selected ? { target: selected } : {}) })) + : listed + const serverItems = server.data.flatMap((plugin): Item[] => { + if (plugin.source.type !== "package") return [] + if (selected !== undefined && plugin.source.target !== selected) return [] + return [ + { + runtime: "Server", + target: plugin.source.target, + name: plugin.id ?? plugin.source.target, + ...(plugin.source.version ? { version: displayVersion(plugin.source.version) } : {}), + outdated: plugin.source.outdated === true, + ...(plugin.state.status === "failed" ? { error: plugin.state.error } : {}), + }, + ] + }) + + const config = yield* Config.Service + const info = yield* config.get() + const configured = [ + ...new Set( + (info.plugins ?? []).flatMap((entry) => { + const target = typeof entry === "string" ? entry : entry.package + if (target.startsWith("-") || target === "*" || target.endsWith(".*") || target.startsWith("opencode.")) return [] + return [target] + }), + ), + ] + const tuiTargets = yield* Effect.promise(async () => { + const installable = await Promise.all(configured.map((target) => Npm.isInstallablePackage(target))) + return configured.filter((target, index) => installable[index] && (selected === undefined || target === selected)) + }) + const npm = yield* Npm.Service + const tuiItems = yield* Effect.forEach( + tuiTargets, + (target) => + Effect.gen(function* () { + const installed = yield* npm.resolve(target, { subpaths: ["tui"] }) + const outdated = yield* npm.check(target).pipe(Effect.exit) + return { + runtime: "TUI" as const, + target, + name: target, + ...(installed.version ? { version: displayVersion(installed.version) } : {}), + outdated: Exit.isSuccess(outdated) && outdated.value, + ...(Exit.isFailure(outdated) ? { error: Cause.pretty(outdated.cause) } : {}), + } + }), + { concurrency: "unbounded" }, + ) + const items = [...serverItems, ...tuiItems] + if (selected !== undefined && !items.length) return yield* Effect.fail(new Error(`Plugin is not configured: ${selected}`)) + return { client, location, items } +}) + +export function displayVersion(version: string) { + return /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(version) ? version.slice(0, 7) : version +} + +export function format(items: readonly Item[]) { + return ["Server", "TUI"] + .flatMap((runtime) => { + const rows = items.filter((item) => item.runtime === runtime) + if (!rows.length) return [] + return [ + runtime, + ...rows.map( + (item) => + ` ${item.name}${item.version ? ` ${item.version}` : ""} (${item.error ? "check failed" : item.outdated ? "update available" : "current"})`, + ), + ] + }) + .join(EOL) +} diff --git a/packages/cli/src/commands/handlers/plugin/list.ts b/packages/cli/src/commands/handlers/plugin/list.ts index a73c2e18493..47c4f1d9f73 100644 --- a/packages/cli/src/commands/handlers/plugin/list.ts +++ b/packages/cli/src/commands/handlers/plugin/list.ts @@ -8,7 +8,9 @@ import { Runtime } from "../../../framework/runtime" import { ServiceConfig } from "../../../services/service-config" import { Config } from "../../../config" import { Global } from "@opencode-ai/util/global" -import { discoverTuiPlugins, localPluginDirectories } from "@opencode-ai/tui/plugin/discovery" +import { Npm } from "@opencode-ai/util/npm" +import { fileURLToPath } from "node:url" +import { discoverTuiPlugins, localPluginDirectories, localSource } from "@opencode-ai/tui/plugin/discovery" export default Runtime.handler( Commands.commands.plugin.commands.list, @@ -22,15 +24,23 @@ export default Runtime.handler( const discovered = yield* Effect.promise(() => localPluginDirectories(process.cwd(), global.config).then(discoverTuiPlugins), ) + const npm = yield* Npm.Service + const configured = yield* Effect.forEach(info.plugins ?? [], (entry) => + Effect.gen(function* () { + const target = typeof entry === "string" ? entry : entry.package + if (target.startsWith("-") || target === "*" || target.endsWith(".*") || target.startsWith("opencode.")) + return [] + const local = localSource(target, path.dirname(config.path)) + if (local) return [{ target: fileURLToPath(local), version: "local" }] + if (!(yield* Effect.promise(() => Npm.isInstallablePackage(target)))) return [] + const installed = yield* npm.resolve(target, { subpaths: ["tui"] }) + if (!installed.entrypoint) return [] + return [{ target, version: installed.version }] + }), + ) const output = format( response.data, - [ - ...(info.plugins ?? []).flatMap((entry) => { - const target = typeof entry === "string" ? entry : entry.package - return target.startsWith("-") ? [] : [{ target, source: "configured" as const }] - }), - ...discovered.map((target) => ({ target, source: "discovered" as const })), - ], + [...configured.flat(), ...discovered.map((target) => ({ target, version: "local" }))], input.builtin, ) if (!output) { @@ -43,37 +53,50 @@ export default Runtime.handler( export function format( plugins: readonly PluginInfo[], - tui: ReadonlyArray<{ readonly target: string; readonly source: "configured" | "discovered" }>, + tui: ReadonlyArray<{ readonly target: string; readonly version?: string }>, builtin = false, ) { const server = plugins .filter((plugin) => builtin || plugin.source.type !== "builtin") - .toSorted((a, b) => name(a).localeCompare(name(b))) - .map((plugin) => `${name(plugin)} (${plugin.state.status})`) - const advertised = plugins.flatMap((plugin) => - plugin.state.status !== "active" || !plugin.features.tui - ? [] - : plugin.source.type === "package" - ? [{ target: plugin.source.target, source: "advertised" as const }] - : plugin.source.type === "local" - ? [{ target: path.dirname(plugin.source.path), source: "advertised" as const }] - : [], - ) - const targets = [...tui, ...advertised] + .map((plugin) => ({ + id: plugin.id ?? "-", + version: + plugin.source.type === "package" + ? (plugin.source.version ?? "-") + : plugin.source.type === "local" + ? "local" + : "-", + target: + plugin.source.type === "package" + ? plugin.source.target + : plugin.source.type === "local" + ? plugin.source.path + : plugin.source.type, + })) + const targets = tui + .filter( + (item) => + !plugins.some((plugin) => + plugin.source.type === "package" + ? plugin.source.target === item.target + : plugin.source.type === "local" && + (plugin.source.path === item.target || + (plugin.features.tui && + path.dirname(plugin.source.path) === + (item.version === "local" && path.extname(item.target) ? path.dirname(item.target) : item.target))), + ), + ) .filter((plugin, index, all) => all.findIndex((candidate) => candidate.target === plugin.target) === index) - .toSorted((a, b) => a.target.localeCompare(b.target)) - .map((plugin) => `${plugin.target} (${plugin.source})`) - return [ - targets.length ? ["TUI", ...targets].join(EOL) : undefined, - server.length ? ["Server", ...server].join(EOL) : undefined, - ] - .filter((section) => section !== undefined) - .join(EOL + EOL) -} - -function name(plugin: PluginInfo) { - if (plugin.id) return plugin.id - if (plugin.source.type === "package") return plugin.source.target - if (plugin.source.type === "local") return plugin.source.path - return plugin.source.type + .map((plugin) => ({ id: "-", version: plugin.version ?? "-", target: plugin.target })) + const rows = [...server, ...targets] + .toSorted((a, b) => a.id.localeCompare(b.id) || a.target.localeCompare(b.target)) + .map((item) => [ + item.id, + /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(item.version) ? item.version.slice(0, 7) : item.version, + item.target, + ]) + if (!rows.length) return "" + const table = [["ID", "VERSION", "SOURCE"], ...rows] + const widths = [0, 1].map((index) => Math.max(...table.map((row) => row[index].length))) + return table.map((row) => `${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}`).join(EOL) } diff --git a/packages/cli/src/commands/handlers/plugin/update.ts b/packages/cli/src/commands/handlers/plugin/update.ts new file mode 100644 index 00000000000..9ac952dbfaa --- /dev/null +++ b/packages/cli/src/commands/handlers/plugin/update.ts @@ -0,0 +1,44 @@ +import { EOL } from "node:os" +import { Cause, Effect, Exit, Option } from "effect" +import { Npm } from "@opencode-ai/util/npm" +import { Commands } from "../../commands" +import { Runtime } from "../../../framework/runtime" +import { inspect } from "./inventory" + +export default Runtime.handler( + Commands.commands.plugin.commands.update, + Effect.fn("cli.plugin.update")(function* (input) { + const result = yield* inspect(Option.getOrUndefined(input.target)) + for (const item of result.items) { + if (!item.error) continue + process.stderr.write(`Failed to check ${item.runtime} plugin "${item.name}": ${item.error}${EOL}`) + } + const selected = result.items.filter((item) => item.outdated) + if (!selected.length) { + process.stdout.write("No plugin updates available" + EOL) + if (result.items.some((item) => item.error)) process.exitCode = 1 + return + } + + const npm = yield* Npm.Service + const updated = yield* Effect.forEach( + selected, + (item) => + (item.runtime === "Server" + ? Effect.promise(() => result.client.plugin.update({ location: result.location, target: item.target })) + : npm.update(item.target, { subpaths: ["tui"] }).pipe(Effect.asVoid) + ).pipe(Effect.exit, Effect.map((result) => ({ item, result }))), + { concurrency: "unbounded" }, + ) + for (const item of updated) { + if (Exit.isSuccess(item.result)) { + process.stdout.write(`Updated ${item.item.runtime} plugin "${item.item.name}"${EOL}`) + continue + } + process.stderr.write( + `Failed to update ${item.item.runtime} plugin "${item.item.name}": ${Cause.pretty(item.result.cause)}${EOL}`, + ) + process.exitCode = 1 + } + }), +) diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index 964ed2865c4..0f715e0479d 100755 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -42,6 +42,8 @@ const Handlers = Runtime.handlers(Commands, { plugin: { list: () => import("./commands/handlers/plugin/list"), add: () => import("./commands/handlers/plugin/add"), + check: () => import("./commands/handlers/plugin/check"), + update: () => import("./commands/handlers/plugin/update"), remove: () => import("./commands/handlers/plugin/remove"), }, models: () => import("./commands/handlers/models"), diff --git a/packages/cli/test/plugin-check.test.ts b/packages/cli/test/plugin-check.test.ts new file mode 100644 index 00000000000..c2f93c53eea --- /dev/null +++ b/packages/cli/test/plugin-check.test.ts @@ -0,0 +1,18 @@ +import { EOL } from "node:os" +import { expect, test } from "bun:test" +import { displayVersion, format, type Item } from "../src/commands/handlers/plugin/inventory" + +test("formats server and TUI package update status", () => { + const items: Item[] = [ + { runtime: "Server", target: "server", name: "server.plugin", version: "1.2.3", outdated: true }, + { runtime: "TUI", target: "tui", name: "tui", version: "2.0.0", outdated: false }, + ] + + expect(format(items)).toBe( + ["Server", " server.plugin 1.2.3 (update available)", "TUI", " tui 2.0.0 (current)"].join(EOL), + ) +}) + +test("shortens Git revisions", () => { + expect(displayVersion("dadba138b7088d61f937869bbc1ef34b1f91188d")).toBe("dadba13") +}) diff --git a/packages/cli/test/plugin-list.test.ts b/packages/cli/test/plugin-list.test.ts index cd5494a7372..5fb055f6f86 100644 --- a/packages/cli/test/plugin-list.test.ts +++ b/packages/cli/test/plugin-list.test.ts @@ -2,14 +2,14 @@ import { expect, test } from "bun:test" import { EOL } from "node:os" import { format } from "../src/commands/handlers/plugin/list" -test("formats server and TUI plugins in sections without builtins", () => { +test("lists plugin IDs, installed versions, and sources without runtime sections", () => { expect( format( [ { id: "opencode.agent", source: { type: "builtin" }, state: { status: "active" }, features: { server: true } }, { id: "acme.dual", - source: { type: "package", target: "acme-plugin@1.0.0" }, + source: { type: "package", target: "acme-plugin@1.0.0", version: "1.0.0" }, state: { status: "active" }, features: { server: true, tui: true }, }, @@ -26,24 +26,22 @@ test("formats server and TUI plugins in sections without builtins", () => { }, ], [ - { target: "tui-only", source: "configured" }, - { target: "/tmp/local.ts", source: "discovered" }, + { target: "tui-only", version: "2.0.0" }, + { target: "/tmp/local.ts", version: "local" }, + { target: "acme-plugin@1.0.0", version: "1.0.0" }, + { target: "/tmp/local/tui.ts", version: "local" }, ], - ), - ).toBe( - [ - "TUI", - "/tmp/local (advertised)", - "/tmp/local.ts (discovered)", - "acme-plugin@1.0.0 (advertised)", - "tui-only (configured)", - "", - "Server", - "acme.dual (active)", - "broken-plugin (failed)", - "local.dual (active)", - ].join(EOL), - ) + ) + .split(EOL) + .map((line) => line.split(/\s{2,}/)), + ).toEqual([ + ["ID", "VERSION", "SOURCE"], + ["-", "local", "/tmp/local.ts"], + ["-", "-", "broken-plugin"], + ["-", "2.0.0", "tui-only"], + ["acme.dual", "1.0.0", "acme-plugin@1.0.0"], + ["local.dual", "local", "/tmp/local/index.ts"], + ]) }) test("includes builtins when requested", () => { @@ -59,6 +57,29 @@ test("includes builtins when requested", () => { ], [], true, - ), - ).toBe(["Server", "opencode.agent (active)"].join(EOL)) + ) + .split(EOL) + .map((line) => line.split(/\s{2,}/)), + ).toEqual([ + ["ID", "VERSION", "SOURCE"], + ["opencode.agent", "-", "builtin"], + ]) +}) + +test("shortens Git commits and leaves absent IDs unknown", () => { + expect( + format( + [ + { + source: { type: "package", target: "github:acme/plugin", version: "a".repeat(40) }, + state: { status: "active" }, + features: { server: true }, + }, + ], + [], + ) + .split(EOL)[1] + .split(/\s{2,}/), + ).toEqual(["-", "aaaaaaa", "github:acme/plugin"]) + expect(format([], [])).toBe("") }) diff --git a/packages/client/src/effect/api/api.ts b/packages/client/src/effect/api/api.ts index f8aabc8c3ee..2a72d0d1ce2 100644 --- a/packages/client/src/effect/api/api.ts +++ b/packages/client/src/effect/api/api.ts @@ -88,6 +88,13 @@ export type PluginListInput = { export type PluginListOutput = { readonly location: Location.Info; readonly data: ReadonlyArray } export type PluginListOperation = (input?: PluginListInput) => Effect.Effect +export type PluginCheckInput = { + readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined + readonly target?: string | undefined +} +export type PluginCheckOutput = { readonly location: Location.Info; readonly data: ReadonlyArray } +export type PluginCheckOperation = (input?: PluginCheckInput) => Effect.Effect + export type PluginUpdateInput = { readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined readonly target: string @@ -97,6 +104,7 @@ export type PluginUpdateOperation = (input: PluginUpdateInput) => Eff export interface PluginApi { readonly list: PluginListOperation + readonly check: PluginCheckOperation readonly update: PluginUpdateOperation } diff --git a/packages/client/src/effect/generated/client.ts b/packages/client/src/effect/generated/client.ts index da4ac26f67c..19deb7a95bf 100644 --- a/packages/client/src/effect/generated/client.ts +++ b/packages/client/src/effect/generated/client.ts @@ -15,6 +15,8 @@ import type { AgentGetOutput, PluginListInput, PluginListOutput, + PluginCheckInput, + PluginCheckOutput, PluginUpdateInput, PluginUpdateOutput, SessionListInput, @@ -324,6 +326,13 @@ const EndpointPluginList = (raw: RawClient["server.plugin"]) => (input?: PluginL raw["plugin.list"]({ query: { location: input?.["location"] } }).pipe(Effect.mapError(mapClientError)), ) +const EndpointPluginCheck = (raw: RawClient["server.plugin"]) => (input?: PluginCheckInput) => + preserveEffect()( + raw["plugin.check"]({ query: { location: input?.["location"] }, payload: { target: input?.["target"] } }).pipe( + Effect.mapError(mapClientError), + ), + ) + const EndpointPluginUpdate = (raw: RawClient["server.plugin"]) => (input: PluginUpdateInput) => preserveEffect()( raw["plugin.update"]({ query: { location: input["location"] }, payload: { target: input["target"] } }).pipe( @@ -333,6 +342,7 @@ const EndpointPluginUpdate = (raw: RawClient["server.plugin"]) => (input: Plugin const adaptGroupPlugin = (raw: RawClient["server.plugin"]) => ({ list: EndpointPluginList(raw), + check: EndpointPluginCheck(raw), update: EndpointPluginUpdate(raw), }) diff --git a/packages/client/src/promise/generated/client.ts b/packages/client/src/promise/generated/client.ts index c6b2bdf2f3b..62319ccffa8 100644 --- a/packages/client/src/promise/generated/client.ts +++ b/packages/client/src/promise/generated/client.ts @@ -9,6 +9,8 @@ import type { AgentGetOutput, PluginListInput, PluginListOutput, + PluginCheckInput, + PluginCheckOutput, PluginUpdateInput, PluginUpdateOutput, SessionListInput, @@ -468,6 +470,19 @@ export function make(options: ClientOptions) { }, requestOptions, ), + check: (input?: PluginCheckInput, requestOptions?: RequestOptions) => + request( + { + method: "POST", + path: `/api/plugin/check`, + query: { location: input?.["location"] }, + body: { target: input?.["target"] }, + successStatus: 200, + declaredStatuses: [400, 401], + empty: false, + }, + requestOptions, + ), update: (input: PluginUpdateInput, requestOptions?: RequestOptions) => request( { diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index af0ea22760e..2e2403704ec 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2585,6 +2585,18 @@ export type PluginListOutput = { data: Array } +export type PluginCheckInput = { + readonly location?: { + readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined + }["location"] + readonly target?: { readonly target?: string | undefined }["target"] +} + +export type PluginCheckOutput = { + location: { directory: string; workspaceID?: string; project: { id: string; directory: string; canonical: string } } + data: Array +} + export type PluginUpdateInput = { readonly location?: { readonly location?: { readonly directory?: string | undefined; readonly workspace?: string | undefined } | undefined diff --git a/packages/core/src/plugin/supervisor.ts b/packages/core/src/plugin/supervisor.ts index e73779447a7..7ec540c80aa 100644 --- a/packages/core/src/plugin/supervisor.ts +++ b/packages/core/src/plugin/supervisor.ts @@ -162,8 +162,10 @@ export const layer = Layer.effect( const reloads = Stream.merge( Stream.merge(sources.changes(), bus.subscribe([Event.Updated, SdkPlugins.Updated])), updates.changes().pipe( - Stream.filter((target) => packages.has(target)), - Stream.tap((target) => Effect.sync(() => outdated.delete(target))), + Stream.filter((update) => packages.has(update.target)), + Stream.tap((update) => + Effect.sync(() => (update.outdated ? outdated.add(update.target) : outdated.delete(update.target))), + ), Stream.map(() => undefined), ), ).pipe( diff --git a/packages/core/src/plugin/update.ts b/packages/core/src/plugin/update.ts index c5f521cf195..ac11740b35d 100644 --- a/packages/core/src/plugin/update.ts +++ b/packages/core/src/plugin/update.ts @@ -9,9 +9,9 @@ import { KeyedMutex } from "../effect/keyed-mutex.js" const interval = 24 * 60 * 60 * 1_000 export interface Interface { - readonly check: (target: string) => Effect.Effect + readonly check: (target: string, options?: { readonly refresh?: boolean }) => Effect.Effect readonly update: (target: string) => Effect.Effect - readonly changes: () => Stream.Stream + readonly changes: () => Stream.Stream<{ readonly target: string; readonly outdated: boolean }> } export class Service extends Context.Service()("@opencode/PluginUpdate") {} @@ -22,28 +22,29 @@ const layer = Layer.effect( const npm = yield* Npm.Service const locks = KeyedMutex.makeUnsafe() const status = new Map() - const changes = yield* PubSub.unbounded() + const changes = yield* PubSub.unbounded<{ readonly target: string; readonly outdated: boolean }>() return Service.of({ - check: (target) => + check: (target, options) => locks.withLock(target)( Effect.gen(function* () { const checkedAt = yield* Clock.currentTimeMillis const current = status.get(target) - if (current && checkedAt - current.checkedAt < interval) return current.outdated + if (!options?.refresh && current && checkedAt - current.checkedAt < interval) return current.outdated const outdated = yield* npm.check(target).pipe( Effect.tapCause((cause) => Effect.logWarning("failed to check plugin update", { target, cause })), Effect.option, ) const value = Option.getOrElse(outdated, () => current?.outdated ?? false) status.set(target, { outdated: value, checkedAt }) + if ((current?.outdated ?? false) !== value) yield* PubSub.publish(changes, { target, outdated: value }) return value }), ), update: (target) => npm.update(target).pipe( Effect.tap(() => Effect.sync(() => status.delete(target))), - Effect.tap(() => PubSub.publish(changes, target)), + Effect.tap(() => PubSub.publish(changes, { target, outdated: false })), Effect.asVoid, ), changes: () => Stream.fromPubSub(changes), diff --git a/packages/core/test/plugin/update.test.ts b/packages/core/test/plugin/update.test.ts index 79755320d82..24953d16ead 100644 --- a/packages/core/test/plugin/update.test.ts +++ b/packages/core/test/plugin/update.test.ts @@ -46,6 +46,6 @@ it.effect("publishes successful package updates", () => yield* updates.update("fixture") - expect(Option.getOrUndefined(yield* Fiber.join(changed))).toBe("fixture") + expect(Option.getOrUndefined(yield* Fiber.join(changed))).toEqual({ target: "fixture", outdated: false }) }), ) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index c2142fb5475..38010e22c49 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -486,6 +486,132 @@ "summary": "List plugins" } }, + "/api/plugin/check": { + "post": { + "tags": ["plugin"], + "operationId": "v2.plugin.check", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.InfoEncoded" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Plugin.Info" + } + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + }, + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "description": "Check one or all package plugins for available updates.", + "summary": "Check plugin updates", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "target": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + } + }, + "required": true + } + } + }, "/api/plugin/update": { "post": { "tags": ["plugin"], diff --git a/packages/protocol/src/groups/plugin.ts b/packages/protocol/src/groups/plugin.ts index c73f502b3be..631b5fe733c 100644 --- a/packages/protocol/src/groups/plugin.ts +++ b/packages/protocol/src/groups/plugin.ts @@ -20,6 +20,22 @@ export const PluginGroup = HttpApiGroup.make("server.plugin") }), ), ) + .add( + HttpApiEndpoint.post("plugin.check", "/api/plugin/check", { + query: LocationQuery, + payload: Schema.Struct({ target: Schema.String.pipe(Schema.optional) }), + success: Location.response(Schema.Array(Plugin.Info)), + error: InvalidRequestError, + }) + .annotateMerge(locationQueryOpenApi) + .annotateMerge( + OpenApi.annotations({ + identifier: "v2.plugin.check", + summary: "Check plugin updates", + description: "Check one or all package plugins for available updates.", + }), + ), + ) .add( HttpApiEndpoint.post("plugin.update", "/api/plugin/update", { query: LocationQuery, diff --git a/packages/server/src/handlers/plugin.ts b/packages/server/src/handlers/plugin.ts index c4c7ce2f668..116b5bb59fb 100644 --- a/packages/server/src/handlers/plugin.ts +++ b/packages/server/src/handlers/plugin.ts @@ -14,6 +14,48 @@ export const PluginHandler = HttpApiBuilder.group(Api, "server.plugin", (handler return yield* response(Plugin.Service.use((plugin) => plugin.list())) }), ) + .handle("plugin.check", (ctx) => + Effect.gen(function* () { + const supervisor = yield* PluginSupervisor.Service + yield* supervisor.flush + const plugins = yield* Plugin.Service + const inventory = yield* plugins.list() + const targets = [ + ...new Set( + inventory.flatMap((plugin) => (plugin.source.type === "package" ? [plugin.source.target] : [])), + ), + ].filter((target) => ctx.payload.target === undefined || target === ctx.payload.target) + if (ctx.payload.target !== undefined && !targets.length) + return yield* new InvalidRequestError({ + message: `Plugin package is not in the current server inventory: ${ctx.payload.target}`, + field: "target", + }) + const updates = yield* PluginUpdate.Service + const outdated = new Map( + yield* Effect.forEach( + targets, + (target) => updates.check(target, { refresh: true }).pipe(Effect.map((value) => [target, value] as const)), + { concurrency: "unbounded" }, + ), + ) + return yield* response( + Effect.succeed( + inventory.map((plugin) => { + if (plugin.source.type !== "package" || !outdated.has(plugin.source.target)) return plugin + return { + ...plugin, + source: { + type: "package" as const, + target: plugin.source.target, + ...(plugin.source.version ? { version: plugin.source.version } : {}), + ...(outdated.get(plugin.source.target) ? { outdated: true as const } : {}), + }, + } + }), + ), + ) + }), + ) .handle("plugin.update", (ctx) => Effect.gen(function* () { const supervisor = yield* PluginSupervisor.Service diff --git a/packages/server/test/plugin-update.test.ts b/packages/server/test/plugin-update.test.ts index 4c022c66c5b..c926b4c2472 100644 --- a/packages/server/test/plugin-update.test.ts +++ b/packages/server/test/plugin-update.test.ts @@ -37,7 +37,7 @@ it.live("updates package plugins in the requested Location", () => Npm.Service.of({ add: () => Effect.sync(entry), resolve: () => Effect.sync(entry), - check: () => Effect.succeed(false), + check: () => Effect.sync(() => version === "1.0.0"), update: () => { if (fail) return Effect.fail(new Npm.InstallFailedError({ dir: plugin })) return Effect.sync(() => (version = "2.0.0")).pipe(Effect.map(entry)) @@ -60,6 +60,23 @@ it.live("updates package plugins in the requested Location", () => ), ) + const checked = yield* Effect.promise(async () => { + const response = await handler( + new Request(`http://opencode.local/api/plugin/check?location[directory]=${encodeURIComponent(project)}`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: "{}", + }), + ) + return response.json() as Promise<{ + data: Array<{ id?: string; source: { target?: string; outdated?: true } }> + }> + }) + expect(checked.data.find((item) => item.id === "fixture.plugin")?.source).toMatchObject({ + target: "fixture-plugin", + outdated: true, + }) + expect((yield* update("fixture-plugin")).status).toBe(204) const listedVersion = yield* Effect.promise(async () => { const response = await handler( diff --git a/packages/www/openapi.json b/packages/www/openapi.json index c2142fb5475..38010e22c49 100644 --- a/packages/www/openapi.json +++ b/packages/www/openapi.json @@ -486,6 +486,132 @@ "summary": "List plugins" } }, + "/api/plugin/check": { + "post": { + "tags": ["plugin"], + "operationId": "v2.plugin.check", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.InfoEncoded" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Plugin.Info" + } + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + }, + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "description": "Check one or all package plugins for available updates.", + "summary": "Check plugin updates", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "target": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + } + }, + "required": true + } + } + }, "/api/plugin/update": { "post": { "tags": ["plugin"], diff --git a/packages/www/public/openapi.json b/packages/www/public/openapi.json index c2142fb5475..38010e22c49 100644 --- a/packages/www/public/openapi.json +++ b/packages/www/public/openapi.json @@ -486,6 +486,132 @@ "summary": "List plugins" } }, + "/api/plugin/check": { + "post": { + "tags": ["plugin"], + "operationId": "v2.plugin.check", + "parameters": [ + { + "name": "location", + "in": "query", + "schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "directory": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "workspace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + }, + { + "type": "null" + } + ] + }, + "required": false, + "style": "deepObject", + "explode": true + } + ], + "security": [], + "responses": { + "200": { + "description": "Success", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "location": { + "$ref": "#/components/schemas/Location.InfoEncoded" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Plugin.Info" + } + } + }, + "required": ["location", "data"], + "additionalProperties": false + } + } + } + }, + "400": { + "description": "InvalidRequestError", + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + }, + { + "$ref": "#/components/schemas/InvalidRequestErrorEncoded" + } + ] + } + } + } + }, + "401": { + "description": "UnauthorizedError", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/UnauthorizedErrorEncoded" + } + } + } + } + }, + "description": "Check one or all package plugins for available updates.", + "summary": "Check plugin updates", + "requestBody": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "target": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "additionalProperties": false + } + } + }, + "required": true + } + } + }, "/api/plugin/update": { "post": { "tags": ["plugin"], diff --git a/packages/www/src/docs/content/plugins.mdx b/packages/www/src/docs/content/plugins.mdx index 353699f3288..ac4fa604e4e 100644 --- a/packages/www/src/docs/content/plugins.mdx +++ b/packages/www/src/docs/content/plugins.mdx @@ -77,9 +77,15 @@ Install, inspect, list, or remove global package plugins with the CLI. opencode2 plugin add opencode-acme-plugin@1.2.0 opencode2 plugin list opencode2 plugin list --builtin +opencode2 plugin check +opencode2 plugin update +opencode2 plugin update opencode-acme-plugin opencode2 plugin remove opencode-acme-plugin@1.2.0 ``` +`plugin check` checks server and TUI-only package plugins for updates. `plugin update` updates every outdated package; +pass a configured package target to check or update only that package. Local plugins and exact package revisions are skipped. + 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 Git credentials.