mirror of
https://github.com/AutoMaker-Org/automaker.git
synced 2026-01-31 20:03:37 +00:00
fix conflicts
This commit is contained in:
@@ -47,6 +47,7 @@ import { createSpecRegenerationRoutes } from './routes/app-spec/index.js';
|
||||
import { createClaudeRoutes } from './routes/claude/index.js';
|
||||
import { ClaudeUsageService } from './services/claude-usage-service.js';
|
||||
import { createGitHubRoutes } from './routes/github/index.js';
|
||||
import { createContextRoutes } from './routes/context/index.js';
|
||||
|
||||
// Load environment variables
|
||||
dotenv.config();
|
||||
@@ -147,6 +148,7 @@ app.use('/api/terminal', createTerminalRoutes());
|
||||
app.use('/api/settings', createSettingsRoutes(settingsService));
|
||||
app.use('/api/claude', createClaudeRoutes(claudeUsageService));
|
||||
app.use('/api/github', createGitHubRoutes());
|
||||
app.use('/api/context', createContextRoutes());
|
||||
|
||||
// Create HTTP server
|
||||
const server = createServer(app);
|
||||
|
||||
@@ -153,9 +153,9 @@ export class ClaudeProvider extends BaseProvider {
|
||||
tier: 'standard' as const,
|
||||
},
|
||||
{
|
||||
id: 'claude-3-5-haiku-20241022',
|
||||
name: 'Claude 3.5 Haiku',
|
||||
modelString: 'claude-3-5-haiku-20241022',
|
||||
id: 'claude-haiku-4-5-20251001',
|
||||
name: 'Claude Haiku 4.5',
|
||||
modelString: 'claude-haiku-4-5-20251001',
|
||||
provider: 'anthropic',
|
||||
description: 'Fastest Claude model',
|
||||
contextWindow: 200000,
|
||||
|
||||
24
apps/server/src/routes/context/index.ts
Normal file
24
apps/server/src/routes/context/index.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Context routes - HTTP API for context file operations
|
||||
*
|
||||
* Provides endpoints for managing context files including
|
||||
* AI-powered image description generation.
|
||||
*/
|
||||
|
||||
import { Router } from 'express';
|
||||
import { createDescribeImageHandler } from './routes/describe-image.js';
|
||||
import { createDescribeFileHandler } from './routes/describe-file.js';
|
||||
|
||||
/**
|
||||
* Create the context router
|
||||
*
|
||||
* @returns Express router with context endpoints
|
||||
*/
|
||||
export function createContextRoutes(): Router {
|
||||
const router = Router();
|
||||
|
||||
router.post('/describe-image', createDescribeImageHandler());
|
||||
router.post('/describe-file', createDescribeFileHandler());
|
||||
|
||||
return router;
|
||||
}
|
||||
220
apps/server/src/routes/context/routes/describe-file.ts
Normal file
220
apps/server/src/routes/context/routes/describe-file.ts
Normal file
@@ -0,0 +1,220 @@
|
||||
/**
|
||||
* POST /context/describe-file endpoint - Generate description for a text file
|
||||
*
|
||||
* Uses Claude Haiku to analyze a text file and generate a concise description
|
||||
* suitable for context file metadata.
|
||||
*
|
||||
* SECURITY: This endpoint validates file paths against ALLOWED_ROOT_DIRECTORY
|
||||
* and reads file content directly (not via Claude's Read tool) to prevent
|
||||
* arbitrary file reads and prompt injection attacks.
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { query } from '@anthropic-ai/claude-agent-sdk';
|
||||
import { createLogger } from '@automaker/utils';
|
||||
import { CLAUDE_MODEL_MAP } from '@automaker/types';
|
||||
import { PathNotAllowedError } from '@automaker/platform';
|
||||
import { createCustomOptions } from '../../../lib/sdk-options.js';
|
||||
import * as secureFs from '../../../lib/secure-fs.js';
|
||||
import * as path from 'path';
|
||||
|
||||
const logger = createLogger('DescribeFile');
|
||||
|
||||
/**
|
||||
* Request body for the describe-file endpoint
|
||||
*/
|
||||
interface DescribeFileRequestBody {
|
||||
/** Path to the file */
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Success response from the describe-file endpoint
|
||||
*/
|
||||
interface DescribeFileSuccessResponse {
|
||||
success: true;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error response from the describe-file endpoint
|
||||
*/
|
||||
interface DescribeFileErrorResponse {
|
||||
success: false;
|
||||
error: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract text content from Claude SDK response messages
|
||||
*/
|
||||
async function extractTextFromStream(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
stream: AsyncIterable<any>
|
||||
): Promise<string> {
|
||||
let responseText = '';
|
||||
|
||||
for await (const msg of stream) {
|
||||
if (msg.type === 'assistant' && msg.message?.content) {
|
||||
const blocks = msg.message.content as Array<{ type: string; text?: string }>;
|
||||
for (const block of blocks) {
|
||||
if (block.type === 'text' && block.text) {
|
||||
responseText += block.text;
|
||||
}
|
||||
}
|
||||
} else if (msg.type === 'result' && msg.subtype === 'success') {
|
||||
responseText = msg.result || responseText;
|
||||
}
|
||||
}
|
||||
|
||||
return responseText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the describe-file request handler
|
||||
*
|
||||
* @returns Express request handler for file description
|
||||
*/
|
||||
export function createDescribeFileHandler(): (req: Request, res: Response) => Promise<void> {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { filePath } = req.body as DescribeFileRequestBody;
|
||||
|
||||
// Validate required fields
|
||||
if (!filePath || typeof filePath !== 'string') {
|
||||
const response: DescribeFileErrorResponse = {
|
||||
success: false,
|
||||
error: 'filePath is required and must be a string',
|
||||
};
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`[DescribeFile] Starting description generation for: ${filePath}`);
|
||||
|
||||
// Resolve the path for logging and cwd derivation
|
||||
const resolvedPath = secureFs.resolvePath(filePath);
|
||||
|
||||
// Read file content using secureFs (validates path against ALLOWED_ROOT_DIRECTORY)
|
||||
// This prevents arbitrary file reads (e.g., /etc/passwd, ~/.ssh/id_rsa)
|
||||
// and prompt injection attacks where malicious filePath values could inject instructions
|
||||
let fileContent: string;
|
||||
try {
|
||||
const content = await secureFs.readFile(resolvedPath, 'utf-8');
|
||||
fileContent = typeof content === 'string' ? content : content.toString('utf-8');
|
||||
} catch (readError) {
|
||||
// Path not allowed - return 403 Forbidden
|
||||
if (readError instanceof PathNotAllowedError) {
|
||||
logger.warn(`[DescribeFile] Path not allowed: ${filePath}`);
|
||||
const response: DescribeFileErrorResponse = {
|
||||
success: false,
|
||||
error: 'File path is not within the allowed directory',
|
||||
};
|
||||
res.status(403).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// File not found
|
||||
if (
|
||||
readError !== null &&
|
||||
typeof readError === 'object' &&
|
||||
'code' in readError &&
|
||||
readError.code === 'ENOENT'
|
||||
) {
|
||||
logger.warn(`[DescribeFile] File not found: ${resolvedPath}`);
|
||||
const response: DescribeFileErrorResponse = {
|
||||
success: false,
|
||||
error: `File not found: ${filePath}`,
|
||||
};
|
||||
res.status(404).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
const errorMessage = readError instanceof Error ? readError.message : 'Unknown error';
|
||||
logger.error(`[DescribeFile] Failed to read file: ${errorMessage}`);
|
||||
const response: DescribeFileErrorResponse = {
|
||||
success: false,
|
||||
error: `Failed to read file: ${errorMessage}`,
|
||||
};
|
||||
res.status(500).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// Truncate very large files to avoid token limits
|
||||
const MAX_CONTENT_LENGTH = 50000;
|
||||
const truncated = fileContent.length > MAX_CONTENT_LENGTH;
|
||||
const contentToAnalyze = truncated
|
||||
? fileContent.substring(0, MAX_CONTENT_LENGTH)
|
||||
: fileContent;
|
||||
|
||||
// Get the filename for context
|
||||
const fileName = path.basename(resolvedPath);
|
||||
|
||||
// Build prompt with file content passed as structured data
|
||||
// The file content is included directly, not via tool invocation
|
||||
const instructionText = `Analyze the following file and provide a 1-2 sentence description suitable for use as context in an AI coding assistant. Focus on what the file contains, its purpose, and why an AI agent might want to use this context in the future (e.g., "API documentation for the authentication endpoints", "Configuration file for database connections", "Coding style guidelines for the project").
|
||||
|
||||
Respond with ONLY the description text, no additional formatting, preamble, or explanation.
|
||||
|
||||
File: ${fileName}${truncated ? ' (truncated)' : ''}`;
|
||||
|
||||
const promptContent = [
|
||||
{ type: 'text' as const, text: instructionText },
|
||||
{ type: 'text' as const, text: `\n\n--- FILE CONTENT ---\n${contentToAnalyze}` },
|
||||
];
|
||||
|
||||
// Use the file's directory as the working directory
|
||||
const cwd = path.dirname(resolvedPath);
|
||||
|
||||
// Use centralized SDK options with proper cwd validation
|
||||
// No tools needed since we're passing file content directly
|
||||
const sdkOptions = createCustomOptions({
|
||||
cwd,
|
||||
model: CLAUDE_MODEL_MAP.haiku,
|
||||
maxTurns: 1,
|
||||
allowedTools: [],
|
||||
sandbox: { enabled: true, autoAllowBashIfSandboxed: true },
|
||||
});
|
||||
|
||||
const promptGenerator = (async function* () {
|
||||
yield {
|
||||
type: 'user' as const,
|
||||
session_id: '',
|
||||
message: { role: 'user' as const, content: promptContent },
|
||||
parent_tool_use_id: null,
|
||||
};
|
||||
})();
|
||||
|
||||
const stream = query({ prompt: promptGenerator, options: sdkOptions });
|
||||
|
||||
// Extract the description from the response
|
||||
const description = await extractTextFromStream(stream);
|
||||
|
||||
if (!description || description.trim().length === 0) {
|
||||
logger.warn('Received empty response from Claude');
|
||||
const response: DescribeFileErrorResponse = {
|
||||
success: false,
|
||||
error: 'Failed to generate description - empty response',
|
||||
};
|
||||
res.status(500).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`Description generated, length: ${description.length} chars`);
|
||||
|
||||
const response: DescribeFileSuccessResponse = {
|
||||
success: true,
|
||||
description: description.trim(),
|
||||
};
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
logger.error('File description failed:', errorMessage);
|
||||
|
||||
const response: DescribeFileErrorResponse = {
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
};
|
||||
res.status(500).json(response);
|
||||
}
|
||||
};
|
||||
}
|
||||
416
apps/server/src/routes/context/routes/describe-image.ts
Normal file
416
apps/server/src/routes/context/routes/describe-image.ts
Normal file
@@ -0,0 +1,416 @@
|
||||
/**
|
||||
* POST /context/describe-image endpoint - Generate description for an image
|
||||
*
|
||||
* Uses Claude Haiku to analyze an image and generate a concise description
|
||||
* suitable for context file metadata.
|
||||
*
|
||||
* IMPORTANT:
|
||||
* The agent runner (chat/auto-mode) sends images as multi-part content blocks (base64 image blocks),
|
||||
* not by asking Claude to use the Read tool to open files. This endpoint now mirrors that approach
|
||||
* so it doesn't depend on Claude's filesystem tool access or working directory restrictions.
|
||||
*/
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import { query } from '@anthropic-ai/claude-agent-sdk';
|
||||
import { createLogger, readImageAsBase64 } from '@automaker/utils';
|
||||
import { CLAUDE_MODEL_MAP } from '@automaker/types';
|
||||
import { createCustomOptions } from '../../../lib/sdk-options.js';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
const logger = createLogger('DescribeImage');
|
||||
|
||||
/**
|
||||
* Allowlist of safe headers to log
|
||||
* All other headers are excluded to prevent leaking sensitive values
|
||||
*/
|
||||
const SAFE_HEADERS_ALLOWLIST = new Set([
|
||||
'content-type',
|
||||
'accept',
|
||||
'user-agent',
|
||||
'host',
|
||||
'referer',
|
||||
'content-length',
|
||||
'origin',
|
||||
'x-request-id',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Filter request headers to only include safe, non-sensitive values
|
||||
*/
|
||||
function filterSafeHeaders(headers: Record<string, unknown>): Record<string, unknown> {
|
||||
const filtered: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(headers)) {
|
||||
if (SAFE_HEADERS_ALLOWLIST.has(key.toLowerCase())) {
|
||||
filtered[key] = value;
|
||||
}
|
||||
}
|
||||
return filtered;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the actual file path, handling Unicode character variations.
|
||||
* macOS screenshots use U+202F (NARROW NO-BREAK SPACE) before AM/PM,
|
||||
* but this may be transmitted as a regular space through the API.
|
||||
*/
|
||||
function findActualFilePath(requestedPath: string): string | null {
|
||||
// First, try the exact path
|
||||
if (fs.existsSync(requestedPath)) {
|
||||
return requestedPath;
|
||||
}
|
||||
|
||||
// Try with Unicode normalization
|
||||
const normalizedPath = requestedPath.normalize('NFC');
|
||||
if (fs.existsSync(normalizedPath)) {
|
||||
return normalizedPath;
|
||||
}
|
||||
|
||||
// If not found, try to find the file in the directory by matching the basename
|
||||
// This handles cases where the space character differs (U+0020 vs U+202F vs U+00A0)
|
||||
const dir = path.dirname(requestedPath);
|
||||
const baseName = path.basename(requestedPath);
|
||||
|
||||
if (!fs.existsSync(dir)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const files = fs.readdirSync(dir);
|
||||
|
||||
// Normalize the requested basename for comparison
|
||||
// Replace various space-like characters with regular space for comparison
|
||||
const normalizeSpaces = (s: string): string => s.replace(/[\u00A0\u202F\u2009\u200A]/g, ' ');
|
||||
|
||||
const normalizedBaseName = normalizeSpaces(baseName);
|
||||
|
||||
for (const file of files) {
|
||||
if (normalizeSpaces(file) === normalizedBaseName) {
|
||||
logger.info(`Found matching file with different space encoding: ${file}`);
|
||||
return path.join(dir, file);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error(`Error reading directory ${dir}: ${err}`);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request body for the describe-image endpoint
|
||||
*/
|
||||
interface DescribeImageRequestBody {
|
||||
/** Path to the image file */
|
||||
imagePath: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Success response from the describe-image endpoint
|
||||
*/
|
||||
interface DescribeImageSuccessResponse {
|
||||
success: true;
|
||||
description: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Error response from the describe-image endpoint
|
||||
*/
|
||||
interface DescribeImageErrorResponse {
|
||||
success: false;
|
||||
error: string;
|
||||
requestId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map SDK/CLI errors to a stable status + user-facing message.
|
||||
*/
|
||||
function mapDescribeImageError(rawMessage: string | undefined): {
|
||||
statusCode: number;
|
||||
userMessage: string;
|
||||
} {
|
||||
const baseResponse = {
|
||||
statusCode: 500,
|
||||
userMessage: 'Failed to generate an image description. Please try again.',
|
||||
};
|
||||
|
||||
if (!rawMessage) return baseResponse;
|
||||
|
||||
if (rawMessage.includes('Claude Code process exited')) {
|
||||
return {
|
||||
statusCode: 503,
|
||||
userMessage:
|
||||
'Claude exited unexpectedly while describing the image. Try again. If it keeps happening, re-run `claude login` or update your API key in Setup so Claude can restart cleanly.',
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
rawMessage.includes('Failed to spawn Claude Code process') ||
|
||||
rawMessage.includes('Claude Code executable not found') ||
|
||||
rawMessage.includes('Claude Code native binary not found')
|
||||
) {
|
||||
return {
|
||||
statusCode: 503,
|
||||
userMessage:
|
||||
'Claude CLI could not be launched. Make sure the Claude CLI is installed and available in PATH, then try again.',
|
||||
};
|
||||
}
|
||||
|
||||
if (rawMessage.toLowerCase().includes('rate limit') || rawMessage.includes('429')) {
|
||||
return {
|
||||
statusCode: 429,
|
||||
userMessage: 'Rate limited while describing the image. Please wait a moment and try again.',
|
||||
};
|
||||
}
|
||||
|
||||
if (rawMessage.toLowerCase().includes('payload too large') || rawMessage.includes('413')) {
|
||||
return {
|
||||
statusCode: 413,
|
||||
userMessage:
|
||||
'The image is too large to send for description. Please resize/compress it and try again.',
|
||||
};
|
||||
}
|
||||
|
||||
return baseResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract text content from Claude SDK response messages and log high-signal stream events.
|
||||
*/
|
||||
async function extractTextFromStream(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
stream: AsyncIterable<any>,
|
||||
requestId: string
|
||||
): Promise<string> {
|
||||
let responseText = '';
|
||||
let messageCount = 0;
|
||||
|
||||
logger.info(`[${requestId}] [Stream] Begin reading SDK stream...`);
|
||||
|
||||
for await (const msg of stream) {
|
||||
messageCount++;
|
||||
const msgType = msg?.type;
|
||||
const msgSubtype = msg?.subtype;
|
||||
|
||||
// Keep this concise but informative. Full error object is logged in catch blocks.
|
||||
logger.info(
|
||||
`[${requestId}] [Stream] #${messageCount} type=${String(msgType)} subtype=${String(msgSubtype ?? '')}`
|
||||
);
|
||||
|
||||
if (msgType === 'assistant' && msg.message?.content) {
|
||||
const blocks = msg.message.content as Array<{ type: string; text?: string }>;
|
||||
logger.info(`[${requestId}] [Stream] assistant blocks=${blocks.length}`);
|
||||
for (const block of blocks) {
|
||||
if (block.type === 'text' && block.text) {
|
||||
responseText += block.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (msgType === 'result' && msgSubtype === 'success') {
|
||||
if (typeof msg.result === 'string' && msg.result.length > 0) {
|
||||
responseText = msg.result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] [Stream] End of stream. messages=${messageCount} textLength=${responseText.length}`
|
||||
);
|
||||
|
||||
return responseText;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the describe-image request handler
|
||||
*
|
||||
* Uses Claude SDK query with multi-part content blocks to include the image (base64),
|
||||
* matching the agent runner behavior.
|
||||
*
|
||||
* @returns Express request handler for image description
|
||||
*/
|
||||
export function createDescribeImageHandler(): (req: Request, res: Response) => Promise<void> {
|
||||
return async (req: Request, res: Response): Promise<void> => {
|
||||
const requestId = `describe-image-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
||||
const startedAt = Date.now();
|
||||
|
||||
// Request envelope logs (high value when correlating failures)
|
||||
// Only log safe headers to prevent leaking sensitive values (auth tokens, cookies, etc.)
|
||||
logger.info(`[${requestId}] ===== POST /api/context/describe-image =====`);
|
||||
logger.info(`[${requestId}] headers=${JSON.stringify(filterSafeHeaders(req.headers))}`);
|
||||
logger.info(`[${requestId}] body=${JSON.stringify(req.body)}`);
|
||||
|
||||
try {
|
||||
const { imagePath } = req.body as DescribeImageRequestBody;
|
||||
|
||||
// Validate required fields
|
||||
if (!imagePath || typeof imagePath !== 'string') {
|
||||
const response: DescribeImageErrorResponse = {
|
||||
success: false,
|
||||
error: 'imagePath is required and must be a string',
|
||||
requestId,
|
||||
};
|
||||
res.status(400).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] imagePath="${imagePath}" type=${typeof imagePath}`);
|
||||
|
||||
// Find the actual file path (handles Unicode space character variations)
|
||||
const actualPath = findActualFilePath(imagePath);
|
||||
if (!actualPath) {
|
||||
logger.error(`[${requestId}] File not found: ${imagePath}`);
|
||||
// Log hex representation of the path for debugging
|
||||
const hexPath = Buffer.from(imagePath).toString('hex');
|
||||
logger.error(`[${requestId}] imagePath hex: ${hexPath}`);
|
||||
const response: DescribeImageErrorResponse = {
|
||||
success: false,
|
||||
error: `File not found: ${imagePath}`,
|
||||
requestId,
|
||||
};
|
||||
res.status(404).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
if (actualPath !== imagePath) {
|
||||
logger.info(`[${requestId}] Using actual path: ${actualPath}`);
|
||||
}
|
||||
|
||||
// Log path + stats (this is often where issues start: missing file, perms, size)
|
||||
let stat: fs.Stats | null = null;
|
||||
try {
|
||||
stat = fs.statSync(actualPath);
|
||||
logger.info(
|
||||
`[${requestId}] fileStats size=${stat.size} bytes mtime=${stat.mtime.toISOString()}`
|
||||
);
|
||||
} catch (statErr) {
|
||||
logger.warn(
|
||||
`[${requestId}] Unable to stat image file (continuing to read base64): ${String(statErr)}`
|
||||
);
|
||||
}
|
||||
|
||||
// Read image and convert to base64 (same as agent runner)
|
||||
logger.info(`[${requestId}] Reading image into base64...`);
|
||||
const imageReadStart = Date.now();
|
||||
const imageData = await readImageAsBase64(actualPath);
|
||||
const imageReadMs = Date.now() - imageReadStart;
|
||||
|
||||
const base64Length = imageData.base64.length;
|
||||
const estimatedBytes = Math.ceil((base64Length * 3) / 4);
|
||||
logger.info(`[${requestId}] imageReadMs=${imageReadMs}`);
|
||||
logger.info(
|
||||
`[${requestId}] image meta filename=${imageData.filename} mime=${imageData.mimeType} base64Len=${base64Length} estBytes=${estimatedBytes}`
|
||||
);
|
||||
|
||||
// Build multi-part prompt with image block (no Read tool required)
|
||||
const instructionText =
|
||||
`Describe this image in 1-2 sentences suitable for use as context in an AI coding assistant. ` +
|
||||
`Focus on what the image shows and its purpose (e.g., "UI mockup showing login form with email/password fields", ` +
|
||||
`"Architecture diagram of microservices", "Screenshot of error message in terminal").\n\n` +
|
||||
`Respond with ONLY the description text, no additional formatting, preamble, or explanation.`;
|
||||
|
||||
const promptContent = [
|
||||
{ type: 'text' as const, text: instructionText },
|
||||
{
|
||||
type: 'image' as const,
|
||||
source: {
|
||||
type: 'base64' as const,
|
||||
media_type: imageData.mimeType,
|
||||
data: imageData.base64,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
logger.info(`[${requestId}] Built multi-part prompt blocks=${promptContent.length}`);
|
||||
|
||||
const cwd = path.dirname(actualPath);
|
||||
logger.info(`[${requestId}] Using cwd=${cwd}`);
|
||||
|
||||
// Use the same centralized option builder used across the server (validates cwd)
|
||||
const sdkOptions = createCustomOptions({
|
||||
cwd,
|
||||
model: CLAUDE_MODEL_MAP.haiku,
|
||||
maxTurns: 1,
|
||||
allowedTools: [],
|
||||
sandbox: { enabled: true, autoAllowBashIfSandboxed: true },
|
||||
});
|
||||
|
||||
logger.info(
|
||||
`[${requestId}] SDK options model=${sdkOptions.model} maxTurns=${sdkOptions.maxTurns} allowedTools=${JSON.stringify(
|
||||
sdkOptions.allowedTools
|
||||
)} sandbox=${JSON.stringify(sdkOptions.sandbox)}`
|
||||
);
|
||||
|
||||
const promptGenerator = (async function* () {
|
||||
yield {
|
||||
type: 'user' as const,
|
||||
session_id: '',
|
||||
message: { role: 'user' as const, content: promptContent },
|
||||
parent_tool_use_id: null,
|
||||
};
|
||||
})();
|
||||
|
||||
logger.info(`[${requestId}] Calling query()...`);
|
||||
const queryStart = Date.now();
|
||||
const stream = query({ prompt: promptGenerator, options: sdkOptions });
|
||||
logger.info(`[${requestId}] query() returned stream in ${Date.now() - queryStart}ms`);
|
||||
|
||||
// Extract the description from the response
|
||||
const extractStart = Date.now();
|
||||
const description = await extractTextFromStream(stream, requestId);
|
||||
logger.info(`[${requestId}] extractMs=${Date.now() - extractStart}`);
|
||||
|
||||
if (!description || description.trim().length === 0) {
|
||||
logger.warn(`[${requestId}] Received empty response from Claude`);
|
||||
const response: DescribeImageErrorResponse = {
|
||||
success: false,
|
||||
error: 'Failed to generate description - empty response',
|
||||
requestId,
|
||||
};
|
||||
res.status(500).json(response);
|
||||
return;
|
||||
}
|
||||
|
||||
const totalMs = Date.now() - startedAt;
|
||||
logger.info(`[${requestId}] Success descriptionLen=${description.length} totalMs=${totalMs}`);
|
||||
|
||||
const response: DescribeImageSuccessResponse = {
|
||||
success: true,
|
||||
description: description.trim(),
|
||||
};
|
||||
res.json(response);
|
||||
} catch (error) {
|
||||
const totalMs = Date.now() - startedAt;
|
||||
const err = error as unknown;
|
||||
const errMessage = err instanceof Error ? err.message : String(err);
|
||||
const errName = err instanceof Error ? err.name : 'UnknownError';
|
||||
const errStack = err instanceof Error ? err.stack : undefined;
|
||||
|
||||
logger.error(`[${requestId}] FAILED totalMs=${totalMs}`);
|
||||
logger.error(`[${requestId}] errorName=${errName}`);
|
||||
logger.error(`[${requestId}] errorMessage=${errMessage}`);
|
||||
if (errStack) logger.error(`[${requestId}] errorStack=${errStack}`);
|
||||
|
||||
// Dump all enumerable + non-enumerable props (this is where stderr/stdout/exitCode often live)
|
||||
try {
|
||||
const props = err && typeof err === 'object' ? Object.getOwnPropertyNames(err) : [];
|
||||
logger.error(`[${requestId}] errorProps=${JSON.stringify(props)}`);
|
||||
if (err && typeof err === 'object') {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const anyErr = err as any;
|
||||
const details = JSON.stringify(anyErr, props as unknown as string[]);
|
||||
logger.error(`[${requestId}] errorDetails=${details}`);
|
||||
}
|
||||
} catch (stringifyErr) {
|
||||
logger.error(`[${requestId}] Failed to serialize error object: ${String(stringifyErr)}`);
|
||||
}
|
||||
|
||||
const { statusCode, userMessage } = mapDescribeImageError(errMessage);
|
||||
const response: DescribeImageErrorResponse = {
|
||||
success: false,
|
||||
error: `${userMessage} (requestId: ${requestId})`,
|
||||
requestId,
|
||||
};
|
||||
res.status(statusCode).json(response);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -7,7 +7,12 @@ import path from 'path';
|
||||
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,
|
||||
loadContextFiles,
|
||||
} from '@automaker/utils';
|
||||
import { ProviderFactory } from '../providers/provider-factory.js';
|
||||
import { createChatOptions, validateWorkingDirectory } from '../lib/sdk-options.js';
|
||||
import { PathNotAllowedError } from '@automaker/platform';
|
||||
@@ -178,12 +183,27 @@ export class AgentService {
|
||||
await this.saveSession(sessionId, session.messages);
|
||||
|
||||
try {
|
||||
// Determine the effective working directory for context loading
|
||||
const effectiveWorkDir = workingDirectory || session.workingDirectory;
|
||||
|
||||
// Load project context files (CLAUDE.md, CODE_QUALITY.md, etc.)
|
||||
const { formattedPrompt: contextFilesPrompt } = await loadContextFiles({
|
||||
projectPath: effectiveWorkDir,
|
||||
fsModule: secureFs as Parameters<typeof loadContextFiles>[0]['fsModule'],
|
||||
});
|
||||
|
||||
// Build combined system prompt with base prompt and context files
|
||||
const baseSystemPrompt = this.getSystemPrompt();
|
||||
const combinedSystemPrompt = contextFilesPrompt
|
||||
? `${contextFilesPrompt}\n\n${baseSystemPrompt}`
|
||||
: baseSystemPrompt;
|
||||
|
||||
// Build SDK options using centralized configuration
|
||||
const sdkOptions = createChatOptions({
|
||||
cwd: workingDirectory || session.workingDirectory,
|
||||
cwd: effectiveWorkDir,
|
||||
model: model,
|
||||
sessionModel: session.model,
|
||||
systemPrompt: this.getSystemPrompt(),
|
||||
systemPrompt: combinedSystemPrompt,
|
||||
abortController: session.abortController!,
|
||||
});
|
||||
|
||||
@@ -203,8 +223,8 @@ export class AgentService {
|
||||
const options: ExecuteOptions = {
|
||||
prompt: '', // Will be set below based on images
|
||||
model: effectiveModel,
|
||||
cwd: workingDirectory || session.workingDirectory,
|
||||
systemPrompt: this.getSystemPrompt(),
|
||||
cwd: effectiveWorkDir,
|
||||
systemPrompt: combinedSystemPrompt,
|
||||
maxTurns: maxTurns,
|
||||
allowedTools: allowedTools,
|
||||
abortController: session.abortController!,
|
||||
|
||||
@@ -11,10 +11,15 @@
|
||||
|
||||
import { ProviderFactory } from '../providers/provider-factory.js';
|
||||
import type { ExecuteOptions, Feature } from '@automaker/types';
|
||||
import { buildPromptWithImages, isAbortError, classifyError } from '@automaker/utils';
|
||||
import {
|
||||
buildPromptWithImages,
|
||||
isAbortError,
|
||||
classifyError,
|
||||
loadContextFiles,
|
||||
} from '@automaker/utils';
|
||||
import { resolveModelString, DEFAULT_MODELS } from '@automaker/model-resolver';
|
||||
import { resolveDependencies, areDependenciesSatisfied } from '@automaker/dependency-resolver';
|
||||
import { getFeatureDir, getAutomakerDir, getFeaturesDir, getContextDir } from '@automaker/platform';
|
||||
import { getFeatureDir, getAutomakerDir, getFeaturesDir } from '@automaker/platform';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
@@ -549,7 +554,10 @@ export class AutoModeService {
|
||||
// Build the prompt - use continuation prompt if provided (for recovery after plan approval)
|
||||
let prompt: string;
|
||||
// Load project context files (CLAUDE.md, CODE_QUALITY.md, etc.) - passed as system prompt
|
||||
const contextFiles = await this.loadContextFiles(projectPath);
|
||||
const { formattedPrompt: contextFilesPrompt } = await loadContextFiles({
|
||||
projectPath,
|
||||
fsModule: secureFs as Parameters<typeof loadContextFiles>[0]['fsModule'],
|
||||
});
|
||||
|
||||
if (options?.continuationPrompt) {
|
||||
// Continuation prompt is used when recovering from a plan approval
|
||||
@@ -595,7 +603,7 @@ export class AutoModeService {
|
||||
projectPath,
|
||||
planningMode: feature.planningMode,
|
||||
requirePlanApproval: feature.requirePlanApproval,
|
||||
systemPrompt: contextFiles || undefined,
|
||||
systemPrompt: contextFilesPrompt || undefined,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -739,7 +747,10 @@ export class AutoModeService {
|
||||
}
|
||||
|
||||
// Load project context files (CLAUDE.md, CODE_QUALITY.md, etc.) - passed as system prompt
|
||||
const contextFiles = await this.loadContextFiles(projectPath);
|
||||
const { formattedPrompt: contextFilesPrompt } = await loadContextFiles({
|
||||
projectPath,
|
||||
fsModule: secureFs as Parameters<typeof loadContextFiles>[0]['fsModule'],
|
||||
});
|
||||
|
||||
// Build complete prompt with feature info, previous context, and follow-up instructions
|
||||
let fullPrompt = `## Follow-up on Feature Implementation
|
||||
@@ -867,7 +878,7 @@ Address the follow-up instructions above. Review the previous work and make the
|
||||
projectPath,
|
||||
planningMode: 'skip', // Follow-ups don't require approval
|
||||
previousContent: previousContext || undefined,
|
||||
systemPrompt: contextFiles || undefined,
|
||||
systemPrompt: contextFilesPrompt || undefined,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1050,63 +1061,6 @@ Address the follow-up instructions above. Review the previous work and make the
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load context files from .automaker/context/ directory
|
||||
* These are user-defined context files (CLAUDE.md, CODE_QUALITY.md, etc.)
|
||||
* that provide project-specific rules and guidelines for the agent.
|
||||
*/
|
||||
private async loadContextFiles(projectPath: string): Promise<string> {
|
||||
// Use path.resolve for cross-platform absolute path handling
|
||||
const contextDir = path.resolve(getContextDir(projectPath));
|
||||
|
||||
try {
|
||||
// Check if directory exists first
|
||||
await secureFs.access(contextDir);
|
||||
|
||||
const files = await secureFs.readdir(contextDir);
|
||||
// Filter for text-based context files (case-insensitive for Windows)
|
||||
const textFiles = files.filter((f) => {
|
||||
const lower = f.toLowerCase();
|
||||
return lower.endsWith('.md') || lower.endsWith('.txt');
|
||||
});
|
||||
|
||||
if (textFiles.length === 0) return '';
|
||||
|
||||
const contents: string[] = [];
|
||||
for (const file of textFiles) {
|
||||
// Use path.join for cross-platform path construction
|
||||
const filePath = path.join(contextDir, file);
|
||||
const content = (await secureFs.readFile(filePath, 'utf-8')) as string;
|
||||
contents.push(`## ${file}\n\n${content}`);
|
||||
}
|
||||
|
||||
console.log(`[AutoMode] Loaded ${textFiles.length} context file(s): ${textFiles.join(', ')}`);
|
||||
|
||||
return `# ⚠️ CRITICAL: Project Context Files - READ AND FOLLOW STRICTLY
|
||||
|
||||
**IMPORTANT**: The following context files contain MANDATORY project-specific rules and conventions. You MUST:
|
||||
1. Read these rules carefully before taking any action
|
||||
2. Follow ALL commands exactly as shown (e.g., if the project uses \`pnpm\`, NEVER use \`npm\` or \`npx\`)
|
||||
3. Follow ALL coding conventions, commit message formats, and architectural patterns specified
|
||||
4. Reference these rules before running ANY shell commands or making commits
|
||||
|
||||
Failure to follow these rules will result in broken builds, failed CI, and rejected commits.
|
||||
|
||||
${contents.join('\n\n---\n\n')}
|
||||
|
||||
---
|
||||
|
||||
**REMINDER**: Before running any command, verify you are using the correct package manager and following the conventions above.
|
||||
|
||||
---
|
||||
|
||||
`;
|
||||
} catch {
|
||||
// Context directory doesn't exist or is empty - this is fine
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze project to gather context
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user