-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextensionManager.js
More file actions
355 lines (303 loc) · 12.2 KB
/
extensionManager.js
File metadata and controls
355 lines (303 loc) · 12.2 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**
* guIDE — Extension Manager
*
* Manages community extensions: install, uninstall, enable, disable.
* Extensions live in <userData>/extensions/ as folders with manifest.json.
* State (enabled/disabled) persisted in <userData>/extensions.json.
*
* Extension Format:
* <extensionDir>/<extension-id>/
* manifest.json — { id, name, version, description, author, category, icon, main, homepage, repository }
* main.js — entry point (not executed yet — future feature)
* icon.png — optional icon
* README.md — optional readme
*/
'use strict';
const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');
const { EventEmitter } = require('events');
const log = require('./logger');
const MANIFEST_REQUIRED_FIELDS = ['id', 'name', 'version'];
class ExtensionManager extends EventEmitter {
constructor(userDataPath) {
super();
this.userDataPath = userDataPath;
this.extensionsDir = path.join(userDataPath, 'extensions');
this.statePath = path.join(userDataPath, 'extensions.json');
this.extensions = []; // { ...manifest, enabled, path, builtin }
this._state = {}; // { [id]: { enabled: bool } }
}
/* ── Lifecycle ─────────────────────────────────────────────────── */
async initialize() {
try { await fs.mkdir(this.extensionsDir, { recursive: true }); } catch {}
await this._loadState();
await this.scanExtensions();
log.info(`[ExtensionManager] Initialized — ${this.extensions.length} extensions found`);
return this.extensions;
}
/* ── Scanning ──────────────────────────────────────────────────── */
async scanExtensions() {
this.extensions = [];
// Scan user extensions directory
await this._scanDir(this.extensionsDir, false);
this.emit('extensions-updated', this.extensions);
return this.extensions;
}
async _scanDir(dir, builtin) {
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
if (!entry.isDirectory()) continue;
const extPath = path.join(dir, entry.name);
const manifestPath = path.join(extPath, 'manifest.json');
try {
const raw = await fs.readFile(manifestPath, 'utf8');
const manifest = JSON.parse(raw);
// Validate required fields
const missing = MANIFEST_REQUIRED_FIELDS.filter(f => !manifest[f]);
if (missing.length > 0) {
log.warn(`[ExtensionManager] Skipping ${entry.name}: missing fields: ${missing.join(', ')}`);
continue;
}
// Sanitize ID — must be lowercase alphanumeric with hyphens
const id = manifest.id.replace(/[^a-z0-9-]/gi, '-').toLowerCase();
const state = this._state[id] || { enabled: true };
this.extensions.push({
id,
name: manifest.name || id,
version: manifest.version || '0.0.0',
description: manifest.description || '',
author: manifest.author || 'Unknown',
category: manifest.category || 'other',
icon: manifest.icon || null,
main: manifest.main || null,
homepage: manifest.homepage || null,
repository: manifest.repository || null,
enabled: state.enabled,
path: extPath,
builtin: !!builtin,
// Runtime hooks — extensions declare tools and panels in manifest
tools: manifest.tools || [], // [{name, description, handler}]
panels: manifest.panels || [], // [{id, title, icon, component}]
chatHooks: manifest.chatHooks || [], // [{event, handler}] — pre/post generation
});
} catch (err) {
log.warn(`[ExtensionManager] Failed to read manifest for ${entry.name}: ${err.message}`);
}
}
}
/* ── Install / Uninstall ──────────────────────────────────────── */
/**
* Install an extension from an extracted directory.
* Expects `srcDir` to contain a manifest.json.
*/
async installFromDir(srcDir) {
const manifestPath = path.join(srcDir, 'manifest.json');
const raw = await fs.readFile(manifestPath, 'utf8');
const manifest = JSON.parse(raw);
const missing = MANIFEST_REQUIRED_FIELDS.filter(f => !manifest[f]);
if (missing.length > 0) {
throw new Error(`Invalid extension: missing ${missing.join(', ')}`);
}
const id = manifest.id.replace(/[^a-z0-9-]/gi, '-').toLowerCase();
const targetDir = path.join(this.extensionsDir, id);
// Remove existing version if present
try { await fs.rm(targetDir, { recursive: true, force: true }); } catch {}
// Copy extension directory
await this._copyDir(srcDir, targetDir);
// Enable by default
this._state[id] = { enabled: true };
await this._saveState();
await this.scanExtensions();
return { id, name: manifest.name };
}
/**
* Install extension from an uploaded zip buffer.
* Extracts to a temp dir, validates manifest, then moves to extensions dir.
*/
async installFromZip(zipBuffer, originalName) {
const os = require('os');
const tmpDir = path.join(os.tmpdir(), `guide-ext-${Date.now()}`);
await fs.mkdir(tmpDir, { recursive: true });
try {
// Extract zip using built-in Node.js zlib + tar, or fallback to manual extraction
// For .zip files, we use a simple unzip approach
const AdmZip = await this._getAdmZip();
if (AdmZip) {
const zip = new AdmZip(zipBuffer);
zip.extractAllTo(tmpDir, true);
} else {
// Fallback: write buffer to tmp file and use system unzip
const tmpZip = path.join(tmpDir, 'extension.zip');
await fs.writeFile(tmpZip, zipBuffer);
const { execSync } = require('child_process');
try {
// Try PowerShell Expand-Archive on Windows, unzip on Unix
if (process.platform === 'win32') {
execSync(`powershell -Command "Expand-Archive -Path '${tmpZip}' -DestinationPath '${tmpDir}' -Force"`, { timeout: 30000 });
} else {
execSync(`unzip -o "${tmpZip}" -d "${tmpDir}"`, { timeout: 30000 });
}
} catch (unzipErr) {
throw new Error(`Failed to extract zip: ${unzipErr.message}`);
}
}
// Find the manifest.json — could be at root or one level deep
let manifestDir = tmpDir;
const hasRootManifest = fsSync.existsSync(path.join(tmpDir, 'manifest.json'));
if (!hasRootManifest) {
// Check one level deep (common in zips: folder/manifest.json)
const entries = await fs.readdir(tmpDir, { withFileTypes: true });
const subDir = entries.find(e => e.isDirectory() && fsSync.existsSync(path.join(tmpDir, e.name, 'manifest.json')));
if (subDir) {
manifestDir = path.join(tmpDir, subDir.name);
} else {
throw new Error('No manifest.json found in the extension package');
}
}
return await this.installFromDir(manifestDir);
} finally {
// Clean up tmp
try { await fs.rm(tmpDir, { recursive: true, force: true }); } catch {}
}
}
async uninstall(extensionId) {
const ext = this.extensions.find(e => e.id === extensionId);
if (!ext) throw new Error(`Extension not found: ${extensionId}`);
if (ext.builtin) throw new Error('Cannot uninstall built-in extensions');
await fs.rm(ext.path, { recursive: true, force: true });
delete this._state[extensionId];
await this._saveState();
await this.scanExtensions();
return { id: extensionId };
}
/* ── Enable / Disable ──────────────────────────────────────────── */
async enable(extensionId) {
const ext = this.extensions.find(e => e.id === extensionId);
if (!ext) throw new Error(`Extension not found: ${extensionId}`);
this._state[extensionId] = { enabled: true };
await this._saveState();
ext.enabled = true;
this.emit('extensions-updated', this.extensions);
return { id: extensionId, enabled: true };
}
async disable(extensionId) {
const ext = this.extensions.find(e => e.id === extensionId);
if (!ext) throw new Error(`Extension not found: ${extensionId}`);
this._state[extensionId] = { enabled: false };
await this._saveState();
ext.enabled = false;
this.emit('extensions-updated', this.extensions);
return { id: extensionId, enabled: false };
}
/* ── Getters ───────────────────────────────────────────────────── */
getInstalled() {
return this.extensions;
}
getExtension(id) {
return this.extensions.find(e => e.id === id) || null;
}
getEnabled() {
return this.extensions.filter(e => e.enabled);
}
getCategories() {
const cats = new Set(this.extensions.map(e => e.category));
return ['all', ...Array.from(cats).sort()];
}
/* ── Persistence ───────────────────────────────────────────────── */
async _loadState() {
try {
const raw = await fs.readFile(this.statePath, 'utf8');
this._state = JSON.parse(raw);
} catch {
this._state = {};
}
}
async _saveState() {
await fs.writeFile(this.statePath, JSON.stringify(this._state, null, 2));
}
/* ── Helpers ───────────────────────────────────────────────────── */
async _copyDir(src, dest) {
await fs.mkdir(dest, { recursive: true });
const entries = await fs.readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = path.join(src, entry.name);
const destPath = path.join(dest, entry.name);
if (entry.isDirectory()) {
await this._copyDir(srcPath, destPath);
} else {
await fs.copyFile(srcPath, destPath);
}
}
}
async _getAdmZip() {
try {
return require('adm-zip');
} catch {
return null;
}
}
/* ── Runtime Hooks ─────────────────────────────────────────── */
/**
* Get all tool definitions from enabled extensions.
* Returns [{extensionId, name, description, handler}]
*/
getExtensionTools() {
const tools = [];
for (const ext of this.extensions) {
if (!ext.enabled || !ext.tools || ext.tools.length === 0) continue;
for (const tool of ext.tools) {
tools.push({
extensionId: ext.id,
name: tool.name,
description: tool.description || '',
handler: tool.handler || null,
});
}
}
return tools;
}
/**
* Get all panel definitions from enabled extensions.
* Returns [{extensionId, id, title, icon, component}]
*/
getExtensionPanels() {
const panels = [];
for (const ext of this.extensions) {
if (!ext.enabled || !ext.panels || ext.panels.length === 0) continue;
for (const panel of ext.panels) {
panels.push({
extensionId: ext.id,
id: panel.id,
title: panel.title || panel.id,
icon: panel.icon || null,
component: panel.component || null,
});
}
}
return panels;
}
/**
* Get chat hooks from enabled extensions for a given event.
* Events: 'pre-generate', 'post-generate', 'pre-tool', 'post-tool'
* Returns [{extensionId, handler}]
*/
getChatHooks(event) {
const hooks = [];
for (const ext of this.extensions) {
if (!ext.enabled || !ext.chatHooks || ext.chatHooks.length === 0) continue;
for (const hook of ext.chatHooks) {
if (hook.event === event) {
hooks.push({ extensionId: ext.id, handler: hook.handler });
}
}
}
return hooks;
}
}
module.exports = { ExtensionManager };