Add a tidier FsToolSet

This commit is contained in:
Alex Gleason committed 2025-07-17 13:46:55 -05:00
1 parent 475b998c1a
commit 0ae7a45dd8
6 files changed
+115 -84

No files matched your search

+15
View File
@@ -41,6 +41,7 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
@@ -1355,6 +1356,11 @@
"resolved": "https://npm.jsr.io/~/11/@jsr/std__encoding/0.224.3.tgz",
"integrity": "sha512-zAuX2QV1zwJ5RSmrnDGVerAtN3pBXpYYNlGzhERW9AiQ1UJd2/xruyB3i5NdTWy2OK2pjETswOj+0+prYTPlxQ=="
},
"node_modules/@jsr/std__internal": {
"version": "1.0.9",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__internal/1.0.9.tgz",
"integrity": "sha512-s+f4qrJzZgPAy7XuFOtgaSaxyPLnnEmAfXGLvRXGxPTL76URLVHkF+hOzqXz+bmk8/awybF6BRsasxtAQOV23Q=="
},
"node_modules/@noble/ciphers": {
"version": "0.5.3",
"resolved": "https://registry.npmjs.org/@noble/ciphers/-/ciphers-0.5.3.tgz",
@@ -3214,6 +3220,15 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@std/path": {
"name": "@jsr/std__path",
"version": "1.1.1",
"resolved": "https://npm.jsr.io/~/11/@jsr/std__path/1.1.1.tgz",
"integrity": "sha512-+x5LgcNUSpMzOZIRmFSjqrMTCxHlgXjWzK8ZFr7lwgHfWZxoVXeis3MFQlkR5mN5uQ61Y1P30Li1PU0yx9uluA==",
"dependencies": {
"@jsr/std__internal": "^1.0.9"
}
},
"node_modules/@swc/core": {
"version": "1.11.24",
"resolved": "https://registry.npmjs.org/@swc/core/-/core-1.11.24.tgz",
+1
View File
@@ -43,6 +43,7 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@std/path": "npm:@jsr/std__path@^1.1.1",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
+7 -71
View File
@@ -1,5 +1,5 @@
import { useState, useRef, useEffect } from 'react';
import { tool, CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage } from 'ai';
import { CoreMessage, generateText, CoreUserMessage, CoreAssistantMessage, CoreToolMessage } from 'ai';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
@@ -7,8 +7,8 @@ import { Card } from '@/components/ui/card';
import { Send, Bot, User, Settings } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useAISettings } from '@/contexts/AISettingsContext';
import { contextualAITools } from '@/lib/ai-tools';
import { z } from 'zod';
import { FsToolSet } from '@/lib/FsToolSet';
import { fsManager } from '@/lib/fs';
interface ChatPaneProps {
projectId: string;
@@ -23,9 +23,6 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
const { settings, isConfigured } = useAISettings();
useEffect(() => {
// Set the current project ID for contextual AI tools
contextualAITools.setCurrentProjectId(projectId);
// Add welcome message
setMessages([
{
@@ -46,13 +43,6 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
throw new Error('AI settings not configured');
}
const fileOperationSchema = z.object({
filePath: z.string(),
content: z.string().optional(),
});
const buildSchema = z.object({});
// Create a custom fetch function for the AI provider
const customFetch = async (url: string, options: RequestInit) => {
return fetch(url, {
@@ -71,7 +61,9 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
apiKey: settings.apiKey,
fetch: settings.baseUrl.includes('openrouter.ai') ? customFetch : undefined,
});
const provider = openai(settings.model);
const toolSet = new FsToolSet(fsManager.fs.promises, `/projects/${projectId}`);
return generateText({
model: provider,
@@ -81,64 +73,8 @@ export function ChatPane({ projectId, projectName }: ChatPaneProps) {
setMessages((prev) => [...prev, ...[...stepResult.response.messages]]);
},
tools: {
readFile: tool({
description: 'Read the contents of a file in the project',
parameters: fileOperationSchema,
execute: async ({ filePath }) => {
return await contextualAITools.readFile(filePath);
},
}),
writeFile: tool({
description: 'Write content to a file in the project',
parameters: fileOperationSchema,
execute: async ({ filePath, content }) => {
return await contextualAITools.writeFile(filePath, content || '');
},
}),
deleteFile: tool({
description: 'Delete a file from the project',
parameters: fileOperationSchema,
execute: async ({ filePath }) => {
return await contextualAITools.deleteFile(filePath);
},
}),
listFiles: tool({
description: 'List files in a directory',
parameters: fileOperationSchema,
execute: async ({ filePath }) => {
return await contextualAITools.listFiles(filePath);
},
}),
fileExists: tool({
description: 'Check if a file exists',
parameters: fileOperationSchema,
execute: async ({ filePath }) => {
return await contextualAITools.fileExists(filePath);
},
}),
buildProject: tool({
description: 'Build the project using Vite',
parameters: buildSchema,
execute: async () => {
return await contextualAITools.buildProject();
},
}),
getProjectStructure: tool({
description: 'Get the complete file structure of the project',
parameters: buildSchema,
execute: async () => {
return await contextualAITools.getProjectStructure();
},
}),
searchFiles: tool({
description: 'Search for files containing specific text',
parameters: z.object({
query: z.string(),
}),
execute: async ({ query }) => {
return await contextualAITools.searchFiles(query);
},
}),
readFile: toolSet.readFile,
writeFile: toolSet.writeFile,
},
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.
+37
View File
@@ -0,0 +1,37 @@
import type LightningFS from '@isomorphic-git/lightning-fs';
import { join } from "@std/path/posix/join";
import { tool } from "ai";
import z from 'zod';
export class FsToolSet {
constructor(readonly fs: LightningFS.PromisifiedFS, private cwd?: string) {}
readonly readFile = tool({
description: 'Read the contents of a file in the project',
parameters: FsToolSet.readFileSchema,
execute: (args) => {
const filepath = join(this.cwd || '', args.filePath);
return this.fs.readFile(filepath, 'utf8');
},
});
readonly writeFile = tool({
description: 'Write content to a file in the project',
parameters: FsToolSet.writeFileSchema,
execute: async (args) => {
const filepath = join(this.cwd || '', args.filePath);
await this.fs.writeFile(filepath, args.content, 'utf8');
return `File ${args.filePath} written successfully`;
},
});
static readFileSchema = z.object({
filePath: z.string(),
content: z.string().optional(),
});
static writeFileSchema = z.object({
filePath: z.string(),
content: z.string(),
});
}
+32 -7
View File
@@ -17,29 +17,54 @@ class ContextualAITools {
async readFile(filePath: string): Promise<string> {
const projectId = this.getCurrentProjectId();
return await fsManager.readFile(projectId, filePath);
try {
return await fsManager.readFile(projectId, filePath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to read file "${filePath}": ${fsError.message}`);
}
}
async writeFile(filePath: string, content: string): Promise<{ success: boolean; message: string }> {
const projectId = this.getCurrentProjectId();
await fsManager.writeFile(projectId, filePath, content);
return { success: true, message: `File ${filePath} written successfully` };
try {
await fsManager.writeFile(projectId, filePath, content);
return { success: true, message: `File ${filePath} written successfully` };
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to write file "${filePath}": ${fsError.message}`);
}
}
async deleteFile(filePath: string): Promise<{ success: boolean; message: string }> {
const projectId = this.getCurrentProjectId();
await fsManager.deleteFile(projectId, filePath);
return { success: true, message: `File ${filePath} deleted successfully` };
try {
await fsManager.deleteFile(projectId, filePath);
return { success: true, message: `File ${filePath} deleted successfully` };
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to delete file "${filePath}": ${fsError.message}`);
}
}
async listFiles(dirPath: string = ''): Promise<string[]> {
const projectId = this.getCurrentProjectId();
return await fsManager.listFiles(projectId, dirPath);
try {
return await fsManager.listFiles(projectId, dirPath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to list files in "${dirPath}": ${fsError.message}`);
}
}
async fileExists(filePath: string): Promise<boolean> {
const projectId = this.getCurrentProjectId();
return await fsManager.fileExists(projectId, filePath);
try {
return await fsManager.fileExists(projectId, filePath);
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
throw new Error(`Failed to check if file exists "${filePath}": ${fsError.message}`);
}
}
async buildProject(): Promise<{ success: boolean; message: string; url: string }> {
+23 -6
View File
@@ -17,8 +17,8 @@ export interface Project {
}
export class FileSystemManager {
private fs: LightningFS;
private dir: string;
fs: LightningFS;
dir: string;
constructor() {
this.fs = new LightningFS('shakespeare-fs');
@@ -197,7 +197,15 @@ export default defineConfig({
async readFile(projectId: string, filePath: string): Promise<string> {
const fullPath = `${this.dir}/${projectId}/${filePath}`;
return await this.fs.promises.readFile(fullPath, 'utf8');
try {
return await this.fs.promises.readFile(fullPath, 'utf8');
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
if (fsError.code === 'ENOENT') {
throw new Error(`File not found: ${filePath}`);
}
throw error;
}
}
async writeFile(projectId: string, filePath: string, content: string): Promise<void> {
@@ -220,8 +228,12 @@ export default defineConfig({
const fullPath = `${this.dir}/${projectId}/${dirPath}`;
try {
return await this.fs.promises.readdir(fullPath);
} catch {
return [];
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
if (fsError.code === 'ENOENT') {
return [];
}
throw error;
}
}
@@ -230,7 +242,12 @@ export default defineConfig({
const fullPath = `${this.dir}/${projectId}/${filePath}`;
await this.fs.promises.stat(fullPath);
return true;
} catch {
} catch (error) {
const fsError = error as NodeJS.ErrnoException;
if (fsError.code === 'ENOENT') {
return false;
}
// For other errors, we still want to know the file doesn't exist
return false;
}
}