mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Shakespeare
This commit is contained in:
14 files changed
+2405
-8
No files matched your search
@@ -0,0 +1,134 @@
|
||||
import { openai } from '@ai-sdk/openai';
|
||||
import { streamText, tool } from 'ai';
|
||||
import { z } from 'zod';
|
||||
import { aiTools } from './ai-tools';
|
||||
|
||||
const fileOperationSchema = z.object({
|
||||
projectId: z.string(),
|
||||
filePath: z.string(),
|
||||
content: z.string().optional(),
|
||||
});
|
||||
|
||||
const buildSchema = z.object({
|
||||
projectId: z.string(),
|
||||
});
|
||||
|
||||
export async function createAIChat(projectId: string, messages: any[]) {
|
||||
const result = await streamText({
|
||||
model: openai('gpt-4-turbo-preview'),
|
||||
messages,
|
||||
tools: {
|
||||
readFile: tool({
|
||||
description: 'Read the contents of a file in the project',
|
||||
parameters: fileOperationSchema,
|
||||
execute: async ({ projectId, filePath }) => {
|
||||
return await aiTools.executeOperation({
|
||||
type: 'read',
|
||||
projectId,
|
||||
filePath,
|
||||
});
|
||||
},
|
||||
}),
|
||||
writeFile: tool({
|
||||
description: 'Write content to a file in the project',
|
||||
parameters: fileOperationSchema,
|
||||
execute: async ({ projectId, filePath, content }) => {
|
||||
return await aiTools.executeOperation({
|
||||
type: 'write',
|
||||
projectId,
|
||||
filePath,
|
||||
content: content || '',
|
||||
});
|
||||
},
|
||||
}),
|
||||
deleteFile: tool({
|
||||
description: 'Delete a file from the project',
|
||||
parameters: fileOperationSchema,
|
||||
execute: async ({ projectId, filePath }) => {
|
||||
return await aiTools.executeOperation({
|
||||
type: 'delete',
|
||||
projectId,
|
||||
filePath,
|
||||
});
|
||||
},
|
||||
}),
|
||||
listFiles: tool({
|
||||
description: 'List files in a directory',
|
||||
parameters: fileOperationSchema,
|
||||
execute: async ({ projectId, filePath }) => {
|
||||
return await aiTools.executeOperation({
|
||||
type: 'list',
|
||||
projectId,
|
||||
filePath,
|
||||
});
|
||||
},
|
||||
}),
|
||||
fileExists: tool({
|
||||
description: 'Check if a file exists',
|
||||
parameters: fileOperationSchema,
|
||||
execute: async ({ projectId, filePath }) => {
|
||||
return await aiTools.executeOperation({
|
||||
type: 'exists',
|
||||
projectId,
|
||||
filePath,
|
||||
});
|
||||
},
|
||||
}),
|
||||
buildProject: tool({
|
||||
description: 'Build the project using Vite',
|
||||
parameters: buildSchema,
|
||||
execute: async ({ projectId }) => {
|
||||
return await aiTools.executeOperation({
|
||||
type: 'build',
|
||||
projectId,
|
||||
});
|
||||
},
|
||||
}),
|
||||
getProjectStructure: tool({
|
||||
description: 'Get the complete file structure of the project',
|
||||
parameters: buildSchema,
|
||||
execute: async ({ projectId }) => {
|
||||
return await aiTools.getProjectStructure(projectId);
|
||||
},
|
||||
}),
|
||||
searchFiles: tool({
|
||||
description: 'Search for files containing specific text',
|
||||
parameters: z.object({
|
||||
projectId: z.string(),
|
||||
query: z.string(),
|
||||
}),
|
||||
execute: async ({ projectId, query }) => {
|
||||
return await aiTools.searchFiles(projectId, query);
|
||||
},
|
||||
}),
|
||||
},
|
||||
system: `You are an AI assistant helping users build custom Nostr websites. You have access to tools that allow you to read, write, and manage files in the project, as well as build the project.
|
||||
|
||||
Key capabilities:
|
||||
- Read and write files in the project
|
||||
- List directory contents
|
||||
- Check if files exist
|
||||
- Build the project using Vite
|
||||
- Get project structure overview
|
||||
- Search through files
|
||||
|
||||
Guidelines:
|
||||
- Always check if files exist before writing to avoid overwriting
|
||||
- Provide helpful explanations of what you're doing
|
||||
- Suggest improvements and best practices
|
||||
- Use modern React patterns and TypeScript
|
||||
- Follow Nostr protocol standards when relevant
|
||||
- Ensure the project builds successfully
|
||||
|
||||
The project uses:
|
||||
- React 18 with TypeScript
|
||||
- Vite for building
|
||||
- TailwindCSS for styling
|
||||
- Nostrify for Nostr integration
|
||||
- shadcn/ui components
|
||||
|
||||
When creating new components or pages, follow the existing patterns in the codebase.`
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { fsManager } from './fs';
|
||||
|
||||
export interface FileOperation {
|
||||
type: 'read' | 'write' | 'delete' | 'list' | 'exists';
|
||||
projectId: string;
|
||||
filePath: string;
|
||||
content?: string;
|
||||
}
|
||||
|
||||
export interface BuildOperation {
|
||||
type: 'build';
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
export type AIToolOperation = FileOperation | BuildOperation;
|
||||
|
||||
export class AITools {
|
||||
async executeOperation(operation: AIToolOperation): Promise<any> {
|
||||
try {
|
||||
switch (operation.type) {
|
||||
case 'read':
|
||||
return await this.readFile(operation.projectId, operation.filePath);
|
||||
|
||||
case 'write':
|
||||
if (!operation.content) {
|
||||
throw new Error('Content is required for write operations');
|
||||
}
|
||||
await this.writeFile(operation.projectId, operation.filePath, operation.content);
|
||||
return { success: true, message: 'File written successfully' };
|
||||
|
||||
case 'delete':
|
||||
await this.deleteFile(operation.projectId, operation.filePath);
|
||||
return { success: true, message: 'File deleted successfully' };
|
||||
|
||||
case 'list':
|
||||
return await this.listFiles(operation.projectId, operation.filePath);
|
||||
|
||||
case 'exists':
|
||||
return await this.fileExists(operation.projectId, operation.filePath);
|
||||
|
||||
case 'build':
|
||||
return await this.buildProject(operation.projectId);
|
||||
|
||||
default:
|
||||
throw new Error(`Unknown operation type: ${(operation as any).type}`);
|
||||
}
|
||||
} catch (error) {
|
||||
return { error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
private async readFile(projectId: string, filePath: string): Promise<string> {
|
||||
return await fsManager.readFile(projectId, filePath);
|
||||
}
|
||||
|
||||
private async writeFile(projectId: string, filePath: string, content: string): Promise<void> {
|
||||
await fsManager.writeFile(projectId, filePath, content);
|
||||
}
|
||||
|
||||
private async deleteFile(projectId: string, filePath: string): Promise<void> {
|
||||
await fsManager.deleteFile(projectId, filePath);
|
||||
}
|
||||
|
||||
private async listFiles(projectId: string, dirPath: string = ''): Promise<string[]> {
|
||||
return await fsManager.listFiles(projectId, dirPath);
|
||||
}
|
||||
|
||||
private async fileExists(projectId: string, filePath: string): Promise<boolean> {
|
||||
return await fsManager.fileExists(projectId, filePath);
|
||||
}
|
||||
|
||||
private async buildProject(projectId: string): Promise<any> {
|
||||
// TODO: Implement Vite build in browser
|
||||
// For now, return a stub
|
||||
return {
|
||||
success: true,
|
||||
message: 'Build started (stub implementation)',
|
||||
url: `/preview/${projectId}`
|
||||
};
|
||||
}
|
||||
|
||||
async getProjectStructure(projectId: string): Promise<any> {
|
||||
const structure: any = {};
|
||||
|
||||
async function buildStructure(currentPath: string, obj: any) {
|
||||
const items = await fsManager.listFiles(projectId, currentPath);
|
||||
|
||||
for (const item of items) {
|
||||
const itemPath = currentPath ? `${currentPath}/${item}` : item;
|
||||
const fullPath = `${fsManager['dir']}/${projectId}/${itemPath}`;
|
||||
|
||||
try {
|
||||
const stat = await fsManager['fs'].promises.stat(fullPath);
|
||||
if (stat.isDirectory()) {
|
||||
obj[item] = {};
|
||||
await buildStructure(itemPath, obj[item]);
|
||||
} else {
|
||||
obj[item] = 'file';
|
||||
}
|
||||
} catch (error) {
|
||||
// Skip inaccessible items
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await buildStructure('', structure);
|
||||
return structure;
|
||||
}
|
||||
|
||||
async searchFiles(projectId: string, query: string): Promise<Array<{path: string, content: string}>> {
|
||||
const results: Array<{path: string, content: string}> = [];
|
||||
|
||||
async function searchDirectory(dirPath: string) {
|
||||
const items = await fsManager.listFiles(projectId, dirPath);
|
||||
|
||||
for (const item of items) {
|
||||
const itemPath = dirPath ? `${dirPath}/${item}` : item;
|
||||
const fullPath = `${fsManager['dir']}/${projectId}/${itemPath}`;
|
||||
|
||||
try {
|
||||
const stat = await fsManager['fs'].promises.stat(fullPath);
|
||||
if (stat.isDirectory()) {
|
||||
await searchDirectory(itemPath);
|
||||
} else {
|
||||
const content = await fsManager.readFile(projectId, itemPath);
|
||||
if (content.toLowerCase().includes(query.toLowerCase())) {
|
||||
results.push({ path: itemPath, content });
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// Skip inaccessible files
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await searchDirectory('');
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
export const aiTools = new AITools();
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import { Buffer } from 'buffer';
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
(window as any).Buffer = Buffer;
|
||||
}
|
||||
|
||||
export interface Project {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
createdAt: Date;
|
||||
lastModified: Date;
|
||||
}
|
||||
|
||||
export class FileSystemManager {
|
||||
private fs: LightningFS;
|
||||
private dir: string;
|
||||
|
||||
constructor() {
|
||||
this.fs = new LightningFS('shakespeare-fs');
|
||||
this.dir = '/projects';
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.fs.promises.mkdir(this.dir);
|
||||
} catch (error) {
|
||||
// Directory might already exist
|
||||
}
|
||||
}
|
||||
|
||||
async createProject(name: string): Promise<Project> {
|
||||
const id = this.generateProjectId(name);
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
|
||||
await this.fs.promises.mkdir(projectPath);
|
||||
|
||||
const project: Project = {
|
||||
id,
|
||||
name,
|
||||
path: projectPath,
|
||||
createdAt: new Date(),
|
||||
lastModified: new Date(),
|
||||
};
|
||||
|
||||
// Save project metadata
|
||||
await this.fs.promises.writeFile(
|
||||
`${projectPath}/.project.json`,
|
||||
JSON.stringify(project, null, 2)
|
||||
);
|
||||
|
||||
// Clone the template
|
||||
await this.cloneTemplate(projectPath);
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
async cloneTemplate(projectPath: string) {
|
||||
const templateUrl = 'https://relay.ngit.dev/npub1q3sle0kvfsehgsuexttt3ugjd8xdklxfwwkh559wxckmzddywnws6cd26p/mkstack.git';
|
||||
|
||||
try {
|
||||
await git.clone({
|
||||
fs: this.fs,
|
||||
http,
|
||||
dir: projectPath,
|
||||
url: templateUrl,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to clone template:', error);
|
||||
// Create basic structure if clone fails
|
||||
await this.createBasicStructure(projectPath);
|
||||
}
|
||||
}
|
||||
|
||||
async createBasicStructure(projectPath: string) {
|
||||
const files = {
|
||||
'package.json': JSON.stringify({
|
||||
name: 'shakespeare-project',
|
||||
version: '0.1.0',
|
||||
type: 'module',
|
||||
scripts: {
|
||||
dev: 'vite',
|
||||
build: 'vite build',
|
||||
preview: 'vite preview'
|
||||
},
|
||||
dependencies: {
|
||||
react: '^18.2.0',
|
||||
'react-dom': '^18.2.0'
|
||||
},
|
||||
devDependencies: {
|
||||
'@types/react': '^18.2.0',
|
||||
'@types/react-dom': '^18.2.0',
|
||||
'@vitejs/plugin-react': '^4.0.0',
|
||||
vite: '^4.4.0'
|
||||
}
|
||||
}, null, 2),
|
||||
'index.html': `<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Shakespeare Project</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>`,
|
||||
'src/main.jsx': `import React from 'react'
|
||||
import ReactDOM from 'react-dom/client'
|
||||
import App from './App.jsx'
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
)`,
|
||||
'src/App.jsx': `import React from 'react'
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="App">
|
||||
<h1>Welcome to your Shakespeare project!</h1>
|
||||
<p>This is a basic React app template.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default App`,
|
||||
'vite.config.js': `import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
})`
|
||||
};
|
||||
|
||||
for (const [filename, content] of Object.entries(files)) {
|
||||
const filePath = `${projectPath}/${filename}`;
|
||||
const dir = filePath.split('/').slice(0, -1).join('/');
|
||||
try {
|
||||
await this.fs.promises.mkdir(dir);
|
||||
} catch (error) {
|
||||
// Directory might already exist
|
||||
}
|
||||
await this.fs.promises.writeFile(filePath, content);
|
||||
}
|
||||
}
|
||||
|
||||
async getProjects(): Promise<Project[]> {
|
||||
try {
|
||||
const projectDirs = await this.fs.promises.readdir(this.dir);
|
||||
const projects: Project[] = [];
|
||||
|
||||
for (const dir of projectDirs) {
|
||||
const projectPath = `${this.dir}/${dir}`;
|
||||
const projectFile = `${projectPath}/.project.json`;
|
||||
|
||||
try {
|
||||
const projectData = await this.fs.promises.readFile(projectFile, 'utf8');
|
||||
const project = JSON.parse(projectData);
|
||||
projects.push({
|
||||
...project,
|
||||
createdAt: new Date(project.createdAt),
|
||||
lastModified: new Date(project.lastModified),
|
||||
});
|
||||
} catch (error) {
|
||||
// Skip invalid projects
|
||||
}
|
||||
}
|
||||
|
||||
return projects.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async getProject(id: string): Promise<Project | null> {
|
||||
try {
|
||||
const projectFile = `${this.dir}/${id}/.project.json`;
|
||||
const projectData = await this.fs.promises.readFile(projectFile, 'utf8');
|
||||
const project = JSON.parse(projectData);
|
||||
return {
|
||||
...project,
|
||||
createdAt: new Date(project.createdAt),
|
||||
lastModified: new Date(project.lastModified),
|
||||
};
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async readFile(projectId: string, filePath: string): Promise<string> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
return await this.fs.promises.readFile(fullPath, 'utf8');
|
||||
}
|
||||
|
||||
async writeFile(projectId: string, filePath: string, content: string): Promise<void> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
const dir = fullPath.split('/').slice(0, -1).join('/');
|
||||
await this.fs.promises.mkdir(dir, { recursive: true });
|
||||
await this.fs.promises.writeFile(fullPath, content);
|
||||
|
||||
// Update last modified
|
||||
await this.updateProjectLastModified(projectId);
|
||||
}
|
||||
|
||||
async deleteFile(projectId: string, filePath: string): Promise<void> {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
await this.fs.promises.unlink(fullPath);
|
||||
await this.updateProjectLastModified(projectId);
|
||||
}
|
||||
|
||||
async listFiles(projectId: string, dirPath: string = ''): Promise<string[]> {
|
||||
const fullPath = `${this.dir}/${projectId}/${dirPath}`;
|
||||
try {
|
||||
return await this.fs.promises.readdir(fullPath);
|
||||
} catch (error) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async fileExists(projectId: string, filePath: string): Promise<boolean> {
|
||||
try {
|
||||
const fullPath = `${this.dir}/${projectId}/${filePath}`;
|
||||
await this.fs.promises.stat(fullPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private generateProjectId(name: string): string {
|
||||
const timestamp = Date.now().toString(36);
|
||||
const slug = name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
return `${slug}-${timestamp}`;
|
||||
}
|
||||
|
||||
private async updateProjectLastModified(projectId: string): Promise<void> {
|
||||
try {
|
||||
const projectFile = `${this.dir}/${projectId}/.project.json`;
|
||||
const projectData = await this.fs.promises.readFile(projectFile, 'utf8');
|
||||
const project = JSON.parse(projectData);
|
||||
project.lastModified = new Date().toISOString();
|
||||
await this.fs.promises.writeFile(projectFile, JSON.stringify(project, null, 2));
|
||||
} catch (error) {
|
||||
// Ignore errors updating last modified
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const fsManager = new FileSystemManager();
|
||||
Reference in new issue
Block a user