diff --git a/docs/design/agent-plugins-v1-native-support.md b/docs/design/agent-plugins-v1-native-support.md new file mode 100644 index 000000000000..22e6711c1f2a --- /dev/null +++ b/docs/design/agent-plugins-v1-native-support.md @@ -0,0 +1,55 @@ +# Agent Plugins v1 Native Support + +## Context + +Qwen Code currently loads `qwen-extension.json` packages directly and converts +Gemini, Claude, and Qoder packages before loading them. Agent Plugins v1 is a +portable format with a root `plugin.json`, direct-child skills under `skills/`, +and an optional root `mcp.json`. Converting it would change the package format +and its runtime semantics. + +This design matches the portable runtime capabilities implemented by Codex at +`646f7c0a91b8e327d263335da68ae8ef212895ce`: skills, stdio MCP, and Streamable +HTTP MCP. Agent Plugin commands, agents, hooks, context, settings, channels, +apps, client-extension namespaces, and legacy SSE MCP are not activated. + +## Design + +Agent Plugins v1 is a native extension package format, not another converter. +A format-aware manifest loader recognizes only the canonical v1 schema, maps +portable metadata into the existing in-memory `ExtensionConfig`, and leaves all +standard files unchanged. Existing install sources and the install metadata +sidecar remain unchanged. + +The Agent Plugin loader discovers only immediate `skills/*/SKILL.md` files and +validates their portable Agent Skills metadata. Invalid skills are skipped +independently. The optional `allowed-tools` field is validated but does not +grant Qwen permissions. Other Qwen-specific skill fields are ignored. + +The root `mcp.json` is validated in two stages. A top-level error disables MCP +for the plugin; an invalid server disables only that entry. Stdio servers use a +stable data directory outside the package and receive client-controlled +`PLUGIN_ROOT` and `PLUGIN_DATA` values. Streamable HTTP servers receive the +portable URL and literal-header checks and stop redirects when a configured or +authorization header is present. Legacy SSE entries are reported and skipped. + +## Package boundary + +Every discovered, read, or executed package path is checked after resolving +symlinks and existing path prefixes. A plugin manifest escape rejects the +plugin, a component-directory escape disables that component, and a skill or +MCP-entry escape skips only that entry. Copied Agent Plugin installs do not +follow symlinks; linked installs apply the same checks at load time. + +## Compatibility + +A root `plugin.json` whose schema belongs to Agent Plugins takes precedence +over other extension manifests. Unsupported Agent Plugins schema versions fail +explicitly; unrelated root `plugin.json` files do not affect existing format +detection. Missing or blank portable versions use the internal version +`1.0.0`. + +The shared origin union gains `AgentPlugins`. Native Agent Plugins still use +the normal extension security consent, but they do not show the converted +third-party-format compatibility warning. Existing Qwen, Gemini, Claude, and +Qoder behavior remains unchanged. diff --git a/docs/users/extension/_meta.ts b/docs/users/extension/_meta.ts index ad072a629e52..4c8e9d36623d 100644 --- a/docs/users/extension/_meta.ts +++ b/docs/users/extension/_meta.ts @@ -1,5 +1,6 @@ export default { introduction: 'Introduction', + 'agent-plugins': 'Agent Plugins v1', 'getting-started-extensions': { display: 'hidden', }, diff --git a/docs/users/extension/agent-plugins.md b/docs/users/extension/agent-plugins.md new file mode 100644 index 000000000000..05c4f2906398 --- /dev/null +++ b/docs/users/extension/agent-plugins.md @@ -0,0 +1,50 @@ +# Agent Plugins v1 + +Qwen Code natively loads portable [Agent Plugins v1](https://agent-plugins.org/) +packages. The package keeps its standard `plugin.json`, `mcp.json`, and +`SKILL.md` files: installation does not generate `qwen-extension.json` or +rewrite portable files. + +Use the existing extension commands with a local directory, link, archive, +Git repository, archive URL, or scoped npm package: + +```bash +qwen extensions install ./my-agent-plugin +qwen extensions link ./my-agent-plugin +qwen extensions install owner/my-agent-plugin +``` + +The root manifest must target the canonical v1 schema: + +```json +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "my-agent-plugin", + "version": "1.0.0" +} +``` + +## Supported capabilities + +| Capability | Support | +| ------------------------------------------ | ---------------------------------------- | +| Direct-child `skills/*/SKILL.md` | Yes | +| stdio MCP servers | Yes | +| Streamable HTTP MCP servers | Yes | +| Legacy HTTP+SSE MCP servers | No; the entry is skipped | +| Commands, agents, and hooks | No; these directories are ignored | +| Qwen context, settings, channels, and apps | No | +| `extensions.*` client namespaces | No; unimplemented namespaces are ignored | + +Skills follow the [Agent Skills specification](https://agentskills.io/specification). +An invalid skill is skipped without disabling valid sibling skills. The +experimental `allowed-tools` field is recognized as a string but does not grant +pre-approved Qwen tools. + +For stdio MCP servers, Qwen Code expands `${PLUGIN_ROOT}` and `${PLUGIN_DATA}` +once in `args`, environment values, and `cwd`. `PLUGIN_DATA` is a writable +per-installation directory whose contents persist across updates and reinstall. +Remote MCP endpoints must use HTTPS, except for loopback HTTP endpoints. + +Agent Plugins v1 is a package format, not a marketplace integration. Install +packages through Qwen Code's existing extension sources. diff --git a/docs/users/extension/extension-releasing.md b/docs/users/extension/extension-releasing.md index 426f3e53745d..1d63dbe236de 100644 --- a/docs/users/extension/extension-releasing.md +++ b/docs/users/extension/extension-releasing.md @@ -73,7 +73,7 @@ To ensure Qwen Code can automatically find the correct release asset for each pl #### Archive structure -Archives must be fully contained extensions and have all the standard requirements - specifically the `qwen-extension.json` file must be at the root of the archive. +Archives must be fully contained extensions and have a supported root manifest: `qwen-extension.json` for a native Qwen extension, or `plugin.json` for an [Agent Plugins v1](./agent-plugins.md) package. The rest of the layout should look exactly the same as a typical extension, see [introduction.md](./introduction.md). @@ -131,7 +131,7 @@ You can publish Qwen Code extensions as scoped npm packages (e.g. `@your-org/my- ### Package requirements -Your npm package must include a `qwen-extension.json` file at the package root. This is the same config file used by all Qwen Code extensions — the npm tarball is simply another delivery mechanism. +Your npm package must include a supported manifest at the package root: `qwen-extension.json` for a native Qwen extension, or `plugin.json` for an [Agent Plugins v1](./agent-plugins.md) package. The npm tarball is simply another delivery mechanism. A minimal package structure looks like: @@ -145,7 +145,7 @@ my-extension/ └── agents/ # optional custom subagents ``` -Make sure `qwen-extension.json` is included in your published package (i.e. not excluded by `.npmignore` or the `files` field in `package.json`). +Make sure the selected root manifest and all referenced package files are included in your published package (i.e. not excluded by `.npmignore` or the `files` field in `package.json`). ### Publishing diff --git a/docs/users/extension/introduction.md b/docs/users/extension/introduction.md index 4c6ca5ffe706..5865af385f48 100644 --- a/docs/users/extension/introduction.md +++ b/docs/users/extension/introduction.md @@ -2,7 +2,7 @@ Qwen Code extensions package prompts, MCP servers, subagents, skills and custom commands into a familiar and user-friendly format. With extensions, you can expand the capabilities of Qwen Code and share those capabilities with others. They are designed to be easily installable and shareable. -Extensions and plugins from [Gemini CLI Extensions Gallery](https://geminicli.com/extensions/), [Claude Code Marketplace](https://claudemarketplaces.com/), and Qoder can be directly installed into Qwen Code. This cross-platform compatibility gives you access to a rich ecosystem of extensions and plugins, dramatically expanding Qwen Code's capabilities without requiring extension authors to maintain separate versions. +Extensions and plugins from [Gemini CLI Extensions Gallery](https://geminicli.com/extensions/), [Claude Code Marketplace](https://claudemarketplaces.com/), Qoder, and the portable [Agent Plugins v1](./agent-plugins.md) format can be directly installed into Qwen Code. This cross-platform compatibility gives you access to a rich ecosystem of extensions and plugins, dramatically expanding Qwen Code's capabilities without requiring extension authors to maintain separate versions. ## Extension management @@ -113,6 +113,18 @@ The installer converts the Qoder manifest to `qwen-extension.json` and preserves When a Qoder plugin contains `system-prompt.md` at its root, Qwen Code loads it as extension context. If the plugin also contains `QWEN.md` or declares other context files, all context files are retained and deduplicated. +#### From Agent Plugins v1 + +Qwen Code natively loads portable Agent Plugins v1 packages without converting or rewriting `plugin.json`, `mcp.json`, or `SKILL.md` files: + +```bash +qwen extensions install ./my-agent-plugin +qwen extensions link ./my-agent-plugin +qwen extensions install owner/my-agent-plugin +``` + +The portable runtime supports Agent Skills plus stdio and Streamable HTTP MCP servers. Commands, agents, hooks, client namespaces, and legacy SSE MCP are not activated. See [Agent Plugins v1](./agent-plugins.md) for the complete support matrix. + #### From npm Registry Qwen Code supports installing extensions from npm registries using scoped package names. This is ideal for teams with private registries that already have auth, versioning, and publishing infrastructure in place. @@ -139,7 +151,7 @@ Only scoped packages (`@scope/package-name`) are supported to avoid ambiguity wi **Authentication** is handled automatically via the `NPM_TOKEN` environment variable or registry-specific `_authToken` entries in your `.npmrc` file. -> **Note:** npm extensions must include a `qwen-extension.json` file at the package root, following the same format as any other Qwen Code extension. See [Extension Releasing](./extension-releasing.md#releasing-through-npm-registry) for packaging details. +> **Note:** npm extensions must include either a native `qwen-extension.json` or an Agent Plugins v1 `plugin.json` at the package root. See [Extension Releasing](./extension-releasing.md#releasing-through-npm-registry) for packaging details. #### From Git Repository @@ -237,7 +249,9 @@ qwen extensions update --all On startup, Qwen Code looks for extensions in `/.qwen/extensions` -Extensions exist as a directory that contains a `qwen-extension.json` file. For example: +Native Qwen extensions exist as a directory that contains a `qwen-extension.json` file. Agent Plugins v1 packages instead retain their root `plugin.json`; see [Agent Plugins v1](./agent-plugins.md). + +For example, a native Qwen extension is stored at: `/.qwen/extensions/my-extension/qwen-extension.json` diff --git a/packages/acp-bridge/src/status.ts b/packages/acp-bridge/src/status.ts index da7af19a0025..c88b3cfee35b 100644 --- a/packages/acp-bridge/src/status.ts +++ b/packages/acp-bridge/src/status.ts @@ -1082,7 +1082,8 @@ export type ServeExtensionOriginSource = | 'QwenCode' | 'Claude' | 'Gemini' - | 'Qoder'; + | 'Qoder' + | 'AgentPlugins'; export interface ServeExtensionCapabilities { mcpServerCount: number; diff --git a/packages/cli/src/commands/extensions/consent.test.ts b/packages/cli/src/commands/extensions/consent.test.ts index 568d2620679e..9097c3d17592 100644 --- a/packages/cli/src/commands/extensions/consent.test.ts +++ b/packages/cli/src/commands/extensions/consent.test.ts @@ -104,6 +104,33 @@ describe('extensionConsentString', () => { expect(result).toContain('Extensions may introduce unexpected behavior'); }); + it('treats Agent Plugins as a native format while keeping safety details', () => { + const result = extensionConsentString( + { + name: 'portable-plugin', + version: '1.0.0', + mcpServers: { local: { command: 'node', args: ['server.js'] } }, + }, + [], + [ + { + name: 'direct', + description: 'Direct skill', + level: 'extension', + filePath: '/test/direct/SKILL.md', + body: 'Instructions', + }, + ], + [], + 'AgentPlugins', + ); + + expect(result).not.toContain('Some features may not work perfectly'); + expect(result).toContain('Extensions may introduce unexpected behavior'); + expect(result).toContain('local'); + expect(result).toContain('direct'); + }); + it('should include MCP servers when present', () => { const config: ExtensionConfig = { name: 'test-extension', diff --git a/packages/cli/src/commands/extensions/consent.ts b/packages/cli/src/commands/extensions/consent.ts index 95c2c291ee19..11ddaee888fa 100644 --- a/packages/cli/src/commands/extensions/consent.ts +++ b/packages/cli/src/commands/extensions/consent.ts @@ -153,7 +153,7 @@ export function extensionConsentString( originSource: string = 'QwenCode', ): string { const output: string[] = []; - if (originSource !== 'QwenCode') { + if (originSource !== 'QwenCode' && originSource !== 'AgentPlugins') { output.push( t( 'You are installing an extension from {{originSource}}. Some features may not work perfectly with Qwen Code.', @@ -163,9 +163,7 @@ export function extensionConsentString( } const mcpServerEntries = Object.entries(extensionConfig.mcpServers || {}); const displayLabel = extensionConfig.displayName ?? extensionConfig.name; - output.push( - t('Installing extension "{{name}}".', { name: displayLabel }), - ); + output.push(t('Installing extension "{{name}}".', { name: displayLabel })); if ( typeof extensionConfig.description === 'string' && extensionConfig.description diff --git a/packages/cli/src/commands/extensions/utils.test.ts b/packages/cli/src/commands/extensions/utils.test.ts index dca03c035330..0f5098dcc5e5 100644 --- a/packages/cli/src/commands/extensions/utils.test.ts +++ b/packages/cli/src/commands/extensions/utils.test.ts @@ -229,4 +229,22 @@ describe('extensionToOutputString', () => { expect(result).not.toContain('user'); expect(result).not.toContain('token'); }); + + it('should display the native Agent Plugins origin', () => { + const extension = createMockExtension({ + installMetadata: { + type: 'local', + source: '/path/to/portable-plugin', + originSource: 'AgentPlugins', + }, + }); + + const result = extensionToOutputString( + extension, + mockExtensionManager, + '/workspace', + ); + + expect(result).toContain('Origin: AgentPlugins'); + }); }); diff --git a/packages/cli/src/commands/extensions/utils.ts b/packages/cli/src/commands/extensions/utils.ts index 8c7aa9e725e9..db4bc93b6c9c 100644 --- a/packages/cli/src/commands/extensions/utils.ts +++ b/packages/cli/src/commands/extensions/utils.ts @@ -96,6 +96,9 @@ export function extensionToOutputString( output += `\n ${t('Path:')} ${extension.path}`; if (extension.installMetadata) { output += `\n ${t('Source:')} ${redactUrlCredentials(extension.installMetadata.source)} (${t('Type:')} ${extension.installMetadata.type})`; + if (extension.installMetadata.originSource) { + output += `\n ${t('Origin:')} ${extension.installMetadata.originSource}`; + } if (extension.installMetadata.ref) { output += `\n ${t('Ref:')} ${extension.installMetadata.ref}`; } diff --git a/packages/cli/src/services/FileCommandLoader.test.ts b/packages/cli/src/services/FileCommandLoader.test.ts index a2a893e6102f..8889cbc8ac7f 100644 --- a/packages/cli/src/services/FileCommandLoader.test.ts +++ b/packages/cli/src/services/FileCommandLoader.test.ts @@ -604,6 +604,40 @@ describe('FileCommandLoader', () => { expect(extCommand?.description).toMatch(/^\[test-ext\]/); }); + it('ignores commands bundled in manually discovered Agent Plugins', async () => { + const extensionDir = path.join( + process.cwd(), + '.qwen/extensions/agent-plugin', + ); + mock({ + [extensionDir]: { + commands: { + 'deploy.toml': 'prompt = "Unconsented command"', + }, + }, + }); + const mockConfig = { + getProjectRoot: vi.fn(() => process.cwd()), + getExtensions: vi.fn(() => [ + { + name: 'agent-plugin', + version: '1.0.0', + isActive: true, + path: extensionDir, + format: 'agent-plugins-v1', + }, + ]), + getFolderTrustFeature: vi.fn(() => false), + getFolderTrust: vi.fn(() => false), + } as unknown as Config; + + const commands = await new FileCommandLoader(mockConfig).loadCommands( + signal, + ); + + expect(commands).toEqual([]); + }); + it('extension commands have extensionName metadata for conflict resolution', async () => { const userCommandsDir = Storage.getUserCommandsDir(); const projectCommandsDir = new Storage( diff --git a/packages/cli/src/services/FileCommandLoader.ts b/packages/cli/src/services/FileCommandLoader.ts index 5c014c072959..55f64f8fb546 100644 --- a/packages/cli/src/services/FileCommandLoader.ts +++ b/packages/cli/src/services/FileCommandLoader.ts @@ -171,7 +171,12 @@ export class FileCommandLoader implements ICommandLoader { if (this.config) { const activeExtensions = this.config .getExtensions() - .filter((ext) => ext.isActive) + .filter( + (ext) => + ext.isActive && + ext.format !== 'agent-plugins-v1' && + ext.installMetadata?.originSource !== 'AgentPlugins', + ) .sort((a, b) => a.name.localeCompare(b.name)); // Sort alphabetically for deterministic loading // Collect command directories from each extension diff --git a/packages/cli/src/ui/components/extensions/views/PluginDetailView.tsx b/packages/cli/src/ui/components/extensions/views/PluginDetailView.tsx index e7fd7571ed59..60a09b30484a 100644 --- a/packages/cli/src/ui/components/extensions/views/PluginDetailView.tsx +++ b/packages/cli/src/ui/components/extensions/views/PluginDetailView.tsx @@ -141,6 +141,11 @@ export const PluginDetailView = ({ {redactUrlCredentials(ext.installMetadata.source)} )} + {ext.installMetadata?.originSource && ( + + {ext.installMetadata.originSource} + + )} {componentSummary(ext)} diff --git a/packages/core/src/config/config.ts b/packages/core/src/config/config.ts index 3c024bc4f8b3..af6e0346b599 100644 --- a/packages/core/src/config/config.ts +++ b/packages/core/src/config/config.ts @@ -673,7 +673,12 @@ function normalizeGitCoAuthor(value: GitCoAuthorParam | undefined): { }; } -export type ExtensionOriginSource = 'QwenCode' | 'Claude' | 'Gemini' | 'Qoder'; +export type ExtensionOriginSource = + | 'QwenCode' + | 'Claude' + | 'Gemini' + | 'Qoder' + | 'AgentPlugins'; export type ExtensionNetworkPolicy = 'public'; export interface ExtensionInstallMetadata { @@ -844,6 +849,7 @@ export class MCPServerConfig { */ readonly scope?: McpServerScope, readonly alwaysLoadTools?: boolean, + readonly agentPluginV1?: boolean, ) {} } diff --git a/packages/core/src/extension/agent-plugins-v1/index.ts b/packages/core/src/extension/agent-plugins-v1/index.ts new file mode 100644 index 000000000000..c71269a42c36 --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/index.ts @@ -0,0 +1,9 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +export * from './manifest.js'; +export * from './mcp.js'; +export * from './skills.js'; diff --git a/packages/core/src/extension/agent-plugins-v1/manifest.test.ts b/packages/core/src/extension/agent-plugins-v1/manifest.test.ts new file mode 100644 index 000000000000..9182c0d6130f --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/manifest.test.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + AGENT_PLUGIN_SCHEMA, + getAgentPluginSchemaStatus, + loadAgentPluginManifest, +} from './manifest.js'; + +describe('Agent Plugins v1 manifest', () => { + let pluginRoot: string; + + beforeEach(() => { + pluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-plugin-')); + }); + + afterEach(() => { + fs.rmSync(pluginRoot, { recursive: true, force: true }); + }); + + it('maps portable metadata without requiring a version', () => { + writeManifest({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'portable.tools', + version: ' ', + description: ' Portable tools ', + unknown: true, + extensions: { 'com.example': 'ignored' }, + }); + + expect(getAgentPluginSchemaStatus(pluginRoot)).toBe('supported'); + expect(loadAgentPluginManifest(pluginRoot)).toEqual({ + name: 'portable.tools', + version: '1.0.0', + displayName: 'portable.tools', + description: 'Portable tools', + }); + }); + + it('distinguishes unsupported and unrelated schemas', () => { + writeManifest({ + $schema: 'https://agent-plugins.org/schemas/2.0.0/plugin.schema.json', + name: 'future-plugin', + }); + expect(getAgentPluginSchemaStatus(pluginRoot)).toBe('unsupported'); + expect(() => loadAgentPluginManifest(pluginRoot)).toThrow( + 'Unsupported Agent Plugins schema', + ); + + writeManifest({ $schema: 'https://example.com/plugin.schema.json' }); + expect(getAgentPluginSchemaStatus(pluginRoot)).toBe('unrelated'); + }); + + it('does not read a non-regular root manifest', () => { + fs.mkdirSync(path.join(pluginRoot, 'plugin.json')); + + expect(getAgentPluginSchemaStatus(pluginRoot)).toBe('unrelated'); + }); + + it('rejects invalid portable fields', () => { + writeManifest({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'UPPERCASE', + }); + expect(() => loadAgentPluginManifest(pluginRoot)).toThrow( + 'Agent Plugins name', + ); + + writeManifest({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'portable', + keywords: ['valid', 1], + }); + expect(() => loadAgentPluginManifest(pluginRoot)).toThrow('keywords'); + }); + + it.runIf(process.platform !== 'win32')( + 'loads a root manifest symlink contained in the plugin', + () => { + const inside = path.join(pluginRoot, 'inside-plugin.json'); + fs.writeFileSync( + inside, + JSON.stringify({ $schema: AGENT_PLUGIN_SCHEMA, name: 'portable' }), + ); + fs.symlinkSync(inside, path.join(pluginRoot, 'plugin.json')); + + expect(loadAgentPluginManifest(pluginRoot)).toMatchObject({ + name: 'portable', + version: '1.0.0', + }); + }, + ); + + it.runIf(process.platform !== 'win32')( + 'rejects a root manifest symlink that escapes the plugin', + () => { + const outside = `${pluginRoot}-outside.json`; + fs.writeFileSync( + outside, + JSON.stringify({ $schema: AGENT_PLUGIN_SCHEMA, name: 'portable' }), + ); + fs.symlinkSync(outside, path.join(pluginRoot, 'plugin.json')); + expect(getAgentPluginSchemaStatus(pluginRoot)).toBe('supported'); + expect(() => loadAgentPluginManifest(pluginRoot)).toThrow( + 'outside plugin root', + ); + fs.rmSync(outside, { force: true }); + }, + ); + + function writeManifest(value: unknown): void { + fs.writeFileSync( + path.join(pluginRoot, 'plugin.json'), + JSON.stringify(value), + ); + } +}); diff --git a/packages/core/src/extension/agent-plugins-v1/manifest.ts b/packages/core/src/extension/agent-plugins-v1/manifest.ts new file mode 100644 index 000000000000..d9871a41c08b --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/manifest.ts @@ -0,0 +1,193 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { createDebugLogger } from '../../utils/debugLogger.js'; +import { resolveContainedExistingPath } from './paths.js'; + +export const AGENT_PLUGIN_MANIFEST = 'plugin.json'; +export const AGENT_PLUGIN_SCHEMA = + 'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json'; +export const AGENT_PLUGIN_SCHEMA_PREFIX = 'https://agent-plugins.org/schemas/'; +export const DEFAULT_AGENT_PLUGIN_VERSION = '1.0.0'; + +const debugLogger = createDebugLogger('AGENT_PLUGINS_V1'); +const MANIFEST_FIELDS = new Set([ + '$schema', + 'name', + 'version', + 'description', + 'author', + 'homepage', + 'repository', + 'license', + 'keywords', + 'extensions', +]); +const AUTHOR_FIELDS = new Set(['name', 'email', 'url']); + +export type AgentPluginSchemaStatus = 'supported' | 'unsupported' | 'unrelated'; + +export interface AgentPluginExtensionConfig { + name: string; + version: string; + displayName: string; + description?: string; +} + +export function getAgentPluginSchemaStatus( + pluginRoot: string, +): AgentPluginSchemaStatus { + const manifestPath = path.join(pluginRoot, AGENT_PLUGIN_MANIFEST); + let resolvedManifestPath: string; + try { + resolvedManifestPath = resolveContainedExistingPath( + pluginRoot, + manifestPath, + ); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + return code === 'ENOENT' || code === 'ENOTDIR' ? 'unrelated' : 'supported'; + } + + let value: unknown; + try { + if (!fs.statSync(resolvedManifestPath).isFile()) return 'unrelated'; + value = JSON.parse( + fs.readFileSync(resolvedManifestPath, 'utf8'), + ) as unknown; + } catch { + return 'unrelated'; + } + if (!isRecord(value) || typeof value['$schema'] !== 'string') { + return 'unrelated'; + } + if (value['$schema'] === AGENT_PLUGIN_SCHEMA) return 'supported'; + return value['$schema'].startsWith(AGENT_PLUGIN_SCHEMA_PREFIX) + ? 'unsupported' + : 'unrelated'; +} + +export function loadAgentPluginManifest( + pluginRoot: string, +): AgentPluginExtensionConfig { + const manifestPath = path.join(pluginRoot, AGENT_PLUGIN_MANIFEST); + const resolvedManifestPath = resolveContainedExistingPath( + pluginRoot, + manifestPath, + ); + if (!fs.statSync(resolvedManifestPath).isFile()) { + throw new Error('Agent Plugins root plugin.json must be a regular file.'); + } + + const value = JSON.parse( + fs.readFileSync(resolvedManifestPath, 'utf8'), + ) as unknown; + if (!isRecord(value)) { + throw new Error('Agent Plugins root plugin.json must contain an object.'); + } + + for (const field of Object.keys(value)) { + if (!MANIFEST_FIELDS.has(field)) { + debugLogger.warn( + `Ignoring unknown Agent Plugins manifest field "${field}".`, + ); + } + } + + const schema = value['$schema']; + if (typeof schema !== 'string') { + throw new Error('Agent Plugins manifest is missing string "$schema".'); + } + if (schema !== AGENT_PLUGIN_SCHEMA) { + throw new Error( + schema.startsWith(AGENT_PLUGIN_SCHEMA_PREFIX) + ? `Unsupported Agent Plugins schema "${schema}". Supported schema: "${AGENT_PLUGIN_SCHEMA}".` + : `Root plugin.json is not an Agent Plugins v1 manifest. Expected "$schema" "${AGENT_PLUGIN_SCHEMA}".`, + ); + } + + const name = value['name']; + if (typeof name !== 'string' || !isValidPluginName(name)) { + throw new Error( + 'Agent Plugins name must be 1-64 lowercase letters, numbers, dots, or hyphens without leading, trailing, or consecutive separators.', + ); + } + + validateOptionalString(value, 'version'); + validateOptionalString(value, 'description'); + validateOptionalString(value, 'homepage'); + validateOptionalString(value, 'repository'); + validateOptionalString(value, 'license'); + validateAuthor(value['author']); + validateKeywords(value['keywords']); + + if (value['extensions'] !== undefined && !isRecord(value['extensions'])) { + debugLogger.warn('Ignoring non-object Agent Plugins extensions field.'); + } + + const version = optionalTrimmedString(value['version']); + const description = optionalTrimmedString(value['description']); + return { + name, + version: version ?? DEFAULT_AGENT_PLUGIN_VERSION, + displayName: name, + ...(description ? { description } : {}), + }; +} + +function isValidPluginName(name: string): boolean { + return ( + name.length <= 64 && + /^(?!.*(?:--|\.\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(name) + ); +} + +function validateOptionalString( + value: Record, + field: string, +): void { + if (value[field] !== undefined && typeof value[field] !== 'string') { + throw new Error(`Agent Plugins manifest "${field}" must be a string.`); + } +} + +function validateAuthor(value: unknown): void { + if (value === undefined) return; + if (!isRecord(value)) { + throw new Error('Agent Plugins manifest "author" must be an object.'); + } + for (const [field, fieldValue] of Object.entries(value)) { + if (!AUTHOR_FIELDS.has(field)) { + throw new Error(`Unknown Agent Plugins author field "${field}".`); + } + if (typeof fieldValue !== 'string') { + throw new Error( + `Agent Plugins author field "${field}" must be a string.`, + ); + } + } +} + +function validateKeywords(value: unknown): void { + if (value === undefined) return; + if (!Array.isArray(value) || value.some((item) => typeof item !== 'string')) { + throw new Error( + 'Agent Plugins manifest "keywords" must be an array of strings.', + ); + } +} + +function optionalTrimmedString(value: unknown): string | undefined { + if (typeof value !== 'string') return undefined; + const trimmed = value.trim(); + return trimmed || undefined; +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} diff --git a/packages/core/src/extension/agent-plugins-v1/mcp.test.ts b/packages/core/src/extension/agent-plugins-v1/mcp.test.ts new file mode 100644 index 000000000000..961697cab28f --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/mcp.test.ts @@ -0,0 +1,350 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { + AGENT_PLUGIN_MCP_SCHEMA, + loadAgentPluginMcpServers, + validateAgentPluginStdioRuntimePaths, +} from './mcp.js'; + +describe('Agent Plugins v1 MCP', () => { + let pluginRoot: string; + let pluginDataRoot: string; + + beforeEach(() => { + pluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-plugin-')); + pluginDataRoot = path.join( + fs.mkdtempSync(path.join(os.tmpdir(), 'agent-plugin-data-parent-')), + 'data', + ); + fs.mkdirSync(path.join(pluginRoot, 'bin'), { recursive: true }); + fs.mkdirSync(path.join(pluginRoot, 'work'), { recursive: true }); + fs.writeFileSync(path.join(pluginRoot, 'bin', 'server'), 'server'); + }); + + afterEach(() => { + fs.rmSync(pluginRoot, { recursive: true, force: true }); + fs.rmSync(path.dirname(pluginDataRoot), { recursive: true, force: true }); + }); + + it('maps valid stdio and Streamable HTTP entries independently', async () => { + const resolvedPluginRoot = fs.realpathSync.native(pluginRoot); + const resolvedDataRoot = path.join( + fs.realpathSync.native(path.dirname(pluginDataRoot)), + path.basename(pluginDataRoot), + ); + writeMcp({ + local: { + type: 'stdio', + command: './bin/server', + args: ['${PLUGIN_ROOT}/input', '${PLUGIN_DATA}/state'], + env: { CACHE: '${PLUGIN_DATA}/cache' }, + cwd: '${PLUGIN_ROOT}/work', + }, + remote: { + type: 'streamable-http', + url: 'https://example.com/mcp', + headers: { + 'X-Plugin': 'portable', + Authorization: 'removed', + 'Content-Type': 'removed', + }, + }, + unsupported: { type: 'sse', url: 'https://example.com/sse' }, + invalid: { type: 'stdio', command: '../escape' }, + }); + + const servers = await loadAgentPluginMcpServers( + pluginRoot, + pluginDataRoot, + { createDataDir: true }, + ); + + expect(Object.keys(servers)).toEqual(['local', 'remote']); + expect(servers['local']).toMatchObject({ + command: path.join(resolvedPluginRoot, 'bin', 'server'), + args: [`${resolvedPluginRoot}/input`, `${resolvedDataRoot}/state`], + cwd: path.join(resolvedPluginRoot, 'work'), + agentPluginV1: true, + }); + expect(servers['local']?.env).toMatchObject({ + PLUGIN_ROOT: resolvedPluginRoot, + PLUGIN_DATA: resolvedDataRoot, + CACHE: `${resolvedDataRoot}/cache`, + }); + expect(servers['remote']).toEqual({ + httpUrl: 'https://example.com/mcp', + headers: { 'X-Plugin': 'portable' }, + agentPluginV1: true, + }); + expect(fs.statSync(pluginDataRoot).isDirectory()).toBe(true); + }); + + it('creates stdio cwd directories inside PLUGIN_DATA', async () => { + writeMcp({ + local: { + type: 'stdio', + command: './bin/server', + cwd: '${PLUGIN_DATA}/work', + }, + }); + + const server = ( + await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot, { + createDataDir: true, + }) + )['local']; + + expect(server).toBeDefined(); + expect(fs.statSync(server!.cwd!).isDirectory()).toBe(true); + expect(() => validateAgentPluginStdioRuntimePaths(server!)).not.toThrow(); + }); + + it('disables all MCP on a top-level error', async () => { + fs.writeFileSync( + path.join(pluginRoot, 'mcp.json'), + JSON.stringify({ + $schema: AGENT_PLUGIN_MCP_SCHEMA, + mcpServers: {}, + unknown: true, + }), + ); + expect(await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot)).toEqual( + {}, + ); + }); + + it('rejects unsafe HTTP endpoints and reserved environment variables', async () => { + writeMcp({ + insecure: { type: 'streamable-http', url: 'http://example.com/mcp' }, + reserved: { + type: 'stdio', + command: 'node', + env: { PLUGIN_ROOT: 'override' }, + }, + loopback: { + type: 'streamable-http', + url: 'http://127.0.0.1:3000/mcp', + }, + }); + expect(await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot)).toEqual( + { + loopback: { + httpUrl: 'http://127.0.0.1:3000/mcp', + agentPluginV1: true, + }, + }, + ); + }); + + it('expands variables once and isolates escaping package paths', async () => { + const resolvedPluginRoot = fs.realpathSync.native(pluginRoot); + const literalDataRoot = path.join( + path.dirname(pluginDataRoot), + '${PLUGIN_ROOT}', + ); + const resolvedLiteralDataRoot = path.join( + fs.realpathSync.native(path.dirname(literalDataRoot)), + path.basename(literalDataRoot), + ); + writeMcp({ + singlePass: { + type: 'stdio', + command: 'node', + args: ['${PLUGIN_DATA}'], + env: { LITERAL: '${PLUGIN_ROOT}/${UNKNOWN}' }, + cwd: '${PLUGIN_DATA}/work', + }, + badCommand: { type: 'stdio', command: './../escape' }, + driveRelativeCommand: { type: 'stdio', command: 'C:escape' }, + badCwd: { type: 'stdio', command: 'node', cwd: './../escape' }, + }); + + const servers = await loadAgentPluginMcpServers( + pluginRoot, + literalDataRoot, + ); + + expect(Object.keys(servers)).toEqual(['singlePass']); + expect(servers['singlePass']?.args).toEqual([resolvedLiteralDataRoot]); + expect(servers['singlePass']?.args?.[0]).toContain('${PLUGIN_ROOT}'); + expect(servers['singlePass']?.env?.['LITERAL']).toBe( + `${resolvedPluginRoot}/${'${UNKNOWN}'}`, + ); + expect(servers['singlePass']?.cwd).toBe( + path.join(resolvedLiteralDataRoot, 'work'), + ); + }); + + it('keeps HTTP servers when the stdio data directory cannot be created', async () => { + const fileParent = path.join(path.dirname(pluginDataRoot), 'file'); + fs.writeFileSync(fileParent, 'not a directory'); + writeMcp({ + local: { type: 'stdio', command: 'node' }, + remote: { + type: 'streamable-http', + url: 'https://example.com/mcp', + }, + }); + + expect( + await loadAgentPluginMcpServers( + pluginRoot, + path.join(fileParent, 'data'), + { createDataDir: true }, + ), + ).toEqual({ + remote: { + httpUrl: 'https://example.com/mcp', + agentPluginV1: true, + }, + }); + }); + + it('validates remote URL and headers per entry', async () => { + writeMcp({ + credentials: { + type: 'streamable-http', + url: 'https://user@example.com/mcp', + }, + fragment: { + type: 'streamable-http', + url: 'https://example.com/mcp#fragment', + }, + duplicateHeader: { + type: 'streamable-http', + url: 'https://example.com/mcp', + headers: { 'X-Test': 'one', 'x-test': 'two' }, + }, + invalidHeader: { + type: 'streamable-http', + url: 'https://example.com/mcp', + headers: { 'X-Test': 'bad\nvalue' }, + }, + ipv6Loopback: { + type: 'streamable-http', + url: 'http://[::1]:3000/mcp', + }, + }); + + expect(await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot)).toEqual( + { + ipv6Loopback: { + httpUrl: 'http://[::1]:3000/mcp', + agentPluginV1: true, + }, + }, + ); + }); + + it('retains valid prototype-named servers and headers as own fields', async () => { + const headers: Record = {}; + Object.defineProperty(headers, '__proto__', { + value: 'literal', + enumerable: true, + }); + const entries: Record = {}; + Object.defineProperty(entries, '__proto__', { + value: { + type: 'streamable-http', + url: 'https://example.com/mcp', + headers, + }, + enumerable: true, + }); + writeMcp(entries); + + const servers = await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot); + + expect(Object.hasOwn(servers, '__proto__')).toBe(true); + expect( + Object.hasOwn(servers['__proto__']?.headers ?? {}, '__proto__'), + ).toBe(true); + }); + + it.runIf(process.platform !== 'win32')( + 'loads an mcp.json symlink contained in the plugin', + async () => { + const inside = path.join(pluginRoot, 'inside-mcp.json'); + fs.writeFileSync( + inside, + JSON.stringify({ + $schema: AGENT_PLUGIN_MCP_SCHEMA, + mcpServers: { + local: { type: 'stdio', command: 'node' }, + }, + }), + ); + fs.symlinkSync(inside, path.join(pluginRoot, 'mcp.json')); + + expect( + await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot), + ).toMatchObject({ + local: { command: 'node', agentPluginV1: true }, + }); + }, + ); + + it.runIf(process.platform !== 'win32')( + 'disables MCP when mcp.json is a symlink escape', + async () => { + const outside = `${pluginRoot}-outside-mcp.json`; + fs.writeFileSync( + outside, + JSON.stringify({ + $schema: AGENT_PLUGIN_MCP_SCHEMA, + mcpServers: {}, + }), + ); + fs.symlinkSync(outside, path.join(pluginRoot, 'mcp.json')); + expect( + await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot), + ).toEqual({}); + fs.rmSync(outside, { force: true }); + }, + ); + + it.runIf(process.platform !== 'win32')( + 'revalidates linked stdio paths immediately before launch', + async () => { + writeMcp({ + local: { + type: 'stdio', + command: './bin/server', + cwd: '${PLUGIN_ROOT}/work', + }, + }); + const server = ( + await loadAgentPluginMcpServers(pluginRoot, pluginDataRoot, { + createDataDir: true, + }) + )['local']; + expect(server).toBeDefined(); + expect(() => validateAgentPluginStdioRuntimePaths(server!)).not.toThrow(); + + const outside = `${pluginRoot}-outside-server`; + fs.writeFileSync(outside, 'outside'); + fs.rmSync(path.join(pluginRoot, 'bin', 'server')); + fs.symlinkSync(outside, path.join(pluginRoot, 'bin', 'server')); + + expect(() => validateAgentPluginStdioRuntimePaths(server!)).toThrow( + 'outside plugin root', + ); + fs.rmSync(outside, { force: true }); + }, + ); + + function writeMcp(mcpServers: Record): void { + fs.writeFileSync( + path.join(pluginRoot, 'mcp.json'), + JSON.stringify({ $schema: AGENT_PLUGIN_MCP_SCHEMA, mcpServers }), + ); + } +}); diff --git a/packages/core/src/extension/agent-plugins-v1/mcp.ts b/packages/core/src/extension/agent-plugins-v1/mcp.ts new file mode 100644 index 000000000000..0e1aa987244e --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/mcp.ts @@ -0,0 +1,436 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { MCPServerConfig } from '../../config/config.js'; +import { createDebugLogger } from '../../utils/debugLogger.js'; +import { + isPathWithin, + resolveContainedExistingPath, + resolveContainedPotentialPath, + resolveExistingPathPrefix, +} from './paths.js'; + +export const AGENT_PLUGIN_MCP_SCHEMA = + 'https://agent-plugins.org/schemas/1.0.0/mcp.schema.json'; + +const debugLogger = createDebugLogger('AGENT_PLUGINS_V1'); +const CLIENT_OWNED_HEADERS = new Set([ + 'accept', + 'authorization', + 'connection', + 'content-encoding', + 'content-length', + 'content-type', + 'host', + 'last-event-id', + 'mcp-protocol-version', + 'mcp-session-id', + 'proxy-authorization', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'user-agent', +]); + +export async function loadAgentPluginMcpServers( + pluginRoot: string, + pluginDataRoot: string, + options: { createDataDir?: boolean } = {}, +): Promise> { + const mcpPath = path.join(pluginRoot, 'mcp.json'); + let contents: string; + try { + const resolvedMcpPath = resolveContainedExistingPath(pluginRoot, mcpPath); + if (!(await fs.promises.stat(resolvedMcpPath)).isFile()) { + debugLogger.warn( + 'Agent Plugins mcp.json is not a regular file; disabling MCP.', + ); + return {}; + } + contents = await fs.promises.readFile(resolvedMcpPath, 'utf8'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return {}; + debugLogger.warn( + `Disabling Agent Plugins MCP: ${error instanceof Error ? error.message : String(error)}`, + ); + return {}; + } + + let value: unknown; + try { + value = JSON.parse(contents) as unknown; + validateMcpFile(value); + } catch (error) { + debugLogger.warn( + `Disabling Agent Plugins MCP: ${error instanceof Error ? error.message : String(error)}`, + ); + return {}; + } + + const servers: Record = {}; + for (const [name, entry] of Object.entries(value['mcpServers'])) { + try { + Object.defineProperty(servers, name, { + value: normalizeServer(entry, pluginRoot, pluginDataRoot), + enumerable: true, + configurable: true, + writable: true, + }); + } catch (error) { + debugLogger.warn( + `Skipping Agent Plugins MCP server "${name}": ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + + if ( + options.createDataDir && + Object.values(servers).some((server) => server.command) + ) { + try { + await fs.promises.mkdir(pluginDataRoot, { recursive: true }); + const resolvedPluginDataRoot = await fs.promises.realpath(pluginDataRoot); + for (const server of Object.values(servers)) { + if ( + server.command && + server.cwd && + isPathWithin(resolvedPluginDataRoot, server.cwd) + ) { + await fs.promises.mkdir(server.cwd, { recursive: true }); + } + } + } catch (error) { + debugLogger.warn( + `Failed to create Agent Plugins data directory; disabling stdio MCP servers: ${error instanceof Error ? error.message : String(error)}`, + ); + for (const [name, server] of Object.entries(servers)) { + if (server.command) delete servers[name]; + } + } + } + return servers; +} + +export function validateAgentPluginStdioRuntimePaths( + server: MCPServerConfig, +): void { + if (!server.agentPluginV1 || !server.command) return; + const pluginRoot = server.env?.['PLUGIN_ROOT']; + const pluginDataRoot = server.env?.['PLUGIN_DATA']; + if (!pluginRoot || !pluginDataRoot) { + throw new Error('Agent Plugins stdio server is missing runtime roots.'); + } + + if (path.isAbsolute(server.command)) { + const command = resolveContainedExistingPath(pluginRoot, server.command); + if (!fs.statSync(command).isFile()) { + throw new Error('Agent Plugins stdio command must be a regular file.'); + } + } + + if (server.cwd) { + let cwd: string; + try { + cwd = resolveContainedExistingPath(pluginRoot, server.cwd); + } catch { + cwd = resolveContainedExistingPath(pluginDataRoot, server.cwd); + } + if (!fs.statSync(cwd).isDirectory()) { + throw new Error('Agent Plugins stdio cwd must be a directory.'); + } + } +} + +function validateMcpFile(value: unknown): asserts value is Record< + string, + unknown +> & { + mcpServers: Record; +} { + if (!isRecord(value)) { + throw new Error('Agent Plugins mcp.json must contain an object.'); + } + const unknown = Object.keys(value).filter( + (field) => field !== '$schema' && field !== 'mcpServers', + ); + if (unknown.length > 0) { + throw new Error(`Unknown Agent Plugins MCP field "${unknown[0]}".`); + } + if (value['$schema'] !== AGENT_PLUGIN_MCP_SCHEMA) { + throw new Error( + `Unsupported Agent Plugins MCP schema "${String(value['$schema'])}".`, + ); + } + if (!isRecord(value['mcpServers'])) { + throw new Error('Agent Plugins mcpServers must be an object.'); + } +} + +function normalizeServer( + value: unknown, + pluginRoot: string, + pluginDataRoot: string, +): MCPServerConfig { + if (!isRecord(value) || typeof value['type'] !== 'string') { + throw new Error('MCP server must be an object with a string type.'); + } + switch (value['type']) { + case 'stdio': + return normalizeStdioServer(value, pluginRoot, pluginDataRoot); + case 'streamable-http': + return normalizeHttpServer(value); + case 'sse': + throw new Error('Legacy SSE transport is not supported.'); + default: + throw new Error(`Unsupported MCP transport "${value['type']}".`); + } +} + +function normalizeStdioServer( + value: Record, + pluginRoot: string, + pluginDataRoot: string, +): MCPServerConfig { + assertOnlyFields(value, ['type', 'command', 'args', 'env', 'cwd']); + const commandValue = value['command']; + if (typeof commandValue !== 'string' || commandValue.length === 0) { + throw new Error('Stdio command must be a non-empty string.'); + } + + const args = value['args'] ?? []; + if (!Array.isArray(args) || args.some((arg) => typeof arg !== 'string')) { + throw new Error('Stdio args must be an array of strings.'); + } + const configuredEnv = value['env'] ?? {}; + if ( + !isRecord(configuredEnv) || + Object.values(configuredEnv).some((entry) => typeof entry !== 'string') + ) { + throw new Error('Stdio env values must be strings.'); + } + for (const key of Object.keys(configuredEnv)) { + if (reservedEnvironmentName(key)) { + throw new Error(`Stdio env cannot override reserved variable "${key}".`); + } + } + const cwdValue = value['cwd'] ?? '${PLUGIN_ROOT}'; + if (typeof cwdValue !== 'string') { + throw new Error('Stdio cwd must be a string.'); + } + + const pluginRootResolved = fs.realpathSync.native(pluginRoot); + const pluginDataResolved = resolveExistingPathPrefix(pluginDataRoot); + const rootString = pluginRootResolved; + const dataString = pluginDataResolved; + const command = normalizeCommand(commandValue, pluginRootResolved); + const expandedArgs = args.map((arg) => + expandPluginVariables(arg, rootString, dataString), + ); + const env = Object.fromEntries( + Object.entries(configuredEnv).map(([key, entry]) => [ + key, + expandPluginVariables(entry as string, rootString, dataString), + ]), + ); + env['PLUGIN_ROOT'] = rootString; + env['PLUGIN_DATA'] = dataString; + + return { + command, + args: expandedArgs, + env, + cwd: normalizeCwd( + cwdValue, + pluginRootResolved, + pluginDataResolved, + rootString, + dataString, + ), + agentPluginV1: true, + }; +} + +function normalizeCommand(command: string, pluginRoot: string): string { + const bare = + !command.includes('/') && + !command.includes('\\') && + path.win32.parse(command).root === ''; + if (bare) return command; + if (!command.startsWith('./') || command.includes('\\')) { + throw new Error( + 'Stdio command must be a bare executable name or a contained ./ path.', + ); + } + return resolveContainedPotentialPath( + pluginRoot, + path.resolve(pluginRoot, command.slice(2)), + ); +} + +function normalizeCwd( + cwd: string, + pluginRoot: string, + pluginDataRoot: string, + rootString: string, + dataString: string, +): string { + if (cwd.includes('\\')) { + throw new Error('Stdio cwd must use portable forward-slash paths.'); + } + let allowedRoot: string; + if (cwd === './' || cwd.startsWith('./')) { + allowedRoot = pluginRoot; + } else if (cwd === '${PLUGIN_ROOT}' || cwd.startsWith('${PLUGIN_ROOT}/')) { + allowedRoot = pluginRoot; + } else if (cwd === '${PLUGIN_DATA}' || cwd.startsWith('${PLUGIN_DATA}/')) { + allowedRoot = pluginDataRoot; + } else { + throw new Error( + 'Stdio cwd must be a contained ./, ${PLUGIN_ROOT}, or ${PLUGIN_DATA} path.', + ); + } + + const expanded = expandPluginVariables(cwd, rootString, dataString); + const resolvedAllowedRoot = resolveExistingPathPrefix(allowedRoot); + const resolved = resolveExistingPathPrefix( + path.isAbsolute(expanded) + ? expanded + : path.resolve(resolvedAllowedRoot, expanded), + ); + if (!isPathWithin(resolvedAllowedRoot, resolved)) { + throw new Error('Expanded stdio cwd escapes its allowed root.'); + } + return resolved; +} + +function normalizeHttpServer(value: Record): MCPServerConfig { + assertOnlyFields(value, ['type', 'url', 'headers']); + const rawUrl = value['url']; + if (typeof rawUrl !== 'string' || rawUrl.length === 0) { + throw new Error('Streamable HTTP url must be a non-empty string.'); + } + validateHttpUrl(rawUrl); + + const rawHeaders = value['headers']; + if (rawHeaders !== undefined && !isRecord(rawHeaders)) { + throw new Error('Streamable HTTP headers must be an object.'); + } + const headers = rawHeaders ? normalizeHeaders(rawHeaders) : undefined; + return { + httpUrl: rawUrl, + ...(headers && Object.keys(headers).length > 0 ? { headers } : {}), + agentPluginV1: true, + }; +} + +function validateHttpUrl(rawUrl: string): void { + let parsed: URL; + try { + parsed = new URL(rawUrl); + } catch (error) { + throw new Error( + `Invalid Streamable HTTP url: ${error instanceof Error ? error.message : String(error)}`, + ); + } + if ( + (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || + !parsed.hostname + ) { + throw new Error('Streamable HTTP url must be absolute HTTP or HTTPS.'); + } + if (parsed.username || parsed.password || parsed.hash) { + throw new Error( + 'Streamable HTTP url must not contain user information or a fragment.', + ); + } + if (parsed.protocol === 'http:' && !isLoopbackHost(parsed.hostname)) { + throw new Error('Non-loopback Streamable HTTP endpoints must use HTTPS.'); + } +} + +function isLoopbackHost(hostname: string): boolean { + const normalized = hostname.replace(/^\[|\]$/g, '').toLowerCase(); + if (normalized === 'localhost' || normalized === '::1') return true; + const ipv4 = normalized.split('.').map(Number); + return ( + ipv4.length === 4 && + ipv4.every( + (part, index) => + Number.isInteger(part) && + part >= 0 && + part <= 255 && + (index !== 0 || part === 127), + ) + ); +} + +function normalizeHeaders( + value: Record, +): Record { + const normalized: Record = {}; + const seen = new Set(); + for (const [name, rawValue] of Object.entries(value)) { + if (typeof rawValue !== 'string') { + throw new Error(`HTTP header "${name}" must have a string value.`); + } + const lowercaseName = name.toLowerCase(); + if (seen.has(lowercaseName)) { + throw new Error(`Duplicate case-insensitive HTTP header "${name}".`); + } + seen.add(lowercaseName); + if (!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(name)) { + throw new Error(`Invalid HTTP header name "${name}".`); + } + for (const character of rawValue) { + const code = character.charCodeAt(0); + if (code <= 8 || (code >= 10 && code <= 31) || code === 127) { + throw new Error(`Invalid HTTP header value for "${name}".`); + } + } + if (!CLIENT_OWNED_HEADERS.has(lowercaseName)) { + Object.defineProperty(normalized, name, { + value: rawValue, + enumerable: true, + configurable: true, + writable: true, + }); + } + } + return normalized; +} + +function assertOnlyFields( + value: Record, + fields: string[], +): void { + const allowed = new Set(fields); + const unknown = Object.keys(value).find((field) => !allowed.has(field)); + if (unknown) throw new Error(`Unknown MCP server field "${unknown}".`); +} + +function reservedEnvironmentName(name: string): boolean { + return process.platform === 'win32' + ? name.toUpperCase() === 'PLUGIN_ROOT' || + name.toUpperCase() === 'PLUGIN_DATA' + : name === 'PLUGIN_ROOT' || name === 'PLUGIN_DATA'; +} + +function expandPluginVariables( + value: string, + pluginRoot: string, + pluginData: string, +): string { + return value.replace(/\$\{PLUGIN_ROOT\}|\$\{PLUGIN_DATA\}/g, (match) => + match === '${PLUGIN_ROOT}' ? pluginRoot : pluginData, + ); +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} diff --git a/packages/core/src/extension/agent-plugins-v1/paths.ts b/packages/core/src/extension/agent-plugins-v1/paths.ts new file mode 100644 index 000000000000..54dcba0ee9b9 --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/paths.ts @@ -0,0 +1,64 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; + +export function isPathWithin(root: string, candidate: string): boolean { + const relative = path.relative(root, candidate); + return ( + relative === '' || + (!relative.startsWith(`..${path.sep}`) && + relative !== '..' && + !path.isAbsolute(relative)) + ); +} + +export function resolveContainedExistingPath( + root: string, + candidate: string, +): string { + const resolvedRoot = fs.realpathSync.native(root); + const resolvedCandidate = fs.realpathSync.native(candidate); + if (!isPathWithin(resolvedRoot, resolvedCandidate)) { + throw new Error( + `Path "${candidate}" resolves outside plugin root "${root}".`, + ); + } + return resolvedCandidate; +} + +export function resolveContainedPotentialPath( + root: string, + candidate: string, +): string { + const resolvedRoot = fs.realpathSync.native(root); + const resolvedCandidate = resolveExistingPathPrefix(path.resolve(candidate)); + if (!isPathWithin(resolvedRoot, resolvedCandidate)) { + throw new Error( + `Path "${candidate}" resolves outside plugin root "${root}".`, + ); + } + return resolvedCandidate; +} + +export function resolveExistingPathPrefix(candidate: string): string { + let current = path.resolve(candidate); + const missingSegments: string[] = []; + + while (true) { + try { + const resolved = fs.realpathSync.native(current); + return path.join(resolved, ...missingSegments); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + const parent = path.dirname(current); + if (parent === current) throw error; + missingSegments.unshift(path.basename(current)); + current = parent; + } + } +} diff --git a/packages/core/src/extension/agent-plugins-v1/skills.test.ts b/packages/core/src/extension/agent-plugins-v1/skills.test.ts new file mode 100644 index 000000000000..3f358a5c8b45 --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/skills.test.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { loadAgentPluginSkills, parseAgentPluginSkill } from './skills.js'; + +describe('Agent Plugins v1 skills', () => { + let pluginRoot: string; + + beforeEach(() => { + pluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-plugin-')); + }); + + afterEach(() => { + fs.rmSync(pluginRoot, { recursive: true, force: true }); + }); + + it('loads only valid direct-child Agent Skills', async () => { + writeSkill( + 'direct', + '---\nname: direct\ndescription: Direct skill\nallowed-tools: Read Bash(git:*)\n---\nDo work.', + ); + writeSkill( + 'bad-name', + '---\nname: mismatch\ndescription: Invalid\n---\nNo.', + ); + writeSkill( + path.join('container', 'nested'), + '---\nname: nested\ndescription: Nested\n---\nNo.', + ); + + const skills = await loadAgentPluginSkills(pluginRoot); + + expect(skills).toHaveLength(1); + expect(skills[0]).toMatchObject({ + name: 'direct', + description: 'Direct skill', + body: 'Do work.', + level: 'extension', + }); + expect(skills[0]?.allowedTools).toBeUndefined(); + }); + + it('validates standard metadata fields', () => { + const filePath = path.join(pluginRoot, 'skills', 'portable', 'SKILL.md'); + const valid = + '---\nname: portable\ndescription: Portable skill\nlicense: Apache-2.0\ncompatibility: Qwen Code\nmetadata:\n author: qwen\nallowed-tools: Read\n---\nBody'; + expect(parseAgentPluginSkill(valid, filePath)).toMatchObject({ + name: 'portable', + description: 'Portable skill', + }); + + expect(() => + parseAgentPluginSkill( + valid.replace('allowed-tools: Read', 'allowed-tools:\n - Read'), + filePath, + ), + ).toThrow('allowed-tools'); + }); + + it.runIf(process.platform !== 'win32')( + 'skips a skill whose manifest resolves outside the plugin', + async () => { + const outside = `${pluginRoot}-outside-skill.md`; + fs.writeFileSync( + outside, + '---\nname: escape\ndescription: Escape\n---\nNo.', + ); + const skillDir = path.join(pluginRoot, 'skills', 'escape'); + fs.mkdirSync(skillDir, { recursive: true }); + fs.symlinkSync(outside, path.join(skillDir, 'SKILL.md')); + + expect(await loadAgentPluginSkills(pluginRoot)).toEqual([]); + fs.rmSync(outside, { force: true }); + }, + ); + + function writeSkill(name: string, content: string): void { + const skillDir = path.join(pluginRoot, 'skills', name); + fs.mkdirSync(skillDir, { recursive: true }); + fs.writeFileSync(path.join(skillDir, 'SKILL.md'), content); + } +}); diff --git a/packages/core/src/extension/agent-plugins-v1/skills.ts b/packages/core/src/extension/agent-plugins-v1/skills.ts new file mode 100644 index 000000000000..8e850dce37b9 --- /dev/null +++ b/packages/core/src/extension/agent-plugins-v1/skills.ts @@ -0,0 +1,166 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { SkillConfig } from '../../skills/types.js'; +import { createDebugLogger } from '../../utils/debugLogger.js'; +import { normalizeContent } from '../../utils/textUtils.js'; +import { parse as parseYaml } from '../../utils/yaml-parser.js'; +import { resolveContainedExistingPath } from './paths.js'; + +const debugLogger = createDebugLogger('AGENT_PLUGINS_V1'); + +export async function loadAgentPluginSkills( + pluginRoot: string, +): Promise { + const skillsPath = path.join(pluginRoot, 'skills'); + let resolvedSkillsPath: string; + try { + resolvedSkillsPath = resolveContainedExistingPath(pluginRoot, skillsPath); + if (!fs.statSync(resolvedSkillsPath).isDirectory()) { + debugLogger.warn('Agent Plugins skills path is not a directory.'); + return []; + } + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; + debugLogger.warn( + `Disabling Agent Plugins skills: ${error instanceof Error ? error.message : String(error)}`, + ); + return []; + } + + let entries: fs.Dirent[]; + try { + entries = await fs.promises.readdir(resolvedSkillsPath, { + withFileTypes: true, + }); + } catch (error) { + debugLogger.warn( + `Disabling Agent Plugins skills: ${error instanceof Error ? error.message : String(error)}`, + ); + return []; + } + const skills: SkillConfig[] = []; + for (const entry of entries) { + const skillDir = path.join(resolvedSkillsPath, entry.name); + try { + const resolvedSkillDir = resolveContainedExistingPath( + pluginRoot, + skillDir, + ); + if (!fs.statSync(resolvedSkillDir).isDirectory()) continue; + const skillManifest = path.join(resolvedSkillDir, 'SKILL.md'); + const resolvedManifest = resolveContainedExistingPath( + pluginRoot, + skillManifest, + ); + if (!fs.statSync(resolvedManifest).isFile()) continue; + const content = await fs.promises.readFile(resolvedManifest, 'utf8'); + skills.push(parseAgentPluginSkill(content, resolvedManifest, entry.name)); + } catch (error) { + debugLogger.warn( + `Skipping Agent Plugins skill "${entry.name}": ${error instanceof Error ? error.message : String(error)}`, + ); + } + } + return skills; +} + +export function parseAgentPluginSkill( + content: string, + filePath: string, + directoryName = path.basename(path.dirname(filePath)), +): SkillConfig { + const normalized = normalizeContent(content); + const match = normalized.match(/^---\n([\s\S]*?)\n---(?:\n|$)([\s\S]*)$/); + if (!match) throw new Error('Missing YAML frontmatter.'); + const frontmatter = parseYaml(match[1]) as unknown; + if (!isRecord(frontmatter)) throw new Error('Frontmatter must be an object.'); + + const name = frontmatter['name']; + if ( + typeof name !== 'string' || + countCharacters(name) > 64 || + !/^(?!.*--)[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(name) + ) { + throw new Error('Invalid Agent Skills name.'); + } + if (name !== directoryName) { + throw new Error('Agent Skills name must match its parent directory.'); + } + + const description = frontmatter['description']; + if ( + typeof description !== 'string' || + description.length === 0 || + countCharacters(description) > 1024 + ) { + throw new Error('Agent Skills description must be 1-1024 characters.'); + } + validateOptionalString(frontmatter, 'license'); + validateCompatibility(frontmatter['compatibility']); + validateMetadata(frontmatter['metadata']); + validateAllowedTools(frontmatter['allowed-tools']); + + return { + name, + description, + filePath, + skillRoot: path.dirname(filePath), + body: match[2].trim(), + level: 'extension', + }; +} + +function validateOptionalString( + frontmatter: Record, + field: string, +): void { + if ( + frontmatter[field] !== undefined && + typeof frontmatter[field] !== 'string' + ) { + throw new Error(`Agent Skills ${field} must be a string.`); + } +} + +function validateCompatibility(value: unknown): void { + if (value === undefined) return; + if ( + typeof value !== 'string' || + value.length === 0 || + countCharacters(value) > 500 + ) { + throw new Error( + 'Agent Skills compatibility must be a 1-500 character string.', + ); + } +} + +function validateMetadata(value: unknown): void { + if (value === undefined) return; + if ( + !isRecord(value) || + Object.values(value).some((entry) => typeof entry !== 'string') + ) { + throw new Error('Agent Skills metadata values must be strings.'); + } +} + +function validateAllowedTools(value: unknown): void { + if (value !== undefined && typeof value !== 'string') { + throw new Error('Agent Skills allowed-tools must be a string.'); + } +} + +function countCharacters(value: string): number { + return Array.from(value).length; +} + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} diff --git a/packages/core/src/extension/extension-converter.test.ts b/packages/core/src/extension/extension-converter.test.ts new file mode 100644 index 000000000000..6a89c92e6f6f --- /dev/null +++ b/packages/core/src/extension/extension-converter.test.ts @@ -0,0 +1,168 @@ +/** + * @license + * Copyright 2026 Qwen Team + * SPDX-License-Identifier: Apache-2.0 + */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { convertCompatibleExtension } from './extension-converter.js'; +import { + AGENT_PLUGIN_SCHEMA, + AGENT_PLUGIN_SCHEMA_PREFIX, +} from './agent-plugins-v1/index.js'; + +describe('Agent Plugins extension conversion', () => { + let pluginRoot: string; + + beforeEach(() => { + pluginRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-plugin-')); + }); + + afterEach(() => { + fs.rmSync(pluginRoot, { recursive: true, force: true }); + }); + + it('selects a supported Agent Plugin without converting it', async () => { + const manifest = JSON.stringify({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'portable-plugin', + }); + fs.writeFileSync(path.join(pluginRoot, 'plugin.json'), manifest); + + await expect(convertCompatibleExtension(pluginRoot)).resolves.toEqual({ + extensionDir: pluginRoot, + originSource: 'AgentPlugins', + externalContent: false, + }); + expect(fs.readFileSync(path.join(pluginRoot, 'plugin.json'), 'utf8')).toBe( + manifest, + ); + expect(fs.existsSync(path.join(pluginRoot, 'qwen-extension.json'))).toBe( + false, + ); + }); + + it('gives an unsupported Agent Plugins schema priority over Qwen format', async () => { + fs.writeFileSync( + path.join(pluginRoot, 'plugin.json'), + JSON.stringify({ + $schema: `${AGENT_PLUGIN_SCHEMA_PREFIX}2.0.0/plugin.schema.json`, + name: 'future-plugin', + }), + ); + fs.writeFileSync( + path.join(pluginRoot, 'qwen-extension.json'), + JSON.stringify({ name: 'qwen-fallback', version: '1.0.0' }), + ); + + await expect(convertCompatibleExtension(pluginRoot)).rejects.toThrow( + 'Unsupported Agent Plugins schema', + ); + }); + + it('leaves an unrelated plugin.json out of format detection', async () => { + fs.writeFileSync( + path.join(pluginRoot, 'plugin.json'), + JSON.stringify({ $schema: 'https://example.com/plugin.schema.json' }), + ); + fs.writeFileSync( + path.join(pluginRoot, 'qwen-extension.json'), + JSON.stringify({ name: 'qwen-extension', version: '1.0.0' }), + ); + + await expect(convertCompatibleExtension(pluginRoot)).resolves.toEqual({ + extensionDir: pluginRoot, + originSource: 'QwenCode', + externalContent: false, + }); + }); + + it('honors an explicit marketplace selection over a root Agent Plugin manifest', async () => { + fs.writeFileSync( + path.join(pluginRoot, 'plugin.json'), + JSON.stringify({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'root-agent-plugin', + }), + ); + fs.mkdirSync(path.join(pluginRoot, '.claude-plugin'), { recursive: true }); + fs.writeFileSync( + path.join(pluginRoot, '.claude-plugin', 'marketplace.json'), + JSON.stringify({ + name: 'sample-marketplace', + owner: { name: 'Test Owner', email: 'owner@example.com' }, + plugins: [ + { + name: 'requested-plugin', + version: '2.0.0', + source: './plugin-src', + }, + ], + }), + ); + const selectedRoot = path.join(pluginRoot, 'plugin-src'); + fs.mkdirSync(path.join(selectedRoot, '.claude-plugin'), { + recursive: true, + }); + fs.writeFileSync( + path.join(selectedRoot, '.claude-plugin', 'plugin.json'), + JSON.stringify({ name: 'requested-plugin', version: '2.0.0' }), + ); + fs.writeFileSync( + path.join(selectedRoot, 'plugin.json'), + JSON.stringify({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'carried-agent-plugin', + }), + ); + + const selected = await convertCompatibleExtension( + pluginRoot, + 'requested-plugin', + ); + expect(selected.originSource).toBe('Claude'); + const selectedConfig = JSON.parse( + fs.readFileSync( + path.join(selected.extensionDir, 'qwen-extension.json'), + 'utf8', + ), + ) as Record; + expect(selectedConfig['name']).toBe('requested-plugin'); + expect(fs.existsSync(path.join(selected.extensionDir, 'plugin.json'))).toBe( + false, + ); + fs.rmSync(selected.extensionDir, { recursive: true, force: true }); + + fs.writeFileSync( + path.join(pluginRoot, 'plugin.json'), + JSON.stringify({ + $schema: `${AGENT_PLUGIN_SCHEMA_PREFIX}2.0.0/plugin.schema.json`, + name: 'future-root-agent-plugin', + }), + ); + fs.writeFileSync( + path.join(selectedRoot, 'plugin.json'), + JSON.stringify({ + $schema: `${AGENT_PLUGIN_SCHEMA_PREFIX}2.0.0/plugin.schema.json`, + name: 'future-carried-agent-plugin', + }), + ); + const selectedWithFutureRoot = await convertCompatibleExtension( + pluginRoot, + 'requested-plugin', + ); + expect(selectedWithFutureRoot.originSource).toBe('Claude'); + expect( + fs.existsSync( + path.join(selectedWithFutureRoot.extensionDir, 'plugin.json'), + ), + ).toBe(false); + fs.rmSync(selectedWithFutureRoot.extensionDir, { + recursive: true, + force: true, + }); + }); +}); diff --git a/packages/core/src/extension/extension-converter.ts b/packages/core/src/extension/extension-converter.ts index 2bc766b53986..c35e24776403 100644 --- a/packages/core/src/extension/extension-converter.ts +++ b/packages/core/src/extension/extension-converter.ts @@ -23,6 +23,11 @@ import type { ExtensionNetworkPolicy, ExtensionOriginSource, } from '../config/config.js'; +import { + AGENT_PLUGIN_MANIFEST, + AGENT_PLUGIN_SCHEMA, + getAgentPluginSchemaStatus, +} from './agent-plugins-v1/manifest.js'; export const SUPPORTED_EXTENSION_MANIFESTS = [ EXTENSIONS_CONFIG_FILENAME, @@ -46,11 +51,20 @@ export async function convertCompatibleExtension( let newExtensionDir = extensionDir; let originSource: ExtensionOriginSource = 'QwenCode'; let externalContent = false; + const agentPluginStatus = pluginName + ? 'unrelated' + : getAgentPluginSchemaStatus(extensionDir); const configFilePath = path.join( extensionDir, SUPPORTED_EXTENSION_MANIFESTS[0], ); - if (fs.existsSync(configFilePath)) { + if (agentPluginStatus === 'unsupported') { + throw new Error( + `Unsupported Agent Plugins schema. Supported schema: "${AGENT_PLUGIN_SCHEMA}".`, + ); + } else if (agentPluginStatus === 'supported') { + originSource = 'AgentPlugins'; + } else if (fs.existsSync(configFilePath)) { newExtensionDir = extensionDir; } else if (isGeminiExtensionConfig(extensionDir)) { newExtensionDir = (await convertGeminiExtensionPackage(extensionDir)) @@ -68,6 +82,11 @@ export async function convertCompatibleExtension( signal, ); newExtensionDir = converted.convertedDir; + if (getAgentPluginSchemaStatus(newExtensionDir) !== 'unrelated') { + fs.rmSync(path.join(newExtensionDir, AGENT_PLUGIN_MANIFEST), { + force: true, + }); + } originSource = 'Claude'; externalContent = converted.externalContent; } else if (fs.existsSync(path.join(extensionDir, QODER_PLUGIN_MANIFEST))) { diff --git a/packages/core/src/extension/extension-store.test.ts b/packages/core/src/extension/extension-store.test.ts index b9db82e2c105..624c2ad83d87 100644 --- a/packages/core/src/extension/extension-store.test.ts +++ b/packages/core/src/extension/extension-store.test.ts @@ -55,6 +55,18 @@ describe('ExtensionStore', () => { ); }; + it('derives a stable contained Agent Plugin data directory', () => { + const store = makeStore(); + const extensionId = 'a'.repeat(64); + + expect(store.agentPluginDataRoot(extensionId)).toBe( + path.join(storeDir, 'plugin-data', 'agent-plugins', extensionId), + ); + expect(() => store.agentPluginDataRoot('../escape')).toThrow( + 'Invalid extension id', + ); + }); + it('imports V1 rules without materializing workspace overrides', async () => { await fsp.writeFile( enablementPath, diff --git a/packages/core/src/extension/extension-store.ts b/packages/core/src/extension/extension-store.ts index e58c19de0959..4fe786580d33 100644 --- a/packages/core/src/extension/extension-store.ts +++ b/packages/core/src/extension/extension-store.ts @@ -245,6 +245,18 @@ export class ExtensionStore { this.lockPath = path.join(this.storeDir, 'lock'); } + agentPluginDataRoot(extensionId: string): string { + if (!/^[a-f0-9]{64}$/.test(extensionId)) { + throw new Error(`Invalid extension id "${extensionId}".`); + } + return path.join( + this.storeDir, + 'plugin-data', + 'agent-plugins', + extensionId, + ); + } + async ensureInitialized( extensions: readonly ExtensionIdentity[], ): Promise { diff --git a/packages/core/src/extension/extensionManager.test.ts b/packages/core/src/extension/extensionManager.test.ts index 477fa58b2abb..032d582a5864 100644 --- a/packages/core/src/extension/extensionManager.test.ts +++ b/packages/core/src/extension/extensionManager.test.ts @@ -30,6 +30,10 @@ import { import type { MCPServerConfig, ExtensionInstallMetadata } from '../index.js'; import { ExtensionStore } from './extension-store.js'; import { ExtensionPreferencesStore } from './extensionPreferences.js'; +import { + AGENT_PLUGIN_MCP_SCHEMA, + AGENT_PLUGIN_SCHEMA, +} from './agent-plugins-v1/index.js'; const mockGit = { clone: vi.fn(), @@ -139,6 +143,53 @@ function createExtension({ return extDir; } +function createAgentPlugin( + pluginRoot: string, + { + name = 'portable-plugin', + version, + }: { name?: string; version?: string } = {}, +): void { + fs.mkdirSync(path.join(pluginRoot, 'skills', 'direct'), { + recursive: true, + }); + fs.mkdirSync(path.join(pluginRoot, 'bin'), { recursive: true }); + fs.writeFileSync( + path.join(pluginRoot, 'plugin.json'), + JSON.stringify({ + $schema: AGENT_PLUGIN_SCHEMA, + name, + ...(version === undefined ? {} : { version }), + }), + ); + fs.writeFileSync( + path.join(pluginRoot, 'skills', 'direct', 'SKILL.md'), + '---\nname: direct\ndescription: Direct skill\nallowed-tools: Read\n---\nPortable instructions.', + ); + fs.writeFileSync(path.join(pluginRoot, 'bin', 'server'), 'portable server'); + fs.writeFileSync( + path.join(pluginRoot, 'mcp.json'), + JSON.stringify({ + $schema: AGENT_PLUGIN_MCP_SCHEMA, + mcpServers: { + local: { + type: 'stdio', + command: './bin/server', + args: ['${PLUGIN_ROOT}', '${PLUGIN_DATA}'], + }, + remote: { + type: 'streamable-http', + url: 'https://example.com/mcp', + }, + legacy: { + type: 'sse', + url: 'https://example.com/sse', + }, + }, + }), + ); +} + describe('extension tests', () => { let tempHomeDir: string; let tempWorkspaceDir: string; @@ -212,6 +263,273 @@ describe('extension tests', () => { ); } + it('installs an Agent Plugin without converting package files', async () => { + const sourcePath = path.join(tempWorkspaceDir, 'portable-source'); + createAgentPlugin(sourcePath); + for (const component of ['commands', 'agents', 'hooks']) { + fs.mkdirSync(path.join(sourcePath, component)); + fs.writeFileSync(path.join(sourcePath, component, 'ignored.md'), 'no'); + } + fs.writeFileSync(path.join(sourcePath, 'QWEN.md'), 'ignored context'); + const sourceContents = new Map( + [ + 'plugin.json', + 'mcp.json', + path.join('skills', 'direct', 'SKILL.md'), + path.join('bin', 'server'), + ].map((file) => [file, fs.readFileSync(path.join(sourcePath, file))]), + ); + const outside = path.join(tempWorkspaceDir, 'outside.txt'); + fs.writeFileSync(outside, 'outside'); + if (process.platform !== 'win32') { + fs.symlinkSync(outside, path.join(sourcePath, 'outside-link')); + } + + const requestConsent = vi.fn(async () => {}); + const manager = createExtensionManager(); + await manager.refreshCache(); + const extension = await manager.installExtension( + { type: 'local', source: sourcePath }, + requestConsent, + ); + + expect(extension.version).toBe('1.0.0'); + expect(extension.format).toBe('agent-plugins-v1'); + expect(extension.installMetadata?.originSource).toBe('AgentPlugins'); + expect(extension.skills?.map((skill) => skill.name)).toEqual(['direct']); + expect(extension.skills?.[0]?.allowedTools).toBeUndefined(); + expect(extension.commands).toEqual([]); + expect(extension.agents).toEqual([]); + expect(extension.contextFiles).toEqual([]); + expect(extension.hooks).toBeUndefined(); + expect(extension.settings).toBeUndefined(); + expect(extension.channels).toBeUndefined(); + expect(Object.keys(extension.mcpServers ?? {})).toEqual([ + 'local', + 'remote', + ]); + expect(extension.mcpServers?.['local']?.agentPluginV1).toBe(true); + expect(extension.mcpServers?.['remote']?.agentPluginV1).toBe(true); + expect(requestConsent).toHaveBeenCalledWith( + expect.objectContaining({ + originSource: 'AgentPlugins', + commands: [], + subagents: [], + skills: [expect.objectContaining({ name: 'direct' })], + }), + ); + + for (const [file, contents] of sourceContents) { + expect(fs.readFileSync(path.join(extension.path, file))).toEqual( + contents, + ); + } + expect( + fs.existsSync(path.join(extension.path, EXTENSIONS_CONFIG_FILENAME)), + ).toBe(false); + expect( + fs.existsSync(path.join(extension.path, INSTALL_METADATA_FILENAME)), + ).toBe(true); + if (process.platform !== 'win32') { + expect(fs.existsSync(path.join(extension.path, 'outside-link'))).toBe( + false, + ); + } + const pluginData = extension.mcpServers?.['local']?.env?.['PLUGIN_DATA']; + expect(pluginData).toBeDefined(); + expect(fs.statSync(pluginData!).isDirectory()).toBe(true); + }); + + it.runIf(process.platform !== 'win32')( + 'installs an Agent Plugin through a symlinked source root', + async () => { + const sourcePath = path.join(tempWorkspaceDir, 'portable-source-real'); + const symlinkPath = path.join(tempWorkspaceDir, 'portable-source-link'); + createAgentPlugin(sourcePath, { name: 'symlinked-plugin' }); + fs.symlinkSync(sourcePath, symlinkPath, 'dir'); + + const manager = createExtensionManager(); + await manager.refreshCache(); + const installed = await manager.installExtension( + { type: 'local', source: symlinkPath }, + async () => {}, + ); + + expect(installed.name).toBe('symlinked-plugin'); + expect(installed.installMetadata).toMatchObject({ + source: symlinkPath, + originSource: 'AgentPlugins', + }); + expect(fs.existsSync(path.join(installed.path, 'plugin.json'))).toBe( + true, + ); + }, + ); + + it('preserves Agent Plugin data across update and reinstall', async () => { + const sourcePath = path.join(tempWorkspaceDir, 'persistent-source'); + createAgentPlugin(sourcePath, { + name: 'persistent-plugin', + version: '1.0.0', + }); + const installMetadata = { type: 'local' as const, source: sourcePath }; + const manager = createExtensionManager(); + await manager.refreshCache(); + + const installed = await manager.installExtension( + installMetadata, + async () => {}, + ); + const pluginData = installed.mcpServers?.['local']?.env?.['PLUGIN_DATA']; + expect(pluginData).toBeDefined(); + fs.writeFileSync(path.join(pluginData!, 'state.txt'), 'persistent'); + + createAgentPlugin(sourcePath, { + name: 'persistent-plugin', + version: '1.0.1', + }); + const updated = await manager.installExtension( + installMetadata, + async () => {}, + undefined, + undefined, + installed.config, + ); + expect(updated.version).toBe('1.0.1'); + expect(updated.mcpServers?.['local']?.env?.['PLUGIN_DATA']).toBe( + pluginData, + ); + expect(fs.readFileSync(path.join(pluginData!, 'state.txt'), 'utf8')).toBe( + 'persistent', + ); + + await manager.uninstallExtensionById(updated.id, false); + const reinstalled = await manager.installExtension( + installMetadata, + async () => {}, + ); + expect(reinstalled.mcpServers?.['local']?.env?.['PLUGIN_DATA']).toBe( + pluginData, + ); + expect(fs.readFileSync(path.join(pluginData!, 'state.txt'), 'utf8')).toBe( + 'persistent', + ); + }); + + it('links an Agent Plugin and fingerprints its native manifest', async () => { + const sourcePath = path.join(tempWorkspaceDir, 'linked-source'); + createAgentPlugin(sourcePath, { + name: 'linked-plugin', + version: '1.0.0', + }); + const manager = createExtensionManager(); + await manager.refreshCache(); + + const linked = await manager.installExtension( + { type: 'link', source: sourcePath }, + async () => {}, + ); + expect(linked.path).toBe(sourcePath); + expect(linked.installMetadata).toMatchObject({ + type: 'link', + source: sourcePath, + originSource: 'AgentPlugins', + }); + expect(await manager.refreshCacheIfSourcesChanged()).toBe(true); + expect(await manager.refreshCacheIfSourcesChanged()).toBe(false); + + const manifest = JSON.parse( + fs.readFileSync(path.join(sourcePath, 'plugin.json'), 'utf8'), + ) as Record; + fs.writeFileSync( + path.join(sourcePath, 'plugin.json'), + JSON.stringify({ ...manifest, version: '1.0.1-longer' }), + ); + expect(await manager.refreshCacheIfSourcesChanged()).toBe(true); + expect(manager.getLoadedExtensions()[0]?.version).toBe('1.0.1-longer'); + const installedPath = path.join(userExtensionsDir, 'linked-plugin'); + expect(fs.readdirSync(installedPath)).toEqual([ + INSTALL_METADATA_FILENAME, + ]); + }); + + it.each([undefined, 42, ''])( + 'isolates link metadata with invalid source %s during refresh', + async (source) => { + const brokenLink = path.join(userExtensionsDir, 'broken-link'); + fs.mkdirSync(brokenLink, { recursive: true }); + fs.writeFileSync( + path.join(brokenLink, INSTALL_METADATA_FILENAME), + JSON.stringify({ type: 'link', source }), + ); + createAgentPlugin(path.join(userExtensionsDir, 'valid-plugin'), { + name: 'valid-plugin', + }); + + const manager = createExtensionManager(); + await expect(manager.refreshCache()).resolves.toBeUndefined(); + expect(manager.getLoadedExtensions().map(({ name }) => name)).toEqual([ + 'valid-plugin', + ]); + }, + ); + + it('installs an Agent Plugin from an archive', async () => { + const archivePath = path.join(tempWorkspaceDir, 'portable-plugin.zip'); + fs.writeFileSync(archivePath, 'synthetic archive'); + mockExtractArchiveFile.mockImplementation( + async (_source: string, destination: string) => { + createAgentPlugin(destination, { name: 'archived-plugin' }); + }, + ); + const manager = createExtensionManager(); + await manager.refreshCache(); + + const installed = await manager.installExtension( + { type: 'local', source: archivePath }, + async () => {}, + ); + + expect(installed.name).toBe('archived-plugin'); + expect(installed.installMetadata?.originSource).toBe('AgentPlugins'); + expect( + fs.existsSync(path.join(installed.path, 'qwen-extension.json')), + ).toBe(false); + }); + + it('installs an Agent Plugin from Git', async () => { + mockGit.clone.mockImplementation(async () => { + createAgentPlugin(mockGit.path(), { name: 'git-agent-plugin' }); + }); + mockGit.getRemotes.mockResolvedValue([ + { + name: 'origin', + refs: { fetch: 'https://github.com/example/portable-plugin' }, + }, + ]); + mockGit.fetch.mockResolvedValue(undefined); + mockGit.checkout.mockResolvedValue(undefined); + const manager = createExtensionManager(); + await manager.refreshCache(); + + const installed = await manager.installExtension( + { + type: 'git', + source: 'https://github.com/example/portable-plugin', + }, + async () => {}, + ); + + expect(installed.name).toBe('git-agent-plugin'); + expect(installed.installMetadata).toMatchObject({ + originSource: 'AgentPlugins', + gitCommit: 'sample-commit', + }); + expect( + fs.existsSync(path.join(installed.path, 'qwen-extension.json')), + ).toBe(false); + }); + it('installs and uninstalls within an injected extension store root', async () => { const archivePath = path.join(tempWorkspaceDir, 'custom-root.zip'); fs.writeFileSync(archivePath, 'archive'); @@ -957,6 +1275,13 @@ describe('extension tests', () => { path.join(pluginConfigDir, 'plugin.json'), JSON.stringify({ name: 'sample-plugin', version: '1.0.0' }), ); + fs.writeFileSync( + path.join(path.dirname(pluginConfigDir), 'plugin.json'), + JSON.stringify({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'carried-agent-plugin', + }), + ); }); mockGit.getRemotes.mockResolvedValue([ { @@ -979,9 +1304,13 @@ describe('extension tests', () => { ); expect(extension.name).toBe('sample-plugin'); + expect(extension.format).toBe('qwen'); expect(extension.installMetadata?.originSource).toBe('Claude'); expect(extension.installMetadata?.gitCommit).toBe('sample-commit'); expect(extension.installMetadata?.externalContent).toBe(false); + expect(fs.existsSync(path.join(extension.path, 'plugin.json'))).toBe( + false, + ); }); it('should drop the recorded commit when a marketplace plugin resolves from an external source', async () => { diff --git a/packages/core/src/extension/extensionManager.ts b/packages/core/src/extension/extensionManager.ts index a58dfa07815c..822777241fcc 100644 --- a/packages/core/src/extension/extensionManager.ts +++ b/packages/core/src/extension/extensionManager.ts @@ -106,9 +106,24 @@ import { type ExtensionStoreSnapshot, type InitialExtensionActivation, } from './extension-store.js'; +import { + AGENT_PLUGIN_MANIFEST, + getAgentPluginSchemaStatus, + loadAgentPluginManifest, + loadAgentPluginMcpServers, + loadAgentPluginSkills, +} from './agent-plugins-v1/index.js'; +import { resolveContainedExistingPath } from './agent-plugins-v1/paths.js'; const debugLogger = createDebugLogger('EXTENSIONS'); +export type ExtensionPackageFormat = 'qwen' | 'agent-plugins-v1'; + +interface LoadedExtensionManifest { + format: ExtensionPackageFormat; + config: ExtensionConfig; +} + // ============================================================================ // Types and Interfaces // ============================================================================ @@ -137,6 +152,7 @@ export interface Extension { isActive: boolean; path: string; config: ExtensionConfig; + format?: ExtensionPackageFormat; installMetadata?: ExtensionInstallMetadata; mcpServers?: Record; @@ -1135,9 +1151,9 @@ export class ExtensionManager { return snapshot; } - private static stampPath(target: string): string { + private static stampPath(target: string, followSymlinks = true): string { try { - const stats = fs.statSync(target); + const stats = followSymlinks ? fs.statSync(target) : fs.lstatSync(target); return `${stats.mtimeMs}:${stats.size}`; } catch { // Absent is a real state and must not collide with any present one — @@ -1155,10 +1171,11 @@ export class ExtensionManager { * A refresh never writes these paths, which is what makes it safe to commit * the pre-load value — see `refreshCacheWithSnapshot`. * - * Deliberately cheap: one `readdir` plus one `stat` per entry, where - * `refreshCache()` parses every manifest and re-lists every extension skill - * directory. That difference is what lets a status read stay self-healing - * without becoming a directory scan. + * Deliberately cheap: one `readdir`, one manifest `stat` per entry, and a + * sidecar read for linked entries, where `refreshCache()` parses every + * manifest and re-lists every extension skill directory. That difference is + * what lets a status read stay self-healing without becoming a directory + * scan. * * mtime-and-size is the usual stat-based approximation, so an edit that * preserves both is not detected. That is acceptable here: this is only the @@ -1174,8 +1191,33 @@ export class ExtensionManager { } const parts: string[] = []; for (const entry of entries) { + const extensionRoot = path.join(this.configDir, entry); + const installMetadata = this.loadInstallMetadata(extensionRoot); + const effectiveRoot = + installMetadata?.type === 'link' && + typeof installMetadata.source === 'string' && + installMetadata.source.length > 0 + ? installMetadata.source + : extensionRoot; + const manifestName = + getAgentPluginSchemaStatus(effectiveRoot) === 'unrelated' + ? EXTENSIONS_CONFIG_FILENAME + : AGENT_PLUGIN_MANIFEST; + let manifestPath = path.join(effectiveRoot, manifestName); + let followManifestSymlink = true; + if (manifestName === AGENT_PLUGIN_MANIFEST) { + try { + manifestPath = resolveContainedExistingPath( + effectiveRoot, + manifestPath, + ); + } catch { + followManifestSymlink = false; + } + } const stamp = ExtensionManager.stampPath( - path.join(this.configDir, entry, EXTENSIONS_CONFIG_FILENAME), + manifestPath, + followManifestSymlink, ); // Entries with no manifest are not extensions — notably the enablement // file, which lives in this directory and is created lazily by the store. @@ -1336,20 +1378,37 @@ export class ExtensionManager { const installMetadata = this.loadInstallMetadata(extensionDir); let effectiveExtensionPath = extensionDir; - if (installMetadata?.type === 'link') { + if ( + installMetadata?.type === 'link' && + typeof installMetadata.source === 'string' && + installMetadata.source.length > 0 + ) { effectiveExtensionPath = installMetadata.source; } try { - let config = this.loadExtensionConfig({ + const loadedManifest = this.loadExtensionManifest({ extensionDir: effectiveExtensionPath, workspaceDir, }); - - config = resolveEnvVarsInObject(config); + let config = loadedManifest.config; + if (loadedManifest.format === 'qwen') { + config = resolveEnvVarsInObject(config); + } + const extensionId = getExtensionId(config, installMetadata); + if (loadedManifest.format === 'agent-plugins-v1') { + config = { + ...config, + mcpServers: await loadAgentPluginMcpServers( + effectiveExtensionPath, + this.extensionStore.agentPluginDataRoot(extensionId), + { createDataDir: true }, + ), + }; + } const extension: Extension = { - id: getExtensionId(config, installMetadata), + id: extensionId, name: config.name, displayName: config.displayName, version: @@ -1357,6 +1416,7 @@ export class ExtensionManager { installMetadata?.marketplaceConfig?.metadata?.version || '1.0.0', path: effectiveExtensionPath, + format: loadedManifest.format, installMetadata, isActive: this.isEnabled(config.name, this.workspaceDir), config, @@ -1373,28 +1433,36 @@ export class ExtensionManager { ); } - if (config.channels) { + if (loadedManifest.format === 'qwen' && config.channels) { extension.channels = config.channels; } - extension.commands = await loadCommandsFromDir( - `${effectiveExtensionPath}/commands`, - ); - - extension.contextFiles = getContextFileNames(config) - .map((contextFileName) => - path.join(effectiveExtensionPath, contextFileName), - ) - .filter((contextFilePath) => fs.existsSync(contextFilePath)); - - extension.skills = await loadSkillsFromDir( - `${effectiveExtensionPath}/skills`, - ); - extension.agents = await loadSubagentFromDir( - `${effectiveExtensionPath}/agents`, - ); + if (loadedManifest.format === 'agent-plugins-v1') { + extension.commands = []; + extension.skills = await loadAgentPluginSkills(effectiveExtensionPath); + extension.agents = []; + } else { + extension.commands = await loadCommandsFromDir( + `${effectiveExtensionPath}/commands`, + ); + extension.contextFiles = getContextFileNames(config) + .map((contextFileName) => + path.join(effectiveExtensionPath, contextFileName), + ) + .filter((contextFilePath) => fs.existsSync(contextFilePath)); + extension.skills = await loadSkillsFromDir( + `${effectiveExtensionPath}/skills`, + ); + extension.agents = await loadSubagentFromDir( + `${effectiveExtensionPath}/agents`, + ); + } - if (config.hooks && typeof config.hooks !== 'string') { + if ( + loadedManifest.format === 'qwen' && + config.hooks && + typeof config.hooks !== 'string' + ) { // Process the hooks to substitute variables like ${CLAUDE_PLUGIN_ROOT} extension.hooks = this.substituteHookVariables( config.hooks, @@ -1403,7 +1471,7 @@ export class ExtensionManager { } // Also load hooks from hooks directory or from config.hooks string path if available and not already set - if (!extension.hooks) { + if (loadedManifest.format === 'qwen' && !extension.hooks) { const hooksDir = path.join(effectiveExtensionPath, 'hooks'); const hooksJsonPath = path.join(hooksDir, 'hooks.json'); @@ -1488,7 +1556,27 @@ export class ExtensionManager { } loadExtensionConfig(context: LoadExtensionContext): ExtensionConfig { + return this.loadExtensionManifest(context).config; + } + + private loadExtensionManifest( + context: LoadExtensionContext, + ): LoadedExtensionManifest { const { extensionDir, workspaceDir = this.workspaceDir } = context; + const agentPluginStatus = getAgentPluginSchemaStatus(extensionDir); + if (agentPluginStatus !== 'unrelated') { + try { + return { + format: 'agent-plugins-v1', + config: loadAgentPluginManifest(extensionDir), + }; + } catch (error) { + throw new Error( + `Failed to load Agent Plugins manifest from ${path.join(extensionDir, 'plugin.json')}: ${getErrorMessage(error)}`, + ); + } + } + const configFilePath = path.join(extensionDir, EXTENSIONS_CONFIG_FILENAME); if (!fs.existsSync(configFilePath)) { throw new Error(`Configuration file not found at ${configFilePath}`); @@ -1512,7 +1600,7 @@ export class ExtensionManager { } validateName(config.name); validateExtensionSettingEnvVars(config.settings); - return config; + return { format: 'qwen', config }; } catch (e) { throw new Error( `Failed to load extension config from ${configFilePath}: ${getErrorMessage( @@ -1849,6 +1937,17 @@ export class ExtensionManager { extensionDir: localSourcePath, workspaceDir: currentDir, }); + const isAgentPlugin = originSource === 'AgentPlugins'; + const extensionId = getExtensionId(newExtensionConfig, installMetadata); + if (isAgentPlugin) { + newExtensionConfig = { + ...newExtensionConfig, + mcpServers: await loadAgentPluginMcpServers( + localSourcePath, + this.extensionStore.agentPluginDataRoot(extensionId), + ), + }; + } if (isUpdate && installMetadata.autoUpdate) { const oldSettings = new Set( @@ -1884,17 +1983,19 @@ export class ExtensionManager { ); } - const commands = await loadCommandsFromDir( - `${localSourcePath}/commands`, - ); + const commands = isAgentPlugin + ? [] + : await loadCommandsFromDir(`${localSourcePath}/commands`); const previousCommands = previous?.commands ?? []; - const skills = await loadSkillsFromDir(`${localSourcePath}/skills`); + const skills = isAgentPlugin + ? await loadAgentPluginSkills(localSourcePath) + : await loadSkillsFromDir(`${localSourcePath}/skills`); const previousSkills = previous?.skills ?? []; - const subagents = await loadSubagentFromDir( - `${localSourcePath}/agents`, - ); + const subagents = isAgentPlugin + ? [] + : await loadSubagentFromDir(`${localSourcePath}/agents`); const previousSubagents = previous?.agents ?? []; if (requestConsent) { @@ -1924,7 +2025,6 @@ export class ExtensionManager { } const destinationPath = path.join(this.configDir, newExtensionName); - const extensionId = getExtensionId(newExtensionConfig, installMetadata); if (isUpdate && previous?.id !== extensionId) { throw new Error( `Extension "${newExtensionName}" changed its stable id during update.`, @@ -1940,7 +2040,9 @@ export class ExtensionManager { stagingPath = await this.extensionStore.createStagingDirectory(); if (installMetadata.type !== 'link') { - await copyExtension(localSourcePath, stagingPath); + await copyExtension(localSourcePath, stagingPath, { + skipSymlinks: isAgentPlugin, + }); } if (isUpdate) { @@ -2737,13 +2839,20 @@ export class ExtensionManager { export async function copyExtension( source: string, destination: string, + options: { skipSymlinks?: boolean } = {}, ): Promise { - await fs.promises.cp(source, destination, { + const copySource = options.skipSymlinks + ? await fs.promises.realpath(source) + : source; + await fs.promises.cp(copySource, destination, { recursive: true, - dereference: true, + dereference: !options.skipSymlinks, filter: async (src: string) => { try { - const stats = await fs.promises.stat(src); + const stats = options.skipSymlinks + ? await fs.promises.lstat(src) + : await fs.promises.stat(src); + if (options.skipSymlinks && stats.isSymbolicLink()) return false; // Only copy regular files and directories // Skip sockets, FIFOs, block devices, and character devices return stats.isFile() || stats.isDirectory(); diff --git a/packages/core/src/extension/github.test.ts b/packages/core/src/extension/github.test.ts index a214dce0c9a0..d33257833547 100644 --- a/packages/core/src/extension/github.test.ts +++ b/packages/core/src/extension/github.test.ts @@ -39,6 +39,7 @@ import { EXTENSIONS_CONFIG_FILENAME } from './variables.js'; import { QODER_PLUGIN_MANIFEST } from './qoder-converter.js'; import { ExtensionStorage } from './storage.js'; import { assertTarArchiveHasNoLinks } from './archive-safety.js'; +import { AGENT_PLUGIN_SCHEMA } from './agent-plugins-v1/index.js'; const mockPlatform = vi.hoisted(() => vi.fn()); const mockArch = vi.hoisted(() => vi.fn()); @@ -2047,6 +2048,30 @@ describe('git extension helpers', () => { ).resolves.toBe('# System context'); }); + it('should extract and flatten a wrapped Agent Plugin archive', async () => { + const archivePath = path.join(tempDir, 'wrapped-agent-plugin.zip'); + const manifest = JSON.stringify({ + $schema: AGENT_PLUGIN_SCHEMA, + name: 'portable-plugin', + }); + const skill = + '---\nname: direct\ndescription: Direct skill\n---\nPortable instructions.'; + const archive = await createZipBuffer(tempDir, [ + { name: 'wrapped/plugin.json', content: manifest }, + { name: 'wrapped/skills/direct/SKILL.md', content: skill }, + ]); + await fs.writeFile(archivePath, archive); + + await extractArchiveFile(archivePath, tempDir); + + await expect( + fs.readFile(path.join(tempDir, 'plugin.json'), 'utf8'), + ).resolves.toBe(manifest); + await expect( + fs.readFile(path.join(tempDir, 'skills', 'direct', 'SKILL.md'), 'utf8'), + ).resolves.toBe(skill); + }); + it('should flatten wrapped archives when the archive file is in the destination', async () => { const archivePath = path.join(tempDir, 'downloaded-extension.zip'); const archiveBuildDir = path.join(tempDir, 'archive-build'); diff --git a/packages/core/src/extension/github.ts b/packages/core/src/extension/github.ts index 1b1045d1249a..0fe26bae59ca 100644 --- a/packages/core/src/extension/github.ts +++ b/packages/core/src/extension/github.ts @@ -26,6 +26,10 @@ import { convertCompatibleExtension, SUPPORTED_EXTENSION_MANIFESTS, } from './extension-converter.js'; +import { + AGENT_PLUGIN_MANIFEST, + getAgentPluginSchemaStatus, +} from './agent-plugins-v1/manifest.js'; import { assertTarArchiveHasNoLinks } from './archive-safety.js'; import { resolveNetworkTarget } from './network-policy.js'; import { extractZipArchive } from './zip-extraction.js'; @@ -1081,12 +1085,18 @@ async function flattenSingleExtensionDirectory( } function getSupportedManifestList(): string { - return SUPPORTED_EXTENSION_MANIFESTS.join(', '); + return [ + ...SUPPORTED_EXTENSION_MANIFESTS, + `${AGENT_PLUGIN_MANIFEST} (Agent Plugins)`, + ].join(', '); } function hasSupportedExtensionSourceManifest(rootPath: string): boolean { - return SUPPORTED_EXTENSION_MANIFESTS.some((manifestPath) => - fs.existsSync(path.join(rootPath, manifestPath)), + return ( + getAgentPluginSchemaStatus(rootPath) !== 'unrelated' || + SUPPORTED_EXTENSION_MANIFESTS.some((manifestPath) => + fs.existsSync(path.join(rootPath, manifestPath)), + ) ); } diff --git a/packages/core/src/tools/mcp-client.test.ts b/packages/core/src/tools/mcp-client.test.ts index 3be07a12135d..5b25da5da981 100644 --- a/packages/core/src/tools/mcp-client.test.ts +++ b/packages/core/src/tools/mcp-client.test.ts @@ -2469,6 +2469,71 @@ lOTTGqPpwFUbw2EMOOpFYuIyzGMIpUNMBjE2gvJiqFQ= expect(fetchSpy).toHaveBeenCalledTimes(1); }); + it('stops Agent Plugin redirects when headers or authorization are present', async () => { + const fetchFn = vi + .fn() + .mockResolvedValue(new Response(null, { status: 204 })); + const configuredHeadersFetch = createStreamableHttpCompatibilityFetch( + 'configured-headers', + fetchFn, + { + httpUrl: 'https://example.com/mcp', + headers: { 'X-Tenant': 'portable' }, + agentPluginV1: true, + }, + ); + const authorizationFetch = createStreamableHttpCompatibilityFetch( + 'authorization', + fetchFn, + { + httpUrl: 'https://example.com/mcp', + agentPluginV1: true, + }, + ); + const ordinaryFetch = createStreamableHttpCompatibilityFetch( + 'ordinary', + fetchFn, + { httpUrl: 'https://example.com/mcp' }, + ); + const requestAuthorizationFetch = + createStreamableHttpCompatibilityFetch( + 'request-authorization', + fetchFn, + { + httpUrl: 'https://example.com/mcp', + agentPluginV1: true, + }, + ); + + await configuredHeadersFetch('https://example.com/mcp', { + method: 'POST', + }); + await authorizationFetch('https://example.com/mcp', { + method: 'POST', + headers: { Authorization: 'Bearer token' }, + }); + await ordinaryFetch('https://example.com/mcp', { method: 'POST' }); + await requestAuthorizationFetch( + new Request('https://example.com/mcp', { + method: 'POST', + headers: { Authorization: 'Bearer token' }, + }), + ); + + expect(fetchFn.mock.calls[0]?.[1]).toMatchObject({ + method: 'POST', + redirect: 'manual', + }); + expect(fetchFn.mock.calls[1]?.[1]).toMatchObject({ + method: 'POST', + redirect: 'manual', + }); + expect(fetchFn.mock.calls[2]?.[1]).toEqual({ method: 'POST' }); + expect(fetchFn.mock.calls[3]?.[1]).toMatchObject({ + redirect: 'manual', + }); + }); + it('treats 400 from optional GET SSE stream as unsupported', async () => { const fetchFn = vi .fn() diff --git a/packages/core/src/tools/mcp-client.ts b/packages/core/src/tools/mcp-client.ts index 7beaa1dd05cd..2a6326b1455e 100644 --- a/packages/core/src/tools/mcp-client.ts +++ b/packages/core/src/tools/mcp-client.ts @@ -28,6 +28,7 @@ import { import { parse } from 'shell-quote'; import type { Config, MCPServerConfig } from '../config/config.js'; import { AuthProviderType, isSdkMcpServerConfig } from '../config/config.js'; +import { validateAgentPluginStdioRuntimePaths } from '../extension/agent-plugins-v1/mcp.js'; import { GoogleCredentialProvider } from '../mcp/google-auth-provider.js'; import { ServiceAccountImpersonationProvider } from '../mcp/sa-impersonation-provider.js'; import { DiscoveredMCPTool } from './mcp-tool.js'; @@ -232,7 +233,18 @@ export function createStreamableHttpCompatibilityFetch( mcpServerConfig?: MCPServerConfig, ): typeof fetch { return async (input, init) => { - const response = await fetchFn(input, init); + const requestHeaders = new Headers( + init?.headers ?? (input instanceof Request ? input.headers : undefined), + ); + const stopAgentPluginRedirect = + mcpServerConfig?.agentPluginV1 === true && + ((mcpServerConfig.headers !== undefined && + Object.keys(mcpServerConfig.headers).length > 0) || + requestHeaders.has('authorization')); + const effectiveInit = stopAgentPluginRedirect + ? { ...init, redirect: 'manual' as const } + : init; + const response = await fetchFn(input, effectiveInit); if ( response.status === 401 && mcpServerConfig && @@ -245,7 +257,7 @@ export function createStreamableHttpCompatibilityFetch( ); } if ( - !isStreamableHttpGetSseRequest(init) || + !isStreamableHttpGetSseRequest(effectiveInit) || !STREAMABLE_HTTP_GET_SSE_FALLBACK_STATUSES.has(response.status) ) { return response; @@ -2228,6 +2240,7 @@ export async function createTransport( } if (mcpServerConfig.command) { + validateAgentPluginStdioRuntimePaths(mcpServerConfig); if (mcpServerConfig.cwd && !existsSync(mcpServerConfig.cwd)) { throw new Error( `MCP server '${mcpServerName}': configured cwd does not exist: ${mcpServerConfig.cwd}`, diff --git a/packages/sdk-typescript/src/daemon/types.ts b/packages/sdk-typescript/src/daemon/types.ts index 5032dfde3882..39c80bccde79 100644 --- a/packages/sdk-typescript/src/daemon/types.ts +++ b/packages/sdk-typescript/src/daemon/types.ts @@ -3921,7 +3921,8 @@ export type DaemonExtensionOriginSource = | 'QwenCode' | 'Claude' | 'Gemini' - | 'Qoder'; + | 'Qoder' + | 'AgentPlugins'; export interface DaemonExtensionCapabilities { mcpServerCount: number;