-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin-manager.js
More file actions
298 lines (251 loc) · 7.73 KB
/
plugin-manager.js
File metadata and controls
298 lines (251 loc) · 7.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env node
/**
* Plugin Manager for Copilot CLI MCP Proxy
*
* Manages plugin installation, loading, and execution
* Plugins can extend Copilot CLI functionality via MCP tools
*/
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
class PluginManager {
constructor(pluginDir = path.join(process.env.HOME, '.copilot', 'plugins')) {
this.pluginDir = pluginDir;
this.metadataFile = path.join(pluginDir, 'plugins.json');
this.loadedPlugins = new Map();
// Ensure plugin directory exists
if (!fs.existsSync(this.pluginDir)) {
fs.mkdirSync(this.pluginDir, { recursive: true });
}
// Ensure metadata file exists
if (!fs.existsSync(this.metadataFile)) {
this.saveMetadata({ plugins: {} });
}
}
/**
* Load plugin metadata
*/
loadMetadata() {
try {
const data = fs.readFileSync(this.metadataFile, 'utf8');
return JSON.parse(data);
} catch (error) {
return { plugins: {} };
}
}
/**
* Save plugin metadata
*/
saveMetadata(metadata) {
fs.writeFileSync(this.metadataFile, JSON.stringify(metadata, null, 2));
}
/**
* List all installed plugins
*/
listPlugins() {
const metadata = this.loadMetadata();
return Object.entries(metadata.plugins).map(([name, info]) => ({
name,
...info
}));
}
/**
* Install a plugin from GitHub
* @param {string} spec - Plugin spec: @owner/repo or @owner/repo/subpath
*/
async installPlugin(spec) {
// Parse spec: @owner/repo or @owner/repo/subpath
const match = spec.match(/^@([^/]+)\/([^/]+)(?:\/(.+))?$/);
if (!match) {
throw new Error(`Invalid plugin spec: ${spec}. Use @owner/repo or @owner/repo/subpath`);
}
const [, owner, repo, subpath] = match;
const pluginName = subpath ? `${owner}-${repo}-${subpath.replace(/\//g, '-')}` : `${owner}-${repo}`;
const pluginPath = path.join(this.pluginDir, pluginName);
// Check if already installed
const metadata = this.loadMetadata();
if (metadata.plugins[pluginName]) {
throw new Error(`Plugin ${pluginName} already installed`);
}
// Clone repository
const repoUrl = `https://github.com/${owner}/${repo}.git`;
const tempDir = path.join(this.pluginDir, `_temp_${Date.now()}`);
try {
console.error(`📦 Cloning ${owner}/${repo}...`);
execSync(`git clone --depth 1 ${repoUrl} "${tempDir}"`, {
stdio: 'pipe',
cwd: this.pluginDir
});
// Move subpath or entire repo to plugin directory
const sourceDir = subpath ? path.join(tempDir, subpath) : tempDir;
if (!fs.existsSync(sourceDir)) {
throw new Error(`Subpath ${subpath} not found in repository`);
}
fs.renameSync(sourceDir, pluginPath);
// Clean up temp directory
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
// Load plugin manifest
const manifestPath = path.join(pluginPath, 'plugin.json');
if (!fs.existsSync(manifestPath)) {
throw new Error('Plugin manifest (plugin.json) not found');
}
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
// Install dependencies if package.json exists
const packageJsonPath = path.join(pluginPath, 'package.json');
if (fs.existsSync(packageJsonPath)) {
console.error(`📦 Installing dependencies...`);
execSync('npm install --production', {
stdio: 'pipe',
cwd: pluginPath
});
}
// Update metadata
metadata.plugins[pluginName] = {
spec,
version: manifest.version || '1.0.0',
enabled: true,
installedAt: new Date().toISOString(),
manifest
};
this.saveMetadata(metadata);
return {
success: true,
name: pluginName,
version: manifest.version || '1.0.0',
description: manifest.description || 'No description'
};
} catch (error) {
// Clean up on failure
if (fs.existsSync(pluginPath)) {
fs.rmSync(pluginPath, { recursive: true, force: true });
}
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
throw error;
}
}
/**
* Uninstall a plugin
*/
uninstallPlugin(name) {
const metadata = this.loadMetadata();
if (!metadata.plugins[name]) {
throw new Error(`Plugin ${name} not found`);
}
const pluginPath = path.join(this.pluginDir, name);
if (fs.existsSync(pluginPath)) {
fs.rmSync(pluginPath, { recursive: true, force: true });
}
delete metadata.plugins[name];
this.saveMetadata(metadata);
return { success: true, name };
}
/**
* Enable a plugin
*/
enablePlugin(name) {
const metadata = this.loadMetadata();
if (!metadata.plugins[name]) {
throw new Error(`Plugin ${name} not found`);
}
metadata.plugins[name].enabled = true;
this.saveMetadata(metadata);
return { success: true, name, enabled: true };
}
/**
* Disable a plugin
*/
disablePlugin(name) {
const metadata = this.loadMetadata();
if (!metadata.plugins[name]) {
throw new Error(`Plugin ${name} not found`);
}
metadata.plugins[name].enabled = false;
this.saveMetadata(metadata);
return { success: true, name, enabled: false };
}
/**
* Load all enabled plugins
*/
loadPlugins() {
const metadata = this.loadMetadata();
const enabledPlugins = Object.entries(metadata.plugins)
.filter(([, info]) => info.enabled);
for (const [name, info] of enabledPlugins) {
try {
const pluginPath = path.join(this.pluginDir, name);
const indexPath = path.join(pluginPath, 'index.js');
if (!fs.existsSync(indexPath)) {
console.error(`⚠️ Plugin ${name}: index.js not found`);
continue;
}
// Load plugin module
delete require.cache[require.resolve(indexPath)]; // Clear cache
const plugin = require(indexPath);
this.loadedPlugins.set(name, {
module: plugin,
manifest: info.manifest
});
console.error(`✅ Loaded plugin: ${name}`);
} catch (error) {
console.error(`❌ Failed to load plugin ${name}:`, error.message);
}
}
return this.loadedPlugins.size;
}
/**
* Get tools from all loaded plugins
*/
getPluginTools() {
const tools = [];
for (const [name, { module, manifest }] of this.loadedPlugins) {
if (typeof module.getTools === 'function') {
try {
const pluginTools = module.getTools();
for (const tool of pluginTools) {
tools.push({
...tool,
name: `${manifest.namespace || name}_${tool.name}`,
pluginName: name
});
}
} catch (error) {
console.error(`❌ Failed to get tools from ${name}:`, error.message);
}
}
}
return tools;
}
/**
* Execute a plugin tool
*/
async executePluginTool(toolName, args) {
// Find plugin that owns this tool
for (const [name, { module }] of this.loadedPlugins) {
if (toolName.startsWith(name) || toolName.startsWith(module.manifest?.namespace)) {
if (typeof module.executeTool === 'function') {
return await module.executeTool(toolName, args);
}
}
}
throw new Error(`No plugin found to handle tool: ${toolName}`);
}
/**
* Get plugin info
*/
getPluginInfo(name) {
const metadata = this.loadMetadata();
const info = metadata.plugins[name];
if (!info) {
throw new Error(`Plugin ${name} not found`);
}
return {
name,
...info
};
}
}
module.exports = PluginManager;