Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

[MUL-6099] Ship official Plugin V1 product vertical slice (#6869)

Jiayuan Zhang5ed57170bcf4
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index f6e4cfa7c8..bbbba6b53e 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -139,6 +139,11 @@ import type {
WebhookDelivery,
NotificationPreferenceResponse,
NotificationPreferences,
+ PluginBindingRequest,
+ PluginCatalogResponse,
+ PluginInstallation,
+ PluginInstallationListResponse,
+ PluginReleaseRequest,
GitHubPullRequest,
ListGitHubInstallationsResponse,
ListGitHubRepositoriesResponse,
@@ -351,6 +356,12 @@ import {
IssueViewListSchema,
IssueViewPreferenceSchema,
EMPTY_ISSUE_VIEW_PREFERENCE,
+ EMPTY_PLUGIN_CATALOG,
+ EMPTY_PLUGIN_INSTALLATION,
+ EMPTY_PLUGIN_INSTALLATION_LIST,
+ PluginCatalogResponseSchema,
+ PluginInstallationListResponseSchema,
+ PluginInstallationSchema,
type IssueView,
type IssueViewPreference,
type CreateIssueViewRequest,
@@ -2132,6 +2143,78 @@ export class ApiClient {
});
}
+ async listPluginCatalog(workspaceId: string): Promise<PluginCatalogResponse> {
+ let raw: unknown;
+ try {
+ raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/catalog`);
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) return EMPTY_PLUGIN_CATALOG;
+ throw error;
+ }
+ return parseWithFallback(raw, PluginCatalogResponseSchema, EMPTY_PLUGIN_CATALOG, {
+ endpoint: "GET /api/workspaces/{id}/plugins/catalog",
+ });
+ }
+
+ async listPluginInstallations(workspaceId: string): Promise<PluginInstallationListResponse> {
+ let raw: unknown;
+ try {
+ raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins`);
+ } catch (error) {
+ if (error instanceof ApiError && error.status === 404) return EMPTY_PLUGIN_INSTALLATION_LIST;
+ throw error;
+ }
+ return parseWithFallback(raw, PluginInstallationListResponseSchema, EMPTY_PLUGIN_INSTALLATION_LIST, {
+ endpoint: "GET /api/workspaces/{id}/plugins",
+ });
+ }
+
+ async installPlugin(workspaceId: string, request: PluginReleaseRequest): Promise<PluginInstallation> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/install`, {
+ method: "POST",
+ body: JSON.stringify(request),
+ });
+ return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {
+ endpoint: "POST /api/workspaces/{id}/plugins/install",
+ });
+ }
+
+ async upgradePlugin(workspaceId: string, installationId: string, request: PluginReleaseRequest): Promise<PluginInstallation> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/upgrade`, {
+ method: "POST",
+ body: JSON.stringify(request),
+ });
+ return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {
+ endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/upgrade",
+ });
+ }
+
+ async setPluginEnabled(
+ workspaceId: string,
+ installationId: string,
+ enabled: boolean,
+ binding: PluginBindingRequest,
+ ): Promise<PluginInstallation> {
+ const action = enabled ? "enable" : "disable";
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/${action}`, {
+ method: "POST",
+ body: JSON.stringify(binding),
+ });
+ return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {
+ endpoint: `POST /api/workspaces/{id}/plugins/{installationId}/${action}`,
+ });
+ }
+
+ async rollbackPlugin(workspaceId: string, installationId: string, version: string): Promise<PluginInstallation> {
+ const raw = await this.fetch<unknown>(`/api/workspaces/${workspaceId}/plugins/${installationId}/rollback`, {
+ method: "POST",
+ body: JSON.stringify({ version }),
+ });
+ return parseWithFallback(raw, PluginInstallationSchema, EMPTY_PLUGIN_INSTALLATION, {
+ endpoint: "POST /api/workspaces/{id}/plugins/{installationId}/rollback",
+ });
+ }
+
// Members
async listMembers(workspaceId: string): Promise<MemberWithUser[]> {
return this.fetch(`/api/workspaces/${workspaceId}/members`);
diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.ts
index 1d7b165e02..51f2805f4b 100644
--- a/packages/core/api/schemas.test.ts
+++ b/packages/core/api/schemas.test.ts
@@ -47,6 +47,9 @@ import {
SquadSchema,
TimelineEntriesSchema,
UserSchema,
+ EMPTY_PLUGIN_CATALOG,
+ PluginCatalogResponseSchema,
+ PluginInstallationSchema,
} from "./schemas";
import { IssueViewSchema, IssueViewListSchema } from "./schemas";
import { parseWithFallback } from "./schema";
@@ -1363,3 +1366,30 @@ describe("WeCom installation schemas", () => {
expect(redeem).toEqual(EMPTY_REDEEM_WECOM_BINDING_TOKEN_RESPONSE);
});
});
+
+describe("Plugin catalog schemas", () => {
+ it("defaults optional release fields without granting trust or compatibility", () => {
+ const parsed = PluginCatalogResponseSchema.parse({
+ releases: [{ plugin_key: "ai.multica.software-delivery", version: "1.0.0" }],
+ });
+ expect(parsed.supported).toBe(true);
+ expect(parsed.releases[0]?.compatible).toBe(false);
+ expect(parsed.releases[0]?.signature_verified).toBe(false);
+ expect(parsed.releases[0]?.contributions).toEqual([]);
+ });
+
+ it("defaults missing lifecycle and binding fields to a disabled error state", () => {
+ const parsed = PluginInstallationSchema.parse({ id: "installation-1" });
+ expect(parsed.enabled).toBe(false);
+ expect(parsed.lifecycle_status).toBe("error");
+ expect(parsed.bindings).toEqual([]);
+ });
+
+ it("degrades a malformed catalog response to unsupported and empty", () => {
+ const parsed = parseWithFallback("not-json", PluginCatalogResponseSchema, EMPTY_PLUGIN_CATALOG, {
+ endpoint: "GET /api/workspaces/{id}/plugins/catalog",
+ });
+ expect(parsed).toEqual(EMPTY_PLUGIN_CATALOG);
+ expect(parsed.supported).toBe(false);
+ });
+});
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index 88d0c3ceaf..7404a07cc9 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -51,6 +51,9 @@ import type {
ListLabelsResponse,
ListWebhookDeliveriesResponse,
NotificationPreferenceResponse,
+ PluginCatalogResponse,
+ PluginInstallation,
+ PluginInstallationListResponse,
ResourceLabelsResponse,
RuntimeModelListRequest,
SearchIssuesResponse,
@@ -64,6 +67,99 @@ import type {
import type { CloudRuntimeNode } from "../runtimes/cloud-runtime";
import type { CreateFeedbackResponse } from "../feedback/types";
+export const PluginBindingSchema = z.object({
+ scope_type: z.string().default("workspace"),
+ scope_id: z.string().default(""),
+ enabled: z.boolean().default(false),
+ revision: z.number().default(0),
+}).loose();
+
+export const PluginInstallationSchema = z.object({
+ id: z.string(),
+ plugin_key: z.string().default(""),
+ display_name: z.string().default(""),
+ desired_version: z.string().default(""),
+ active_version: z.string().optional(),
+ enabled: z.boolean().default(false),
+ desired_generation: z.number().default(0),
+ active_generation: z.number().default(0),
+ lifecycle_status: z.string().default("error"),
+ health_state: z.string().optional(),
+ health_reason: z.string().optional(),
+ contributions: z.array(z.string()).default([]),
+ bindings: z.array(PluginBindingSchema).default([]),
+}).loose();
+
+export const EMPTY_PLUGIN_INSTALLATION: PluginInstallation = {
+ id: "",
+ plugin_key: "",
+ display_name: "",
+ desired_version: "",
+ enabled: false,
+ desired_generation: 0,
+ active_generation: 0,
+ lifecycle_status: "error",
+ contributions: [],
+ bindings: [],
+};
+
+export const PluginInstallationListResponseSchema = z.object({
+ plugins: z.array(PluginInstallationSchema).default([]),
+}).loose();
+
+export const EMPTY_PLUGIN_INSTALLATION_LIST: PluginInstallationListResponse = {
+ plugins: [],
+};
+
+export const PluginCatalogContributionSchema = z.object({
+ key: z.string(),
+ type: z.string().default(""),
+ name: z.string().default(""),
+ description: z.string().default(""),
+ entry_path: z.string().default(""),
+ entry_digest: z.string().default(""),
+}).loose();
+
+export const PluginCatalogReleaseSchema = z.object({
+ plugin_key: z.string(),
+ name: z.string().default(""),
+ description: z.string().default(""),
+ version: z.string(),
+ publisher: z.string().default(""),
+ publisher_type: z.string().default(""),
+ trust_tier: z.string().default(""),
+ source_kind: z.string().default("bundled"),
+ source_ref: z.string().default(""),
+ requested_capabilities: z.array(z.string()).default([]),
+ host_api: z.string().default(""),
+ required_daemon_features: z.array(z.string()).default([]),
+ signature_key_id: z.string().default(""),
+ signature_verified: z.boolean().default(false),
+ manifest_digest: z.string().default(""),
+ archive_digest: z.string().default(""),
+ artifact_digest: z.string().default(""),
+ compatible: z.boolean().default(false),
+ compatibility_reason: z.string().optional(),
+ contributions: z.array(PluginCatalogContributionSchema).default([]),
+ installation: PluginInstallationSchema.optional(),
+}).loose();
+
+export const PluginCatalogResponseSchema = z.object({
+ releases: z.array(PluginCatalogReleaseSchema).default([]),
+ diagnostics: z.array(z.object({
+ source_ref: z.string().default(""),
+ code: z.string().default("unknown"),
+ message: z.string().default(""),
+ }).loose()).default([]),
+ supported: z.boolean().optional().default(true),
+}).loose();
+
+export const EMPTY_PLUGIN_CATALOG: PluginCatalogResponse = {
+ releases: [],
+ diagnostics: [],
+ supported: false,
+};
+
export const GitHubInstallationSchema = z.object({
id: z.string(),
workspace_id: z.string(),
diff --git a/packages/core/feature-flags/index.ts b/packages/core/feature-flags/index.ts
index ac24ac189c..b8de1a631d 100644
--- a/packages/core/feature-flags/index.ts
+++ b/packages/core/feature-flags/index.ts
@@ -17,7 +17,7 @@ export type {
export { FeatureFlagService } from "./service";
export { StaticProvider } from "./static-provider";
export { ChainProvider } from "./chain-provider";
-export { COMPOSIO_MCP_APPS_FLAG } from "./keys";
+export { COMPOSIO_MCP_APPS_FLAG, PLUGINS_V1_FLAG } from "./keys";
export {
FeatureFlagsProvider,
useFeatureFlagService,
diff --git a/packages/core/feature-flags/keys.ts b/packages/core/feature-flags/keys.ts
index 1212264ec1..2b234ee230 100644
--- a/packages/core/feature-flags/keys.ts
+++ b/packages/core/feature-flags/keys.ts
@@ -1 +1,2 @@
export const COMPOSIO_MCP_APPS_FLAG = "composio_mcp_apps";
+export const PLUGINS_V1_FLAG = "plugins_v1";
diff --git a/packages/core/package.json b/packages/core/package.json
index ab16cad23a..b42eb12c01 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -79,6 +79,9 @@
"./projects/queries": "./projects/queries.ts",
"./projects/mutations": "./projects/mutations.ts",
"./projects/config": "./projects/config.ts",
+ "./plugins": "./plugins/index.ts",
+ "./plugins/queries": "./plugins/queries.ts",
+ "./plugins/mutations": "./plugins/mutations.ts",
"./labels": "./labels/index.ts",
"./labels/queries": "./labels/queries.ts",
"./labels/mutations": "./labels/mutations.ts",
diff --git a/packages/core/permissions/index.ts b/packages/core/permissions/index.ts
index 4091d8ed1a..ec535d0467 100644
--- a/packages/core/permissions/index.ts
+++ b/packages/core/permissions/index.ts
@@ -18,3 +18,4 @@ export {
useAgentPermissions,
useSkillPermissions,
} from "./use-resource-permissions";
+export { useCurrentMember } from "./use-current-member";
diff --git a/packages/core/plugins/index.ts b/packages/core/plugins/index.ts
new file mode 100644
index 0000000000..7a84634243
--- /dev/null
+++ b/packages/core/plugins/index.ts
@@ -0,0 +1,3 @@
+export * from "./queries";
+export * from "./mutations";
+export * from "./version";
diff --git a/packages/core/plugins/mutations.ts b/packages/core/plugins/mutations.ts
new file mode 100644
index 0000000000..0b50d04ae9
--- /dev/null
+++ b/packages/core/plugins/mutations.ts
@@ -0,0 +1,47 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { api } from "../api";
+import type { PluginBindingRequest, PluginReleaseRequest } from "../types";
+import { pluginKeys } from "./queries";
+
+function useInvalidatePlugins(wsId: string) {
+ const queryClient = useQueryClient();
+ return () => queryClient.invalidateQueries({ queryKey: pluginKeys.all(wsId) });
+}
+
+export function useInstallPlugin(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: (request: PluginReleaseRequest) => api.installPlugin(wsId, request),
+ onSettled: invalidate,
+ });
+}
+
+export function useUpgradePlugin(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: ({ installationId, ...request }: PluginReleaseRequest & { installationId: string }) =>
+ api.upgradePlugin(wsId, installationId, request),
+ onSettled: invalidate,
+ });
+}
+
+export function useSetPluginEnabled(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: ({ installationId, enabled, binding }: {
+ installationId: string;
+ enabled: boolean;
+ binding: PluginBindingRequest;
+ }) => api.setPluginEnabled(wsId, installationId, enabled, binding),
+ onSettled: invalidate,
+ });
+}
+
+export function useRollbackPlugin(wsId: string) {
+ const invalidate = useInvalidatePlugins(wsId);
+ return useMutation({
+ mutationFn: ({ installationId, version }: { installationId: string; version: string }) =>
+ api.rollbackPlugin(wsId, installationId, version),
+ onSettled: invalidate,
+ });
+}
diff --git a/packages/core/plugins/queries.ts b/packages/core/plugins/queries.ts
new file mode 100644
index 0000000000..4a4fbf7a3b
--- /dev/null
+++ b/packages/core/plugins/queries.ts
@@ -0,0 +1,24 @@
+import { queryOptions } from "@tanstack/react-query";
+import { api } from "../api";
+
+export const pluginKeys = {
+ all: (wsId: string) => ["workspaces", wsId, "plugins"] as const,
+ catalog: (wsId: string) => [...pluginKeys.all(wsId), "catalog"] as const,
+ installed: (wsId: string) => [...pluginKeys.all(wsId), "installed"] as const,
+};
+
+export function pluginCatalogOptions(wsId: string) {
+ return queryOptions({
+ queryKey: pluginKeys.catalog(wsId),
+ queryFn: () => api.listPluginCatalog(wsId),
+ enabled: wsId.length > 0,
+ });
+}
+
+export function pluginInstallationsOptions(wsId: string) {
+ return queryOptions({
+ queryKey: pluginKeys.installed(wsId),
+ queryFn: () => api.listPluginInstallations(wsId),
+ enabled: wsId.length > 0,
+ });
+}
diff --git a/packages/core/plugins/version.test.ts b/packages/core/plugins/version.test.ts
new file mode 100644
index 0000000000..b86c316191
--- /dev/null
+++ b/packages/core/plugins/version.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { comparePluginVersions } from "./version";
+
+describe("comparePluginVersions", () => {
+ it.each([
+ ["1.1.0", "1.0.0", 1],
+ ["1.0.0", "1.0.0", 0],
+ ["1.0.0", "1.0.0-rc.1", 1],
+ ["1.0.0-rc.10", "1.0.0-rc.9", 1],
+ ["1.0.0-beta.1", "1.0.0-1", 1],
+ ["1.0.0-rc.1", "1.0.0-rc.1.1", -1],
+ ["1.2.1+r1", "1.2.0", 1],
+ ["1.2.1+r2", "1.2.1+r1", 0],
+ ["100000000000000000000.0.0", "99999999999999999999.0.0", 1],
+ ])("orders %s against %s", (left, right, expectedSign) => {
+ expect(Math.sign(comparePluginVersions(left, right))).toBe(expectedSign);
+ });
+});
diff --git a/packages/core/plugins/version.ts b/packages/core/plugins/version.ts
new file mode 100644
index 0000000000..81571637f1
--- /dev/null
+++ b/packages/core/plugins/version.ts
@@ -0,0 +1,62 @@
+const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
+
+interface ParsedVersion {
+ numeric: [string, string, string];
+ prerelease: string[];
+}
+
+function parseVersion(version: string): ParsedVersion | null {
+ const match = SEMVER_RE.exec(version);
+ if (!match) return null;
+ return {
+ numeric: [match[1]!, match[2]!, match[3]!],
+ prerelease: match[4]?.split(".") ?? [],
+ };
+}
+
+function compareNumericIdentifier(left: string, right: string): number {
+ const normalizedLeft = left.replace(/^0+/, "") || "0";
+ const normalizedRight = right.replace(/^0+/, "") || "0";
+ if (normalizedLeft.length !== normalizedRight.length) {
+ return normalizedLeft.length - normalizedRight.length;
+ }
+ return normalizedLeft < normalizedRight ? -1 : normalizedLeft > normalizedRight ? 1 : 0;
+}
+
+/** Compare two validated Plugin manifest versions using SemVer precedence. */
+export function comparePluginVersions(left: string, right: string): number {
+ const parsedLeft = parseVersion(left);
+ const parsedRight = parseVersion(right);
+ if (!parsedLeft || !parsedRight) {
+ return left < right ? -1 : left > right ? 1 : 0;
+ }
+
+ for (let index = 0; index < parsedLeft.numeric.length; index += 1) {
+ const comparison = compareNumericIdentifier(parsedLeft.numeric[index]!, parsedRight.numeric[index]!);
+ if (comparison !== 0) return comparison;
+ }
+
+ const leftPrerelease = parsedLeft.prerelease;
+ const rightPrerelease = parsedRight.prerelease;
+ if (leftPrerelease.length === 0 && rightPrerelease.length === 0) return 0;
+ if (leftPrerelease.length === 0) return 1;
+ if (rightPrerelease.length === 0) return -1;
+
+ for (let index = 0; index < leftPrerelease.length && index < rightPrerelease.length; index += 1) {
+ const leftIdentifier = leftPrerelease[index]!;
+ const rightIdentifier = rightPrerelease[index]!;
+ const leftIsNumeric = /^\d+$/.test(leftIdentifier);
+ const rightIsNumeric = /^\d+$/.test(rightIdentifier);
+ if (leftIsNumeric && rightIsNumeric) {
+ const comparison = compareNumericIdentifier(leftIdentifier, rightIdentifier);
+ if (comparison !== 0) return comparison;
+ } else if (leftIsNumeric) {
+ return -1;
+ } else if (rightIsNumeric) {
+ return 1;
+ } else if (leftIdentifier !== rightIdentifier) {
+ return leftIdentifier < rightIdentifier ? -1 : 1;
+ }
+ }
+ return leftPrerelease.length - rightPrerelease.length;
+}
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index 1ee4f019ac..2f4d0b0907 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -77,6 +77,17 @@ export type {
} from "./agent";
export { RUNTIME_PROFILE_PROTOCOL_FAMILIES } from "./agent";
export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser, Invitation } from "./workspace";
+export type {
+ PluginBinding,
+ PluginInstallation,
+ PluginCatalogContribution,
+ PluginCatalogRelease,
+ PluginCatalogDiagnostic,
+ PluginCatalogResponse,
+ PluginInstallationListResponse,
+ PluginReleaseRequest,
+ PluginBindingRequest,
+} from "./plugin";
export type { InboxItem, InboxSeverity, InboxItemType, InboxWorkspaceUnread } from "./inbox";
export type { NotificationGroupKey, NotificationGroupValue, NotificationPreferences, NotificationPreferenceResponse } from "./notification-preference";
export type { Comment, CommentType, CommentAuthorType, CommentTriggerPreview, CommentTriggerPreviewAgent, CommentTriggerSource, CommentTriggerOutcome, CommentTriggerStatus, Reaction } from "./comment";
diff --git a/packages/core/types/plugin.ts b/packages/core/types/plugin.ts
new file mode 100644
index 0000000000..51e946ad63
--- /dev/null
+++ b/packages/core/types/plugin.ts
@@ -0,0 +1,81 @@
+export interface PluginBinding {
+ scope_type: string;
+ scope_id: string;
+ enabled: boolean;
+ revision: number;
+}
+
+export interface PluginInstallation {
+ id: string;
+ plugin_key: string;
+ display_name: string;
+ desired_version: string;
+ active_version?: string;
+ enabled: boolean;
+ desired_generation: number;
+ active_generation: number;
+ lifecycle_status: string;
+ health_state?: string;
+ health_reason?: string;
+ contributions: string[];
+ bindings: PluginBinding[];
+}
+
+export interface PluginCatalogContribution {
+ key: string;
+ type: string;
+ name: string;
+ description: string;
+ entry_path: string;
+ entry_digest: string;
+}
+
+export interface PluginCatalogRelease {
+ plugin_key: string;
+ name: string;
+ description: string;
+ version: string;
+ publisher: string;
+ publisher_type: string;
+ trust_tier: string;
+ source_kind: string;
+ source_ref: string;
+ requested_capabilities: string[];
+ host_api: string;
+ required_daemon_features: string[];
+ signature_key_id: string;
+ signature_verified: boolean;
+ manifest_digest: string;
+ archive_digest: string;
+ artifact_digest: string;
+ compatible: boolean;
+ compatibility_reason?: string;
+ contributions: PluginCatalogContribution[];
+ installation?: PluginInstallation;
+}
+
+export interface PluginCatalogDiagnostic {
+ source_ref: string;
+ code: string;
+ message: string;
+}
+
+export interface PluginCatalogResponse {
+ releases: PluginCatalogRelease[];
+ diagnostics: PluginCatalogDiagnostic[];
+ supported: boolean;
+}
+
+export interface PluginInstallationListResponse {
+ plugins: PluginInstallation[];
+}
+
+export interface PluginReleaseRequest {
+ plugin_key: string;
+ version: string;
+}
+
+export interface PluginBindingRequest {
+ scope_type: "workspace" | "agent";
+ scope_id: string;
+}
diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.json
index 4e0df1a983..2c4f81e954 100644
--- a/packages/views/locales/en/settings.json
+++ b/packages/views/locales/en/settings.json
@@ -182,7 +182,64 @@
"members": "Members",
"labels": "Labels",
"properties": "Properties",
- "quick_actions": "Quick Actions"
+ "quick_actions": "Quick Actions",
+ "plugins": "Plugins"
+ }
+ },
+ "plugins": {
+ "title": "Plugins",
+ "description": "Review, install, scope, and manage signed capabilities delivered by Multica.",
+ "loading": "Loading Plugins",
+ "load_failed": "Plugins couldn't be loaded",
+ "load_failed_description": "Try again. Existing enabled Plugins and pinned runs are unaffected.",
+ "backend_unavailable": "Plugin management isn't available",
+ "backend_unavailable_description": "This server predates the bundled Plugin catalog. Update the backend to manage Plugins here.",
+ "catalog_degraded": "Some bundled releases were isolated",
+ "catalog_degraded_description": "A bundled source failed validation. Healthy signed releases remain available.",
+ "read_only": "Read-only access",
+ "read_only_description": "Workspace owners and admins can install or change Plugin bindings.",
+ "empty": "No bundled Plugins are available.",
+ "official": "Official",
+ "signed": "Signature verified",
+ "signature_unverified": "Signature unverified",
+ "incompatible": "Incompatible release",
+ "incompatible_description": "This release requires a newer host API or daemon capability and cannot be activated.",
+ "install_disabled_hint": "Installation is disabled by default. Choose a workspace or agent scope after installing.",
+ "install": "Install",
+ "installed_disabled": "Plugin installed and left disabled",
+ "active_version": "Active version:",
+ "health": "Health:",
+ "bindings": "Enabled scopes",
+ "unknown_agent": "Unknown agent",
+ "workspace_scope": "Workspace",
+ "agent_scope": "Agent",
+ "binding_disabled": "Plugin binding disabled",
+ "disable_binding": "Disable",
+ "no_bindings": "No enabled scopes. New runs do not receive this Plugin.",
+ "enable_scope": "Enable scope",
+ "enabled": "Plugin scope enabled",
+ "disable_workspace": "Disable workspace",
+ "disabled": "Plugin disabled for new tasks",
+ "upgraded": "Plugin upgraded",
+ "rolled_back": "Plugin rolled back",
+ "upgrade_to": "Upgrade to v{{version}}",
+ "rollback_to": "Rollback to v{{version}}",
+ "action_failed": "Plugin action failed",
+ "none": "None",
+ "states": {
+ "disabled": "Disabled",
+ "activating": "Activating",
+ "healthy": "Healthy",
+ "degraded": "Degraded",
+ "failed": "Failed"
+ },
+ "review": {
+ "contributes": "Contributes",
+ "permissions": "Requested capability",
+ "compatibility": "Compatibility",
+ "host_api": "Host API",
+ "publisher": "Publisher and signing identity",
+ "none": "None"
}
},
"properties": {
diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.json
index 0a4e1669ab..b2d2d25547 100644
--- a/packages/views/locales/ja/settings.json
+++ b/packages/views/locales/ja/settings.json
@@ -182,7 +182,64 @@
"members": "メンバー",
"labels": "ラベル",
"properties": "プロパティ",
- "quick_actions": "クイックアクション"
+ "quick_actions": "クイックアクション",
+ "plugins": "Plugins"
+ }
+ },
+ "plugins": {
+ "title": "Plugins",
+ "description": "Multica が提供する署名済み機能を確認、インストール、スコープ設定、管理します。",
+ "loading": "Plugins を読み込み中",
+ "load_failed": "Plugins を読み込めませんでした",
+ "load_failed_description": "再試行してください。有効な Plugins と固定済みの作業には影響しません。",
+ "backend_unavailable": "Plugin 管理を利用できません",
+ "backend_unavailable_description": "このサーバーは bundled Plugin catalog に対応していません。バックエンドを更新してください。",
+ "catalog_degraded": "一部の bundled release を隔離しました",
+ "catalog_degraded_description": "bundled source の検証に失敗しました。正常な署名済み release は引き続き利用できます。",
+ "read_only": "読み取り専用",
+ "read_only_description": "ワークスペースの owner と admin が Plugin とバインドを変更できます。",
+ "empty": "利用可能な bundled Plugins はありません。",
+ "official": "公式",
+ "signed": "署名検証済み",
+ "signature_unverified": "署名未検証",
+ "incompatible": "互換性のない release",
+ "incompatible_description": "新しい Host API またはデーモン機能が必要なため、有効化できません。",
+ "install_disabled_hint": "インストール後は無効です。ワークスペースまたはエージェントのスコープを選択してください。",
+ "install": "インストール",
+ "installed_disabled": "Plugin を無効のままインストールしました",
+ "active_version": "有効なバージョン:",
+ "health": "状態:",
+ "bindings": "有効なスコープ",
+ "unknown_agent": "不明なエージェント",
+ "workspace_scope": "ワークスペース",
+ "agent_scope": "エージェント",
+ "binding_disabled": "Plugin バインドを無効にしました",
+ "disable_binding": "無効化",
+ "no_bindings": "有効なスコープはありません。新しい作業にはこの Plugin が追加されません。",
+ "enable_scope": "スコープを有効化",
+ "enabled": "Plugin スコープを有効にしました",
+ "disable_workspace": "ワークスペースで無効化",
+ "disabled": "新しい作業で Plugin を無効にしました",
+ "upgraded": "Plugin をアップグレードしました",
+ "rolled_back": "Plugin をロールバックしました",
+ "upgrade_to": "v{{version}} にアップグレード",
+ "rollback_to": "v{{version}} にロールバック",
+ "action_failed": "Plugin 操作に失敗しました",
+ "none": "なし",
+ "states": {
+ "disabled": "無効",
+ "activating": "有効化中",
+ "healthy": "正常",
+ "degraded": "低下",
+ "failed": "失敗"
+ },
+ "review": {
+ "contributes": "提供内容",
+ "permissions": "要求する capability",
+ "compatibility": "互換性",
+ "host_api": "Host API",
+ "publisher": "発行元と署名 ID",
+ "none": "なし"
}
},
"properties": {
diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.json
index 5de7e49a7e..6501856b91 100644
--- a/packages/views/locales/ko/settings.json
+++ b/packages/views/locales/ko/settings.json
@@ -182,7 +182,64 @@
"members": "멤버",
"labels": "레이블",
"properties": "속성",
- "quick_actions": "퀵 액션"
+ "quick_actions": "퀵 액션",
+ "plugins": "Plugins"
+ }
+ },
+ "plugins": {
+ "title": "Plugins",
+ "description": "Multica가 제공하는 서명된 기능을 검토, 설치, 범위 지정 및 관리합니다.",
+ "loading": "Plugins 불러오는 중",
+ "load_failed": "Plugins를 불러오지 못했습니다",
+ "load_failed_description": "다시 시도하세요. 활성 Plugins와 고정된 작업에는 영향이 없습니다.",
+ "backend_unavailable": "Plugin 관리를 사용할 수 없습니다",
+ "backend_unavailable_description": "이 서버는 bundled Plugin catalog를 지원하지 않습니다. 백엔드를 업데이트하세요.",
+ "catalog_degraded": "일부 bundled release가 격리되었습니다",
+ "catalog_degraded_description": "bundled source 검증에 실패했습니다. 정상적인 서명 release는 계속 사용할 수 있습니다.",
+ "read_only": "읽기 전용",
+ "read_only_description": "워크스페이스 owner와 admin이 Plugin 및 바인딩을 변경할 수 있습니다.",
+ "empty": "사용 가능한 bundled Plugins가 없습니다.",
+ "official": "공식",
+ "signed": "서명 확인됨",
+ "signature_unverified": "서명 미확인",
+ "incompatible": "호환되지 않는 release",
+ "incompatible_description": "최신 Host API 또는 데몬 기능이 필요하여 활성화할 수 없습니다.",
+ "install_disabled_hint": "설치 후 기본적으로 비활성화됩니다. 워크스페이스 또는 에이전트 범위를 선택하세요.",
+ "install": "설치",
+ "installed_disabled": "Plugin을 비활성 상태로 설치했습니다",
+ "active_version": "활성 버전:",
+ "health": "상태:",
+ "bindings": "활성 범위",
+ "unknown_agent": "알 수 없는 에이전트",
+ "workspace_scope": "워크스페이스",
+ "agent_scope": "에이전트",
+ "binding_disabled": "Plugin 바인딩을 비활성화했습니다",
+ "disable_binding": "비활성화",
+ "no_bindings": "활성 범위가 없습니다. 새 작업에 이 Plugin이 추가되지 않습니다.",
+ "enable_scope": "범위 활성화",
+ "enabled": "Plugin 범위를 활성화했습니다",
+ "disable_workspace": "워크스페이스 비활성화",
+ "disabled": "새 작업에서 Plugin을 비활성화했습니다",
+ "upgraded": "Plugin을 업그레이드했습니다",
+ "rolled_back": "Plugin을 롤백했습니다",
+ "upgrade_to": "v{{version}}로 업그레이드",
+ "rollback_to": "v{{version}}로 롤백",
+ "action_failed": "Plugin 작업에 실패했습니다",
+ "none": "없음",
+ "states": {
+ "disabled": "비활성",
+ "activating": "활성화 중",
+ "healthy": "정상",
+ "degraded": "성능 저하",
+ "failed": "실패"
+ },
+ "review": {
+ "contributes": "제공 항목",
+ "permissions": "요청 capability",
+ "compatibility": "호환성",
+ "host_api": "Host API",
+ "publisher": "게시자 및 서명 ID",
+ "none": "없음"
}
},
"properties": {
diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.json
index d7ba8c57d4..aa845499e9 100644
--- a/packages/views/locales/zh-Hans/settings.json
+++ b/packages/views/locales/zh-Hans/settings.json
@@ -182,7 +182,64 @@
"members": "成员",
"labels": "标签",
"properties": "属性",
- "quick_actions": "快捷操作"
+ "quick_actions": "快捷操作",
+ "plugins": "Plugins"
+ }
+ },
+ "plugins": {
+ "title": "Plugins",
+ "description": "审查、安装、设置作用范围并管理由 Multica 交付的签名能力。",
+ "loading": "正在加载 Plugins",
+ "load_failed": "无法加载 Plugins",
+ "load_failed_description": "请重试。已启用的 Plugins 和已固定的 task 不受影响。",
+ "backend_unavailable": "Plugin 管理不可用",
+ "backend_unavailable_description": "当前服务端版本不支持 bundled Plugin catalog。请更新后端后再在此管理。",
+ "catalog_degraded": "部分 bundled release 已隔离",
+ "catalog_degraded_description": "有 bundled source 未通过校验。其余已签名的健康 release 仍可使用。",
+ "read_only": "只读访问",
+ "read_only_description": "工作区 owner 和 admin 可以安装 Plugin 或更改绑定。",
+ "empty": "没有可用的 bundled Plugins。",
+ "official": "官方",
+ "signed": "签名已验证",
+ "signature_unverified": "签名未验证",
+ "incompatible": "Release 不兼容",
+ "incompatible_description": "此 release 需要更新的 Host API 或守护进程能力,无法激活。",
+ "install_disabled_hint": "安装后默认停用。安装完成后再选择工作区或智能体作用范围。",
+ "install": "安装",
+ "installed_disabled": "Plugin 已安装并保持停用",
+ "active_version": "当前版本:",
+ "health": "健康状态:",
+ "bindings": "已启用的作用范围",
+ "unknown_agent": "未知智能体",
+ "workspace_scope": "工作区",
+ "agent_scope": "智能体",
+ "binding_disabled": "Plugin 绑定已停用",
+ "disable_binding": "停用",
+ "no_bindings": "没有已启用的作用范围。新 task 不会获得此 Plugin。",
+ "enable_scope": "启用此范围",
+ "enabled": "Plugin 作用范围已启用",
+ "disable_workspace": "停用工作区",
+ "disabled": "Plugin 已对新 task 停用",
+ "upgraded": "Plugin 已升级",
+ "rolled_back": "Plugin 已回滚",
+ "upgrade_to": "升级到 v{{version}}",
+ "rollback_to": "回滚到 v{{version}}",
+ "action_failed": "Plugin 操作失败",
+ "none": "无",
+ "states": {
+ "disabled": "已停用",
+ "activating": "正在激活",
+ "healthy": "健康",
+ "degraded": "已降级",
+ "failed": "失败"
+ },
+ "review": {
+ "contributes": "贡献内容",
+ "permissions": "请求的 capability",
+ "compatibility": "兼容性",
+ "host_api": "Host API",
+ "publisher": "发布者与签名身份",
+ "none": "无"
}
},
"properties": {
diff --git a/packages/views/settings/components/index.ts b/packages/views/settings/components/index.ts
index ba802aabe8..94cd6705df 100644
--- a/packages/views/settings/components/index.ts
+++ b/packages/views/settings/components/index.ts
@@ -1,3 +1,4 @@
export { SettingsPage } from "./settings-page";
export type { ExtraSettingsTab } from "./settings-page";
+export { PluginsTab } from "./plugins-tab";
export { LabelsTab } from "./labels-tab";
diff --git a/packages/views/settings/components/plugins-tab.test.tsx b/packages/views/settings/components/plugins-tab.test.tsx
new file mode 100644
index 0000000000..b2c94735f1
--- /dev/null
+++ b/packages/views/settings/components/plugins-tab.test.tsx
@@ -0,0 +1,163 @@
+import type { ReactNode } from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { I18nProvider } from "@multica/core/i18n/react";
+import enCommon from "../../locales/en/common.json";
+import enSettings from "../../locales/en/settings.json";
+
+const mockInstall = vi.hoisted(() => vi.fn());
+const mockSetEnabled = vi.hoisted(() => vi.fn());
+const mockUpgrade = vi.hoisted(() => vi.fn());
+const mockRollback = vi.hoisted(() => vi.fn());
+
+const data = vi.hoisted(() => ({
+ catalog: {
+ supported: true,
+ diagnostics: [],
+ releases: [{
+ plugin_key: "ai.multica.software-delivery",
+ name: "Software Delivery",
+ description: "Official Multica software-delivery workflow skills.",
+ version: "1.1.0",
+ publisher: "multica",
+ publisher_type: "official",
+ trust_tier: "official",
+ source_kind: "bundled",
+ source_ref: "bundled://ai.multica.software-delivery/1.1.0",
+ requested_capabilities: ["agent.skill.contribute"],
+ host_api: ">=1.0.0 <2.0.0",
+ required_daemon_features: ["execution-manifest-v1", "agent-skill-v1"],
+ signature_key_id: "multica-plugin-release-2026-01",
+ signature_verified: true,
+ manifest_digest: "sha256:manifest",
+ archive_digest: "sha256:archive",
+ artifact_digest: "sha256:artifact",
+ compatible: true,
+ contributions: [{
+ key: "review-readiness",
+ type: "agent.skill.v1",
+ name: "review-readiness",
+ description: "Verify that a software change is ready for review and handoff.",
+ entry_path: "skills/review-readiness/SKILL.md",
+ entry_digest: "sha256:entry",
+ }],
+ }],
+ },
+ installed: { plugins: [] as Array<Record<string, unknown>> },
+ agents: [{ id: "agent-1", name: "Reviewer", archived_at: null }],
+ role: "owner" as "owner" | "admin" | "member",
+}));
+
+vi.mock("@tanstack/react-query", () => ({
+ useQuery: (options: { queryKey?: readonly string[] }) => {
+ const key = options.queryKey?.join(":") ?? "";
+ if (key.includes("catalog")) return { data: data.catalog, isPending: false, isError: false };
+ if (key.includes("installed")) return { data: data.installed, isPending: false, isError: false };
+ return { data: data.agents, isPending: false, isError: false };
+ },
+}));
+
+vi.mock("@multica/core/plugins", () => ({
+ comparePluginVersions: (left: string, right: string) => left.localeCompare(right),
+ pluginCatalogOptions: () => ({ queryKey: ["plugins", "catalog"] }),
+ pluginInstallationsOptions: () => ({ queryKey: ["plugins", "installed"] }),
+ useInstallPlugin: () => ({ mutateAsync: mockInstall, isPending: false }),
+ useSetPluginEnabled: () => ({ mutateAsync: mockSetEnabled, isPending: false }),
+ useUpgradePlugin: () => ({ mutateAsync: mockUpgrade, isPending: false }),
+ useRollbackPlugin: () => ({ mutateAsync: mockRollback, isPending: false }),
+}));
+
+vi.mock("@multica/core/workspace/queries", () => ({
+ agentListOptions: () => ({ queryKey: ["agents"] }),
+}));
+
+vi.mock("@multica/core/paths", () => ({
+ useCurrentWorkspace: () => ({ id: "workspace-1", name: "Acme", slug: "acme" }),
+}));
+
+vi.mock("@multica/core/permissions", () => ({
+ useCurrentMember: () => ({ role: data.role, isLoading: false }),
+}));
+
+vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+import { PluginsTab } from "./plugins-tab";
+
+const TEST_RESOURCES = { en: { common: enCommon, settings: enSettings } };
+
+function Wrapper({ children }: { children: ReactNode }) {
+ return <I18nProvider locale="en" resources={TEST_RESOURCES}>{children}</I18nProvider>;
+}
+
+describe("PluginsTab", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ data.role = "owner";
+ data.catalog.releases[0]!.compatible = true;
+ data.catalog.releases[0]!.signature_verified = true;
+ data.installed.plugins = [];
+ mockInstall.mockResolvedValue({});
+ mockSetEnabled.mockResolvedValue({});
+ });
+
+ it("renders the install review and keeps installation disabled by default", async () => {
+ const user = userEvent.setup();
+ render(<PluginsTab />, { wrapper: Wrapper });
+
+ expect(screen.getByText("review-readiness")).toBeInTheDocument();
+ expect(screen.getByText("agent.skill.contribute")).toBeInTheDocument();
+ expect(screen.getByText("Signature verified")).toBeInTheDocument();
+ expect(screen.getByText(/Installation is disabled by default/)).toBeInTheDocument();
+
+ await user.click(screen.getByRole("button", { name: "Install" }));
+ await waitFor(() => expect(mockInstall).toHaveBeenCalledWith({
+ plugin_key: "ai.multica.software-delivery",
+ version: "1.1.0",
+ }));
+ });
+
+ it("enables an installed Plugin for the workspace through a generic binding", async () => {
+ const user = userEvent.setup();
+ data.installed.plugins = [{
+ id: "installation-1",
+ plugin_key: "ai.multica.software-delivery",
+ display_name: "Software Delivery",
+ desired_version: "1.1.0",
+ active_version: "1.1.0",
+ enabled: false,
+ desired_generation: 1,
+ active_generation: 1,
+ lifecycle_status: "installed",
+ contributions: ["review-readiness"],
+ bindings: [],
+ }];
+ render(<PluginsTab />, { wrapper: Wrapper });
+
+ expect(screen.getByText("Disabled")).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "Enable scope" }));
+ await waitFor(() => expect(mockSetEnabled).toHaveBeenCalledWith({
+ installationId: "installation-1",
+ enabled: true,
+ binding: { scope_type: "workspace", scope_id: "workspace-1" },
+ }));
+ });
+
+ it("fails closed when compatibility or signature evidence is absent", () => {
+ data.catalog.releases[0]!.compatible = false;
+ data.catalog.releases[0]!.signature_verified = false;
+ render(<PluginsTab />, { wrapper: Wrapper });
+
+ expect(screen.getByText("Incompatible release")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Install" })).toBeDisabled();
+ });
+
+ it("keeps the catalog visible but actions read-only for members", () => {
+ data.role = "member";
+ render(<PluginsTab />, { wrapper: Wrapper });
+
+ expect(screen.getByText("Read-only access")).toBeInTheDocument();
+ expect(screen.getByText("review-readiness")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Install" })).toBeDisabled();
+ });
+});
diff --git a/packages/views/settings/components/plugins-tab.tsx b/packages/views/settings/components/plugins-tab.tsx
new file mode 100644
index 0000000000..fca75224ca
--- /dev/null
+++ b/packages/views/settings/components/plugins-tab.tsx
@@ -0,0 +1,388 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { AlertCircle, CheckCircle2, Loader2, PackageCheck, ShieldCheck } from "lucide-react";
+import { toast } from "sonner";
+import { agentListOptions } from "@multica/core/workspace/queries";
+import { useCurrentMember } from "@multica/core/permissions";
+import {
+ comparePluginVersions,
+ pluginCatalogOptions,
+ pluginInstallationsOptions,
+ useInstallPlugin,
+ useRollbackPlugin,
+ useSetPluginEnabled,
+ useUpgradePlugin,
+} from "@multica/core/plugins";
+import { useCurrentWorkspace } from "@multica/core/paths";
+import type { PluginCatalogRelease, PluginInstallation } from "@multica/core/types";
+import { Alert, AlertDescription, AlertTitle } from "@multica/ui/components/ui/alert";
+import { Badge } from "@multica/ui/components/ui/badge";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@multica/ui/components/ui/select";
+import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { useT } from "../../i18n";
+import { SettingsCard, SettingsSection, SettingsTab } from "./settings-layout";
+
+type BindingScope = "workspace" | "agent";
+
+function installationState(installation: PluginInstallation): "disabled" | "activating" | "healthy" | "degraded" | "failed" {
+ if (installation.enabled !== true) return "disabled";
+ if (installation.lifecycle_status === "activating") return "activating";
+ if (installation.health_state === "error" || installation.lifecycle_status === "error") return "failed";
+ if (installation.health_state === "degraded" || installation.lifecycle_status === "degraded") return "degraded";
+ return "healthy";
+}
+
+export function PluginsTab() {
+ const { t } = useT("settings");
+ const workspace = useCurrentWorkspace();
+ const wsId = workspace?.id ?? "";
+ const currentMember = useCurrentMember(wsId);
+ const canManage = currentMember.role === "owner" || currentMember.role === "admin";
+ const catalogQuery = useQuery(pluginCatalogOptions(wsId));
+ const installationsQuery = useQuery(pluginInstallationsOptions(wsId));
+ const agentsQuery = useQuery(agentListOptions(wsId));
+ const installMutation = useInstallPlugin(wsId);
+ const upgradeMutation = useUpgradePlugin(wsId);
+ const enabledMutation = useSetPluginEnabled(wsId);
+ const rollbackMutation = useRollbackPlugin(wsId);
+ const [selectedVersions, setSelectedVersions] = useState<Record<string, string>>({});
+ const [selectedScopes, setSelectedScopes] = useState<Record<string, BindingScope>>({});
+ const [selectedAgents, setSelectedAgents] = useState<Record<string, string>>({});
+
+ const releasesByPlugin = useMemo(() => {
+ const grouped = new Map<string, PluginCatalogRelease[]>();
+ for (const release of catalogQuery.data?.releases ?? []) {
+ const versions = grouped.get(release.plugin_key) ?? [];
+ versions.push(release);
+ grouped.set(release.plugin_key, versions);
+ }
+ for (const versions of grouped.values()) {
+ versions.sort((left, right) => comparePluginVersions(right.version, left.version));
+ }
+ return [...grouped.entries()];
+ }, [catalogQuery.data?.releases]);
+
+ const installations = useMemo(
+ () => new Map((installationsQuery.data?.plugins ?? []).map((installation) => [installation.plugin_key, installation])),
+ [installationsQuery.data?.plugins],
+ );
+ const agents = (agentsQuery.data ?? []).filter((agent) => !agent.archived_at);
+ const isMutating = installMutation.isPending || upgradeMutation.isPending || enabledMutation.isPending || rollbackMutation.isPending;
+
+ const reportError = (error: unknown) => {
+ toast.error(error instanceof Error ? error.message : t(($) => $.plugins.action_failed));
+ };
+
+ if (catalogQuery.isPending || installationsQuery.isPending) {
+ return (
+ <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>
+ <SettingsCard>
+ <div className="space-y-3 p-4" aria-label={t(($) => $.plugins.loading)}>
+ <Skeleton className="h-5 w-48" />
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-8 w-28" />
+ </div>
+ </SettingsCard>
+ </SettingsTab>
+ );
+ }
+
+ if (catalogQuery.isError || installationsQuery.isError) {
+ return (
+ <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>
+ <Alert variant="destructive">
+ <AlertCircle />
+ <AlertTitle>{t(($) => $.plugins.load_failed)}</AlertTitle>
+ <AlertDescription>{t(($) => $.plugins.load_failed_description)}</AlertDescription>
+ </Alert>
+ </SettingsTab>
+ );
+ }
+
+ if (catalogQuery.data?.supported !== true) {
+ return (
+ <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>
+ <Alert>
+ <AlertCircle />
+ <AlertTitle>{t(($) => $.plugins.backend_unavailable)}</AlertTitle>
+ <AlertDescription>{t(($) => $.plugins.backend_unavailable_description)}</AlertDescription>
+ </Alert>
+ </SettingsTab>
+ );
+ }
+
+ return (
+ <SettingsTab title={t(($) => $.plugins.title)} description={t(($) => $.plugins.description)}>
+ {catalogQuery.data.diagnostics.length > 0 ? (
+ <Alert variant="destructive">
+ <AlertCircle />
+ <AlertTitle>{t(($) => $.plugins.catalog_degraded)}</AlertTitle>
+ <AlertDescription>{t(($) => $.plugins.catalog_degraded_description)}</AlertDescription>
+ </Alert>
+ ) : null}
+
+ {!canManage && !currentMember.isLoading ? (
+ <Alert>
+ <ShieldCheck />
+ <AlertTitle>{t(($) => $.plugins.read_only)}</AlertTitle>
+ <AlertDescription>{t(($) => $.plugins.read_only_description)}</AlertDescription>
+ </Alert>
+ ) : null}
+
+ {releasesByPlugin.length === 0 ? (
+ <SettingsCard>
+ <div className="p-6 text-center text-body text-muted-foreground">
+ {t(($) => $.plugins.empty)}
+ </div>
+ </SettingsCard>
+ ) : null}
+
+ {releasesByPlugin.map(([pluginKey, versions]) => {
+ const latest = versions[0];
+ if (!latest) return null;
+ const installation = installations.get(pluginKey) ?? latest.installation;
+ const selectedVersion = selectedVersions[pluginKey] ?? latest.version;
+ const selectedRelease = versions.find((release) => release.version === selectedVersion) ?? latest;
+ const upgrade = installation && comparePluginVersions(latest.version, installation.desired_version) > 0 ? latest : null;
+ const rollback = installation
+ ? versions.find((release) => comparePluginVersions(release.version, installation.desired_version) < 0)
+ : null;
+ const scope = installation ? selectedScopes[installation.id] ?? "workspace" : "workspace";
+ const selectedAgent = installation ? selectedAgents[installation.id] ?? agents[0]?.id ?? "" : "";
+ const state = installation ? installationState(installation) : null;
+ const activeBindings = installation?.bindings.filter((binding) => binding.enabled === true) ?? [];
+ const workspaceBindingActive = activeBindings.some((binding) => binding.scope_type === "workspace");
+
+ return (
+ <SettingsSection key={pluginKey}>
+ <SettingsCard>
+ <div className="space-y-5 p-4 sm:p-5">
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <PackageCheck className="size-4 text-brand" />
+ <h3 className="text-title font-semibold">{latest.name}</h3>
+ <Badge variant="outline">{t(($) => $.plugins.official)}</Badge>
+ {latest.signature_verified === true ? (
+ <Badge variant="secondary"><ShieldCheck />{t(($) => $.plugins.signed)}</Badge>
+ ) : (
+ <Badge variant="destructive">{t(($) => $.plugins.signature_unverified)}</Badge>
+ )}
+ {state ? (
+ <Badge variant={state === "failed" ? "destructive" : state === "healthy" ? "default" : "secondary"}>
+ {state === "activating" ? <Loader2 className="animate-spin" /> : null}
+ {t(($) => $.plugins.states[state])}
+ </Badge>
+ ) : null}
+ </div>
+ <p className="mt-1 text-body text-muted-foreground">{latest.description}</p>
+ <p className="mt-1 break-all font-mono text-caption text-muted-foreground">{pluginKey}</p>
+ </div>
+ <Badge variant="outline">{installation?.desired_version ?? selectedRelease.version}</Badge>
+ </div>
+
+ <div className="grid gap-4 text-caption sm:grid-cols-2">
+ <div>
+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.contributes)}</div>
+ <ul className="mt-1 space-y-1 text-muted-foreground">
+ {selectedRelease.contributions.map((contribution) => (
+ <li key={contribution.key}>
+ <span className="font-medium text-foreground">{contribution.name}</span>
+ {" · "}{contribution.type}{" — "}{contribution.description}
+ </li>
+ ))}
+ </ul>
+ </div>
+ <div>
+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.permissions)}</div>
+ <p className="mt-1 text-muted-foreground">
+ {selectedRelease.requested_capabilities.join(", ") || t(($) => $.plugins.review.none)}
+ </p>
+ </div>
+ <div>
+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.compatibility)}</div>
+ <p className="mt-1 text-muted-foreground">
+ {t(($) => $.plugins.review.host_api)} {selectedRelease.host_api}{" · "}
+ {selectedRelease.required_daemon_features.join(", ")}
+ </p>
+ </div>
+ <div>
+ <div className="font-medium text-foreground">{t(($) => $.plugins.review.publisher)}</div>
+ <p className="mt-1 break-all text-muted-foreground">
+ {selectedRelease.publisher}{" · "}{selectedRelease.signature_key_id}
+ </p>
+ </div>
+ </div>
+
+ {selectedRelease.compatible !== true ? (
+ <Alert variant="destructive">
+ <AlertCircle />
+ <AlertTitle>{t(($) => $.plugins.incompatible)}</AlertTitle>
+ <AlertDescription>{t(($) => $.plugins.incompatible_description)}</AlertDescription>
+ </Alert>
+ ) : null}
+
+ {!installation ? (
+ <div className="flex flex-col gap-2 border-t border-surface-border pt-4 sm:flex-row sm:items-center sm:justify-between">
+ <p className="text-caption text-muted-foreground">{t(($) => $.plugins.install_disabled_hint)}</p>
+ <div className="flex items-center gap-2">
+ <Select
+ items={versions.map((release) => ({ value: release.version, label: release.version }))}
+ value={selectedVersion}
+ onValueChange={(value) => value && setSelectedVersions((current) => ({ ...current, [pluginKey]: value }))}
+ >
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {versions.map((release) => <SelectItem key={release.version} value={release.version}>{release.version}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ <Button
+ disabled={!canManage || isMutating || selectedRelease.compatible !== true || selectedRelease.signature_verified !== true}
+ onClick={() => installMutation.mutateAsync({ plugin_key: pluginKey, version: selectedRelease.version })
+ .then(() => toast.success(t(($) => $.plugins.installed_disabled)))
+ .catch(reportError)}
+ >
+ {installMutation.isPending ? <Loader2 className="animate-spin" /> : null}
+ {t(($) => $.plugins.install)}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <div className="space-y-4 border-t border-surface-border pt-4">
+ <div className="flex flex-wrap items-center gap-2 text-caption text-muted-foreground">
+ <span>{t(($) => $.plugins.active_version)} {installation.active_version || t(($) => $.plugins.none)}</span>
+ <span>·</span>
+ <span>{t(($) => $.plugins.health)} {installation.health_state || installation.lifecycle_status}</span>
+ </div>
+
+ {activeBindings.length > 0 ? (
+ <div className="space-y-2">
+ <div className="text-caption font-medium">{t(($) => $.plugins.bindings)}</div>
+ {activeBindings.map((binding) => {
+ const agentName = binding.scope_type === "agent"
+ ? agents.find((agent) => agent.id === binding.scope_id)?.name ?? t(($) => $.plugins.unknown_agent)
+ : workspace?.name ?? t(($) => $.plugins.workspace_scope);
+ return (
+ <div key={`${binding.scope_type}:${binding.scope_id}`} className="flex items-center justify-between gap-3 rounded-lg bg-muted px-3 py-2">
+ <span className="text-caption">{binding.scope_type === "agent" ? t(($) => $.plugins.agent_scope) : t(($) => $.plugins.workspace_scope)} · {agentName}</span>
+ <Button
+ size="xs"
+ variant="ghost"
+ disabled={!canManage || isMutating}
+ onClick={() => enabledMutation.mutateAsync({
+ installationId: installation.id,
+ enabled: false,
+ binding: { scope_type: binding.scope_type === "agent" ? "agent" : "workspace", scope_id: binding.scope_id },
+ }).then(() => toast.success(t(($) => $.plugins.binding_disabled))).catch(reportError)}
+ >
+ {t(($) => $.plugins.disable_binding)}
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="text-caption text-muted-foreground">{t(($) => $.plugins.no_bindings)}</p>
+ )}
+
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center">
+ <Select
+ items={[
+ { value: "workspace", label: t(($) => $.plugins.workspace_scope) },
+ { value: "agent", label: t(($) => $.plugins.agent_scope) },
+ ]}
+ value={scope}
+ onValueChange={(value) => value && setSelectedScopes((current) => ({ ...current, [installation.id]: value as BindingScope }))}
+ >
+ <SelectTrigger><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="workspace">{t(($) => $.plugins.workspace_scope)}</SelectItem>
+ <SelectItem value="agent">{t(($) => $.plugins.agent_scope)}</SelectItem>
+ </SelectContent>
+ </Select>
+ {scope === "agent" ? (
+ <Select
+ items={agents.map((agent) => ({ value: agent.id, label: agent.name }))}
+ value={selectedAgent}
+ onValueChange={(value) => value && setSelectedAgents((current) => ({ ...current, [installation.id]: value }))}
+ >
+ <SelectTrigger className="max-w-56"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ {agents.map((agent) => <SelectItem key={agent.id} value={agent.id}>{agent.name}</SelectItem>)}
+ </SelectContent>
+ </Select>
+ ) : null}
+ <Button
+ disabled={!canManage || isMutating || (scope === "agent" && !selectedAgent)}
+ onClick={() => enabledMutation.mutateAsync({
+ installationId: installation.id,
+ enabled: true,
+ binding: {
+ scope_type: scope,
+ scope_id: scope === "workspace" ? wsId : selectedAgent,
+ },
+ }).then(() => toast.success(t(($) => $.plugins.enabled))).catch(reportError)}
+ >
+ {enabledMutation.isPending ? <Loader2 className="animate-spin" /> : <CheckCircle2 />}
+ {t(($) => $.plugins.enable_scope)}
+ </Button>
+ <Button
+ variant="outline"
+ disabled={!canManage || isMutating || !workspaceBindingActive}
+ onClick={() => enabledMutation.mutateAsync({
+ installationId: installation.id,
+ enabled: false,
+ binding: { scope_type: "workspace", scope_id: wsId },
+ }).then(() => toast.success(t(($) => $.plugins.disabled))).catch(reportError)}
+ >
+ {t(($) => $.plugins.disable_workspace)}
+ </Button>
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ {upgrade ? (
+ <Button
+ variant="outline"
+ disabled={!canManage || isMutating || upgrade.compatible !== true}
+ onClick={() => upgradeMutation.mutateAsync({
+ installationId: installation.id,
+ plugin_key: pluginKey,
+ version: upgrade.version,
+ }).then(() => toast.success(t(($) => $.plugins.upgraded))).catch(reportError)}
+ >
+ {upgradeMutation.isPending ? <Loader2 className="animate-spin" /> : null}
+ {t(($) => $.plugins.upgrade_to, { version: upgrade.version })}
+ </Button>
+ ) : null}
+ {rollback ? (
+ <Button
+ variant="outline"
+ disabled={!canManage || isMutating}
+ onClick={() => rollbackMutation.mutateAsync({ installationId: installation.id, version: rollback.version })
+ .then(() => toast.success(t(($) => $.plugins.rolled_back)))
+ .catch(reportError)}
+ >
+ {rollbackMutation.isPending ? <Loader2 className="animate-spin" /> : null}
+ {t(($) => $.plugins.rollback_to, { version: rollback.version })}
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ )}
+ </div>
+ </SettingsCard>
+ </SettingsSection>
+ );
+ })}
+ </SettingsTab>
+ );
+}
diff --git a/packages/views/settings/components/settings-page.test.tsx b/packages/views/settings/components/settings-page.test.tsx
index f35701faca..02fec2f7b3 100644
--- a/packages/views/settings/components/settings-page.test.tsx
+++ b/packages/views/settings/components/settings-page.test.tsx
@@ -2,6 +2,8 @@ import { fireEvent, screen } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { SidebarProvider, useSidebar } from "@multica/ui/components/ui/sidebar";
+import { configStore } from "@multica/core/config";
+import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";
import { renderWithI18n } from "../../test/i18n";
// This file tests the settings SHELL — the chrome around the tabs — so every
@@ -25,15 +27,17 @@ vi.mock("./labels-tab", stub("LabelsTab"));
vi.mock("./properties-tab", stub("PropertiesTab"));
vi.mock("./quick-actions-tab", stub("QuickActionsTab"));
vi.mock("./keyboard-shortcuts-tab", stub("KeyboardShortcutsTab"));
+vi.mock("./plugins-tab", stub("PluginsTab"));
vi.mock("@multica/core/paths", () => ({
useCurrentWorkspace: () => ({ name: "Acme" }),
}));
const replace = vi.fn();
+const navigationState = { search: "" };
vi.mock("../../navigation", () => ({
useNavigation: () => ({
- searchParams: new URLSearchParams(),
+ searchParams: new URLSearchParams(navigationState.search),
pathname: "/acme/settings",
replace,
}),
@@ -60,6 +64,8 @@ function trigger() {
beforeEach(() => {
layout.compact = true;
+ navigationState.search = "";
+ configStore.getState().setFeatureFlags({});
replace.mockClear();
});
@@ -105,3 +111,25 @@ describe("SettingsPage nav trigger", () => {
expect(screen.getByText("Settings")).toBeInTheDocument();
});
});
+
+describe("SettingsPage Plugin feature flag", () => {
+ it("hides Plugins and falls back from a direct tab URL when disabled", () => {
+ navigationState.search = "tab=plugins";
+
+ renderWithI18n(<SettingsPage />);
+
+ expect(screen.queryByRole("tab", { name: "Plugins" })).not.toBeInTheDocument();
+ expect(screen.queryByText("PluginsTab")).not.toBeInTheDocument();
+ expect(screen.getByText("AccountTab")).toBeInTheDocument();
+ });
+
+ it("shows and mounts Plugins when explicitly enabled", () => {
+ navigationState.search = "tab=plugins";
+ configStore.getState().setFeatureFlags({ [PLUGINS_V1_FLAG]: true });
+
+ renderWithI18n(<SettingsPage />);
+
+ expect(screen.getByRole("tab", { name: "Plugins" })).toBeInTheDocument();
+ expect(screen.getByText("PluginsTab")).toBeInTheDocument();
+ });
+});
diff --git a/packages/views/settings/components/settings-page.tsx b/packages/views/settings/components/settings-page.tsx
index ea49d238eb..a59048d021 100644
--- a/packages/views/settings/components/settings-page.tsx
+++ b/packages/views/settings/components/settings-page.tsx
@@ -16,11 +16,14 @@ import {
Keyboard,
ListTodo,
Zap,
+ Blocks,
} from "lucide-react";
import { GitHubMark } from "./github-mark";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@multica/ui/components/ui/tabs";
import { useIsMobile } from "@multica/ui/hooks/use-mobile";
import { useCurrentWorkspace } from "@multica/core/paths";
+import { useFeatureEnabled } from "@multica/core/config";
+import { PLUGINS_V1_FLAG } from "@multica/core/feature-flags";
import { useNavigation } from "../../navigation";
import { AccountTab } from "./account-tab";
import { PreferencesTab } from "./preferences-tab";
@@ -38,6 +41,7 @@ import { LabelsTab } from "./labels-tab";
import { PropertiesTab } from "./properties-tab";
import { QuickActionsTab } from "./quick-actions-tab";
import { KeyboardShortcutsTab } from "./keyboard-shortcuts-tab";
+import { PluginsTab } from "./plugins-tab";
import { CollapsedNavTrigger } from "../../layout/page-header";
import { useT } from "../../i18n";
@@ -62,6 +66,7 @@ const WORKSPACE_TAB_KEYS = [
"labels",
"properties",
"quick_actions",
+ "plugins",
] as const;
const WORKSPACE_TAB_VALUES = {
general: "workspace",
@@ -73,6 +78,7 @@ const WORKSPACE_TAB_VALUES = {
labels: "labels",
properties: "properties",
quick_actions: "quick-actions",
+ plugins: "plugins",
} as const;
const WORKSPACE_TAB_ICONS = {
general: Settings,
@@ -84,6 +90,7 @@ const WORKSPACE_TAB_ICONS = {
labels: Tags,
properties: SlidersHorizontal,
quick_actions: Zap,
+ plugins: Blocks,
} as const;
const DEFAULT_TAB = "profile";
@@ -117,6 +124,12 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
const workspaceName = useCurrentWorkspace()?.name;
const navigation = useNavigation();
const isMobile = useIsMobile();
+ const pluginsEnabled = useFeatureEnabled(PLUGINS_V1_FLAG, false);
+
+ const visibleWorkspaceTabKeys = React.useMemo(
+ () => WORKSPACE_TAB_KEYS.filter((key) => key !== "plugins" || pluginsEnabled),
+ [pluginsEnabled],
+ );
// Whitelist of valid tab values; unknown ?tab=… values silently fall back to
// the default. Whitelisting also blocks junk like ?tab=<script> from
@@ -125,10 +138,10 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
() =>
new Set<string>([
...ACCOUNT_TAB_KEYS,
- ...Object.values(WORKSPACE_TAB_VALUES),
+ ...visibleWorkspaceTabKeys.map((key) => WORKSPACE_TAB_VALUES[key]),
...(extraAccountTabs?.map((tab) => tab.value) ?? []),
]),
- [extraAccountTabs],
+ [extraAccountTabs, visibleWorkspaceTabKeys],
);
const tabFromUrl = navigation.searchParams.get(TAB_QUERY_KEY);
@@ -204,7 +217,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<span className="hidden truncate px-2 pb-1 pt-4 text-caption font-medium text-muted-foreground md:block">
{workspaceName ?? t(($) => $.page.workspace_fallback)}
</span>
- {WORKSPACE_TAB_KEYS.map((key) => {
+ {visibleWorkspaceTabKeys.map((key) => {
const Icon = WORKSPACE_TAB_ICONS[key];
return (
<TabsTrigger
@@ -241,6 +254,7 @@ export function SettingsPage({ extraAccountTabs }: SettingsPageProps = {}) {
<TabsContent value="labels"><LabelsTab /></TabsContent>
<TabsContent value="properties"><PropertiesTab /></TabsContent>
<TabsContent value="quick-actions"><QuickActionsTab /></TabsContent>
+ {pluginsEnabled ? <TabsContent value="plugins"><PluginsTab /></TabsContent> : null}
{extraAccountTabs?.map((tab) => (
<TabsContent key={tab.value} value={tab.value}>{tab.content}</TabsContent>
))}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 4697cafbd7..3e17c02f0d 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -1160,6 +1160,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Get("/runtime-profiles", h.ListRuntimeProfiles)
r.Get("/runtime-profiles/{profileId}", h.GetRuntimeProfile)
r.Get("/plugins", h.ListPlugins)
+ r.Get("/plugins/catalog", h.ListPluginCatalog)
+ r.Get("/plugins/catalog/{pluginKey}", h.GetPluginCatalogRelease)
})
// Admin-level access
r.Group(func(r chi.Router) {
@@ -1177,6 +1179,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Patch("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)
r.Put("/runtime-profiles/{profileId}", h.UpdateRuntimeProfile)
r.Delete("/runtime-profiles/{profileId}", h.DeleteRuntimeProfile)
+ r.Post("/plugins/install", h.InstallPlugin)
+ r.Post("/plugins/{installationId}/upgrade", h.UpgradePlugin)
r.Post("/plugins/{installationId}/enable", h.EnablePlugin)
r.Post("/plugins/{installationId}/disable", h.DisablePlugin)
r.Post("/plugins/{installationId}/rollback", h.RollbackPlugin)
diff --git a/server/internal/featureflags/keys.go b/server/internal/featureflags/keys.go
index 16300020ef..c75fb9e082 100644
--- a/server/internal/featureflags/keys.go
+++ b/server/internal/featureflags/keys.go
@@ -13,6 +13,11 @@ const (
// The access model exists to gate Composio sharing, so the two ship on the
// same switch.
ComposioMCPApps = "composio_mcp_apps"
+ // PluginsV1 gates the user-facing Plugin catalog and lifecycle management
+ // APIs while the first product slice is dogfooded. It deliberately does not
+ // gate pinned Task/Run execution: disabling discovery and management must not
+ // mutate an immutable execution manifest that is already in flight.
+ PluginsV1 = "plugins_v1"
// agentBuilderCompat is no longer a release flag. Keep publishing the key
// as enabled so installed desktop clients that still gate the AI creation
// entry on this config decision receive the permanently enabled behavior.
@@ -32,12 +37,17 @@ const (
var frontendPublicFlags = []string{
ComposioMCPApps,
+ PluginsV1,
}
func ComposioMCPAppsEnabled(ctx context.Context, flags *featureflag.Service) bool {
return flags.IsEnabled(ctx, ComposioMCPApps, false)
}
+func PluginsV1Enabled(ctx context.Context, flags *featureflag.Service) bool {
+ return flags.IsEnabled(ctx, PluginsV1, false)
+}
+
func EvaluateFrontendPublicFlags(ctx context.Context, flags *featureflag.Service) map[string]bool {
out := make(map[string]bool, len(frontendPublicFlags)+3)
for _, key := range frontendPublicFlags {
diff --git a/server/internal/featureflags/keys_test.go b/server/internal/featureflags/keys_test.go
index 3ec72eaa8a..c38abcf093 100644
--- a/server/internal/featureflags/keys_test.go
+++ b/server/internal/featureflags/keys_test.go
@@ -37,3 +37,10 @@ func TestAgentSkillTogglesCompatDecisionStaysEnabled(t *testing.T) {
t.Fatal("agent skill toggles must stay enabled for installed v0.4.0 clients")
}
}
+
+func TestPluginsV1DefaultsOff(t *testing.T) {
+ flags := EvaluateFrontendPublicFlags(context.Background(), nil)
+ if flags[PluginsV1] {
+ t.Fatal("plugins_v1 must stay disabled unless explicitly enabled")
+ }
+}
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index f8d98bb644..29bcb7bbf7 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -412,6 +412,9 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {
if cfg.FeatureFlags["composio_mcp_apps"] {
t.Fatalf("composio_mcp_apps: want false by default, got true")
}
+ if cfg.FeatureFlags["plugins_v1"] {
+ t.Fatalf("plugins_v1: want false by default, got true")
+ }
if !cfg.FeatureFlags["agents_skill_toggles"] {
t.Fatalf("agents_skill_toggles: want true for installed v0.4.0 clients, got false")
}
@@ -432,3 +435,22 @@ func TestGetConfigExposesFrontendFeatureFlags(t *testing.T) {
t.Fatalf("composio_mcp_apps: want true with flag enabled, got false")
}
}
+
+func TestGetConfigExposesEnabledPluginsV1Flag(t *testing.T) {
+ h := &Handler{}
+ withPluginsV1Flag(t, h, true)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)
+ w := httptest.NewRecorder()
+ h.GetConfig(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetConfig enabled plugins_v1: expected 200, got %d: %s", w.Code, w.Body.String())
+ }
+ var cfg AppConfig
+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {
+ t.Fatalf("decode enabled config: %v", err)
+ }
+ if !cfg.FeatureFlags["plugins_v1"] {
+ t.Fatal("plugins_v1: want true with flag enabled, got false")
+ }
+}
diff --git a/server/internal/handler/featureflag_test.go b/server/internal/handler/featureflag_test.go
index 9d80eae3b7..683f159849 100644
--- a/server/internal/handler/featureflag_test.go
+++ b/server/internal/handler/featureflag_test.go
@@ -11,6 +11,10 @@ func withComposioMCPAppsFlag(t *testing.T, h *Handler, enabled bool) {
withFeatureFlag(t, h, featureflags.ComposioMCPApps, enabled)
}
+func withPluginsV1Flag(t *testing.T, h *Handler, enabled bool) {
+ withFeatureFlag(t, h, featureflags.PluginsV1, enabled)
+}
+
func withFeatureFlag(t *testing.T, h *Handler, key string, enabled bool) {
t.Helper()
provider := featureflag.NewStaticProvider()
diff --git a/server/internal/handler/plugin.go b/server/internal/handler/plugin.go
index 9deb9ec39c..6e31b5d9fd 100644
--- a/server/internal/handler/plugin.go
+++ b/server/internal/handler/plugin.go
@@ -1,28 +1,55 @@
package handler
import (
+ "context"
"encoding/json"
+ "errors"
+ "log/slog"
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/pluginbundled"
+ "github.com/multica-ai/multica/server/internal/service"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+func (h *Handler) pluginsV1Enabled(ctx context.Context) bool {
+ return featureflags.PluginsV1Enabled(ctx, h.FeatureFlags)
+}
+
+func (h *Handler) requirePluginsV1(w http.ResponseWriter, r *http.Request) bool {
+ if h.pluginsV1Enabled(r.Context()) {
+ return true
+ }
+ writeError(w, http.StatusServiceUnavailable, "Plugin management is not enabled")
+ return false
+}
+
+type pluginBindingResponse struct {
+ ScopeType string `json:"scope_type"`
+ ScopeID string `json:"scope_id"`
+ Enabled bool `json:"enabled"`
+ Revision int64 `json:"revision"`
+}
+
type pluginInstallationResponse struct {
- ID string `json:"id"`
- PluginKey string `json:"plugin_key"`
- DisplayName string `json:"display_name"`
- DesiredVersion string `json:"desired_version"`
- ActiveVersion string `json:"active_version,omitempty"`
- Enabled bool `json:"enabled"`
- DesiredGeneration int64 `json:"desired_generation"`
- ActiveGeneration int64 `json:"active_generation"`
- LifecycleStatus string `json:"lifecycle_status"`
- HealthState string `json:"health_state,omitempty"`
- HealthReason string `json:"health_reason,omitempty"`
- Contributions []string `json:"contributions"`
+ ID string `json:"id"`
+ PluginKey string `json:"plugin_key"`
+ DisplayName string `json:"display_name"`
+ DesiredVersion string `json:"desired_version"`
+ ActiveVersion string `json:"active_version,omitempty"`
+ Enabled bool `json:"enabled"`
+ DesiredGeneration int64 `json:"desired_generation"`
+ ActiveGeneration int64 `json:"active_generation"`
+ LifecycleStatus string `json:"lifecycle_status"`
+ HealthState string `json:"health_state,omitempty"`
+ HealthReason string `json:"health_reason,omitempty"`
+ Contributions []string `json:"contributions"`
+ Bindings []pluginBindingResponse `json:"bindings"`
}
func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.PluginInstallation, health *db.PluginHealth) (pluginInstallationResponse, error) {
@@ -44,16 +71,33 @@ func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.Pl
ActiveGeneration: installation.ActiveGeneration,
LifecycleStatus: installation.LifecycleStatus,
Contributions: []string{},
+ Bindings: []pluginBindingResponse{},
}
- if contributions, err := h.Queries.ListPluginContributionsByRelease(r.Context(), desired.ID); err == nil {
- for _, contribution := range contributions {
- response.Contributions = append(response.Contributions, contribution.ContributionKey)
- }
+ contributions, err := h.Queries.ListPluginContributionsByRelease(r.Context(), desired.ID)
+ if err != nil {
+ return pluginInstallationResponse{}, err
+ }
+ for _, contribution := range contributions {
+ response.Contributions = append(response.Contributions, contribution.ContributionKey)
+ }
+ bindings, err := h.Queries.ListLatestPluginBindings(r.Context(), installation.ID)
+ if err != nil {
+ return pluginInstallationResponse{}, err
+ }
+ for _, binding := range bindings {
+ response.Bindings = append(response.Bindings, pluginBindingResponse{
+ ScopeType: binding.ScopeType,
+ ScopeID: uuidToString(binding.ScopeID),
+ Enabled: binding.Enabled,
+ Revision: binding.BindingRevision,
+ })
}
if installation.ActiveReleaseID.Valid {
- if active, err := h.Queries.GetPluginRelease(r.Context(), installation.ActiveReleaseID); err == nil {
- response.ActiveVersion = active.Version
+ active, err := h.Queries.GetPluginRelease(r.Context(), installation.ActiveReleaseID)
+ if err != nil {
+ return pluginInstallationResponse{}, err
}
+ response.ActiveVersion = active.Version
}
if health != nil {
response.HealthState = health.State
@@ -63,13 +107,16 @@ func (h *Handler) pluginInstallationResponse(r *http.Request, installation db.Pl
}
func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
if !ok {
return
}
installations, err := h.Queries.ListWorkspacePluginInstallations(r.Context(), workspaceID)
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to list plugins")
+ writeError(w, http.StatusInternalServerError, "failed to list Plugins")
return
}
healthRows, _ := h.Queries.ListWorkspacePluginHealth(r.Context(), workspaceID)
@@ -89,26 +136,232 @@ func (h *Handler) ListPlugins(w http.ResponseWriter, r *http.Request) {
}
response, err := h.pluginInstallationResponse(r, installation, healthPtr)
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to load plugin")
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin")
return
}
responses = append(responses, response)
}
+ writeJSON(w, http.StatusOK, map[string]any{"plugins": responses})
+}
+
+type pluginCatalogContributionResponse struct {
+ Key string `json:"key"`
+ Type string `json:"type"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ EntryPath string `json:"entry_path"`
+ EntryDigest string `json:"entry_digest"`
+}
+
+type pluginCatalogReleaseResponse struct {
+ PluginKey string `json:"plugin_key"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Version string `json:"version"`
+ Publisher string `json:"publisher"`
+ PublisherType string `json:"publisher_type"`
+ TrustTier string `json:"trust_tier"`
+ SourceKind string `json:"source_kind"`
+ SourceRef string `json:"source_ref"`
+ RequestedCapabilities []string `json:"requested_capabilities"`
+ HostAPI string `json:"host_api"`
+ RequiredDaemonFeatures []string `json:"required_daemon_features"`
+ SignatureKeyID string `json:"signature_key_id"`
+ SignatureVerified bool `json:"signature_verified"`
+ ManifestDigest string `json:"manifest_digest"`
+ ArchiveDigest string `json:"archive_digest"`
+ ArtifactDigest string `json:"artifact_digest"`
+ Compatible bool `json:"compatible"`
+ CompatibilityReason string `json:"compatibility_reason,omitempty"`
+ Contributions []pluginCatalogContributionResponse `json:"contributions"`
+ Installation *pluginInstallationResponse `json:"installation,omitempty"`
+}
+
+func (h *Handler) catalogReleaseResponse(r *http.Request, workspaceID pgtype.UUID, entry pluginbundled.CatalogEntry) (pluginCatalogReleaseResponse, error) {
+ manifest := entry.Release.Manifest
+ response := pluginCatalogReleaseResponse{
+ PluginKey: manifest.Metadata.Key,
+ Name: manifest.Metadata.Name,
+ Description: manifest.Metadata.Description,
+ Version: manifest.Metadata.Version,
+ Publisher: manifest.Metadata.Publisher,
+ PublisherType: entry.PublisherType,
+ TrustTier: entry.TrustTier,
+ SourceKind: entry.Release.SourceKind,
+ SourceRef: entry.Release.SourceRef,
+ RequestedCapabilities: append([]string(nil), manifest.RequestedCapabilities...),
+ HostAPI: manifest.Compatibility.HostAPI,
+ RequiredDaemonFeatures: append([]string(nil), manifest.Compatibility.RequiredDaemonFeatures...),
+ SignatureKeyID: entry.Release.SignatureKeyID,
+ SignatureVerified: true,
+ ManifestDigest: entry.Release.ManifestDigest,
+ ArchiveDigest: entry.Release.ArchiveDigest,
+ ArtifactDigest: entry.Release.ArtifactDigest,
+ Compatible: entry.Compatible,
+ CompatibilityReason: entry.CompatibilityWhy,
+ Contributions: make([]pluginCatalogContributionResponse, 0, len(entry.Release.Contributions)),
+ }
+ for _, contribution := range entry.Release.Contributions {
+ response.Contributions = append(response.Contributions, pluginCatalogContributionResponse{
+ Key: contribution.Key,
+ Type: contribution.Type,
+ Name: contribution.DisplayName,
+ Description: contribution.Description,
+ EntryPath: contribution.EntryPath,
+ EntryDigest: contribution.EntryDigest,
+ })
+ }
+ identity, err := h.Queries.GetPluginIdentityByKey(r.Context(), manifest.Metadata.Key)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return response, nil
+ }
+ if err != nil {
+ return pluginCatalogReleaseResponse{}, err
+ }
+ installation, err := h.Queries.GetWorkspacePluginInstallation(r.Context(), db.GetWorkspacePluginInstallationParams{
+ WorkspaceID: workspaceID,
+ PluginID: identity.ID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ return response, nil
+ }
+ if err != nil {
+ return pluginCatalogReleaseResponse{}, err
+ }
+ installed, err := h.pluginInstallationResponse(r, installation, nil)
+ if err != nil {
+ return pluginCatalogReleaseResponse{}, err
+ }
+ response.Installation = &installed
+ return response, nil
+}
+
+func (h *Handler) ListPluginCatalog(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
+ workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ entries := h.PluginService.CatalogEntries()
+ responses := make([]pluginCatalogReleaseResponse, 0, len(entries))
+ for _, entry := range entries {
+ response, err := h.catalogReleaseResponse(r, workspaceID, entry)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin catalog")
+ return
+ }
+ responses = append(responses, response)
+ }
+ diagnostics := h.PluginService.CatalogDiagnostics()
+ if diagnostics == nil {
+ diagnostics = []pluginbundled.Diagnostic{}
+ }
writeJSON(w, http.StatusOK, map[string]any{
- "plugins": responses,
+ "releases": responses,
+ "diagnostics": diagnostics,
})
}
+func (h *Handler) GetPluginCatalogRelease(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
+ workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
+ if !ok {
+ return
+ }
+ entry, found := h.PluginService.FindCatalogRelease(chi.URLParam(r, "pluginKey"), r.URL.Query().Get("version"))
+ if !found {
+ writeError(w, http.StatusNotFound, "Plugin release not found")
+ return
+ }
+ response, err := h.catalogReleaseResponse(r, workspaceID, entry)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin catalog")
+ return
+ }
+ writeJSON(w, http.StatusOK, response)
+}
+
+type pluginReleaseRequest struct {
+ PluginKey string `json:"plugin_key"`
+ Version string `json:"version"`
+}
+
+func (h *Handler) InstallPlugin(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
+ workspaceID, actorID, ok := pluginRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ var request pluginReleaseRequest
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.PluginKey == "" || request.Version == "" {
+ writeError(w, http.StatusBadRequest, "plugin_key and version are required")
+ return
+ }
+ installation, err := h.PluginService.InstallCatalogRelease(r.Context(), workspaceID, actorID, request.PluginKey, request.Version)
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ response, err := h.pluginInstallationResponse(r, installation, nil)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin")
+ return
+ }
+ writeJSON(w, http.StatusCreated, response)
+}
+
+func (h *Handler) UpgradePlugin(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
+ workspaceID, actorID, ok := pluginRequestIDs(w, r)
+ if !ok {
+ return
+ }
+ installationID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "installationId"), "installation_id")
+ if !ok {
+ return
+ }
+ var request pluginReleaseRequest
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil || request.PluginKey == "" || request.Version == "" {
+ writeError(w, http.StatusBadRequest, "plugin_key and version are required")
+ return
+ }
+ installation, err := h.PluginService.UpgradeCatalogRelease(r.Context(), workspaceID, installationID, actorID, request.PluginKey, request.Version)
+ if err != nil {
+ writePluginError(w, r, err)
+ return
+ }
+ response, err := h.pluginInstallationResponse(r, installation, nil)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin")
+ return
+ }
+ writeJSON(w, http.StatusOK, response)
+}
+
type pluginBindingRequest struct {
ScopeType string `json:"scope_type"`
ScopeID string `json:"scope_id"`
}
func (h *Handler) EnablePlugin(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
h.setPluginEnabled(w, r, true)
}
func (h *Handler) DisablePlugin(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
h.setPluginEnabled(w, r, false)
}
@@ -131,30 +384,33 @@ func (h *Handler) setPluginEnabled(w http.ResponseWriter, r *http.Request, enabl
if request.ScopeType == "workspace" && request.ScopeID == "" {
request.ScopeID = uuidToString(workspaceID)
}
- scopeID, err := util.ParseUUID(request.ScopeID)
- if err != nil {
- writeError(w, http.StatusBadRequest, "scope_id must be a UUID")
+ scopeID, ok := parseUUIDOrBadRequest(w, request.ScopeID, "scope_id")
+ if !ok {
return
}
var installation db.PluginInstallation
+ var err error
if enabled {
installation, err = h.PluginService.EnablePlugin(r.Context(), workspaceID, installationID, actorID, request.ScopeType, scopeID)
} else {
installation, err = h.PluginService.DisablePlugin(r.Context(), workspaceID, installationID, actorID, request.ScopeType, scopeID)
}
if err != nil {
- writeError(w, http.StatusConflict, err.Error())
+ writePluginError(w, r, err)
return
}
response, err := h.pluginInstallationResponse(r, installation, nil)
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to load plugin")
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin")
return
}
writeJSON(w, http.StatusOK, response)
}
func (h *Handler) RollbackPlugin(w http.ResponseWriter, r *http.Request) {
+ if !h.requirePluginsV1(w, r) {
+ return
+ }
workspaceID, actorID, ok := pluginRequestIDs(w, r)
if !ok {
return
@@ -172,17 +428,42 @@ func (h *Handler) RollbackPlugin(w http.ResponseWriter, r *http.Request) {
}
installation, err := h.PluginService.RollbackPlugin(r.Context(), workspaceID, installationID, actorID, request.Version)
if err != nil {
- writeError(w, http.StatusConflict, err.Error())
+ writePluginError(w, r, err)
return
}
response, err := h.pluginInstallationResponse(r, installation, nil)
if err != nil {
- writeError(w, http.StatusInternalServerError, "failed to load plugin")
+ writeError(w, http.StatusInternalServerError, "failed to load Plugin")
return
}
writeJSON(w, http.StatusOK, response)
}
+func writePluginError(w http.ResponseWriter, r *http.Request, err error) {
+ var pluginErr *service.PluginError
+ if !errors.As(err, &pluginErr) {
+ slog.Error("Plugin request failed", "method", r.Method, "path", r.URL.Path, "error", err)
+ writeError(w, http.StatusInternalServerError, "Plugin operation failed")
+ return
+ }
+ status := http.StatusInternalServerError
+ switch pluginErr.Kind {
+ case service.PluginErrorInvalid:
+ status = http.StatusBadRequest
+ case service.PluginErrorNotFound:
+ status = http.StatusNotFound
+ case service.PluginErrorConflict:
+ status = http.StatusConflict
+ case service.PluginErrorIncompatible:
+ status = http.StatusUnprocessableEntity
+ default:
+ slog.Error("Plugin request returned unknown classified error", "error", err)
+ writeError(w, http.StatusInternalServerError, "Plugin operation failed")
+ return
+ }
+ writeError(w, status, pluginErr.Message)
+}
+
func pluginRequestIDs(w http.ResponseWriter, r *http.Request) (pgtype.UUID, pgtype.UUID, bool) {
workspaceID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "workspace_id")
if !ok {
diff --git a/server/internal/handler/plugin_test.go b/server/internal/handler/plugin_test.go
index ff1890db92..60e9ade78f 100644
--- a/server/internal/handler/plugin_test.go
+++ b/server/internal/handler/plugin_test.go
@@ -3,16 +3,50 @@ package handler
import (
"bytes"
"context"
+ "encoding/json"
+ "errors"
"net/http"
"net/http/httptest"
+ "strings"
"testing"
"github.com/go-chi/chi/v5"
- "github.com/multica-ai/multica/server/internal/service"
+ "github.com/jackc/pgx/v5"
"github.com/multica-ai/multica/server/internal/testutil/plugintest"
- "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
)
+type failPluginDetailQueryDB struct {
+ db.DBTX
+ queryFragment string
+ queryRowFragment string
+ failQueryRowAtMatch int
+ queryRowMatches int
+}
+
+func (database *failPluginDetailQueryDB) Query(ctx context.Context, query string, args ...any) (pgx.Rows, error) {
+ if database.queryFragment != "" && strings.Contains(query, database.queryFragment) {
+ return nil, errors.New("forced Plugin detail query failure")
+ }
+ return database.DBTX.Query(ctx, query, args...)
+}
+
+type pluginDetailErrorRow struct{}
+
+func (pluginDetailErrorRow) Scan(...any) error {
+ return errors.New("forced Plugin detail query failure")
+}
+
+func (database *failPluginDetailQueryDB) QueryRow(ctx context.Context, query string, args ...any) pgx.Row {
+ if database.queryRowFragment != "" && strings.Contains(query, database.queryRowFragment) {
+ database.queryRowMatches++
+ if database.queryRowMatches == database.failQueryRowAtMatch {
+ return pluginDetailErrorRow{}
+ }
+ }
+ return database.DBTX.QueryRow(ctx, query, args...)
+}
+
func pluginHandlerRequest(method, path string, body []byte, params map[string]string) *http.Request {
request := httptest.NewRequest(method, path, bytes.NewReader(body))
request.Header.Set("X-User-ID", testUserID)
@@ -25,6 +59,7 @@ func pluginHandlerRequest(method, path string, body []byte, params map[string]st
}
func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {
+ withPluginsV1Flag(t, testHandler, true)
cleanup := func() {
ctx := context.Background()
testPool.Exec(ctx, `DELETE FROM plugin_health WHERE workspace_id = $1`, testWorkspaceID)
@@ -37,22 +72,52 @@ func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {
cleanup()
t.Cleanup(cleanup)
- release, err := plugintest.ReviewReadinessRelease()
- if err != nil {
- t.Fatalf("reference release: %v", err)
+ recorder := httptest.NewRecorder()
+ testHandler.ListPluginCatalog(recorder, pluginHandlerRequest(http.MethodGet, "/plugins/catalog", nil, map[string]string{"id": testWorkspaceID}))
+ if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"signature_verified":true`)) || !bytes.Contains(recorder.Body.Bytes(), []byte(plugintest.ReviewReadinessPluginKey)) {
+ t.Fatalf("catalog status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ var catalogPayload struct {
+ Diagnostics json.RawMessage `json:"diagnostics"`
}
- installed, err := testHandler.PluginService.InstallPluginRelease(
- context.Background(),
- util.MustParseUUID(testWorkspaceID),
- util.MustParseUUID(testUserID),
- service.PluginReleasePublication{Release: release, PublisherType: "official", TrustTier: "official"},
- )
- if err != nil {
- t.Fatalf("install reference release: %v", err)
+ if err := json.Unmarshal(recorder.Body.Bytes(), &catalogPayload); err != nil {
+ t.Fatalf("decode catalog: %v", err)
+ }
+ if !bytes.Equal(catalogPayload.Diagnostics, []byte(`[]`)) {
+ t.Fatalf("empty catalog diagnostics must be an array, got %s", catalogPayload.Diagnostics)
}
- params := map[string]string{"id": testWorkspaceID, "installationId": uuidToString(installed.ID)}
- recorder := httptest.NewRecorder()
+ recorder = httptest.NewRecorder()
+ testHandler.InstallPlugin(recorder, pluginHandlerRequest(
+ http.MethodPost,
+ "/plugins/install",
+ []byte(`{"plugin_key":"ai.multica.software-delivery","version":"1.0.0"}`),
+ map[string]string{"id": testWorkspaceID},
+ ))
+ if recorder.Code != http.StatusCreated {
+ t.Fatalf("install status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ var installed pluginInstallationResponse
+ if err := json.Unmarshal(recorder.Body.Bytes(), &installed); err != nil {
+ t.Fatalf("decode installation: %v", err)
+ }
+ if installed.Enabled || installed.LifecycleStatus != "installed" {
+ t.Fatalf("install must remain disabled: %+v", installed)
+ }
+
+ params := map[string]string{"id": testWorkspaceID, "installationId": installed.ID}
+ recorder = httptest.NewRecorder()
+ testHandler.EnablePlugin(recorder, pluginHandlerRequest(
+ http.MethodPost,
+ "/plugins/enable",
+ []byte(`{"scope_type":"workspace","scope_id":"00000000-0000-0000-0000-000000000001"}`),
+ params,
+ ))
+ if recorder.Code != http.StatusNotFound || bytes.Contains(recorder.Body.Bytes(), []byte("no rows")) {
+ t.Fatalf("cross-workspace binding status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+
+ recorder = httptest.NewRecorder()
testHandler.EnablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/enable", nil, params))
if recorder.Code != http.StatusOK {
t.Fatalf("enable status=%d body=%s", recorder.Code, recorder.Body.String())
@@ -63,6 +128,53 @@ func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {
if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(plugintest.ReviewReadinessPluginKey)) {
t.Fatalf("list status=%d body=%s", recorder.Code, recorder.Body.String())
}
+ for _, test := range []struct {
+ name string
+ queryFragment string
+ queryRowFragment string
+ failQueryRowAtMatch int
+ }{
+ {name: "contributions", queryFragment: "FROM plugin_contribution"},
+ {name: "bindings", queryFragment: "FROM plugin_binding"},
+ {name: "active release", queryRowFragment: "FROM plugin_release\nWHERE id = $1", failQueryRowAtMatch: 2},
+ } {
+ t.Run("list fails closed when "+test.name+" cannot be read", func(t *testing.T) {
+ failingHandler := *testHandler
+ failingHandler.Queries = db.New(&failPluginDetailQueryDB{
+ DBTX: testPool,
+ queryFragment: test.queryFragment,
+ queryRowFragment: test.queryRowFragment,
+ failQueryRowAtMatch: test.failQueryRowAtMatch,
+ })
+ recorder := httptest.NewRecorder()
+ failingHandler.ListPlugins(recorder, pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{"id": testWorkspaceID}))
+ if recorder.Code != http.StatusInternalServerError {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ })
+ }
+
+ recorder = httptest.NewRecorder()
+ testHandler.UpgradePlugin(recorder, pluginHandlerRequest(
+ http.MethodPost,
+ "/plugins/upgrade",
+ []byte(`{"plugin_key":"ai.multica.software-delivery","version":"1.1.0"}`),
+ params,
+ ))
+ if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"desired_version":"1.1.0"`)) {
+ t.Fatalf("upgrade status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+
+ recorder = httptest.NewRecorder()
+ testHandler.UpgradePlugin(recorder, pluginHandlerRequest(
+ http.MethodPost,
+ "/plugins/upgrade",
+ []byte(`{"plugin_key":"ai.multica.software-delivery","version":"1.0.0"}`),
+ params,
+ ))
+ if recorder.Code != http.StatusConflict || !bytes.Contains(recorder.Body.Bytes(), []byte("not newer")) {
+ t.Fatalf("downgrade through upgrade status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
recorder = httptest.NewRecorder()
testHandler.DisablePlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/disable", nil, params))
@@ -72,7 +184,46 @@ func TestPluginHTTPLifecycleForInstalledReferenceRelease(t *testing.T) {
recorder = httptest.NewRecorder()
testHandler.RollbackPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/rollback", []byte(`{"version":"1.0.0"}`), params))
- if recorder.Code != http.StatusOK {
+ if recorder.Code != http.StatusOK || !bytes.Contains(recorder.Body.Bytes(), []byte(`"desired_version":"1.0.0"`)) {
t.Fatalf("rollback status=%d body=%s", recorder.Code, recorder.Body.String())
}
+
+ recorder = httptest.NewRecorder()
+ testHandler.RollbackPlugin(recorder, pluginHandlerRequest(http.MethodPost, "/plugins/rollback", []byte(`{"version":"9.9.9"}`), params))
+ if recorder.Code != http.StatusNotFound || bytes.Contains(recorder.Body.Bytes(), []byte("no rows")) {
+ t.Fatalf("safe missing rollback status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+}
+
+func TestPluginManagementUnavailableWhenFlagDisabled(t *testing.T) {
+ h := &Handler{}
+ request := func() *http.Request {
+ return pluginHandlerRequest(http.MethodGet, "/plugins", nil, map[string]string{
+ "id": testWorkspaceID,
+ "installationId": "00000000-0000-0000-0000-000000000001",
+ "pluginKey": plugintest.ReviewReadinessPluginKey,
+ })
+ }
+
+ for name, handler := range map[string]http.HandlerFunc{
+ "list installed": h.ListPlugins,
+ "list catalog": h.ListPluginCatalog,
+ "catalog detail": h.GetPluginCatalogRelease,
+ "install": h.InstallPlugin,
+ "upgrade": h.UpgradePlugin,
+ "enable": h.EnablePlugin,
+ "disable": h.DisablePlugin,
+ "rollback": h.RollbackPlugin,
+ } {
+ t.Run(name, func(t *testing.T) {
+ recorder := httptest.NewRecorder()
+ handler(recorder, request())
+ if recorder.Code != http.StatusServiceUnavailable {
+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
+ }
+ if bytes.Contains(recorder.Body.Bytes(), []byte(plugintest.ReviewReadinessPluginKey)) {
+ t.Fatalf("disabled response leaked catalog data: %s", recorder.Body.String())
+ }
+ })
+ }
}
diff --git a/server/internal/pluginbundled/README.md b/server/internal/pluginbundled/README.md
new file mode 100644
index 0000000000..edee91b1b6
--- /dev/null
+++ b/server/internal/pluginbundled/README.md
@@ -0,0 +1,27 @@
+# Bundled Plugin release catalog
+
+This package is the production acquisition boundary for official Plugins that
+ship with the Multica server. It discovers release directories generically,
+rebuilds their ZIP archives deterministically, validates the manifest and
+artifact, and verifies the detached Ed25519 signature against
+`trust_roots.json` before exposing a release to the catalog.
+
+Each release directory contains:
+
+- `release.json`: source and publisher metadata plus the signing-key ID.
+- `release.sig`: a detached base64 Ed25519 signature.
+- `multica.plugin.json` and the static contribution payloads that form the ZIP.
+
+The signing private key is intentionally not stored in this repository or the
+server binary. Release automation must build the same deterministic ZIP, sign
+the Plugin release envelope offline, and commit only the detached signature.
+Run the reproducibility and trust-boundary checks from `server/`:
+
+```sh
+go test ./internal/pluginbundled -count=1
+```
+
+A malformed, tampered, or unknown-key release is isolated as a safe catalog
+diagnostic. It does not prevent other releases or the server from starting.
+The public API admits only this bundled source in V1; no `private_dev` upload or
+server-file-path acquisition route is exposed.
diff --git a/server/internal/pluginbundled/catalog.go b/server/internal/pluginbundled/catalog.go
new file mode 100644
index 0000000000..bfef13a013
--- /dev/null
+++ b/server/internal/pluginbundled/catalog.go
@@ -0,0 +1,436 @@
+// Package pluginbundled discovers and validates immutable Plugin releases
+// shipped with the Multica server binary.
+package pluginbundled
+
+import (
+ "archive/zip"
+ "bytes"
+ "crypto/ed25519"
+ "embed"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io/fs"
+ "path"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/multica-ai/multica/server/pkg/plugincontract"
+)
+
+const (
+ PublisherTypeOfficial = "official"
+ TrustTierOfficial = "official"
+)
+
+//go:embed trust_roots.json releases
+var bundledFS embed.FS
+
+// CatalogEntry is a validated bundled release plus the acquisition-boundary
+// trust decision used when it is installed into a workspace.
+type CatalogEntry struct {
+ Release plugincontract.ValidatedRelease
+ PublisherType string
+ TrustTier string
+ Compatible bool
+ CompatibilityWhy string
+}
+
+// Diagnostic reports a release that could not be admitted without preventing
+// healthy releases, or the server, from loading.
+type Diagnostic struct {
+ SourceRef string `json:"source_ref"`
+ Code string `json:"code"`
+ Message string `json:"message"`
+}
+
+// Catalog is immutable after construction and safe for concurrent reads.
+type Catalog struct {
+ entries map[string]map[string]CatalogEntry
+ diagnostics []Diagnostic
+}
+
+type trustRootFile struct {
+ Keys []struct {
+ ID string `json:"id"`
+ PublicKey string `json:"public_key"`
+ } `json:"keys"`
+}
+
+type releaseMetadata struct {
+ SourceRef string `json:"source_ref"`
+ SignatureKeyID string `json:"signature_key_id"`
+ SignatureFile string `json:"signature_file"`
+ PublisherType string `json:"publisher_type"`
+ TrustTier string `json:"trust_tier"`
+}
+
+// Load discovers the releases embedded in the production server. A bad trust
+// root or release becomes a catalog diagnostic; it never blocks Kernel startup.
+func Load() *Catalog {
+ return LoadFromFS(bundledFS)
+}
+
+// LoadFromFS is the testable discovery boundary for bundled sources.
+func LoadFromFS(source fs.FS) *Catalog {
+ catalog := &Catalog{entries: make(map[string]map[string]CatalogEntry)}
+ verifier, err := loadTrustStore(source)
+ if err != nil {
+ catalog.diagnostics = append(catalog.diagnostics, Diagnostic{
+ SourceRef: "bundled://trust-roots",
+ Code: "trust_roots_invalid",
+ Message: "Bundled Plugin trust roots could not be loaded.",
+ })
+ return catalog
+ }
+
+ var metadataFiles []string
+ if err := fs.WalkDir(source, "releases", func(name string, entry fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ catalog.diagnostics = append(catalog.diagnostics, Diagnostic{
+ SourceRef: "bundled://" + name,
+ Code: "source_unreadable",
+ Message: "A bundled Plugin source could not be read.",
+ })
+ return fs.SkipDir
+ }
+ if !entry.IsDir() && path.Base(name) == "release.json" {
+ metadataFiles = append(metadataFiles, name)
+ }
+ return nil
+ }); err != nil {
+ catalog.diagnostics = append(catalog.diagnostics, Diagnostic{
+ SourceRef: "bundled://releases",
+ Code: "source_unreadable",
+ Message: "Bundled Plugin releases could not be discovered.",
+ })
+ return catalog
+ }
+ sort.Strings(metadataFiles)
+ for _, metadataFile := range metadataFiles {
+ entry, diagnostic := loadRelease(source, verifier, metadataFile)
+ if diagnostic != nil {
+ catalog.diagnostics = append(catalog.diagnostics, *diagnostic)
+ continue
+ }
+ key := entry.Release.Manifest.Metadata.Key
+ version := entry.Release.Manifest.Metadata.Version
+ if catalog.entries[key] == nil {
+ catalog.entries[key] = make(map[string]CatalogEntry)
+ }
+ if _, duplicate := catalog.entries[key][version]; duplicate {
+ catalog.diagnostics = append(catalog.diagnostics, Diagnostic{
+ SourceRef: entry.Release.SourceRef,
+ Code: "duplicate_release",
+ Message: "A duplicate bundled Plugin release was ignored.",
+ })
+ continue
+ }
+ catalog.entries[key][version] = entry
+ }
+ return catalog
+}
+
+func loadTrustStore(source fs.FS) (*plugincontract.Ed25519TrustStore, error) {
+ raw, err := fs.ReadFile(source, "trust_roots.json")
+ if err != nil {
+ return nil, err
+ }
+ decoder := json.NewDecoder(bytes.NewReader(raw))
+ decoder.DisallowUnknownFields()
+ var roots trustRootFile
+ if err := decoder.Decode(&roots); err != nil {
+ return nil, err
+ }
+ keys := make(map[string]ed25519.PublicKey, len(roots.Keys))
+ for _, root := range roots.Keys {
+ decoded, err := base64.StdEncoding.DecodeString(root.PublicKey)
+ if err != nil {
+ return nil, err
+ }
+ keys[root.ID] = ed25519.PublicKey(decoded)
+ }
+ if len(keys) == 0 {
+ return nil, errors.New("bundled Plugin trust store is empty")
+ }
+ return plugincontract.NewEd25519TrustStore(keys)
+}
+
+func loadRelease(source fs.FS, verifier plugincontract.ReleaseVerifier, metadataFile string) (CatalogEntry, *Diagnostic) {
+ releaseDir := path.Dir(metadataFile)
+ metadataRaw, err := fs.ReadFile(source, metadataFile)
+ if err != nil {
+ return CatalogEntry{}, releaseDiagnostic(releaseDir, "release_metadata_invalid")
+ }
+ decoder := json.NewDecoder(bytes.NewReader(metadataRaw))
+ decoder.DisallowUnknownFields()
+ var metadata releaseMetadata
+ if err := decoder.Decode(&metadata); err != nil || metadata.SourceRef == "" || metadata.SignatureKeyID == "" || metadata.SignatureFile == "" {
+ return CatalogEntry{}, releaseDiagnostic(releaseDir, "release_metadata_invalid")
+ }
+ if metadata.PublisherType != PublisherTypeOfficial || metadata.TrustTier != TrustTierOfficial {
+ return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "publisher_not_official")
+ }
+ archive, err := buildArchive(source, releaseDir, metadata.SignatureFile)
+ if err != nil {
+ return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "artifact_invalid")
+ }
+ signatureRaw, err := fs.ReadFile(source, path.Join(releaseDir, metadata.SignatureFile))
+ if err != nil {
+ return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "signature_missing")
+ }
+ signature, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(signatureRaw)))
+ if err != nil {
+ return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, "signature_invalid")
+ }
+ release, err := plugincontract.ValidateReleaseCandidate(plugincontract.ReleaseCandidate{
+ Archive: archive,
+ SourceKind: plugincontract.SourceBundled,
+ SourceRef: metadata.SourceRef,
+ SignatureKeyID: metadata.SignatureKeyID,
+ Signature: signature,
+ }, verifier)
+ if err != nil {
+ code := "artifact_invalid"
+ if errors.Is(err, plugincontract.ErrInvalidSignature) || errors.Is(err, plugincontract.ErrUnknownSigningKey) {
+ code = "signature_invalid"
+ }
+ return CatalogEntry{}, releaseDiagnostic(metadata.SourceRef, code)
+ }
+ compatible, why := compatibleWithV1Host(release.Manifest)
+ return CatalogEntry{
+ Release: release,
+ PublisherType: metadata.PublisherType,
+ TrustTier: metadata.TrustTier,
+ Compatible: compatible,
+ CompatibilityWhy: why,
+ }, nil
+}
+
+func releaseDiagnostic(sourceRef, code string) *Diagnostic {
+ if !strings.HasPrefix(sourceRef, "bundled://") {
+ sourceRef = "bundled://" + strings.TrimPrefix(sourceRef, "releases/")
+ }
+ return &Diagnostic{
+ SourceRef: sourceRef,
+ Code: code,
+ Message: "A bundled Plugin release failed validation and was isolated.",
+ }
+}
+
+func buildArchive(source fs.FS, releaseDir, signatureFile string) ([]byte, error) {
+ var files []string
+ if err := fs.WalkDir(source, releaseDir, func(name string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ relative := strings.TrimPrefix(name, releaseDir+"/")
+ if relative == "release.json" || relative == signatureFile {
+ return nil
+ }
+ files = append(files, name)
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if len(files) == 0 {
+ return nil, errors.New("bundled Plugin release has no artifact files")
+ }
+ sort.Strings(files)
+ var buffer bytes.Buffer
+ writer := zip.NewWriter(&buffer)
+ for _, name := range files {
+ content, err := fs.ReadFile(source, name)
+ if err != nil {
+ return nil, err
+ }
+ header := &zip.FileHeader{
+ Name: strings.TrimPrefix(name, releaseDir+"/"),
+ Method: zip.Store,
+ }
+ header.SetMode(0o600)
+ header.SetModTime(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC))
+ entry, err := writer.CreateHeader(header)
+ if err != nil {
+ return nil, err
+ }
+ if _, err := entry.Write(content); err != nil {
+ return nil, err
+ }
+ }
+ if err := writer.Close(); err != nil {
+ return nil, err
+ }
+ return buffer.Bytes(), nil
+}
+
+func compatibleWithV1Host(manifest plugincontract.Manifest) (bool, string) {
+ if manifest.Compatibility.HostAPI != ">=1.0.0 <2.0.0" {
+ return false, "host_api_unsupported"
+ }
+ supported := map[string]bool{
+ plugincontract.DaemonFeatureExecutionManifestV1: true,
+ plugincontract.DaemonFeatureAgentSkillV1: true,
+ }
+ for _, feature := range manifest.Compatibility.RequiredDaemonFeatures {
+ if !supported[feature] {
+ return false, "daemon_feature_unsupported"
+ }
+ }
+ return true, ""
+}
+
+// List returns every admitted release in stable plugin/version order.
+func (c *Catalog) List() []CatalogEntry {
+ if c == nil {
+ return nil
+ }
+ var entries []CatalogEntry
+ for _, versions := range c.entries {
+ for _, entry := range versions {
+ entries = append(entries, entry)
+ }
+ }
+ sort.Slice(entries, func(i, j int) bool {
+ left := entries[i].Release.Manifest.Metadata
+ right := entries[j].Release.Manifest.Metadata
+ if left.Key != right.Key {
+ return left.Key < right.Key
+ }
+ return compareSemver(left.Version, right.Version) > 0
+ })
+ return entries
+}
+
+// Find resolves an exact immutable bundled release.
+func (c *Catalog) Find(pluginKey, version string) (CatalogEntry, bool) {
+ if c == nil || c.entries[pluginKey] == nil {
+ return CatalogEntry{}, false
+ }
+ entry, ok := c.entries[pluginKey][version]
+ return entry, ok
+}
+
+// Latest resolves the highest semantic version for a Plugin.
+func (c *Catalog) Latest(pluginKey string) (CatalogEntry, bool) {
+ versions := c.entries[pluginKey]
+ var latest CatalogEntry
+ found := false
+ for _, entry := range versions {
+ if !found || compareSemver(entry.Release.Manifest.Metadata.Version, latest.Release.Manifest.Metadata.Version) > 0 {
+ latest = entry
+ found = true
+ }
+ }
+ return latest, found
+}
+
+func (c *Catalog) Diagnostics() []Diagnostic {
+ if c == nil {
+ return nil
+ }
+ return append([]Diagnostic(nil), c.diagnostics...)
+}
+
+// IsNewerVersion reports whether candidate is strictly newer than current.
+// Both inputs have already passed the Plugin manifest's semantic-version
+// validation before reaching the bundled catalog.
+func IsNewerVersion(candidate, current string) bool {
+ return compareSemver(candidate, current) > 0
+}
+
+func compareSemver(left, right string) int {
+ parse := func(value string) ([3]string, []string) {
+ var numeric [3]string
+ withoutBuild, _, _ := strings.Cut(value, "+")
+ main, prerelease, _ := strings.Cut(withoutBuild, "-")
+ copy(numeric[:], strings.Split(main, "."))
+ if prerelease == "" {
+ return numeric, nil
+ }
+ return numeric, strings.Split(prerelease, ".")
+ }
+ leftNumeric, leftPrerelease := parse(left)
+ rightNumeric, rightPrerelease := parse(right)
+ for index := range leftNumeric {
+ if comparison := compareNumericIdentifier(leftNumeric[index], rightNumeric[index]); comparison != 0 {
+ return comparison
+ }
+ }
+ if len(leftPrerelease) == 0 && len(rightPrerelease) == 0 {
+ return 0
+ }
+ if len(leftPrerelease) == 0 {
+ return 1
+ }
+ if len(rightPrerelease) == 0 {
+ return -1
+ }
+ for index := 0; index < len(leftPrerelease) && index < len(rightPrerelease); index++ {
+ leftIdentifier := leftPrerelease[index]
+ rightIdentifier := rightPrerelease[index]
+ leftNumber := isNumericIdentifier(leftIdentifier)
+ rightNumber := isNumericIdentifier(rightIdentifier)
+ switch {
+ case leftNumber && rightNumber:
+ if comparison := compareNumericIdentifier(leftIdentifier, rightIdentifier); comparison != 0 {
+ return comparison
+ }
+ case leftNumber:
+ return -1
+ case rightNumber:
+ return 1
+ default:
+ if comparison := strings.Compare(leftIdentifier, rightIdentifier); comparison != 0 {
+ return comparison
+ }
+ }
+ }
+ return len(leftPrerelease) - len(rightPrerelease)
+}
+
+func compareNumericIdentifier(left, right string) int {
+ left = strings.TrimLeft(left, "0")
+ right = strings.TrimLeft(right, "0")
+ if left == "" {
+ left = "0"
+ }
+ if right == "" {
+ right = "0"
+ }
+ if len(left) != len(right) {
+ return len(left) - len(right)
+ }
+ return strings.Compare(left, right)
+}
+
+func isNumericIdentifier(value string) bool {
+ if value == "" {
+ return false
+ }
+ for _, character := range value {
+ if character < '0' || character > '9' {
+ return false
+ }
+ }
+ return true
+}
+
+// VerifyReproducibleRelease rebuilds a source release and returns the exact
+// immutable identities used by release automation and repository tests.
+func VerifyReproducibleRelease(source fs.FS, releaseDir, signatureFile string) (plugincontract.Artifact, error) {
+ archive, err := buildArchive(source, releaseDir, signatureFile)
+ if err != nil {
+ return plugincontract.Artifact{}, err
+ }
+ artifact, err := plugincontract.ValidateArtifact(archive)
+ if err != nil {
+ return plugincontract.Artifact{}, fmt.Errorf("validate reproducible bundled artifact: %w", err)
+ }
+ return artifact, nil
+}
diff --git a/server/internal/pluginbundled/catalog_test.go b/server/internal/pluginbundled/catalog_test.go
new file mode 100644
index 0000000000..c868e52ad7
--- /dev/null
+++ b/server/internal/pluginbundled/catalog_test.go
@@ -0,0 +1,86 @@
+package pluginbundled
+
+import (
+ "io/fs"
+ "testing"
+ "testing/fstest"
+)
+
+func TestBundledCatalogLoadsSignedOfficialReleases(t *testing.T) {
+ catalog := Load()
+ if diagnostics := catalog.Diagnostics(); len(diagnostics) != 0 {
+ t.Fatalf("diagnostics = %+v", diagnostics)
+ }
+ entries := catalog.List()
+ if len(entries) != 2 {
+ t.Fatalf("entries = %d, want 2", len(entries))
+ }
+ latest, ok := catalog.Latest("ai.multica.software-delivery")
+ if !ok || latest.Release.Manifest.Metadata.Version != "1.1.0" {
+ t.Fatalf("latest = %+v, %v", latest.Release.Manifest.Metadata, ok)
+ }
+ if !latest.Compatible || latest.PublisherType != PublisherTypeOfficial || latest.TrustTier != TrustTierOfficial {
+ t.Fatalf("unexpected admission = %+v", latest)
+ }
+ if latest.Release.ArtifactDigest != "sha256:c0064980c253c567f9df90999b158c670989bb60d213289d2f3c36b9a8b591ff" {
+ t.Fatalf("artifact digest = %s", latest.Release.ArtifactDigest)
+ }
+ if len(latest.Release.Contributions) != 1 || latest.Release.Contributions[0].Key != "review-readiness" {
+ t.Fatalf("contributions = %+v", latest.Release.Contributions)
+ }
+}
+
+func TestBundledCatalogIsolatesTamperedRelease(t *testing.T) {
+ copyFS := make(fstest.MapFS)
+ if err := fs.WalkDir(bundledFS, ".", func(name string, entry fs.DirEntry, err error) error {
+ if err != nil || entry.IsDir() {
+ return err
+ }
+ content, readErr := fs.ReadFile(bundledFS, name)
+ if readErr != nil {
+ return readErr
+ }
+ copyFS[name] = &fstest.MapFile{Data: append([]byte(nil), content...), Mode: 0o600}
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ tampered := "releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md"
+ copyFS[tampered].Data = append(copyFS[tampered].Data, []byte("\ntampered")...)
+
+ catalog := LoadFromFS(copyFS)
+ if len(catalog.List()) != 1 {
+ t.Fatalf("healthy releases = %d, want 1", len(catalog.List()))
+ }
+ if _, ok := catalog.Find("ai.multica.software-delivery", "1.1.0"); ok {
+ t.Fatal("tampered release was admitted")
+ }
+ if diagnostics := catalog.Diagnostics(); len(diagnostics) != 1 || diagnostics[0].Code != "signature_invalid" {
+ t.Fatalf("diagnostics = %+v", diagnostics)
+ }
+}
+
+func TestIsNewerVersion(t *testing.T) {
+ tests := []struct {
+ candidate string
+ current string
+ want bool
+ }{
+ {candidate: "1.1.0", current: "1.0.0", want: true},
+ {candidate: "2.0.0", current: "1.9.9", want: true},
+ {candidate: "1.0.0", current: "1.0.0", want: false},
+ {candidate: "1.0.0", current: "1.1.0", want: false},
+ {candidate: "1.0.0", current: "1.0.0-rc.1", want: true},
+ {candidate: "1.0.0-rc.10", current: "1.0.0-rc.9", want: true},
+ {candidate: "1.0.0-beta.1", current: "1.0.0-1", want: true},
+ {candidate: "1.0.0-rc.1", current: "1.0.0-rc.1.1", want: false},
+ {candidate: "1.2.1+r1", current: "1.2.0", want: true},
+ {candidate: "1.2.1+r2", current: "1.2.1+r1", want: false},
+ {candidate: "100000000000000000000.0.0", current: "99999999999999999999.0.0", want: true},
+ }
+ for _, test := range tests {
+ if got := IsNewerVersion(test.candidate, test.current); got != test.want {
+ t.Errorf("IsNewerVersion(%q, %q) = %v, want %v", test.candidate, test.current, got, test.want)
+ }
+ }
+}
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/multica.plugin.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/multica.plugin.json
new file mode 100644
index 0000000000..76df21cb67
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/multica.plugin.json
@@ -0,0 +1,26 @@
+{
+ "api_version": "multica.plugin/v1",
+ "kind": "Plugin",
+ "metadata": {
+ "key": "ai.multica.software-delivery",
+ "name": "Software Delivery",
+ "description": "Official Multica software-delivery workflow skills.",
+ "version": "1.0.0",
+ "publisher": "multica"
+ },
+ "compatibility": {
+ "host_api": ">=1.0.0 <2.0.0",
+ "required_daemon_features": ["execution-manifest-v1", "agent-skill-v1"]
+ },
+ "requested_capabilities": ["agent.skill.contribute"],
+ "contributes": {
+ "agent_skills": [
+ {
+ "key": "review-readiness",
+ "name": "review-readiness",
+ "description": "Verify that a software change is ready for review and handoff.",
+ "entry": "skills/review-readiness/SKILL.md"
+ }
+ ]
+ }
+}
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.json
new file mode 100644
index 0000000000..b74acf9d20
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.json
@@ -0,0 +1,7 @@
+{
+ "source_ref": "bundled://ai.multica.software-delivery/1.0.0",
+ "signature_key_id": "multica-plugin-release-2026-01",
+ "signature_file": "release.sig",
+ "publisher_type": "official",
+ "trust_tier": "official"
+}
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.sig b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.sig
new file mode 100644
index 0000000000..fa076516f8
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/release.sig
@@ -0,0 +1 @@
+QvywEh5534Pkh1pXl6D16upCwUo44Dq9T4MB6wHl2Tcfvu+cPqdiWMZ0RFkTcfcO1pre9D3ItjhrrFjWzANuDA==
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/skills/review-readiness/SKILL.md b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/skills/review-readiness/SKILL.md
new file mode 100644
index 0000000000..9680fe6878
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.0.0/skills/review-readiness/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: review-readiness
+description: Verify that a software change has enough evidence, rollout planning, and review context to be safely reviewed.
+---
+
+# Review readiness
+
+Use this skill when preparing a software change for review or deciding whether it is ready to hand off.
+
+## Check the change
+
+1. State the user-visible or operational outcome in one sentence.
+2. Confirm the diff is scoped to that outcome and call out intentional exclusions.
+3. Record the tests or other evidence that directly exercise the changed behavior.
+4. Identify data migrations, compatibility constraints, rollout steps, and rollback steps.
+5. Surface unresolved risks or decisions instead of hiding them in implementation detail.
+
+## Produce the handoff
+
+Return a compact review brief with:
+
+- outcome and scope;
+- key architectural choices;
+- evidence run and its result;
+- rollout and rollback notes;
+- open risks or decisions;
+- exact files or interfaces where reviewers should focus.
+
+Do not claim readiness when required evidence is missing. Say what is missing and the smallest next action that would provide it.
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/multica.plugin.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/multica.plugin.json
new file mode 100644
index 0000000000..a732ecf32b
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/multica.plugin.json
@@ -0,0 +1,26 @@
+{
+ "api_version": "multica.plugin/v1",
+ "kind": "Plugin",
+ "metadata": {
+ "key": "ai.multica.software-delivery",
+ "name": "Software Delivery",
+ "description": "Official Multica software-delivery workflow skills.",
+ "version": "1.1.0",
+ "publisher": "multica"
+ },
+ "compatibility": {
+ "host_api": ">=1.0.0 <2.0.0",
+ "required_daemon_features": ["execution-manifest-v1", "agent-skill-v1"]
+ },
+ "requested_capabilities": ["agent.skill.contribute"],
+ "contributes": {
+ "agent_skills": [
+ {
+ "key": "review-readiness",
+ "name": "review-readiness",
+ "description": "Verify that a software change is ready for review and handoff.",
+ "entry": "skills/review-readiness/SKILL.md"
+ }
+ ]
+ }
+}
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.json b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.json
new file mode 100644
index 0000000000..83afb07c84
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.json
@@ -0,0 +1,7 @@
+{
+ "source_ref": "bundled://ai.multica.software-delivery/1.1.0",
+ "signature_key_id": "multica-plugin-release-2026-01",
+ "signature_file": "release.sig",
+ "publisher_type": "official",
+ "trust_tier": "official"
+}
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.sig b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.sig
new file mode 100644
index 0000000000..684724caa9
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/release.sig
@@ -0,0 +1 @@
++Yl4EQvwqHlH5mZFkaD2v25Tes8O4LJ1rrRHTnb9K5dtNBePWjka9ZkWKXJs8FZL8H4r1Z/NhZr9MflV9CjxDA==
diff --git a/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md
new file mode 100644
index 0000000000..67a622fd4a
--- /dev/null
+++ b/server/internal/pluginbundled/releases/ai.multica.software-delivery/1.1.0/skills/review-readiness/SKILL.md
@@ -0,0 +1,29 @@
+---
+name: review-readiness
+description: Verify that a software change has enough evidence, rollout planning, and review context to be safely reviewed.
+---
+
+# Review readiness
+
+Use this skill when preparing a software change for review or deciding whether it is ready to hand off.
+
+## Check the change
+
+1. State the user-visible or operational outcome in one sentence.
+2. Confirm the diff is scoped to that outcome and call out intentional exclusions.
+3. Record the tests or other evidence that directly exercise the changed behavior, including failure paths.
+4. Identify migrations, compatibility constraints, rollout steps, observability, and rollback steps.
+5. Surface unresolved risks or decisions instead of hiding them in implementation detail.
+
+## Produce the handoff
+
+Return a compact review brief with:
+
+- outcome and scope;
+- key architectural choices;
+- evidence run and its result;
+- rollout, observability, and rollback notes;
+- open risks or decisions;
+- exact files or interfaces where reviewers should focus.
+
+Do not claim readiness when required evidence is missing. Say what is missing and the smallest next action that would provide it.
diff --git a/server/internal/pluginbundled/trust_roots.json b/server/internal/pluginbundled/trust_roots.json
new file mode 100644
index 0000000000..f30a695933
--- /dev/null
+++ b/server/internal/pluginbundled/trust_roots.json
@@ -0,0 +1,8 @@
+{
+ "keys": [
+ {
+ "id": "multica-plugin-release-2026-01",
+ "public_key": "40uevCZru/bYuAhZpoNzowNemnBUfGsvdWvFAQGMyyY="
+ }
+ ]
+}
diff --git a/server/internal/service/plugin.go b/server/internal/service/plugin.go
index 9adc2caecf..14deb0050e 100644
--- a/server/internal/service/plugin.go
+++ b/server/internal/service/plugin.go
@@ -9,6 +9,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/pluginbundled"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/plugincontract"
@@ -17,12 +18,132 @@ import (
)
type PluginService struct {
- Queries *db.Queries
- TxStarter TxStarter
+ Queries *db.Queries
+ TxStarter TxStarter
+ BundledCatalog *pluginbundled.Catalog
}
func NewPluginService(queries *db.Queries, txStarter TxStarter) *PluginService {
- return &PluginService{Queries: queries, TxStarter: txStarter}
+ return &PluginService{
+ Queries: queries,
+ TxStarter: txStarter,
+ BundledCatalog: pluginbundled.Load(),
+ }
+}
+
+type PluginErrorKind string
+
+const (
+ PluginErrorInvalid PluginErrorKind = "invalid"
+ PluginErrorNotFound PluginErrorKind = "not_found"
+ PluginErrorConflict PluginErrorKind = "conflict"
+ PluginErrorIncompatible PluginErrorKind = "incompatible"
+)
+
+type PluginError struct {
+ Kind PluginErrorKind
+ Message string
+ Err error
+}
+
+func (e *PluginError) Error() string {
+ if e.Err != nil {
+ return e.Message + ": " + e.Err.Error()
+ }
+ return e.Message
+}
+
+func (e *PluginError) Unwrap() error { return e.Err }
+
+func newPluginError(kind PluginErrorKind, message string, err error) error {
+ return &PluginError{Kind: kind, Message: message, Err: err}
+}
+
+func (s *PluginService) CatalogEntries() []pluginbundled.CatalogEntry {
+ return s.BundledCatalog.List()
+}
+
+func (s *PluginService) CatalogDiagnostics() []pluginbundled.Diagnostic {
+ return s.BundledCatalog.Diagnostics()
+}
+
+func (s *PluginService) FindCatalogRelease(pluginKey, version string) (pluginbundled.CatalogEntry, bool) {
+ if version == "" {
+ return s.BundledCatalog.Latest(pluginKey)
+ }
+ return s.BundledCatalog.Find(pluginKey, version)
+}
+
+func (s *PluginService) InstallCatalogRelease(ctx context.Context, workspaceID, actorID pgtype.UUID, pluginKey, version string) (db.PluginInstallation, error) {
+ entry, ok := s.FindCatalogRelease(pluginKey, version)
+ if !ok {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin release not found", nil)
+ }
+ if !entry.Compatible {
+ return db.PluginInstallation{}, newPluginError(PluginErrorIncompatible, "Plugin release is incompatible with this Multica version", nil)
+ }
+ return s.InstallPluginRelease(ctx, workspaceID, actorID, PluginReleasePublication{
+ Release: entry.Release,
+ PublisherType: entry.PublisherType,
+ TrustTier: entry.TrustTier,
+ })
+}
+
+func (s *PluginService) UpgradeCatalogRelease(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, pluginKey, version string) (db.PluginInstallation, error) {
+ entry, ok := s.FindCatalogRelease(pluginKey, version)
+ if !ok {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin release not found", nil)
+ }
+ if !entry.Compatible {
+ return db.PluginInstallation{}, newPluginError(PluginErrorIncompatible, "Plugin release is incompatible with this Multica version", nil)
+ }
+
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.PluginInstallation{}, err
+ }
+ defer tx.Rollback(ctx) //nolint:errcheck
+ q := s.Queries.WithTx(tx)
+ installation, err := q.GetPluginInstallation(ctx, installationID)
+ if err != nil || installation.WorkspaceID != workspaceID {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)
+ }
+ identity, err := q.GetPluginIdentity(ctx, installation.PluginID)
+ if err != nil || identity.PluginKey != pluginKey {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)
+ }
+ currentRelease, err := q.GetPluginRelease(ctx, installation.DesiredReleaseID)
+ if err != nil {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation release not found", nil)
+ }
+ if !pluginbundled.IsNewerVersion(entry.Release.Manifest.Metadata.Version, currentRelease.Version) {
+ return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Target Plugin release is not newer than the installed release", nil)
+ }
+ _, release, err := ensurePluginRelease(ctx, q, PluginReleasePublication{
+ Release: entry.Release,
+ PublisherType: entry.PublisherType,
+ TrustTier: entry.TrustTier,
+ })
+ if err != nil {
+ return db.PluginInstallation{}, err
+ }
+ installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
+ Enabled: installation.Enabled,
+ UpdatedBy: actorID,
+ WorkspaceID: workspaceID,
+ DesiredReleaseID: release.ID,
+ ID: installationID,
+ })
+ if err != nil {
+ return db.PluginInstallation{}, fmt.Errorf("set Plugin desired release: %w", err)
+ }
+ if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {
+ return db.PluginInstallation{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.PluginInstallation{}, err
+ }
+ return s.Queries.GetPluginInstallation(ctx, installationID)
}
// PluginReleasePublication carries the trust decision made by the acquisition
@@ -49,11 +170,11 @@ func (s *PluginService) InstallPluginRelease(ctx context.Context, workspaceID, a
if err != nil {
return db.PluginInstallation{}, err
}
- if existing, err := q.GetWorkspacePluginInstallation(ctx, db.GetWorkspacePluginInstallationParams{
+ if _, err := q.GetWorkspacePluginInstallation(ctx, db.GetWorkspacePluginInstallationParams{
WorkspaceID: workspaceID,
PluginID: identity.ID,
}); err == nil {
- return db.PluginInstallation{}, fmt.Errorf("plugin is already installed as %s", util.UUIDToString(existing.ID))
+ return db.PluginInstallation{}, newPluginError(PluginErrorConflict, "Plugin is already installed", nil)
} else if !errors.Is(err, pgx.ErrNoRows) {
return db.PluginInstallation{}, err
}
@@ -92,10 +213,10 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginR
releaseData := publication.Release
manifest := releaseData.Manifest
if publication.PublisherType == "" || publication.TrustTier == "" {
- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("plugin publisher type and trust tier are required")
+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorInvalid, "Plugin publisher trust is required", nil)
}
if len(releaseData.Files) == 0 {
- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("validated plugin release contains no artifact files")
+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorInvalid, "Plugin release contains no artifact files", nil)
}
if err := q.LockPluginRegistryKey(ctx, manifest.Metadata.Key); err != nil {
return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("lock plugin registry key: %w", err)
@@ -115,7 +236,7 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginR
return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("ensure plugin identity: %w", err)
}
if identity.PublisherID != manifest.Metadata.Publisher || identity.PublisherType != publication.PublisherType || identity.TrustTier != publication.TrustTier {
- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("plugin identity %q conflicts with its registered publisher", manifest.Metadata.Key)
+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin publisher conflicts with the registered identity", nil)
}
release, err := q.GetPluginReleaseByVersion(ctx, db.GetPluginReleaseByVersionParams{
@@ -182,7 +303,7 @@ func ensurePluginRelease(ctx context.Context, q *db.Queries, publication PluginR
return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("ensure plugin release: %w", err)
}
if release.ManifestDigest != releaseData.ManifestDigest || release.ArtifactDigest != releaseData.ArtifactDigest || release.ArchiveDigest != releaseData.ArchiveDigest {
- return db.PluginIdentity{}, db.PluginRelease{}, fmt.Errorf("plugin release %s@%s conflicts with immutable registry content", manifest.Metadata.Key, manifest.Metadata.Version)
+ return db.PluginIdentity{}, db.PluginRelease{}, newPluginError(PluginErrorConflict, "Plugin release conflicts with immutable registry content", nil)
}
return identity, release, nil
}
@@ -197,7 +318,7 @@ func (s *PluginService) DisablePlugin(ctx context.Context, workspaceID, installa
func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, installationID, actorID pgtype.UUID, scopeType string, scopeID pgtype.UUID, enabled bool) (db.PluginInstallation, error) {
if scopeType != "workspace" && scopeType != "agent" {
- return db.PluginInstallation{}, fmt.Errorf("scope_type must be workspace or agent")
+ return db.PluginInstallation{}, newPluginError(PluginErrorInvalid, "scope_type must be workspace or agent", nil)
}
tx, err := s.TxStarter.Begin(ctx)
if err != nil {
@@ -207,21 +328,15 @@ func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, insta
q := s.Queries.WithTx(tx)
installation, err := q.GetPluginInstallation(ctx, installationID)
if err != nil || installation.WorkspaceID != workspaceID {
- return db.PluginInstallation{}, fmt.Errorf("plugin installation not found")
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)
}
- globalEnabled := enabled || (scopeType == "agent" && installation.Enabled)
- if scopeType == "agent" && !enabled {
- globalEnabled = installation.Enabled
+ if scopeType == "workspace" && scopeID != workspaceID {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin binding target not found", nil)
}
- installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
- Enabled: globalEnabled,
- UpdatedBy: actorID,
- WorkspaceID: workspaceID,
- DesiredReleaseID: installation.DesiredReleaseID,
- ID: installationID,
- })
- if err != nil {
- return db.PluginInstallation{}, fmt.Errorf("set plugin desired state: %w", err)
+ if scopeType == "agent" {
+ if _, err := q.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{ID: scopeID, WorkspaceID: workspaceID}); err != nil {
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin binding target not found", nil)
+ }
}
if _, err := q.CreatePluginBindingRevision(ctx, db.CreatePluginBindingRevisionParams{
ScopeType: scopeType,
@@ -233,6 +348,27 @@ func (s *PluginService) setPluginBinding(ctx context.Context, workspaceID, insta
}); err != nil {
return db.PluginInstallation{}, fmt.Errorf("create plugin binding: %w", err)
}
+ bindings, err := q.ListLatestPluginBindings(ctx, installationID)
+ if err != nil {
+ return db.PluginInstallation{}, fmt.Errorf("list plugin bindings: %w", err)
+ }
+ globalEnabled := false
+ for _, binding := range bindings {
+ if binding.Enabled {
+ globalEnabled = true
+ break
+ }
+ }
+ installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
+ Enabled: globalEnabled,
+ UpdatedBy: actorID,
+ WorkspaceID: workspaceID,
+ DesiredReleaseID: installation.DesiredReleaseID,
+ ID: installationID,
+ })
+ if err != nil {
+ return db.PluginInstallation{}, fmt.Errorf("set plugin desired state: %w", err)
+ }
if _, err := s.reconcileWorkspaceTx(ctx, q, workspaceID); err != nil {
return db.PluginInstallation{}, err
}
@@ -251,7 +387,7 @@ func (s *PluginService) RollbackPlugin(ctx context.Context, workspaceID, install
q := s.Queries.WithTx(tx)
installation, err := q.GetPluginInstallation(ctx, installationID)
if err != nil || installation.WorkspaceID != workspaceID {
- return db.PluginInstallation{}, fmt.Errorf("plugin installation not found")
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Plugin installation not found", nil)
}
identity, err := q.GetPluginIdentity(ctx, installation.PluginID)
if err != nil {
@@ -262,7 +398,7 @@ func (s *PluginService) RollbackPlugin(ctx context.Context, workspaceID, install
Version: version,
})
if err != nil {
- return db.PluginInstallation{}, fmt.Errorf("rollback release not found")
+ return db.PluginInstallation{}, newPluginError(PluginErrorNotFound, "Rollback release not found", nil)
}
installation, err = q.SetPluginInstallationDesiredState(ctx, db.SetPluginInstallationDesiredStateParams{
Enabled: installation.Enabled,
diff --git a/server/internal/service/plugin_integration_test.go b/server/internal/service/plugin_integration_test.go
index 3a111290e7..4ef07ae34e 100644
--- a/server/internal/service/plugin_integration_test.go
+++ b/server/internal/service/plugin_integration_test.go
@@ -143,6 +143,23 @@ func TestReferencePluginInstallEnablePinDisableAndRetry(t *testing.T) {
if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, newTaskID); err != nil {
t.Fatalf("complete disabled task: %v", err)
}
+ agentUUID := util.MustParseUUID(agentID)
+ installation, err = pluginService.EnablePlugin(ctx, workspaceUUID, installation.ID, actorUUID, "agent", agentUUID)
+ if err != nil || !installation.Enabled {
+ t.Fatalf("enable agent scope: installation=%+v err=%v", installation, err)
+ }
+ agentTaskID := createTask(nil)
+ agentBundles, _, _, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(agentTaskID))
+ if err != nil || len(agentBundles) != 1 {
+ t.Fatalf("agent-scoped Plugin missing from task: bundles=%d err=%v", len(agentBundles), err)
+ }
+ if _, err := pool.Exec(ctx, `UPDATE agent_task_queue SET status = 'completed', completed_at = now() WHERE id = $1`, agentTaskID); err != nil {
+ t.Fatalf("complete agent-scoped task: %v", err)
+ }
+ installation, err = pluginService.DisablePlugin(ctx, workspaceUUID, installation.ID, actorUUID, "agent", agentUUID)
+ if err != nil || installation.Enabled {
+ t.Fatalf("disable last active binding: installation=%+v err=%v", installation, err)
+ }
retryTaskID := createTask(firstTaskID)
retryBundles, _, retryManifest, err := taskService.LoadTaskPluginSkillBundles(ctx, util.MustParseUUID(retryTaskID))
if err != nil || len(retryBundles) != 1 || retryManifest.SnapshotDigest != manifest.SnapshotDigest {
diff --git a/server/internal/testutil/plugintest/review_readiness.go b/server/internal/testutil/plugintest/review_readiness.go
index 3d27b93794..37f18cfa91 100644
--- a/server/internal/testutil/plugintest/review_readiness.go
+++ b/server/internal/testutil/plugintest/review_readiness.go
@@ -1,144 +1,25 @@
-// Package plugintest contains reference releases used only by Plugin V1 tests.
+// Package plugintest exposes production bundled Plugin releases to lifecycle
+// and execution-chain tests. Production code never depends on this package.
package plugintest
import (
- "archive/zip"
- "bytes"
- "crypto/ed25519"
- "encoding/base64"
- "encoding/json"
"fmt"
- "time"
+ "github.com/multica-ai/multica/server/internal/pluginbundled"
"github.com/multica-ai/multica/server/pkg/plugincontract"
)
const (
ReviewReadinessPluginKey = "ai.multica.software-delivery"
ReviewReadinessVersion = "1.0.0"
- releaseKeyID = "multica-plugin-release-test-2026-01"
- releasePublicKeyBase64 = "l5+eyMIoTHPAC3AWhgpHgxEvjwYtt1gsj1PvQB8zwvU="
- releaseSignatureBase64 = "sLa3lBwIrqg1zbKcK6b53HRE/8ZLXG+hBeP2aq/Cn0S/36mPIaMUkiSL+3N+YL/a04YkL26sQd9CpjCgx7zqBQ=="
)
-const reviewReadinessSkill = `---
-name: review-readiness
-description: Verify that a software change has enough evidence, rollout planning, and review context to be safely reviewed.
----
-
-# Review readiness
-
-Use this skill when preparing a software change for review or deciding whether it is ready to hand off.
-
-## Check the change
-
-1. State the user-visible or operational outcome in one sentence.
-2. Confirm the diff is scoped to that outcome and call out intentional exclusions.
-3. Record the tests or other evidence that directly exercise the changed behavior.
-4. Identify data migrations, compatibility constraints, rollout steps, and rollback steps.
-5. Surface unresolved risks or decisions instead of hiding them in implementation detail.
-
-## Produce the handoff
-
-Return a compact review brief with:
-
-- outcome and scope;
-- key architectural choices;
-- evidence run and its result;
-- rollout and rollback notes;
-- open risks or decisions;
-- exact files or interfaces where reviewers should focus.
-
-Do not claim readiness when required evidence is missing. Say what is missing and the smallest next action that would provide it.
-`
-
-func reviewReadinessManifest() plugincontract.Manifest {
- return plugincontract.Manifest{
- APIVersion: plugincontract.APIVersionV1,
- Kind: plugincontract.KindPlugin,
- Metadata: plugincontract.Metadata{
- Key: ReviewReadinessPluginKey,
- Name: "Software Delivery",
- Description: "Official Multica software-delivery workflow skills.",
- Version: ReviewReadinessVersion,
- Publisher: "multica",
- },
- Compatibility: plugincontract.Compatibility{
- HostAPI: ">=1.0.0 <2.0.0",
- RequiredDaemonFeatures: []string{
- plugincontract.DaemonFeatureExecutionManifestV1,
- plugincontract.DaemonFeatureAgentSkillV1,
- },
- },
- RequestedCapabilities: []string{plugincontract.CapabilityAgentSkillContribute},
- Contributes: plugincontract.ManifestContributions{AgentSkills: []plugincontract.AgentSkillContribution{{
- Key: "review-readiness",
- Name: "review-readiness",
- Description: "Verify that a software change is ready for review and handoff.",
- Entry: "skills/review-readiness/SKILL.md",
- }}},
- }
-}
-
-func reviewReadinessArchive() ([]byte, error) {
- manifest, err := json.Marshal(reviewReadinessManifest())
- if err != nil {
- return nil, err
- }
- files := []struct {
- name string
- content []byte
- }{
- {name: plugincontract.ManifestFilename, content: manifest},
- {name: "skills/review-readiness/SKILL.md", content: []byte(reviewReadinessSkill)},
- }
-
- var buffer bytes.Buffer
- writer := zip.NewWriter(&buffer)
- for _, file := range files {
- header := &zip.FileHeader{Name: file.name, Method: zip.Store}
- header.SetMode(0o600)
- header.SetModTime(time.Date(1980, 1, 1, 0, 0, 0, 0, time.UTC))
- entry, err := writer.CreateHeader(header)
- if err != nil {
- return nil, fmt.Errorf("create reference plugin entry: %w", err)
- }
- if _, err := entry.Write(file.content); err != nil {
- return nil, fmt.Errorf("write reference plugin entry: %w", err)
- }
- }
- if err := writer.Close(); err != nil {
- return nil, fmt.Errorf("close reference plugin archive: %w", err)
- }
- return buffer.Bytes(), nil
-}
-
-// ReviewReadinessRelease returns a signed reference release for lifecycle and
-// execution-chain tests. It is not imported by the production server.
+// ReviewReadinessRelease returns the same signed, validated artifact shipped
+// by the production bundled catalog.
func ReviewReadinessRelease() (plugincontract.ValidatedRelease, error) {
- archive, err := reviewReadinessArchive()
- if err != nil {
- return plugincontract.ValidatedRelease{}, err
- }
- publicKey, err := base64.StdEncoding.DecodeString(releasePublicKeyBase64)
- if err != nil {
- return plugincontract.ValidatedRelease{}, fmt.Errorf("decode reference plugin trust root: %w", err)
- }
- signature, err := base64.StdEncoding.DecodeString(releaseSignatureBase64)
- if err != nil {
- return plugincontract.ValidatedRelease{}, fmt.Errorf("decode reference plugin signature: %w", err)
- }
- trustStore, err := plugincontract.NewEd25519TrustStore(map[string]ed25519.PublicKey{
- releaseKeyID: ed25519.PublicKey(publicKey),
- })
- if err != nil {
- return plugincontract.ValidatedRelease{}, err
+ entry, ok := pluginbundled.Load().Find(ReviewReadinessPluginKey, ReviewReadinessVersion)
+ if !ok {
+ return plugincontract.ValidatedRelease{}, fmt.Errorf("bundled review-readiness release is unavailable")
}
- return plugincontract.ValidateReleaseCandidate(plugincontract.ReleaseCandidate{
- Archive: archive,
- SourceKind: plugincontract.SourceBundled,
- SourceRef: "test://software-delivery/1.0.0",
- SignatureKeyID: releaseKeyID,
- Signature: signature,
- }, trustStore)
+ return entry.Release, nil
}