Implement plugins system / skills

This commit is contained in:
Alex Gleason committed 2025-11-05 23:44:14 -06:00
1 parent 39e0d48b3e
commit c24f72b34c
23 files changed
+1310 -8

No files matched your search

+6 -1
View File
@@ -48,13 +48,14 @@ const queryClient = new QueryClient({
});
// Get OS-specific default paths for Electron
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string } {
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } {
if (!globalThis.electron) {
// Browser defaults - use virtual filesystem paths
return {
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
fsPathPlugins: "/plugins",
};
}
@@ -68,6 +69,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathProjects: "~/Documents/Projects",
fsPathConfig: "~/AppData/Local/shakespeare",
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
};
} else if (platform.includes('mac')) {
// macOS
@@ -75,6 +77,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathProjects: "~/Projects",
fsPathConfig: "~/Library/Application Support/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
};
} else {
// Linux and other Unix-like systems
@@ -82,6 +85,7 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
fsPathProjects: "~/Projects",
fsPathConfig: "~/.config/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/.config/shakespeare/plugins",
};
}
}
@@ -109,6 +113,7 @@ const defaultConfig: AppConfig = {
fsPathProjects: electronPaths.fsPathProjects,
fsPathConfig: electronPaths.fsPathConfig,
fsPathTmp: electronPaths.fsPathTmp,
fsPathPlugins: electronPaths.fsPathPlugins,
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true,
};
+2
View File
@@ -38,6 +38,7 @@ const AppConfigSchema = z.object({
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
fsPathPlugins: z.string().min(1),
sentryDsn: z.string(),
sentryEnabled: z.boolean(),
}) satisfies z.ZodType<AppConfig>;
@@ -74,6 +75,7 @@ export function AppProvider(props: AppProviderProps) {
config.fsPathConfig = expandPath(config.fsPathConfig);
config.fsPathProjects = expandPath(config.fsPathProjects);
config.fsPathTmp = expandPath(config.fsPathTmp);
config.fsPathPlugins = expandPath(config.fsPathPlugins);
const appContextValue: AppContextType = {
config,
+246
View File
@@ -0,0 +1,246 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { usePlugins } from '@/hooks/usePlugins';
import { useToast } from '@/hooks/useToast';
import { Alert, AlertDescription } from '@/components/ui/alert';
export function PluginsSection() {
const { t } = useTranslation();
const { toast } = useToast();
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
const [gitUrl, setGitUrl] = useState('');
const handleAddPlugin = async () => {
if (!gitUrl.trim()) return;
try {
const pluginName = await clonePlugin.mutateAsync({ gitUrl: gitUrl.trim() });
toast({
title: t('pluginAdded'),
description: t('pluginAddedDescription', { name: pluginName }),
});
setGitUrl('');
} catch (error) {
toast({
title: t('pluginAddFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
const handleSyncPlugin = async (pluginName: string) => {
try {
await syncPlugin.mutateAsync(pluginName);
toast({
title: t('pluginSynced'),
description: t('pluginSyncedDescription', { name: pluginName }),
});
} catch (error) {
toast({
title: t('pluginSyncFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
const handleDeletePlugin = async (pluginName: string) => {
try {
await deletePlugin.mutateAsync(pluginName);
toast({
title: t('pluginDeleted'),
description: t('pluginDeletedDescription', { name: pluginName }),
});
} catch (error) {
toast({
title: t('pluginDeleteFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
// Group skills by plugin
const skillsByPlugin = skills.reduce((acc, skill) => {
if (!acc[skill.plugin]) {
acc[skill.plugin] = [];
}
acc[skill.plugin].push(skill);
return acc;
}, {} as Record<string, typeof skills>);
return (
<div className="space-y-3">
<div className="flex items-center gap-2">
<Puzzle className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('plugins')}</h4>
</div>
{/* Add Plugin Section */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-plugin" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<span className="text-sm font-medium">{t('addPlugin')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="plugin-git-url">{t('gitRepositoryUrl')}</Label>
<Input
id="plugin-git-url"
placeholder="https://github.com/user/plugin.git"
value={gitUrl}
onChange={(e) => setGitUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && gitUrl.trim()) {
handleAddPlugin();
}
}}
/>
</div>
<Button
onClick={handleAddPlugin}
disabled={!gitUrl.trim() || clonePlugin.isPending}
className="gap-2 w-full"
>
{clonePlugin.isPending ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
{t('cloning')}
</>
) : (
<>
<Check className="h-4 w-4" />
{t('addPlugin')}
</>
)}
</Button>
<p className="text-xs text-muted-foreground">
{t('pluginDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* Configured Plugins List */}
{plugins.length > 0 ? (
<div className="space-y-2">
{plugins.map((pluginName) => {
const pluginSkills = skillsByPlugin[pluginName] || [];
const isSyncing = syncPlugin.isPending && syncPlugin.variables === pluginName;
const isDeleting = deletePlugin.isPending && deletePlugin.variables === pluginName;
return (
<Accordion key={pluginName} type="single" collapsible className="w-full">
<AccordionItem value={pluginName} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Puzzle className="h-4 w-4 text-primary" />
<span className="font-medium">{pluginName}</span>
{pluginSkills.length > 0 && (
<span className="text-xs text-muted-foreground">
({pluginSkills.length} {pluginSkills.length === 1 ? 'skill' : 'skills'})
</span>
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
{/* Skills List */}
{pluginSkills.length > 0 && (
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">{t('skills')}</Label>
<div className="space-y-1">
{pluginSkills.map((skill) => (
<div
key={skill.name}
className="flex items-start gap-2 p-2 rounded-md bg-muted/50"
>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium font-mono">{skill.name}</div>
<div className="text-xs text-muted-foreground line-clamp-2">
{skill.description}
</div>
</div>
</div>
))}
</div>
</div>
)}
{pluginSkills.length === 0 && (
<Alert>
<AlertDescription className="text-xs">
{t('noSkillsFound')}
</AlertDescription>
</Alert>
)}
{/* Plugin Actions */}
<div className="flex gap-2 pt-2">
<Button
variant="outline"
size="sm"
onClick={() => handleSyncPlugin(pluginName)}
disabled={isSyncing || isDeleting}
className="flex-1"
>
{isSyncing ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('syncing')}
</>
) : (
<>
<RefreshCw className="h-4 w-4 mr-2" />
{t('sync')}
</>
)}
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => handleDeletePlugin(pluginName)}
disabled={isSyncing || isDeleting}
className="flex-1"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('deleting')}
</>
) : (
<>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</>
)}
</Button>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
);
})}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noPluginsConfigured')}
</AlertDescription>
</Alert>
)}
</div>
);
}
+4
View File
@@ -38,6 +38,7 @@ describe('SentryProvider', () => {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
};
render(
@@ -73,6 +74,7 @@ describe('SentryProvider', () => {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
};
render(
@@ -109,6 +111,7 @@ describe('SentryProvider', () => {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
};
render(
@@ -148,6 +151,7 @@ describe('SentryProvider', () => {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
};
render(
+3 -3
View File
@@ -17,7 +17,7 @@ interface SessionManagerProviderProps {
*/
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const { projectsPath, pluginsPath } = useFSPaths();
const { settings } = useAISettings();
const { models } = useProviderModels();
const { user, metadata } = useCurrentUser();
@@ -26,8 +26,8 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
const sessionManager = useMemo(() => {
const getProviderModels = () => models;
const getCurrentUser = () => ({ user, metadata });
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath);
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath]);
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
// Cleanup on unmount
useEffect(() => {
+4 -2
View File
@@ -34,6 +34,7 @@ import { NostrPublishEventsTool } from '@/lib/tools/NostrPublishEventsTool';
import { ShellTool } from '@/lib/tools/ShellTool';
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { SkillTool } from '@/lib/tools/SkillTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
@@ -78,7 +79,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const { user } = useCurrentUser();
const { models } = useProviderModels();
const { config } = useAppContext();
const { projectsPath, tmpPath } = useFSPaths();
const { projectsPath, tmpPath, pluginsPath } = useFSPaths();
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const [isDragOver, setIsDragOver] = useState(false);
const [scrolledProjects] = useState(() => new Set<string>());
@@ -167,6 +168,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_publish_events: new NostrPublishEventsTool(),
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath),
};
// Add deploy tool only if user is logged in
@@ -178,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, handleFileChanged]);
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
+2
View File
@@ -38,6 +38,8 @@ export interface AppConfig {
fsPathConfig: string;
/** VFS path for temporary files directory */
fsPathTmp: string;
/** VFS path for plugins directory */
fsPathPlugins: string;
/** Sentry DSN for error reporting (empty string = disabled) */
sentryDsn: string;
/** Whether the user has enabled Sentry error reporting */
+1
View File
@@ -56,6 +56,7 @@ describe('useAIProjectId', () => {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
},
+2
View File
@@ -15,5 +15,7 @@ export function useFSPaths() {
configPath: config.fsPathConfig,
/** Temporary files directory path (default: /tmp) */
tmpPath: config.fsPathTmp,
/** Plugins directory path (default: /plugins) */
pluginsPath: config.fsPathPlugins,
};
}
+1
View File
@@ -48,6 +48,7 @@ function createWrapper(corsProxy: string) {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
};
+127
View File
@@ -0,0 +1,127 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, getAllSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { useGit } from './useGit';
import { join } from 'path-browserify';
/**
* Hook to manage plugins and skills
*/
export function usePlugins() {
const { fs } = useFS();
const { pluginsPath } = useFSPaths();
const queryClient = useQueryClient();
const { git } = useGit();
// Query to get all plugins
const pluginsQuery = useQuery({
queryKey: ['plugins', pluginsPath],
queryFn: async () => {
return await getPlugins(fs, pluginsPath);
},
});
// Query to get all skills
const skillsQuery = useQuery({
queryKey: ['skills', pluginsPath],
queryFn: async () => {
return await getAllSkills(fs, pluginsPath);
},
});
// Mutation to clone a plugin from a git URL
const clonePlugin = useMutation({
mutationFn: async ({ gitUrl, pluginName }: { gitUrl: string; pluginName?: string }) => {
// Extract plugin name from git URL if not provided
let name = pluginName;
if (!name) {
// Extract from URL: https://github.com/user/repo.git -> repo
const match = gitUrl.match(/\/([^/]+?)(\.git)?$/);
if (!match) {
throw new Error('Invalid git URL');
}
name = match[1];
}
const pluginDir = join(pluginsPath, name);
// Ensure plugins directory exists
try {
await fs.stat(pluginsPath);
} catch {
await fs.mkdir(pluginsPath, { recursive: true });
}
// Check if plugin already exists
try {
await fs.stat(pluginDir);
throw new Error(`Plugin "${name}" already exists`);
} catch (error) {
// Plugin doesn't exist, continue
if (error instanceof Error && error.message.includes('already exists')) {
throw error;
}
}
// Clone the repository
await git.clone({
dir: pluginDir,
url: gitUrl,
depth: 1,
singleBranch: true,
});
return name;
},
onSuccess: () => {
// Invalidate queries to refresh the lists
queryClient.invalidateQueries({ queryKey: ['plugins', pluginsPath] });
queryClient.invalidateQueries({ queryKey: ['skills', pluginsPath] });
},
});
// Mutation to sync (pull) a plugin
const syncPlugin = useMutation({
mutationFn: async (pluginName: string) => {
const pluginDir = join(pluginsPath, pluginName);
// Pull latest changes
await git.pull({
dir: pluginDir,
singleBranch: true,
fastForward: true,
});
return pluginName;
},
onSuccess: () => {
// Invalidate queries to refresh the lists
queryClient.invalidateQueries({ queryKey: ['plugins', pluginsPath] });
queryClient.invalidateQueries({ queryKey: ['skills', pluginsPath] });
},
});
// Mutation to delete a plugin
const deletePlugin = useMutation({
mutationFn: async (pluginName: string) => {
await deletePluginFn(fs, pluginsPath, pluginName);
return pluginName;
},
onSuccess: () => {
// Invalidate queries to refresh the lists
queryClient.invalidateQueries({ queryKey: ['plugins', pluginsPath] });
queryClient.invalidateQueries({ queryKey: ['skills', pluginsPath] });
},
});
return {
plugins: pluginsQuery.data || [],
isLoadingPlugins: pluginsQuery.isLoading,
skills: skillsQuery.data || [],
isLoadingSkills: skillsQuery.isLoading,
clonePlugin,
syncPlugin,
deletePlugin,
};
}
+4
View File
@@ -63,6 +63,7 @@ export class SessionManager {
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
private corsProxy?: string;
private projectsPath: string;
private pluginsPath?: string;
constructor(
fs: JSRuntimeFS,
@@ -71,12 +72,14 @@ export class SessionManager {
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
corsProxy?: string,
projectsPath = '/projects',
pluginsPath?: string,
) {
this.fs = fs;
this.aiSettings = aiSettings;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
this.projectsPath = projectsPath;
this.pluginsPath = pluginsPath;
this.corsProxy = corsProxy;
}
@@ -242,6 +245,7 @@ export class SessionManager {
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
pluginsPath: this.pluginsPath,
user,
metadata,
});
+208
View File
@@ -0,0 +1,208 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { LightningFSAdapter } from './LightningFSAdapter';
import LightningFS from '@isomorphic-git/lightning-fs';
import {
getPlugins,
getPluginSkills,
getAllSkills,
findSkill,
readSkillContent,
isValidSkillName,
} from './plugins';
describe('plugins', () => {
let fs: LightningFSAdapter;
beforeEach(() => {
const lightningFS = new LightningFS('test-plugins-fs');
fs = new LightningFSAdapter(lightningFS.promises);
});
describe('isValidSkillName', () => {
it('should validate alphanumeric lowercase names', () => {
expect(isValidSkillName('test')).toBe(true);
expect(isValidSkillName('test123')).toBe(true);
expect(isValidSkillName('abc')).toBe(true);
});
it('should reject invalid names', () => {
expect(isValidSkillName('Test')).toBe(false);
expect(isValidSkillName('test-name')).toBe(false);
expect(isValidSkillName('test_name')).toBe(false);
expect(isValidSkillName('test name')).toBe(false);
expect(isValidSkillName('test-123')).toBe(false);
});
});
describe('getPlugins', () => {
it('should return empty array when plugins directory does not exist', async () => {
const plugins = await getPlugins(fs, '/plugins');
expect(plugins).toEqual([]);
});
it('should return list of plugin directories', async () => {
await fs.mkdir('/plugins/plugin1', { recursive: true });
await fs.mkdir('/plugins/plugin2', { recursive: true });
await fs.writeFile('/plugins/file.txt', 'not a directory');
const plugins = await getPlugins(fs, '/plugins');
expect(plugins).toContain('plugin1');
expect(plugins).toContain('plugin2');
expect(plugins).not.toContain('file.txt');
});
});
describe('getPluginSkills', () => {
it('should return empty array when plugin has no skills', async () => {
await fs.mkdir('/plugins/plugin1', { recursive: true });
const skills = await getPluginSkills(fs, '/plugins', 'plugin1');
expect(skills).toEqual([]);
});
it('should return skills with valid SKILL.md files', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: myskill
description: A test skill
---
# My Skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
});
});
it('should skip skills with invalid names', async () => {
const skillPath = '/plugins/testplugin/skills/InvalidSkill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: InvalidSkill
description: Has uppercase letters
---
Content`
);
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
expect(skills).toEqual([]);
});
it('should skip skills missing required frontmatter', async () => {
const skillPath = '/plugins/testplugin/skills/incomplete';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: incomplete
---
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
expect(skills).toEqual([]);
});
});
describe('getAllSkills', () => {
it('should return skills from all plugins', async () => {
// Plugin 1
const skill1Path = '/plugins/plugin1/skills/skill1';
await fs.mkdir(skill1Path, { recursive: true });
await fs.writeFile(
`${skill1Path}/SKILL.md`,
`---
name: skill1
description: First skill
---
Content`
);
// Plugin 2
const skill2Path = '/plugins/plugin2/skills/skill2';
await fs.mkdir(skill2Path, { recursive: true });
await fs.writeFile(
`${skill2Path}/SKILL.md`,
`---
name: skill2
description: Second skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins');
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('skill1');
expect(skills.map((s) => s.name)).toContain('skill2');
});
});
describe('findSkill', () => {
it('should find a skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: findme
description: Find this skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
});
it('should return null when skill not found', async () => {
const skill = await findSkill(fs, '/plugins', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
const content = `---
name: myskill
description: A test skill
---
# My Skill
This is the skill content.`;
await fs.writeFile(`${skillPath}/SKILL.md`, content);
const skill = {
name: 'myskill',
description: 'A test skill',
path: skillPath,
plugin: 'testplugin',
};
const readContent = await readSkillContent(fs, skill);
expect(readContent).toBe(content);
});
});
});
+167
View File
@@ -0,0 +1,167 @@
import { join } from 'path-browserify';
import matter from 'gray-matter';
import type { JSRuntimeFS } from './JSRuntime';
export interface Skill {
/** Skill name (alphanumeric lowercase only) */
name: string;
/** Human-readable description of what the skill does */
description: string;
/** Full path to the skill directory */
path: string;
/** Plugin name that contains this skill */
plugin: string;
}
export interface SkillFrontmatter {
name: string;
description: string;
[key: string]: unknown;
}
/**
* Validates a skill name (alphanumeric lowercase only)
*/
export function isValidSkillName(name: string): boolean {
return /^[a-z0-9]+$/.test(name);
}
/**
* Get all plugins from the plugins directory
*/
export async function getPlugins(fs: JSRuntimeFS, pluginsPath: string): Promise<string[]> {
try {
const entries = await fs.readdir(pluginsPath);
const plugins: string[] = [];
for (const entry of entries) {
const stat = await fs.stat(join(pluginsPath, entry));
if (stat.isDirectory()) {
plugins.push(entry);
}
}
return plugins;
} catch {
// Plugins directory doesn't exist yet
return [];
}
}
/**
* Get all skills from a plugin
*/
export async function getPluginSkills(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
const skillsDir = join(pluginsPath, pluginName, 'skills');
try {
const skillDirs = await fs.readdir(skillsDir);
for (const skillDir of skillDirs) {
const skillPath = join(skillsDir, skillDir);
const stat = await fs.stat(skillPath);
if (!stat.isDirectory()) continue;
const skillFilePath = join(skillPath, 'SKILL.md');
try {
const skillContent = await fs.readFile(skillFilePath, 'utf8');
const { data } = matter(skillContent);
const frontmatter = data as SkillFrontmatter;
// Validate required fields
if (!frontmatter.name || !frontmatter.description) {
console.warn(`Skill at ${skillPath} missing required frontmatter fields (name, description)`);
continue;
}
// Validate skill name format
if (!isValidSkillName(frontmatter.name)) {
console.warn(`Skill at ${skillPath} has invalid name "${frontmatter.name}" (must be alphanumeric lowercase only)`);
continue;
}
skills.push({
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: pluginName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
continue;
}
}
} catch {
// Skills directory doesn't exist for this plugin
return [];
}
return skills;
}
/**
* Get all skills from all plugins
*/
export async function getAllSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getPluginSkills(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
return allSkills;
}
/**
* Find a skill by name across all plugins
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath);
return skills.find(skill => skill.name === skillName) || null;
}
/**
* Read the SKILL.md content for a skill
*/
export async function readSkillContent(fs: JSRuntimeFS, skill: Skill): Promise<string> {
const skillFilePath = join(skill.path, 'SKILL.md');
return await fs.readFile(skillFilePath, 'utf8');
}
/**
* Delete a plugin directory
*/
export async function deletePlugin(fs: JSRuntimeFS, pluginsPath: string, pluginName: string): Promise<void> {
const pluginPath = join(pluginsPath, pluginName);
// Recursively delete the plugin directory
async function rmrf(path: string): Promise<void> {
const stat = await fs.stat(path);
if (stat.isDirectory()) {
const entries = await fs.readdir(path);
for (const entry of entries) {
await rmrf(join(path, entry));
}
await fs.rmdir(path);
} else {
await fs.unlink(path);
}
}
await rmrf(pluginPath);
}
+31 -1
View File
@@ -4,6 +4,7 @@ import { join } from "path-browserify";
import OpenAI from "openai";
import { nip19 } from "nostr-tools";
import { JSRuntimeFS } from "./JSRuntime";
import { getAllSkills } from "./plugins";
export interface MakeSystemPromptOpts {
name: string;
@@ -12,12 +13,13 @@ export interface MakeSystemPromptOpts {
mode: "init" | "agent";
fs: JSRuntimeFS;
cwd: string;
pluginsPath?: string;
user?: NUser;
metadata?: NostrMetadata;
}
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { name, profession, tools, mode, fs, cwd, user, metadata } = opts;
const { name, profession, tools, mode, fs, cwd, pluginsPath, user, metadata } = opts;
let system = mode === "init"
? `You are ${name}, an expert ${profession}. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.`
@@ -180,6 +182,34 @@ The user expects you to handle all technical implementation while they focus on
}
}
// Add skills section
system += "\n\n## Skills\n\n";
if (pluginsPath) {
try {
const skills = await getAllSkills(fs, pluginsPath);
if (skills.length > 0) {
system += "You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.\n\n";
system += "Available skills:\n\n";
for (const skill of skills) {
system += `- **${skill.name}**: ${skill.description}\n - Plugin: ${skill.plugin}\n - Path: ${skill.path}\n`;
}
system += `\n**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.\n`;
} else {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
} catch {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
} else {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
system += `\nUsers can configure skills in Settings > AI (${location.origin}/settings/ai) by adding plugins that contain skills.`;
// Add README.md if it exists
try {
const readmePath = join(cwd, "README.md");
+55
View File
@@ -0,0 +1,55 @@
import { z } from 'zod';
import type { Tool } from './Tool';
import type { JSRuntimeFS } from '../JSRuntime';
import { findSkill, readSkillContent } from '../plugins';
interface SkillParams {
name: string;
}
export class SkillTool implements Tool<SkillParams> {
private fs: JSRuntimeFS;
private pluginsPath: string;
readonly description = 'Load and execute a skill from the configured plugins. Skills are reusable AI workflows that can be invoked by name.';
readonly inputSchema = z.object({
name: z.string().describe('The name of the skill to execute (alphanumeric lowercase only)'),
});
constructor(fs: JSRuntimeFS, pluginsPath: string) {
this.fs = fs;
this.pluginsPath = pluginsPath;
}
async execute(args: SkillParams): Promise<string> {
const { name } = args;
try {
// Find the skill across all plugins
const skill = await findSkill(this.fs, this.pluginsPath, name);
if (!skill) {
throw new Error(`Skill "${name}" not found. Use the skill tool to list available skills or configure plugins in Settings > AI.`);
}
// Read and return the skill content
const content = await readSkillContent(this.fs, skill);
return `# Skill: ${skill.name}
**Plugin**: ${skill.plugin}
**Description**: ${skill.description}
**Path**: ${skill.path}
---
${content}`;
} catch (error) {
if (error instanceof Error) {
throw error;
}
throw new Error(`Failed to execute skill "${name}": ${String(error)}`);
}
}
}
+30 -1
View File
@@ -453,5 +453,34 @@
"invalidGiftCard": "Invalid Gift Card",
"giftCardNotFound": "This gift card could not be found.",
"alreadyRedeemed": "Already Redeemed",
"giftCardAlreadyRedeemed": "This gift card has already been redeemed."
"giftCardAlreadyRedeemed": "This gift card has already been redeemed.",
"plugins": "Plugins",
"addPlugin": "Add Plugin",
"gitRepositoryUrl": "Git Repository URL",
"pluginDescription": "Plugins can contain skills that extend the AI's capabilities with specialized workflows.",
"cloning": "Cloning...",
"pluginAdded": "Plugin Added",
"pluginAddedDescription": "Plugin \"{{name}}\" has been added successfully.",
"pluginAddFailed": "Failed to Add Plugin",
"sync": "Sync",
"syncing": "Syncing...",
"pluginSynced": "Plugin Synced",
"pluginSyncedDescription": "Plugin \"{{name}}\" has been synced successfully.",
"pluginSyncFailed": "Failed to Sync Plugin",
"pluginDeleted": "Plugin Deleted",
"pluginDeletedDescription": "Plugin \"{{name}}\" has been deleted successfully.",
"pluginDeleteFailed": "Failed to Delete Plugin",
"skills": "Skills",
"noSkillsFound": "No skills found in this plugin.",
"noPluginsConfigured": "No plugins configured. Add a plugin to get started.",
"pluginsDirectory": "Plugins Directory",
"pluginsDirectoryDescription": "Directory where plugins are stored in the virtual filesystem.",
"filesystemPaths": "Filesystem Paths",
"projectsDirectory": "Projects Directory",
"projectsDirectoryDescription": "Directory where projects are stored in the virtual filesystem.",
"configDirectory": "Config Directory",
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
"temporaryDirectory": "Temporary Directory",
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
"deleting": "Deleting..."
}
+4
View File
@@ -36,6 +36,7 @@ import { useNavigate, Link } from 'react-router-dom';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { PluginsSection } from '@/components/PluginsSection';
interface SortableProviderItemProps {
provider: AIProvider;
@@ -564,6 +565,9 @@ export function AISettings() {
</AccordionItem>
</Accordion>
</div>
{/* Plugins Section */}
<PluginsSection />
</div>
{/* Render credits dialog outside of accordion structure */}
+24
View File
@@ -29,6 +29,7 @@ export function SystemSettings() {
const [fsPathProjectsInput, setFsPathProjectsInput] = useState(config.fsPathProjects);
const [fsPathConfigInput, setFsPathConfigInput] = useState(config.fsPathConfig);
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
// Service Worker state
@@ -571,6 +572,29 @@ export function SystemSettings() {
{t('temporaryDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
{t('pluginsDirectory')}
</Label>
<Input
id="fs-path-plugins"
type="text"
placeholder="/plugins"
value={fsPathPluginsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathPluginsInput(value);
updateConfig((current) => ({
...current,
fsPathPlugins: value,
}));
}}
/>
<p className="text-xs text-muted-foreground">
{t('pluginsDirectoryDescription')}
</p>
</div>
</div>
</AccordionContent>
</AccordionItem>
+1
View File
@@ -47,6 +47,7 @@ export function TestApp({ children }: TestAppProps) {
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
sentryDsn: '',
sentryEnabled: false,
};