Merge branch 'main' into feature/shared-packages

This commit is contained in:
Test User
2025-12-20 23:55:03 -05:00
76 changed files with 1898 additions and 893 deletions

View File

@@ -4,12 +4,17 @@
*/
import path from "path";
import fs from "fs/promises";
import * as secureFs from "../lib/secure-fs.js";
import type { EventEmitter } from "../lib/events.js";
import type { ExecuteOptions } from "@automaker/types";
import { readImageAsBase64, buildPromptWithImages, isAbortError } from "@automaker/utils";
import {
readImageAsBase64,
buildPromptWithImages,
isAbortError,
} from "@automaker/utils";
import { ProviderFactory } from "../providers/provider-factory.js";
import { createChatOptions } from "../lib/sdk-options.js";
import { isPathAllowed, PathNotAllowedError } from "@automaker/platform";
interface Message {
id: string;
@@ -59,7 +64,7 @@ export class AgentService {
}
async initialize(): Promise<void> {
await fs.mkdir(this.stateDir, { recursive: true });
await secureFs.mkdir(this.stateDir, { recursive: true });
}
/**
@@ -77,11 +82,22 @@ export class AgentService {
const metadata = await this.loadMetadata();
const sessionMetadata = metadata[sessionId];
// Determine the effective working directory
const effectiveWorkingDirectory = workingDirectory || process.cwd();
const resolvedWorkingDirectory = path.resolve(effectiveWorkingDirectory);
// Validate that the working directory is allowed
if (!isPathAllowed(resolvedWorkingDirectory)) {
throw new Error(
`Working directory ${effectiveWorkingDirectory} is not allowed`
);
}
this.sessions.set(sessionId, {
messages,
isRunning: false,
abortController: null,
workingDirectory: workingDirectory || process.cwd(),
workingDirectory: resolvedWorkingDirectory,
sdkSessionId: sessionMetadata?.sdkSessionId, // Load persisted SDK session ID
});
}
@@ -388,7 +404,7 @@ export class AgentService {
const sessionFile = path.join(this.stateDir, `${sessionId}.json`);
try {
const data = await fs.readFile(sessionFile, "utf-8");
const data = (await secureFs.readFile(sessionFile, "utf-8")) as string;
return JSON.parse(data);
} catch {
return [];
@@ -399,7 +415,7 @@ export class AgentService {
const sessionFile = path.join(this.stateDir, `${sessionId}.json`);
try {
await fs.writeFile(
await secureFs.writeFile(
sessionFile,
JSON.stringify(messages, null, 2),
"utf-8"
@@ -412,7 +428,10 @@ export class AgentService {
async loadMetadata(): Promise<Record<string, SessionMetadata>> {
try {
const data = await fs.readFile(this.metadataFile, "utf-8");
const data = (await secureFs.readFile(
this.metadataFile,
"utf-8"
)) as string;
return JSON.parse(data);
} catch {
return {};
@@ -420,7 +439,7 @@ export class AgentService {
}
async saveMetadata(metadata: Record<string, SessionMetadata>): Promise<void> {
await fs.writeFile(
await secureFs.writeFile(
this.metadataFile,
JSON.stringify(metadata, null, 2),
"utf-8"
@@ -458,11 +477,29 @@ export class AgentService {
const sessionId = this.generateId();
const metadata = await this.loadMetadata();
// Determine the effective working directory
const effectiveWorkingDirectory =
workingDirectory || projectPath || process.cwd();
const resolvedWorkingDirectory = path.resolve(effectiveWorkingDirectory);
// Validate that the working directory is allowed
if (!isPathAllowed(resolvedWorkingDirectory)) {
throw new PathNotAllowedError(effectiveWorkingDirectory);
}
// Validate that projectPath is allowed if provided
if (projectPath) {
const resolvedProjectPath = path.resolve(projectPath);
if (!isPathAllowed(resolvedProjectPath)) {
throw new PathNotAllowedError(projectPath);
}
}
const session: SessionMetadata = {
id: sessionId,
name,
projectPath,
workingDirectory: workingDirectory || projectPath || process.cwd(),
workingDirectory: resolvedWorkingDirectory,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
model,
@@ -521,7 +558,7 @@ export class AgentService {
// Delete session file
try {
const sessionFile = path.join(this.stateDir, `${sessionId}.json`);
await fs.unlink(sessionFile);
await secureFs.unlink(sessionFile);
} catch {
// File may not exist
}

File diff suppressed because it is too large Load Diff

View File

@@ -4,9 +4,9 @@
*/
import path from "path";
import fs from "fs/promises";
import type { Feature } from "@automaker/types";
import { createLogger } from "@automaker/utils";
import * as secureFs from "../lib/secure-fs.js";
import {
getFeaturesDir,
getFeatureDir,
@@ -39,8 +39,12 @@ export class FeatureLoader {
*/
private async deleteOrphanedImages(
projectPath: string,
oldPaths: Array<string | { path: string; [key: string]: unknown }> | undefined,
newPaths: Array<string | { path: string; [key: string]: unknown }> | undefined
oldPaths:
| Array<string | { path: string; [key: string]: unknown }>
| undefined,
newPaths:
| Array<string | { path: string; [key: string]: unknown }>
| undefined
): Promise<void> {
if (!oldPaths || oldPaths.length === 0) {
return;
@@ -59,8 +63,8 @@ export class FeatureLoader {
if (!newPathSet.has(oldPath)) {
try {
// Paths are now absolute
await fs.unlink(oldPath);
logger.info(`Deleted orphaned image: ${oldPath}`);
await secureFs.unlink(oldPath);
console.log(`[FeatureLoader] Deleted orphaned image: ${oldPath}`);
} catch (error) {
// Ignore errors when deleting (file may already be gone)
logger.warn(
@@ -87,10 +91,11 @@ export class FeatureLoader {
}
const featureImagesDir = this.getFeatureImagesDir(projectPath, featureId);
await fs.mkdir(featureImagesDir, { recursive: true });
await secureFs.mkdir(featureImagesDir, { recursive: true });
const updatedPaths: Array<string | { path: string; [key: string]: unknown }> =
[];
const updatedPaths: Array<
string | { path: string; [key: string]: unknown }
> = [];
for (const imagePath of imagePaths) {
try {
@@ -110,7 +115,7 @@ export class FeatureLoader {
// Check if file exists
try {
await fs.access(fullOriginalPath);
await secureFs.access(fullOriginalPath);
} catch {
logger.warn(
`[FeatureLoader] Image not found, skipping: ${fullOriginalPath}`
@@ -123,14 +128,14 @@ export class FeatureLoader {
const newPath = path.join(featureImagesDir, filename);
// Copy the file
await fs.copyFile(fullOriginalPath, newPath);
logger.info(
await secureFs.copyFile(fullOriginalPath, newPath);
console.log(
`[FeatureLoader] Copied image: ${originalPath} -> ${newPath}`
);
// Try to delete the original temp file
try {
await fs.unlink(fullOriginalPath);
await secureFs.unlink(fullOriginalPath);
} catch {
// Ignore errors when deleting temp file
}
@@ -163,14 +168,20 @@ export class FeatureLoader {
* Get the path to a feature's feature.json file
*/
getFeatureJsonPath(projectPath: string, featureId: string): string {
return path.join(this.getFeatureDir(projectPath, featureId), "feature.json");
return path.join(
this.getFeatureDir(projectPath, featureId),
"feature.json"
);
}
/**
* Get the path to a feature's agent-output.md file
*/
getAgentOutputPath(projectPath: string, featureId: string): string {
return path.join(this.getFeatureDir(projectPath, featureId), "agent-output.md");
return path.join(
this.getFeatureDir(projectPath, featureId),
"agent-output.md"
);
}
/**
@@ -189,13 +200,15 @@ export class FeatureLoader {
// Check if features directory exists
try {
await fs.access(featuresDir);
await secureFs.access(featuresDir);
} catch {
return [];
}
// Read all feature directories
const entries = await fs.readdir(featuresDir, { withFileTypes: true });
const entries = (await secureFs.readdir(featuresDir, {
withFileTypes: true,
})) as any[];
const featureDirs = entries.filter((entry) => entry.isDirectory());
// Load each feature
@@ -205,7 +218,10 @@ export class FeatureLoader {
const featureJsonPath = this.getFeatureJsonPath(projectPath, featureId);
try {
const content = await fs.readFile(featureJsonPath, "utf-8");
const content = (await secureFs.readFile(
featureJsonPath,
"utf-8"
)) as string;
const feature = JSON.parse(content);
if (!feature.id) {
@@ -252,7 +268,10 @@ export class FeatureLoader {
async get(projectPath: string, featureId: string): Promise<Feature | null> {
try {
const featureJsonPath = this.getFeatureJsonPath(projectPath, featureId);
const content = await fs.readFile(featureJsonPath, "utf-8");
const content = (await secureFs.readFile(
featureJsonPath,
"utf-8"
)) as string;
return JSON.parse(content);
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
@@ -281,7 +300,7 @@ export class FeatureLoader {
await ensureAutomakerDir(projectPath);
// Create feature directory
await fs.mkdir(featureDir, { recursive: true });
await secureFs.mkdir(featureDir, { recursive: true });
// Migrate images from temp directory to feature directory
const migratedImagePaths = await this.migrateImages(
@@ -300,7 +319,7 @@ export class FeatureLoader {
};
// Write feature.json
await fs.writeFile(
await secureFs.writeFile(
featureJsonPath,
JSON.stringify(feature, null, 2),
"utf-8"
@@ -352,7 +371,7 @@ export class FeatureLoader {
// Write back to file
const featureJsonPath = this.getFeatureJsonPath(projectPath, featureId);
await fs.writeFile(
await secureFs.writeFile(
featureJsonPath,
JSON.stringify(updatedFeature, null, 2),
"utf-8"
@@ -368,8 +387,8 @@ export class FeatureLoader {
async delete(projectPath: string, featureId: string): Promise<boolean> {
try {
const featureDir = this.getFeatureDir(projectPath, featureId);
await fs.rm(featureDir, { recursive: true, force: true });
logger.info(`Deleted feature ${featureId}`);
await secureFs.rm(featureDir, { recursive: true, force: true });
console.log(`[FeatureLoader] Deleted feature ${featureId}`);
return true;
} catch (error) {
logger.error(
@@ -389,7 +408,10 @@ export class FeatureLoader {
): Promise<string | null> {
try {
const agentOutputPath = this.getAgentOutputPath(projectPath, featureId);
const content = await fs.readFile(agentOutputPath, "utf-8");
const content = (await secureFs.readFile(
agentOutputPath,
"utf-8"
)) as string;
return content;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
@@ -412,10 +434,10 @@ export class FeatureLoader {
content: string
): Promise<void> {
const featureDir = this.getFeatureDir(projectPath, featureId);
await fs.mkdir(featureDir, { recursive: true });
await secureFs.mkdir(featureDir, { recursive: true });
const agentOutputPath = this.getAgentOutputPath(projectPath, featureId);
await fs.writeFile(agentOutputPath, content, "utf-8");
await secureFs.writeFile(agentOutputPath, content, "utf-8");
}
/**
@@ -427,7 +449,7 @@ export class FeatureLoader {
): Promise<void> {
try {
const agentOutputPath = this.getAgentOutputPath(projectPath, featureId);
await fs.unlink(agentOutputPath);
await secureFs.unlink(agentOutputPath);
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
throw error;

View File

@@ -7,9 +7,9 @@
* - Per-project settings ({projectPath}/.automaker/settings.json)
*/
import fs from "fs/promises";
import path from "path";
import { createLogger } from "@automaker/utils";
import * as secureFs from "../lib/secure-fs.js";
import {
getGlobalSettingsPath,
getCredentialsPath,
@@ -47,12 +47,12 @@ async function atomicWriteJson(filePath: string, data: unknown): Promise<void> {
const content = JSON.stringify(data, null, 2);
try {
await fs.writeFile(tempPath, content, "utf-8");
await fs.rename(tempPath, filePath);
await secureFs.writeFile(tempPath, content, "utf-8");
await secureFs.rename(tempPath, filePath);
} catch (error) {
// Clean up temp file if it exists
try {
await fs.unlink(tempPath);
await secureFs.unlink(tempPath);
} catch {
// Ignore cleanup errors
}
@@ -65,7 +65,7 @@ async function atomicWriteJson(filePath: string, data: unknown): Promise<void> {
*/
async function readJsonFile<T>(filePath: string, defaultValue: T): Promise<T> {
try {
const content = await fs.readFile(filePath, "utf-8");
const content = (await secureFs.readFile(filePath, "utf-8")) as string;
return JSON.parse(content) as T;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
@@ -81,7 +81,7 @@ async function readJsonFile<T>(filePath: string, defaultValue: T): Promise<T> {
*/
async function fileExists(filePath: string): Promise<boolean> {
try {
await fs.access(filePath);
await secureFs.access(filePath);
return true;
} catch {
return false;
@@ -232,9 +232,7 @@ export class SettingsService {
* @param updates - Partial Credentials (usually just apiKeys)
* @returns Promise resolving to complete updated Credentials object
*/
async updateCredentials(
updates: Partial<Credentials>
): Promise<Credentials> {
async updateCredentials(updates: Partial<Credentials>): Promise<Credentials> {
await ensureDataDir(this.dataDir);
const credentialsPath = getCredentialsPath(this.dataDir);
@@ -270,8 +268,6 @@ export class SettingsService {
*/
async getMaskedCredentials(): Promise<{
anthropic: { configured: boolean; masked: string };
google: { configured: boolean; masked: string };
openai: { configured: boolean; masked: string };
}> {
const credentials = await this.getCredentials();
@@ -285,14 +281,6 @@ export class SettingsService {
configured: !!credentials.apiKeys.anthropic,
masked: maskKey(credentials.apiKeys.anthropic),
},
google: {
configured: !!credentials.apiKeys.google,
masked: maskKey(credentials.apiKeys.google),
},
openai: {
configured: !!credentials.apiKeys.openai,
masked: maskKey(credentials.apiKeys.openai),
},
};
}
@@ -563,8 +551,7 @@ export class SettingsService {
// Get theme from project object
const project = projects.find((p) => p.path === projectPath);
if (project?.theme) {
projectSettings.theme =
project.theme as ProjectSettings["theme"];
projectSettings.theme = project.theme as ProjectSettings["theme"];
}
if (boardBackgroundByProject?.[projectPath]) {
@@ -586,7 +573,9 @@ export class SettingsService {
migratedProjectCount++;
}
} catch (e) {
errors.push(`Failed to migrate project settings for ${projectPath}: ${e}`);
errors.push(
`Failed to migrate project settings for ${projectPath}: ${e}`
);
}
}