feat: integrate marketplace plugins with coding runtime

This commit is contained in:
2026-08-28 18:02:51 +08:00
parent 1d64b89499
commit 05917a789a
21 changed files with 1921 additions and 29 deletions

View File

@@ -40,6 +40,20 @@ import {
createCodingCapabilityRegistry,
} from '../coding-plugins/registry';
import { createDataServicePluginAdapter } from '../coding-plugins/adapters/data-service';
import { AccountPluginCache } from '../coding-plugins/account-plugin-cache';
import {
createMarketplaceClient,
type MarketplaceClient,
} from '../coding-plugins/marketplace-client';
import {
PluginPackageStore,
type PluginPackageStore as PluginPackageStoreType,
} from '../coding-plugins/package-store';
import {
createEffectivePluginResolver,
type EffectivePluginResolver,
} from '../coding-plugins/effective-resolver';
import { subscribeWorksSquareSession } from '../services/works-square-session';
import { PluginPolicyClient } from '../services/plugin-policy-client';
import {
loadBundledCodingPluginDefinitionsSync,
@@ -47,7 +61,9 @@ import {
} from '../coding-plugins/manifest';
import {
createCodingProjectPluginService,
createCodingPluginMarketplaceService,
type CodingProjectPluginService,
type CodingPluginMarketplaceService,
} from './coding-product-services';
export interface CodingCompositionPaths {
@@ -64,6 +80,11 @@ export interface CreateCodingCompositionOptions {
paths: CodingCompositionPaths;
getLocalProxyCredential?(): string | undefined;
acquireBackgroundLease?(lease: { id: string; kind: 'coding-run' }): () => void;
marketplaceClient?: MarketplaceClient;
packageStore?: PluginPackageStoreType;
accountCache?: AccountPluginCache;
clientVersion?: string;
policyClient?: PluginPolicyClient;
}
export function resolveCodingPiRuntimePaths(input: {
@@ -105,6 +126,38 @@ export function createCodingComposition(
entryPath: path.basename(skill.entryPath),
}))
));
const accountCache = options.accountCache ?? new AccountPluginCache();
const marketplaceClient = options.marketplaceClient ?? createMarketplaceClient({ accountCache });
const packageStore = options.packageStore ?? new PluginPackageStore({
rootDir: path.join(options.paths.userDataDir, 'coding-plugins'),
marketplace: marketplaceClient,
accountCache,
clientVersion: options.clientVersion ?? '2.0.0',
});
const activePluginReleaseCounts = new Map<string, number>();
const registerActivePluginReleases = (releaseIds: readonly string[]): (() => void) => {
const uniqueReleaseIds = [...new Set(releaseIds)];
for (const releaseId of uniqueReleaseIds) {
const count = activePluginReleaseCounts.get(releaseId) ?? 0;
if (count === 0) packageStore.registerActiveWorker(releaseId);
activePluginReleaseCounts.set(releaseId, count + 1);
}
let released = false;
return () => {
if (released) return;
released = true;
for (const releaseId of uniqueReleaseIds) {
const count = activePluginReleaseCounts.get(releaseId) ?? 0;
if (count <= 1) {
activePluginReleaseCounts.delete(releaseId);
packageStore.releaseActiveWorker(releaseId);
} else {
activePluginReleaseCounts.set(releaseId, count - 1);
}
}
};
};
let effectiveResolver: EffectivePluginResolver | undefined;
const projectStore = options.projectStore ?? createCodingProjectStore(options.storage);
const attachments = new CodingAttachmentStore(
path.join(options.paths.userDataDir, 'coding-runtime', 'attachments'),
@@ -114,6 +167,14 @@ export function createCodingComposition(
attachments,
bundledSkillsDir: options.paths.bundledSkillsDir,
pluginSkillSources,
getPluginSkillSources: async () => effectiveResolver
? (await effectiveResolver.getSkillSources()).map((source) => ({
id: source.id,
pluginId: source.pluginId,
directory: source.directory,
entryPath: source.entryPath,
}))
: [],
});
const extensionHost = new PiManagedExtensionHost();
extensionHost.configureProductTools(productTools);
@@ -172,9 +233,17 @@ export function createCodingComposition(
});
const dataService = createDataServiceOperations({ projects });
const dataServiceAdapter = createDataServicePluginAdapter(dataService);
const policyClient = new PluginPolicyClient();
const policyClient = options.policyClient ?? new PluginPolicyClient();
const knownPluginIds = new Set(pluginDefinitions.map(({ id }) => id));
// Existing user Releases are discovered from the device index at startup;
// unlike the bundled catalog they cannot be enumerated synchronously. Keep
// the ProjectPluginService's known-ID gate accurate for a reopened app while
// preserving unknown IDs in existing project files.
void packageStore.readInstalledIndex()
.then((records) => records.forEach(({ pluginId }) => knownPluginIds.add(pluginId)))
.catch(() => undefined);
const projectPlugins = createProjectPluginService({
knownPluginIds: pluginDefinitions.map(({ id }) => id),
knownPluginIds: () => [...knownPluginIds],
onManagedInputsChanged: async ({ projectPath }) => {
runtime?.markResourcesStale();
const conversations = await conversationStoreForProject(projectPath).read()
@@ -187,11 +256,21 @@ export function createCodingComposition(
await plugins?.deactivate(projectPath, pluginId);
},
});
effectiveResolver = createEffectivePluginResolver({
definitions: pluginDefinitions,
packageStore,
marketplace: marketplaceClient,
accountCache,
getAccountBinding: () => marketplaceClient.getCurrentAccountBinding(),
getEnabledPluginIds: (projectPath) => projectPlugins.getEnabledPluginIds(projectPath),
policyClient,
});
const capabilityRegistry = createCodingCapabilityRegistry({
policyClient,
projectPlugins,
adapters: [dataServiceAdapter],
definitions: pluginDefinitions,
effectiveResolver,
getDurableProjectId: async (projectPath, localProjectId) => {
const active = await projects.requireActiveRealProjectWithIdentity(projectPath);
if (active.project.id !== localProjectId) {
@@ -207,6 +286,15 @@ export function createCodingComposition(
policyClient,
adapters: [dataServiceAdapter],
definitions: pluginDefinitions,
effectiveResolver,
getDefinitions: async () => {
const installed = await packageStore.readInstalledIndex();
const definitions = await Promise.all(installed.map(async ({ pluginId }) => {
const release = await packageStore.getInstalled(pluginId);
return release?.definition ?? null;
}));
return definitions.flatMap((definition) => definition ? [definition] : []);
},
});
const workerPool = new PiWorkerPool({
processBudget,
@@ -217,6 +305,10 @@ export function createCodingComposition(
cliPath: options.paths.cliPath,
userDataDir: options.paths.userDataDir,
bundledSkillsDir: options.paths.bundledSkillsDir,
getSkillRoots: async () => (effectiveResolver
? (await effectiveResolver.getSkillSources()).map(({ packageRoot }) => packageRoot)
: []),
registerActivePluginReleases,
loadProviderInput,
resolveCredential: resolvePiProviderCredentialFromSecretStore,
...(getLocalProxyCredential
@@ -240,6 +332,9 @@ export function createCodingComposition(
? { getLocalProxyCredential: async () => getLocalProxyCredential() }
: {}),
capabilityRegistry,
getSkillRoots: async () => (effectiveResolver
? (await effectiveResolver.getSkillSources()).map(({ packageRoot }) => packageRoot)
: []),
});
const subagents = new PiSubagentScheduler({
openChild: childOpener,
@@ -278,10 +373,33 @@ export function createCodingComposition(
});
},
});
const invalidateManagedResources = async (): Promise<void> => {
runtime?.markResourcesStale();
const projectPaths = [...conversationStores.entries()];
for (const [, store] of projectPaths) {
const conversationsInProject = await store.read()
.then((file) => file.conversations)
.catch(() => []);
for (const conversation of conversationsInProject) registry.forget(conversation.id);
}
};
const pluginMarketplace: CodingPluginMarketplaceService = createCodingPluginMarketplaceService({
marketplace: marketplaceClient,
packageStore,
clientVersion: options.clientVersion ?? '2.0.0',
onChanged: async ({ pluginId, kind }) => {
if (kind === 'install' || kind === 'update') knownPluginIds.add(pluginId);
await invalidateManagedResources();
},
});
const unsubscribeMarketplaceSession = subscribeWorksSquareSession(() => {
void invalidateManagedResources();
});
const host = createCodingProductHost({
projects,
productTools,
getEnabledPluginIds: (projectPath) => projectPlugins.getEnabledPluginIds(projectPath),
effectiveResolver,
listPiCommands: (conversationId) => conversations.listLiveCommands(conversationId),
});
previewDataSession = createPreviewDataSessionManager({ projects });
@@ -297,6 +415,8 @@ export function createCodingComposition(
attachments,
dataService,
plugins,
pluginMarketplace,
marketplace: pluginMarketplace,
previewDataSession,
productTools,
projects,
@@ -322,8 +442,14 @@ export function createCodingComposition(
unsubscribeBrowserLifecycle();
const active = await projects.getActiveProject();
if (active) await plugins?.deactivate(active.path);
await subagents.close();
await runtime.shutdown();
try {
await subagents.close();
await runtime.shutdown();
} finally {
unsubscribeMarketplaceSession();
packageStore.dispose();
marketplaceClient.dispose();
}
},
};
}

View File

@@ -35,6 +35,18 @@ import type {
PluginPolicyClient,
PluginPolicyClientState,
} from '../services/plugin-policy-client';
import type {
CatalogPage,
CatalogQuery,
MarketplaceClient,
PluginDetail,
} from '../coding-plugins/marketplace-client';
import type {
InstallationSnapshot,
PluginPackageStore,
} from '../coding-plugins/package-store';
import type { MarketplaceLibrarySnapshot } from '../coding-plugins/account-plugin-cache';
import type { EffectivePluginResolver } from '../coding-plugins/effective-resolver';
export interface ActiveCodingProject {
id: string;
@@ -56,6 +68,9 @@ export interface CodingProductComposition {
dataService: DataServiceOperations;
previewDataSession?: PreviewDataSessionManager;
productTools: PiProductTools;
pluginMarketplace: CodingPluginMarketplaceService;
/** Alias retained for Main callers that refer to the Marketplace service directly. */
marketplace: CodingPluginMarketplaceService;
plugins: CodingProjectPluginService;
projects: CodingProjectService;
conversations: CodingConversationService;
@@ -65,6 +80,83 @@ export interface CodingProductComposition {
shutdown(): Promise<void>;
}
export type PublicPluginInstallation = Readonly<{
status: InstallationSnapshot['status'];
pluginId: string;
releaseId?: string;
version?: string;
reason?: string;
}>;
/** Main-owned Marketplace facade. It never exposes package roots or manifests. */
export interface CodingPluginMarketplaceService {
readCatalog(input?: CatalogQuery): Promise<CatalogPage>;
readDetail(pluginId: string): Promise<PluginDetail>;
readLibrary(): Promise<MarketplaceLibrarySnapshot>;
acquire(pluginId: string): Promise<MarketplaceLibrarySnapshot>;
remove(pluginId: string): Promise<MarketplaceLibrarySnapshot>;
install(pluginId: string): Promise<PublicPluginInstallation>;
update(pluginId: string): Promise<PublicPluginInstallation>;
uninstall(pluginId: string): Promise<PublicPluginInstallation>;
}
export interface CreateCodingPluginMarketplaceServiceOptions {
marketplace: MarketplaceClient;
packageStore: PluginPackageStore;
clientVersion: string;
onChanged?(event: {
pluginId: string;
kind: 'acquire' | 'remove' | 'install' | 'update' | 'uninstall';
}): Promise<void> | void;
}
function publicInstallation(snapshot: InstallationSnapshot): PublicPluginInstallation {
return {
status: snapshot.status,
pluginId: snapshot.pluginId,
...(snapshot.releaseId ? { releaseId: snapshot.releaseId } : {}),
...(snapshot.version ? { version: snapshot.version } : {}),
...(snapshot.reason ? { reason: snapshot.reason } : {}),
};
}
export function createCodingPluginMarketplaceService(
options: CreateCodingPluginMarketplaceServiceOptions,
): CodingPluginMarketplaceService {
const install = async (pluginId: string, kind: 'install' | 'update'): Promise<PublicPluginInstallation> => {
const snapshot = await options.packageStore.resolveAndInstall({
pluginId,
makeloreVersion: options.clientVersion,
channel: 'stable',
});
await options.onChanged?.({ pluginId, kind });
return publicInstallation(snapshot);
};
const uninstall = async (pluginId: string): Promise<PublicPluginInstallation> => {
const snapshot = await options.packageStore.removeUnused(pluginId);
await options.onChanged?.({ pluginId, kind: 'uninstall' });
return publicInstallation(snapshot);
};
return {
readCatalog: (input = {}) => options.marketplace.readCatalog(input),
readDetail: (pluginId) => options.marketplace.readDetail(pluginId),
readLibrary: () => options.marketplace.readLibrary(),
acquire: async (pluginId) => {
const snapshot = await options.marketplace.acquire(pluginId);
await options.onChanged?.({ pluginId, kind: 'acquire' });
return snapshot;
},
remove: async (pluginId) => {
const snapshot = await options.marketplace.remove(pluginId);
await options.onChanged?.({ pluginId, kind: 'remove' });
return snapshot;
},
install: (pluginId) => install(pluginId, 'install'),
update: (pluginId) => install(pluginId, 'update'),
uninstall,
};
}
export type CodingPluginEffectiveState =
| 'unavailable'
| 'disabled'
@@ -149,6 +241,8 @@ export interface CreateCodingProjectPluginServiceOptions {
policyClient: Pick<PluginPolicyClient, 'refresh' | 'getState'>;
adapters: readonly CodingPluginAdapter[];
definitions: readonly CodingPluginDefinition[];
getDefinitions?(): readonly CodingPluginDefinition[] | Promise<readonly CodingPluginDefinition[]>;
effectiveResolver?: EffectivePluginResolver;
}
function policyOperation(
@@ -256,9 +350,18 @@ function effectiveState(input: {
export function createCodingProjectPluginService(
options: CreateCodingProjectPluginServiceOptions,
): CodingProjectPluginService {
const definitions = options.definitions;
const adapters = new Map(options.adapters.map((adapter) => [adapter.pluginId, adapter]));
async function definitions(): Promise<readonly CodingPluginDefinition[]> {
const result = new Map(options.definitions.map((definition) => [definition.id, definition]));
for (const definition of options.getDefinitions ? await options.getDefinitions() : []) {
// Bundled definitions are code-owned and cannot be shadowed by an
// installed package reusing their identifier.
if (!result.has(definition.id)) result.set(definition.id, definition);
}
return [...result.values()];
}
async function project(localProjectId: string) {
const id = localProjectId.trim();
if (!id) {
@@ -269,24 +372,42 @@ export function createCodingProjectPluginService(
async function list(localProjectId: string): Promise<CodingPluginProjectProjection> {
const localProject = await project(localProjectId);
await options.policyClient.refresh();
const pluginDefinitions = await definitions();
if (pluginDefinitions.some(({ requiresBackend }) => requiresBackend)) {
await options.policyClient.refresh();
}
const policy = options.policyClient.getState();
const [selection, config] = await Promise.all([
options.projectPlugins.getEnabledPluginIds(localProject.path),
readCodingProjectConfigV2(localProject.path),
]);
const assignedSkillIds = config.status === 'valid'
? [...new Set(config.config.agents
.filter((agent) => agent.enabled && !agent.archivedAt)
.flatMap(({ skillIds }) => skillIds))]
: [];
const effective = options.effectiveResolver
? await options.effectiveResolver.resolve({
projectId: localProject.id,
projectPath: localProject.path,
assignedSkillIds,
role: 'parent',
})
: null;
const durableProjectId = config.status === 'valid' ? config.config.projectId ?? null : null;
const items = await Promise.all(definitions.map(async (definition) => {
const items = await Promise.all(pluginDefinitions.map(async (definition) => {
const enabled = selection.includes(definition.id);
const adapter = adapters.get(definition.id);
let backend: PluginBackendProjection;
try {
backend = adapter ? boundedBackend(await adapter.inspect(localProject.path)) : degradedBackend();
backend = adapter
? boundedBackend(await adapter.inspect(localProject.path))
: definition.requiresBackend ? degradedBackend() : { status: 'not_required' };
} catch {
backend = degradedBackend();
}
const pluginPolicy = policy.catalog?.plugins.find(({ plugin_id }) => plugin_id === definition.id);
const policyAvailable = Boolean(
const policyAvailable = !definition.requiresBackend || Boolean(
pluginPolicy?.supported_contract_versions.includes(definition.contractVersion),
);
const capabilityIds = [...new Set(definition.operations.map(({ capabilityId }) => capabilityId))];
@@ -314,6 +435,16 @@ export function createCodingProjectPluginService(
return operations.length > 0 ? [{ id: capabilityId, operations }] : [];
});
const agents = config.status === 'valid' ? config.config.agents : [];
const effectiveReason = effective?.unavailableReasons.find(({ pluginId }) => pluginId === definition.id);
const hasEffectiveSkill = effective?.effectiveSkillIds.some((skillId) => (
definition.skills.some(({ id }) => id === skillId)
)) ?? false;
let state = effectiveState({ enabled, policyAvailable, backend });
if (effective && effectiveReason?.code === 'project_disabled') state = 'disabled';
else if (effective && !hasEffectiveSkill && effectiveReason
&& ['account_required', 'library_required', 'library_unavailable', 'release_not_installed',
'release_invalid', 'runtime_suspended', 'policy_unavailable', 'policy_unsupported']
.includes(effectiveReason.code)) state = 'unavailable';
return {
id: definition.id,
version: definition.version,
@@ -322,7 +453,7 @@ export function createCodingProjectPluginService(
displayName: definition.displayName,
description: definition.description,
enabled,
state: effectiveState({ enabled, policyAvailable, backend }),
state,
backend,
skills: definition.skills.map((skill) => ({
id: skill.id,
@@ -377,6 +508,7 @@ export interface CodingProductHostOptions {
productTools: PiProductTools;
files?: CodingProjectFileService;
getEnabledPluginIds?(projectPath: string): Promise<readonly string[]>;
effectiveResolver?: EffectivePluginResolver;
listPiCommands?(conversationId: string): Promise<unknown>;
}
@@ -483,23 +615,53 @@ export function createCodingProductHost(options: CodingProductHostOptions): Codi
},
async listSkills(agentId) {
const project = await activeProject();
const enabledPluginIds = options.getEnabledPluginIds
? await options.getEnabledPluginIds(project.path)
: [];
const assignedSkillIds = await selectedSkillIds(project.path, agentId);
const effective = options.effectiveResolver
? await options.effectiveResolver.resolve({
projectId: project.id,
projectPath: project.path,
assignedSkillIds,
role: 'parent',
})
: null;
// Keep the raw assignment for the Renderer projection so a known
// disabled Skill remains visible as selected/ineffective. The resolver
// still supplies the availability set; only the worker opener receives
// the effective subset.
const skillIds = assignedSkillIds;
const enabledPluginIds = effective
? effective.effectiveSkillIds
: options.getEnabledPluginIds
? await options.getEnabledPluginIds(project.path)
: [];
return await options.productTools.listSkills(
await selectedSkillIds(project.path, agentId),
skillIds,
enabledPluginIds,
);
},
async listCommands(conversationId) {
const context = await conversationContext(conversationId);
const enabledPluginIds = options.getEnabledPluginIds
? await options.getEnabledPluginIds(context.project.path)
: [];
const effective = options.effectiveResolver
? await options.effectiveResolver.resolve({
projectId: context.project.id,
projectPath: context.project.path,
assignedSkillIds: context.skillIds,
role: 'parent',
})
: null;
// Commands are projected from the assignment, while ProductTools marks
// only resolver-approved Skills effective. This preserves disabled
// assignment state without loading it into a worker.
const skillIds = context.skillIds;
const enabledPluginIds = effective
? effective.effectiveSkillIds
: options.getEnabledPluginIds
? await options.getEnabledPluginIds(context.project.path)
: [];
const piCommands = options.listPiCommands
? normalizePiCommands(await options.listPiCommands(conversationId))
: [];
return await options.productTools.listCommands(context.skillIds, piCommands, enabledPluginIds);
return await options.productTools.listCommands(skillIds, piCommands, enabledPluginIds);
},
async getChanges(conversationId) {
await conversationContext(conversationId);

View File

@@ -22,6 +22,7 @@ import { handleCodingAttachmentRoutes } from './routes/coding-attachments';
import { handleCodingProjectRoutes } from './routes/coding-projects';
import { handleCodingConversationRoutes } from './routes/coding-conversations';
import { handleCodingPluginRoutes } from './routes/coding-plugins';
import { handlePluginMarketplaceRoutes } from './routes/plugin-marketplace';
export type HostApiRouteHandler = (
req: IncomingMessage,
@@ -50,6 +51,7 @@ export const hostApiRouteHandlers: readonly HostApiRouteHandler[] = [
handleUserSyncRoutes,
handleCodingAttachmentRoutes,
handleCodingProjectRoutes,
handlePluginMarketplaceRoutes,
handleCodingPluginRoutes,
handleCodingConversationRoutes,
handleCodingFileRoutes,

View File

@@ -0,0 +1,238 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import {
MarketplaceClientError,
type CatalogQuery,
} from '../../coding-plugins/marketplace-client';
import { PluginPackageStoreError } from '../../coding-plugins/package-store';
import type { HostApiContext } from '../context';
import { parseJsonBody, sendJson } from '../route-utils';
import type { CodingPluginMarketplaceService } from '../coding-product-services';
const ROOT = '/api/coding/plugin-marketplace';
const DETAIL = /^\/api\/coding\/plugin-marketplace\/plugins\/([^/]+)$/u;
const LIBRARY_MUTATION = /^\/api\/coding\/plugin-marketplace\/library\/([^/]+)$/u;
const INSTALLATION = /^\/api\/coding\/plugin-marketplace\/install\/([^/]+)$/u;
const UPDATE = /^\/api\/coding\/plugin-marketplace\/update\/([^/]+)$/u;
const PLUGIN_ID = /^[a-z][a-z0-9.-]{0,127}$/u;
class PluginMarketplaceRouteError extends Error {
constructor(
readonly status: 400 | 401 | 404 | 409 | 422 | 503,
readonly code: string,
message: string,
) {
super(message);
this.name = 'PluginMarketplaceRouteError';
}
}
function invalid(message: string): never {
throw new PluginMarketplaceRouteError(400, 'plugin_request_invalid', message);
}
function routePluginId(value: string): string {
let decoded: string;
try {
decoded = decodeURIComponent(value).trim();
} catch {
return invalid('plugin id is invalid');
}
if (!PLUGIN_ID.test(decoded)) return invalid('plugin id is invalid');
return decoded;
}
function exactNoQuery(url: URL): void {
if (url.search) invalid('This Marketplace route does not accept query parameters');
}
function catalogQuery(url: URL): CatalogQuery {
const allowed = new Set(['query', 'category', 'featured', 'limit', 'cursor']);
for (const key of url.searchParams.keys()) {
if (!allowed.has(key) || url.searchParams.getAll(key).length !== 1) {
invalid('Catalog query is invalid');
}
}
const rawFeatured = url.searchParams.get('featured');
if (rawFeatured !== null && rawFeatured !== 'true' && rawFeatured !== 'false') {
invalid('featured is invalid');
}
const rawLimit = url.searchParams.get('limit');
const limit = rawLimit === null ? undefined : Number(rawLimit);
if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)) {
invalid('limit is invalid');
}
const text = (key: string, maximum: number): string | undefined => {
const value = url.searchParams.get(key);
if (value === null) return undefined;
const normalized = value.trim();
if (!normalized || normalized.length > maximum) invalid(`${key} is invalid`);
return normalized;
};
return {
...(text('query', 120) === undefined ? {} : { query: text('query', 120) }),
...(text('category', 128) === undefined ? {} : { category: text('category', 128) }),
...(rawFeatured === null ? {} : { featured: rawFeatured === 'true' }),
...(limit === undefined ? {} : { limit }),
...(text('cursor', 1024) === undefined ? {} : { cursor: text('cursor', 1024) }),
};
}
async function exactEmptyBody(req: IncomingMessage): Promise<void> {
const body = await parseJsonBody<unknown>(req);
if (!body || typeof body !== 'object' || Array.isArray(body)
|| Object.keys(body as Record<string, unknown>).length !== 0) {
invalid('This Marketplace action does not accept a request body');
}
}
function sendError(res: ServerResponse, error: unknown): void {
if (error instanceof PluginMarketplaceRouteError) {
sendJson(res, error.status, { success: false, code: error.code, error: error.message });
return;
}
if (error instanceof MarketplaceClientError) {
const status = error.status === 401 || error.code === 'marketplace_auth_required' ? 401
: error.status === 404 ? 404
: error.code === 'marketplace_account_changed' ? 409
: error.code === 'marketplace_request_invalid' ? 400
: error.status === 403 ? 403
: error.status === 409 ? 409
: error.status === 422 ? 422
: 503;
const code = status === 401 ? 'plugin_auth_required'
: status === 403 ? 'plugin_library_required'
: status === 404 ? 'plugin_not_found'
: status === 409 ? (error.code === 'marketplace_account_changed'
? 'plugin_account_changed' : 'plugin_release_not_ready')
: status === 422 ? 'plugin_validation_failed'
: status === 400 ? 'plugin_request_invalid'
: 'plugin_backend_unavailable';
sendJson(res, status, {
success: false,
code,
error: status === 401 ? 'Marketplace authentication is required'
: status === 403 ? 'Marketplace Library access is required'
: status === 404 ? 'Plugin was not found'
: status === 409 ? (error.code === 'marketplace_account_changed'
? 'Marketplace account changed' : 'Plugin Release is not ready')
: status === 422 ? 'Plugin validation failed'
: status === 400 ? 'Marketplace request is invalid'
: 'Marketplace service is temporarily unavailable',
});
return;
}
if (error instanceof PluginPackageStoreError) {
const status = error.code === 'plugin_release_unavailable' || error.code === 'plugin_beta_selection_required'
|| error.code === 'plugin_release_conflict' || error.code === 'plugin_incompatible_client'
? 409
: error.code === 'plugin_artifact_invalid' || error.code === 'plugin_signature_invalid'
|| error.code === 'plugin_manifest_invalid' ? 422
: error.code === 'plugin_account_changed' ? 409 : 503;
const code = error.code === 'plugin_account_changed' ? 'plugin_account_changed'
: status === 409 ? 'plugin_release_not_ready'
: status === 422 ? 'plugin_artifact_invalid'
: 'plugin_backend_unavailable';
sendJson(res, status, {
success: false,
code,
error: status === 409 ? 'Plugin Release is not ready'
: status === 422 ? 'Plugin artifact is invalid'
: 'Plugin installation is temporarily unavailable',
});
return;
}
if (error instanceof SyntaxError) {
sendJson(res, 400, { success: false, code: 'plugin_request_invalid', error: 'Request body is invalid' });
return;
}
sendJson(res, 503, {
success: false,
code: 'plugin_backend_unavailable',
error: 'Marketplace service is temporarily unavailable',
});
}
function service(ctx: HostApiContext): CodingPluginMarketplaceService | null {
const products = ctx.codingProducts as (HostApiContext['codingProducts'] & {
marketplace?: CodingPluginMarketplaceService;
}) | undefined;
return products?.pluginMarketplace ?? products?.marketplace ?? null;
}
function isKnownPath(pathname: string): boolean {
return pathname === `${ROOT}/catalog`
|| pathname === `${ROOT}/library`
|| DETAIL.test(pathname)
|| LIBRARY_MUTATION.test(pathname)
|| INSTALLATION.test(pathname)
|| UPDATE.test(pathname);
}
export async function handlePluginMarketplaceRoutes(
req: IncomingMessage,
res: ServerResponse,
url: URL,
ctx: HostApiContext,
): Promise<boolean> {
if (!isKnownPath(url.pathname)) return false;
const marketplace = service(ctx);
if (!marketplace) {
sendJson(res, 503, {
success: false,
code: 'plugin_backend_unavailable',
error: 'Marketplace service is temporarily unavailable',
});
return true;
}
try {
if (url.pathname === `${ROOT}/catalog` && req.method === 'GET') {
sendJson(res, 200, await marketplace.readCatalog(catalogQuery(url)));
return true;
}
const detailMatch = DETAIL.exec(url.pathname);
if (detailMatch && req.method === 'GET') {
exactNoQuery(url);
sendJson(res, 200, await marketplace.readDetail(routePluginId(detailMatch[1])));
return true;
}
if (url.pathname === `${ROOT}/library` && req.method === 'GET') {
exactNoQuery(url);
sendJson(res, 200, await marketplace.readLibrary());
return true;
}
const libraryMatch = LIBRARY_MUTATION.exec(url.pathname);
if (libraryMatch && (req.method === 'PUT' || req.method === 'DELETE')) {
exactNoQuery(url);
await exactEmptyBody(req);
const pluginId = routePluginId(libraryMatch[1]);
sendJson(res, 200, req.method === 'PUT'
? await marketplace.acquire(pluginId)
: await marketplace.remove(pluginId));
return true;
}
const installationMatch = INSTALLATION.exec(url.pathname);
if (installationMatch && (req.method === 'POST' || req.method === 'DELETE')) {
exactNoQuery(url);
await exactEmptyBody(req);
const pluginId = routePluginId(installationMatch[1]);
const result = req.method === 'DELETE'
? await marketplace.uninstall(pluginId)
: await marketplace.install(pluginId);
sendJson(res, 200, result);
return true;
}
const updateMatch = UPDATE.exec(url.pathname);
if (updateMatch && req.method === 'POST') {
exactNoQuery(url);
await exactEmptyBody(req);
sendJson(res, 200, await marketplace.update(routePluginId(updateMatch[1])));
return true;
}
return false;
} catch (error) {
sendError(res, error);
return true;
}
}
export const handleCodingPluginMarketplaceRoutes = handlePluginMarketplaceRoutes;