Make FS paths configurable

This commit is contained in:
Alex Gleason committed 2025-10-23 14:50:05 -05:00
1 parent f89a481c9c
commit d75bd386aa
43 files changed
+393 -124

No files matched your search

+3 -1
View File
@@ -19,6 +19,8 @@ export interface Project {
export interface ProjectsManagerOptions {
fs: JSRuntimeFS;
git: Git;
/** Projects directory path (default: /projects) */
projectsPath?: string;
}
export class ProjectsManager {
@@ -29,7 +31,7 @@ export class ProjectsManager {
constructor(options: ProjectsManagerOptions) {
this.fs = options.fs;
this.git = options.git;
this.dir = '/projects';
this.dir = options.projectsPath || '/projects';
}
async init() {
+6 -3
View File
@@ -61,6 +61,7 @@ export class SessionManager {
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
private corsProxy?: string;
private projectsPath: string;
constructor(
fs: JSRuntimeFS,
@@ -68,11 +69,13 @@ export class SessionManager {
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
corsProxy?: string,
projectsPath = '/projects',
) {
this.fs = fs;
this.aiSettings = aiSettings;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
this.projectsPath = projectsPath;
this.corsProxy = corsProxy;
}
@@ -90,7 +93,7 @@ export class SessionManager {
// Try to load existing history
try {
const dotAI = new DotAI(this.fs, `/projects/${projectId}`);
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
@@ -232,7 +235,7 @@ export class SessionManager {
};
const systemPrompt = await makeSystemPrompt({
cwd: `/projects/${projectId}`,
cwd: `${this.projectsPath}/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
@@ -568,7 +571,7 @@ export class SessionManager {
if (!session) return;
try {
const dotAI = new DotAI(this.fs, `/projects/${session.projectId}`);
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
await dotAI.setHistory(session.sessionName, session.messages);
} catch (error) {
console.warn('Failed to save session history:', error);
+64 -22
View File
@@ -5,10 +5,29 @@ import type { AIProvider, AISettings } from '@/contexts/AISettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
const CONFIG_DIR = '/config';
const AI_CONFIG_PATH = `${CONFIG_DIR}/ai.json`;
const GIT_CONFIG_PATH = `${CONFIG_DIR}/git.json`;
const DEPLOY_CONFIG_PATH = `${CONFIG_DIR}/deploy.json`;
/**
* Get AI config file path
* @param configPath - Custom config path (default: /config)
*/
function getAIConfigPath(configPath = '/config'): string {
return `${configPath}/ai.json`;
}
/**
* Get Git config file path
* @param configPath - Custom config path (default: /config)
*/
function getGitConfigPath(configPath = '/config'): string {
return `${configPath}/git.json`;
}
/**
* Get Deploy config file path
* @param configPath - Custom config path (default: /config)
*/
function getDeployConfigPath(configPath = '/config'): string {
return `${configPath}/deploy.json`;
}
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
id: z.string(),
@@ -91,26 +110,31 @@ const deploySettingsSchema = z.object({
/**
* Ensures the config directory exists
* @param fs - Filesystem instance
* @param configPath - Custom config path (default: /config)
*/
async function ensureConfigDir(fs: JSRuntimeFS): Promise<void> {
async function ensureConfigDir(fs: JSRuntimeFS, configPath = '/config'): Promise<void> {
try {
await fs.stat(CONFIG_DIR);
await fs.stat(configPath);
} catch {
await fs.mkdir(CONFIG_DIR, { recursive: true });
await fs.mkdir(configPath, { recursive: true });
}
}
/**
* Read AI settings from VFS
* @param fs - Filesystem instance
* @param configPath - Custom config path (default: /config)
*/
export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): Promise<AISettings> {
const defaultSettings: AISettings = {
providers: [],
recentlyUsedModels: [],
};
try {
const content = await fs.readFile(AI_CONFIG_PATH, 'utf8');
const aiConfigPath = getAIConfigPath(configPath);
const content = await fs.readFile(aiConfigPath, 'utf8');
const data = JSON.parse(content);
return aiSettingsSchema.parse(data);
} catch (error) {
@@ -123,16 +147,22 @@ export async function readAISettings(fs: JSRuntimeFS): Promise<AISettings> {
/**
* Write AI settings to VFS
* @param fs - Filesystem instance
* @param settings - AI settings to write
* @param configPath - Custom config path (default: /config)
*/
export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings): Promise<void> {
await ensureConfigDir(fs);
await fs.writeFile(AI_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
export async function writeAISettings(fs: JSRuntimeFS, settings: AISettings, configPath = '/config'): Promise<void> {
await ensureConfigDir(fs, configPath);
const aiConfigPath = getAIConfigPath(configPath);
await fs.writeFile(aiConfigPath, JSON.stringify(settings, null, 2), 'utf8');
}
/**
* Read Git settings from VFS
* @param fs - Filesystem instance
* @param configPath - Custom config path (default: /config)
*/
export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
export async function readGitSettings(fs: JSRuntimeFS, configPath = '/config'): Promise<GitSettings> {
const defaultSettings: GitSettings = {
credentials: {},
hostTokens: {},
@@ -141,7 +171,8 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
// Try to read from VFS first
try {
const content = await fs.readFile(GIT_CONFIG_PATH, 'utf8');
const gitConfigPath = getGitConfigPath(configPath);
const content = await fs.readFile(gitConfigPath, 'utf8');
const data = JSON.parse(content);
const parsed = gitSettingsSchema.parse(data);
// Ensure hostTokens exists even if not in parsed data
@@ -156,22 +187,29 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
/**
* Write Git settings to VFS
* @param fs - Filesystem instance
* @param settings - Git settings to write
* @param configPath - Custom config path (default: /config)
*/
export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings): Promise<void> {
await ensureConfigDir(fs);
await fs.writeFile(GIT_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings, configPath = '/config'): Promise<void> {
await ensureConfigDir(fs, configPath);
const gitConfigPath = getGitConfigPath(configPath);
await fs.writeFile(gitConfigPath, JSON.stringify(settings, null, 2), 'utf8');
}
/**
* Read Deploy settings from VFS
* @param fs - Filesystem instance
* @param configPath - Custom config path (default: /config)
*/
export async function readDeploySettings(fs: JSRuntimeFS): Promise<DeploySettings> {
export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'): Promise<DeploySettings> {
const defaultSettings: DeploySettings = {
providers: [],
};
try {
const content = await fs.readFile(DEPLOY_CONFIG_PATH, 'utf8');
const deployConfigPath = getDeployConfigPath(configPath);
const content = await fs.readFile(deployConfigPath, 'utf8');
const data = JSON.parse(content);
return deploySettingsSchema.parse(data);
} catch (error) {
@@ -184,9 +222,13 @@ export async function readDeploySettings(fs: JSRuntimeFS): Promise<DeploySetting
/**
* Write Deploy settings to VFS
* @param fs - Filesystem instance
* @param settings - Deploy settings to write
* @param configPath - Custom config path (default: /config)
*/
export async function writeDeploySettings(fs: JSRuntimeFS, settings: DeploySettings): Promise<void> {
await ensureConfigDir(fs);
await fs.writeFile(DEPLOY_CONFIG_PATH, JSON.stringify(settings, null, 2), 'utf8');
export async function writeDeploySettings(fs: JSRuntimeFS, settings: DeploySettings, configPath = '/config'): Promise<void> {
await ensureConfigDir(fs, configPath);
const deployConfigPath = getDeployConfigPath(configPath);
await fs.writeFile(deployConfigPath, JSON.stringify(settings, null, 2), 'utf8');
}
+4 -3
View File
@@ -46,13 +46,14 @@ export async function generateUniqueFilename(
}
/**
* Save a file to the /tmp directory with deduplication
* Save a file to the tmp directory with deduplication
* @param fs - Filesystem instance
* @param file - File object to save
* @param tmpPath - Custom tmp path (default: /tmp)
* @returns Promise<string> - Full path where the file was saved
*/
export async function saveFileToTmp(fs: JSRuntimeFS, file: File): Promise<string> {
const tmpDir = '/tmp';
export async function saveFileToTmp(fs: JSRuntimeFS, file: File, tmpPath = '/tmp'): Promise<string> {
const tmpDir = tmpPath;
// Convert spaces to underscores in the filename
const sanitizedFilename = file.name.replace(/\s+/g, '_');
const uniqueFilename = await generateUniqueFilename(fs, tmpDir, sanitizedFilename);
+52 -16
View File
@@ -15,12 +15,23 @@ export function isAbsolutePath(path: string): boolean {
* Check if write operations are allowed for the given path
*
* Write operations are only allowed in:
* - /tmp/ directory and its subdirectories
* - /projects/ directory and its subdirectories (project directories)
* - Configured tmp directory and its subdirectories
* - Configured projects directory and its subdirectories (project directories)
* - Relative paths (always allowed, regardless of where they resolve to)
* - Absolute paths that resolve to within the current working directory
*
* @param path - The path to check
* @param cwd - Current working directory (optional)
* @param options - Optional configuration for allowed paths
*/
export function isWriteAllowed(path: string, cwd?: string): boolean {
export function isWriteAllowed(
path: string,
cwd?: string,
options?: {
tmpPath?: string;
projectsPath?: string;
}
): boolean {
// Always allow relative paths (this follows traditional Unix security model)
if (!isAbsolutePath(path)) {
return true;
@@ -29,13 +40,17 @@ export function isWriteAllowed(path: string, cwd?: string): boolean {
// For absolute paths, apply restrictions
const absolutePath = normalize(path);
// Allow writes to /tmp/ and its subdirectories
if (absolutePath.startsWith('/tmp/') || absolutePath === '/tmp') {
// Get configured paths with defaults
const tmpPath = options?.tmpPath || '/tmp';
const projectsPath = options?.projectsPath || '/projects';
// Allow writes to tmp directory and its subdirectories
if (absolutePath.startsWith(tmpPath + '/') || absolutePath === tmpPath) {
return true;
}
// Allow writes to /projects/ and its subdirectories (project directories)
if (absolutePath.startsWith('/projects/') || absolutePath === '/projects') {
// Allow writes to projects directory and its subdirectories (project directories)
if (absolutePath.startsWith(projectsPath + '/') || absolutePath === projectsPath) {
return true;
}
@@ -57,14 +72,24 @@ export function isWriteAllowed(path: string, cwd?: string): boolean {
* @param path - The path to validate (can be absolute or relative)
* @param operationName - Name of the operation for error messages (e.g., 'touch', 'mkdir')
* @param cwd - Current working directory for context in error messages
* @param options - Optional configuration for allowed paths
* @throws Error if the path is not allowed for write operations
*/
export function validateWritePath(path: string, operationName: string, cwd?: string): void {
if (!isWriteAllowed(path, cwd)) {
export function validateWritePath(
path: string,
operationName: string,
cwd?: string,
options?: {
tmpPath?: string;
projectsPath?: string;
}
): void {
if (!isWriteAllowed(path, cwd, options)) {
const tmpPath = options?.tmpPath || '/tmp';
const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : '';
throw new Error(
`${operationName}: write access denied to ${path}. ` +
`Write operations are only allowed in project directories and /tmp/${cwdInfo}`
`Write operations are only allowed in project directories and ${tmpPath}${cwdInfo}`
);
}
}
@@ -75,23 +100,34 @@ export function validateWritePath(path: string, operationName: string, cwd?: str
* @param path - The path that was denied
* @param toolName - Name of the tool/command for context
* @param cwd - Current working directory for context
* @param options - Optional configuration for allowed paths
* @returns Formatted error message
*/
export function createWriteAccessDeniedError(path: string, toolName?: string, cwd?: string): string {
export function createWriteAccessDeniedError(
path: string,
toolName?: string,
cwd?: string,
options?: {
tmpPath?: string;
projectsPath?: string;
}
): string {
const prefix = toolName ? `❌ Write access denied to "${path}".` : `Write access denied to ${path}.`;
const cwdInfo = cwd ? `\n\nCurrent working directory: ${cwd}` : '';
const tmpPath = options?.tmpPath || '/tmp';
const projectsPath = options?.projectsPath || '/projects';
return (
`${prefix}\n\n` +
`Write operations are only allowed in:\n` +
`- Current working directory and subdirectories\n` +
`- Project directories (/projects/ and subdirectories)\n` +
`- Temporary directory (/tmp/ and subdirectories)\n` +
`- Project directories (${projectsPath}/ and subdirectories)\n` +
`- Temporary directory (${tmpPath}/ and subdirectories)\n` +
`- Relative paths (resolved relative to current directory)\n\n` +
`💡 Examples of allowed paths:\n` +
`- "src/index.ts" (relative to current directory)\n` +
`- "/projects/my-project/src/file.js" (absolute project path)\n` +
`- "/tmp/temp-file.txt" (temporary files)\n` +
`- "/tmp/workspace/file.js" (temporary workspace)${cwdInfo}`
`- "${projectsPath}/my-project/src/file.js" (absolute project path)\n` +
`- "${tmpPath}/temp-file.txt" (temporary files)\n` +
`- "${tmpPath}/workspace/file.js" (temporary workspace)${cwdInfo}`
);
}
+12 -12
View File
@@ -8,7 +8,7 @@ import type { JSRuntimeFS } from './JSRuntime';
*/
async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: number): Promise<void> {
const now = Date.now();
try {
// Check if directory exists
try {
@@ -23,14 +23,14 @@ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: numb
// Get directory contents
const entries = await fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
try {
const stat = await fs.stat(fullPath);
const fileAge = now - (stat.mtimeMs || 0);
if (fileAge > maxAgeMs) {
if (entry.isDirectory()) {
// Recursively clean subdirectory first, then remove it
@@ -62,19 +62,19 @@ async function cleanupDirectory(fs: JSRuntimeFS, dirPath: string, maxAgeMs: numb
}
/**
* Cleans up the /tmp directory by removing files older than 1 hour
* Cleans up the tmp directory by removing files older than 1 hour
* @param fs - The filesystem instance
* @param tmpPath - Custom tmp path (default: /tmp)
*/
export async function cleanupTmpDirectory(fs: JSRuntimeFS): Promise<void> {
export async function cleanupTmpDirectory(fs: JSRuntimeFS, tmpPath = '/tmp'): Promise<void> {
const ONE_HOUR_MS = 60 * 60 * 1000; // 1 hour in milliseconds
const tmpPath = '/tmp';
console.log('Starting /tmp directory cleanup...');
console.log(`Starting ${tmpPath} directory cleanup...`);
try {
await cleanupDirectory(fs, tmpPath, ONE_HOUR_MS);
console.log('Completed /tmp directory cleanup');
console.log(`Completed ${tmpPath} directory cleanup`);
} catch (error) {
console.error('Error during /tmp cleanup:', error);
console.error(`Error during ${tmpPath} cleanup:`, error);
}
}
+7 -3
View File
@@ -15,6 +15,8 @@ interface TextEditorStrReplaceParams {
export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
readonly description = "Replace a string in a file with a new string";
@@ -27,17 +29,19 @@ export class TextEditorStrReplaceTool implements Tool<TextEditorStrReplaceParams
),
});
constructor(fs: JSRuntimeFS, cwd: string) {
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
}
async execute(args: TextEditorStrReplaceParams): Promise<string> {
const { path, old_str, new_str, normalize_whitespace = true } = args;
// Check write permissions
if (!isWriteAllowed(path, this.cwd)) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd));
if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
// Ban editing dependencies in package.json
+5 -3
View File
@@ -13,6 +13,7 @@ interface TextEditorViewParams {
export class TextEditorViewTool implements Tool<TextEditorViewParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
readonly description = "View the contents of a text file or directory";
@@ -28,9 +29,10 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
),
});
constructor(fs: JSRuntimeFS, cwd: string) {
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
}
async execute(args: TextEditorViewParams): Promise<string> {
@@ -52,9 +54,9 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
// Special handling for /projects directory - only show project directories, not their contents
// Special handling for projects directory - only show project directories, not their contents
const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash
if (normalizedPath === '/projects') {
if (normalizedPath === this.projectsPath) {
const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children
return tree;
}
+7 -3
View File
@@ -13,6 +13,8 @@ interface TextEditorWriteParams {
export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
private fs: JSRuntimeFS;
private cwd: string;
private projectsPath: string;
private tmpPath: string;
readonly description = "Create or overwrite a file with new content";
@@ -23,17 +25,19 @@ export class TextEditorWriteTool implements Tool<TextEditorWriteParams> {
file_text: z.string().describe("Content to write to the file"),
});
constructor(fs: JSRuntimeFS, cwd: string) {
constructor(fs: JSRuntimeFS, cwd: string, options?: { projectsPath?: string; tmpPath?: string }) {
this.fs = fs;
this.cwd = cwd;
this.projectsPath = options?.projectsPath || '/projects';
this.tmpPath = options?.tmpPath || '/tmp';
}
async execute(args: TextEditorWriteParams): Promise<string> {
const { path, file_text } = args;
// Check write permissions
if (!isWriteAllowed(path, this.cwd)) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd));
if (!isWriteAllowed(path, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath })) {
throw new Error(createWriteAccessDeniedError(path, undefined, this.cwd, { projectsPath: this.projectsPath, tmpPath: this.tmpPath }));
}
if (