Function bodies 284 total
TaskFileManager.hasFinalResult method · typescript · L472-L483 (12 LOC)src/task/file-manager.ts
async hasFinalResult(taskId: string): Promise<boolean> {
const finalResultPath = path.join(this.getTaskDir(taskId), 'final_result.md');
try {
await fs.access(finalResultPath);
logger.debug({ taskId, finalResultPath }, 'Final result detected');
return true;
} catch {
logger.debug({ taskId }, 'Final result not detected');
return false;
}
}IterationBridge.constructor method · typescript · L65-L71 (7 LOC)src/task/iteration-bridge.ts
constructor(config: IterationBridgeConfig) {
this.evaluatorConfig = config.evaluatorConfig;
this.iteration = config.iteration;
this.taskId = config.taskId;
this.chatId = config.chatId;
this.fileManager = new TaskFileManager();
}IterationBridge.getExecutorOutput method · typescript · L204-L210 (7 LOC)src/task/iteration-bridge.ts
async getExecutorOutput(): Promise<string> {
try {
return await this.fileManager.readExecution(this.taskId, this.iteration);
} catch {
return '';
}
}parseBaseToolName function · typescript · L23-L30 (8 LOC)src/task/mcp-utils.ts
export function parseBaseToolName(toolName: string): string {
if (!toolName) {
return '';
}
return toolName.includes('__')
? toolName.split('__').pop() || toolName
: toolName;
}loadSkill function · typescript · L182-L223 (42 LOC)src/task/skill-loader.ts
export async function loadSkill(skillName: string): Promise<SkillLoadResult> {
try {
const skillsBaseDir = Config.getSkillsDir();
const skillPath = path.join(
skillsBaseDir,
skillName,
'SKILL.md'
);
logger.debug({ skillName, skillPath }, 'Loading skill file');
const content = await fs.readFile(skillPath, 'utf-8');
const { frontmatter, contentStart } = parseSkillFrontmatter(content);
const skillContent = content.slice(contentStart).trim();
const skill: ParsedSkill = {
name: (frontmatter['name'] as string) || skillName,
description: (frontmatter['description'] as string) || '',
disableModelInvocation: (frontmatter['disableModelInvocation'] as boolean) ?? false,
allowedTools: (frontmatter['allowedTools'] as string[]) || [],
content: skillContent,
};
logger.info({
skillName: skill.name,
toolCount: skill.allowedTools.length,
contentLength: skillContent.length,
}, 'Skill loadeloadSkillOrThrow function · typescript · L233-L245 (13 LOC)src/task/skill-loader.ts
export async function loadSkillOrThrow(skillName: string): Promise<ParsedSkill> {
const result = await loadSkill(skillName);
if (!result.success || !result.skill) {
throw new Error(
`Required skill "${skillName}" failed to load. ` +
`Error: ${result.error || 'Unknown error'}. ` +
`Please ensure skills directory is configured and ${skillName}/SKILL.md exists.`
);
}
return result.skill;
}TaskFileWatcher.start method · typescript · L72-L93 (22 LOC)src/task/task-file-watcher.ts
async start(): Promise<void> {
if (this.running) {
logger.warn('Task file watcher already running');
return;
}
// Ensure directory exists
await fs.promises.mkdir(this.tasksDir, { recursive: true });
// Scan existing tasks to avoid reprocessing
await this.scanExistingTasks();
this.running = true;
// Start polling
this.scheduleNextPoll();
logger.info(
{ tasksDir: this.tasksDir, pollIntervalMs: this.pollIntervalMs },
'Task file watcher started (polling mode)'
);
}About: code-quality intelligence by Repobility · https://repobility.com
TaskFileWatcher.scheduleNextPoll method · typescript · L98-L108 (11 LOC)src/task/task-file-watcher.ts
private scheduleNextPoll(): void {
if (!this.running) return;
this.pollTimer = setTimeout(() => {
this.poll().catch((error) => {
logger.error({ err: error }, 'Error during poll');
}).finally(() => {
this.scheduleNextPoll();
});
}, this.pollIntervalMs);
}TaskFileWatcher.scanExistingTasks method · typescript · L113-L131 (19 LOC)src/task/task-file-watcher.ts
private async scanExistingTasks(): Promise<void> {
try {
const entries = await fs.promises.readdir(this.tasksDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const taskFile = path.join(this.tasksDir, entry.name, 'task.md');
if (await this.fileExists(taskFile)) {
this.processedTasks.add(taskFile);
logger.debug({ taskFile }, 'Existing task registered');
}
}
}
logger.info({ count: this.processedTasks.size }, 'Scanned existing tasks');
} catch (error) {
logger.error({ err: error }, 'Failed to scan existing tasks');
}
}TaskFileWatcher.stop method · typescript · L136-L145 (10 LOC)src/task/task-file-watcher.ts
stop(): void {
this.running = false;
if (this.pollTimer) {
clearTimeout(this.pollTimer);
this.pollTimer = null;
}
logger.info('Task file watcher stopped');
}TaskFileWatcher.poll method · typescript · L157-L192 (36 LOC)src/task/task-file-watcher.ts
private async poll(): Promise<void> {
try {
const entries = await fs.promises.readdir(this.tasksDir, { withFileTypes: true });
for (const entry of entries) {
if (entry.isDirectory()) {
const taskFile = path.join(this.tasksDir, entry.name, 'task.md');
// Skip if already processed
if (this.processedTasks.has(taskFile)) {
continue;
}
// Check if task.md exists
if (await this.fileExists(taskFile)) {
const metadata = await this.parseTaskFile(taskFile);
if (metadata) {
// Mark as processed
this.processedTasks.add(taskFile);
logger.info(
{ messageId: metadata.messageId, chatId: metadata.chatId, taskFile },
'New task detected, triggering dialogue'
);
// Trigger dialogue
this.onTaskCreated(taskFile, metadata.messageId, metadata.chatId);
}
TaskFileWatcher.fileExists method · typescript · L197-L204 (8 LOC)src/task/task-file-watcher.ts
private async fileExists(filePath: string): Promise<boolean> {
try {
await fs.promises.access(filePath);
return true;
} catch {
return false;
}
}TaskFileWatcher.parseTaskFile method · typescript · L209-L231 (23 LOC)src/task/task-file-watcher.ts
private async parseTaskFile(filePath: string): Promise<TaskMetadata | null> {
try {
const content = await fs.promises.readFile(filePath, 'utf-8');
// Extract Task ID (messageId)
const taskIdMatch = content.match(/\*\*Task ID\*\*:\s*(\S+)/);
const messageId = taskIdMatch?.[1];
// Extract Chat ID
const chatIdMatch = content.match(/\*\*Chat ID\*\*:\s*(\S+)/);
const chatId = chatIdMatch?.[1];
if (!messageId || !chatId) {
logger.warn({ filePath, hasTaskId: !!messageId, hasChatId: !!chatId }, 'Task file missing required metadata');
return null;
}
return { messageId, chatId };
} catch (error) {
logger.error({ err: error, filePath }, 'Failed to parse task file');
return null;
}
}detectMimeType function · typescript · L46-L83 (38 LOC)src/transport/file-client.ts
function detectMimeType(filePath: string): string | undefined {
const ext = path.extname(filePath).toLowerCase();
const mimeTypes: Record<string, string> = {
'.txt': 'text/plain',
'.md': 'text/markdown',
'.json': 'application/json',
'.pdf': 'application/pdf',
'.doc': 'application/msword',
'.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'.xls': 'application/vnd.ms-excel',
'.xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.ppt': 'application/vnd.ms-powerpoint',
'.pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.webp': 'image/webp',
'.zip': 'application/zip',
'.tar': 'application/x-tar',
'.gz': 'application/gzip',
'.mp3': 'audio/mpeg',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.csvFileClient.constructor method · typescript · L107-L117 (11 LOC)src/transport/file-client.ts
constructor(config: FileClientConfig) {
this.baseUrl = config.commNodeUrl.replace(/\/$/, '');
this.timeout = config.timeout ?? 30000;
this.downloadDir = config.downloadDir;
logger.info({
baseUrl: this.baseUrl,
timeout: this.timeout,
downloadDir: this.downloadDir,
}, 'FileClient created');
}Repobility · open methodology · https://repobility.com/research/
FileClient.uploadFile method · typescript · L126-L171 (46 LOC)src/transport/file-client.ts
async uploadFile(filePath: string, chatId?: string): Promise<FileReference> {
const buffer = await fs.readFile(filePath);
const fileName = path.basename(filePath);
const mimeType = detectMimeType(filePath);
logger.info({ filePath, fileName, size: buffer.length, chatId }, 'Uploading file');
const request: FileUploadRequest = {
fileName,
mimeType: mimeType || 'application/octet-stream',
content: buffer.toString('base64'),
chatId,
};
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const response = await fetch(`${this.baseUrl}/api/files`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
signal: controller.signal,
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Failed to upload file: ${response.status} ${text}`);
FileClient.downloadFile method · typescript · L179-L211 (33 LOC)src/transport/file-client.ts
async downloadFile(fileRef: FileReference): Promise<Buffer> {
logger.info({ fileId: fileRef.id, fileName: fileRef.fileName }, 'Downloading file');
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const response = await fetch(`${this.baseUrl}/api/files/${fileRef.id}`, {
method: 'GET',
signal: controller.signal,
});
if (!response.ok) {
const text = await response.text();
throw new Error(`Failed to download file: ${response.status} ${text}`);
}
const result = (await response.json()) as APIResponse<FileDownloadResponse>;
if (!result.success || !result.data) {
throw new Error(result.error || 'Failed to download file');
}
logger.info(
{ fileId: fileRef.id, size: result.data.content.length },
'File downloaded'
);
return Buffer.from(result.data.content, 'base64');
} finally {
cFileClient.downloadToFile method · typescript · L220-L233 (14 LOC)src/transport/file-client.ts
async downloadToFile(fileRef: FileReference, localPath?: string): Promise<string> {
const buffer = await this.downloadFile(fileRef);
const savePath =
localPath ||
path.join(this.downloadDir || '/tmp', fileRef.id, fileRef.fileName);
await fs.mkdir(path.dirname(savePath), { recursive: true });
await fs.writeFile(savePath, buffer);
logger.info({ fileId: fileRef.id, savePath }, 'File saved to local path');
return savePath;
}FileClient.getFileInfo method · typescript · L241-L269 (29 LOC)src/transport/file-client.ts
async getFileInfo(fileId: string): Promise<FileReference | null> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const response = await fetch(`${this.baseUrl}/api/files/${fileId}/info`, {
method: 'GET',
signal: controller.signal,
});
if (!response.ok) {
if (response.status === 404) {
return null;
}
const text = await response.text();
throw new Error(`Failed to get file info: ${response.status} ${text}`);
}
const result = (await response.json()) as APIResponse<{ fileRef: FileReference }>;
if (!result.success || !result.data) {
return null;
}
return result.data.fileRef;
} finally {
clearTimeout(timeoutId);
}
}createFileReference function · typescript · L110-L133 (24 LOC)src/types/file-reference.ts
export function createFileReference(
fileName: string,
source: 'user' | 'agent',
options?: {
mimeType?: string;
size?: number;
storageKey?: string;
chatId?: string;
expiresInMs?: number;
}
): FileReference {
const now = Date.now();
return {
id: uuidv4(),
fileName,
mimeType: options?.mimeType,
size: options?.size,
source,
storageKey: options?.storageKey,
chatId: options?.chatId,
createdAt: now,
expiresAt: options?.expiresInMs ? now + options.expiresInMs : undefined,
};
}parseArgValue function · typescript · L76-L82 (7 LOC)src/utils/cli-args.ts
function parseArgValue(args: string[], flag: string): string | undefined {
const index = args.indexOf(flag);
if (index !== -1 && args[index + 1]) {
return args[index + 1];
}
return undefined;
}parseGlobalArgs function · typescript · L99-L148 (50 LOC)src/utils/cli-args.ts
export function parseGlobalArgs(args: string[] = process.argv.slice(2)): GlobalArgs {
const transportConfig = Config.getTransportConfig();
const channelsConfig = Config.getChannelsConfig();
// Default values
const defaultPort = parseInt(process.env.PORT || '3001', 10);
const defaultHost = process.env.HOST || '0.0.0.0';
const defaultCommUrl = process.env.COMM_URL || 'ws://localhost:3001';
const defaultAuthToken = transportConfig.http?.authToken || process.env.AUTH_TOKEN;
const defaultRestPort = channelsConfig?.rest?.port || 3000;
const defaultEnableRest = channelsConfig?.rest?.enabled ?? true;
// Parse prompt mode
const promptIndex = args.indexOf('--prompt');
const promptMode = promptIndex !== -1;
// Parse mode
let mode: RunMode | null = null;
if (args[0] === 'start') {
const modeValue = parseArgValue(args, '--mode');
if (modeValue && ['comm', 'exec'].includes(modeValue)) {
mode = modeValue as RunMode;
}
}
// Parse other arguments
getCommNodeConfig function · typescript · L153-L164 (12 LOC)src/utils/cli-args.ts
export function getCommNodeConfig(globalArgs: GlobalArgs): CommNodeConfig {
const channelsConfig = Config.getChannelsConfig();
return {
port: globalArgs.port,
host: globalArgs.host,
authToken: globalArgs.authToken,
restPort: globalArgs.restPort || channelsConfig?.rest?.port || 3000,
enableRestChannel: globalArgs.enableRestChannel ?? channelsConfig?.rest?.enabled ?? true,
restAuthToken: channelsConfig?.rest?.authToken,
};
}Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
getExecNodeConfig function · typescript · L169-L174 (6 LOC)src/utils/cli-args.ts
export function getExecNodeConfig(globalArgs: GlobalArgs): ExecNodeConfig {
return {
commUrl: globalArgs.commUrl,
authToken: globalArgs.authToken,
};
}getCliModeConfig function · typescript · L179-L196 (18 LOC)src/utils/cli-args.ts
export function getCliModeConfig(globalArgs: GlobalArgs): CliModeConfig | null {
if (!globalArgs.promptMode) return null;
const promptIndex = globalArgs.promptArgs.indexOf('--prompt');
const prompt = promptIndex !== -1 && globalArgs.promptArgs[promptIndex + 1]
? globalArgs.promptArgs[promptIndex + 1]
: globalArgs.promptArgs.join(' ');
if (!prompt || prompt.trim() === '' || prompt === '--prompt') {
return null;
}
return {
prompt,
feishuChatId: globalArgs.feishuChatId,
port: globalArgs.port,
};
}AppError.constructor method · typescript · L85-L112 (28 LOC)src/utils/error-handler.ts
constructor(
message: string,
category: ErrorCategory = ErrorCategory.UNKNOWN,
severity: ErrorSeverity = ErrorSeverity.ERROR,
options: {
retryable?: boolean;
transient?: boolean;
userMessage?: string;
context?: Record<string, unknown>;
cause?: Error;
} = {}
) {
super(message, { cause: options.cause });
this.name = 'AppError';
this.category = category;
this.severity = severity;
this.retryable = options.retryable ?? false;
this.transient = options.transient ?? false;
this.userMessage = options.userMessage;
this.context = options.context;
this.originalError = options.cause;
this.errorId = this.generateErrorId();
// Ensure proper stack trace
if (Error.captureStackTrace) {
Error.captureStackTrace(this, AppError);
}
}AppError.toJSON method · typescript · L118-L136 (19 LOC)src/utils/error-handler.ts
toJSON() {
return {
errorId: this.errorId,
name: this.name,
message: this.message,
category: this.category,
severity: this.severity,
retryable: this.retryable,
transient: this.transient,
userMessage: this.userMessage,
context: this.context,
stack: this.stack,
originalError: this.originalError ? {
name: this.originalError.name,
message: this.originalError.message,
stack: this.originalError.stack
} : undefined
};
}getErrorHandlerLogger function · typescript · L147-L152 (6 LOC)src/utils/error-handler.ts
function getErrorHandlerLogger(): Logger {
if (!errorLogger) {
errorLogger = createLogger('ErrorHandler');
}
return errorLogger;
}classifyError function · typescript · L157-L240 (84 LOC)src/utils/error-handler.ts
export function classifyError(error: Error | unknown): ErrorCategory {
// If it's already an AppError, return its category
if (error instanceof AppError) {
return error.category;
}
if (!(error instanceof Error)) {
return ErrorCategory.UNKNOWN;
}
const message = error.message.toLowerCase();
const name = error.constructor.name.toLowerCase();
// Network errors
if (
name.includes('network') ||
name.includes('timeout') ||
message.includes('etimedout') ||
message.includes('enotfound') ||
message.includes('econnrefused') ||
message.includes('econnreset')
) {
return ErrorCategory.NETWORK;
}
// Timeout errors
if (
message.includes('timeout') ||
name.includes('timeout')
) {
return ErrorCategory.TIMEOUT;
}
// API/HTTP errors
if (
name.includes('http') ||
name.includes('api') ||
message.includes('rate limit') ||
message.includes('429') ||
message.includes('500')
) {
return ErrorCategoryisRetryable function · typescript · L245-L274 (30 LOC)src/utils/error-handler.ts
export function isRetryable(error: Error | unknown): boolean {
if (error instanceof AppError) {
return error.retryable;
}
if (!(error instanceof Error)) {
return false;
}
const category = classifyError(error);
// Network and timeout errors are typically retryable
const retryableCategories = [
ErrorCategory.NETWORK,
ErrorCategory.TIMEOUT,
ErrorCategory.API
];
// Check for specific retryable error patterns
const message = error.message.toLowerCase();
const isRetryablePattern =
message.includes('timeout') ||
message.includes('etimedout') ||
message.includes('econnreset') ||
message.includes('rate limit') ||
message.includes('503') ||
message.includes('502');
return retryableCategories.includes(category) || isRetryablePattern;
}isTransient function · typescript · L279-L304 (26 LOC)src/utils/error-handler.ts
export function isTransient(error: Error | unknown): boolean {
if (error instanceof AppError) {
return error.transient;
}
if (!(error instanceof Error)) {
return false;
}
const category = classifyError(error);
// Network and timeout errors are typically transient
const transientCategories = [
ErrorCategory.NETWORK,
ErrorCategory.TIMEOUT
];
const message = error.message.toLowerCase();
const isTransientPattern =
message.includes('timeout') ||
message.includes('etimedout') ||
message.includes('econnreset') ||
message.includes('rate limit');
return transientCategories.includes(category) || isTransientPattern;
}Same scanner, your repo: https://repobility.com — Repobility
getSeverity function · typescript · L309-L328 (20 LOC)src/utils/error-handler.ts
export function getSeverity(error: Error | unknown): ErrorSeverity {
if (error instanceof AppError) {
return error.severity;
}
const category = classifyError(error);
// Configuration errors are fatal
if (category === ErrorCategory.CONFIGURATION) {
return ErrorSeverity.FATAL;
}
// Permission errors are typically fatal (need admin intervention)
if (category === ErrorCategory.PERMISSION) {
return ErrorSeverity.FATAL;
}
// Default to error level
return ErrorSeverity.ERROR;
}createUserMessage function · typescript · L333-L364 (32 LOC)src/utils/error-handler.ts
export function createUserMessage(error: Error | unknown): string {
if (error instanceof AppError) {
return error.userMessage || error.message;
}
if (!(error instanceof Error)) {
return 'An unknown error occurred';
}
const category = classifyError(error);
switch (category) {
case ErrorCategory.NETWORK:
return 'Network error. Please check your connection and try again.';
case ErrorCategory.TIMEOUT:
return 'Operation timed out. Please try again.';
case ErrorCategory.API:
return 'Service unavailable. Please try again later.';
case ErrorCategory.VALIDATION:
return 'Invalid input. Please check your request and try again.';
case ErrorCategory.PERMISSION:
return 'You do not have permission to perform this action.';
case ErrorCategory.CONFIGURATION:
return 'Configuration error. Please contact support.';
case ErrorCategory.FILESYSTEM:
return 'File system error. Please check file permissions.';
case enrichError function · typescript · L369-L409 (41 LOC)src/utils/error-handler.ts
export function enrichError(
error: Error | unknown,
context: ErrorContext = {}
): AppError {
// If it's already an AppError, merge context
if (error instanceof AppError) {
return new AppError(
error.message,
error.category,
error.severity,
{
...error.context,
...context,
cause: error.originalError || error
}
);
}
// Convert unknown error to Error
const errorObj = error instanceof Error ? error : new Error(String(error));
// Classify the error
const category = context.category || classifyError(errorObj);
const severity = context.errorId ? ErrorSeverity.FATAL : getSeverity(errorObj);
const retryable = context.retryable ?? isRetryable(errorObj);
const transient = context.transient ?? isTransient(errorObj);
const userMessage = context.userMessage || createUserMessage(errorObj);
return new AppError(
errorObj.message,
category,
severity,
{
retryable,
transient,
userlogError function · typescript · L414-L445 (32 LOC)src/utils/error-handler.ts
export function logError(
error: Error | unknown,
context: ErrorContext = {},
customLogger?: Logger
): void {
const logger = customLogger || getErrorHandlerLogger();
const enriched = enrichError(error, context);
const {severity} = enriched;
const logData: Record<string, unknown> = {
err: error instanceof Error ? error : undefined,
errorId: enriched.errorId,
category: enriched.category,
retryable: enriched.retryable,
transient: enriched.transient,
userMessage: enriched.userMessage,
...context
};
// Log at appropriate level
switch (severity) {
case ErrorSeverity.FATAL:
logger.fatal(logData, enriched.message);
break;
case ErrorSeverity.ERROR:
logger.error(logData, enriched.message);
break;
case ErrorSeverity.WARN:
logger.warn(logData, enriched.message);
break;
}
}AgentExecutionError.constructor method · typescript · L16-L43 (28 LOC)src/utils/errors.ts
constructor(
message: string,
public options: {
/** Original error that caused this error */
cause?: Error;
/** Agent type that threw the error */
agent?: string;
/** Task ID being processed */
taskId?: string;
/** Iteration number */
iteration?: number;
/** Whether the error is recoverable (can retry) */
recoverable?: boolean;
}
) {
super(message);
this.name = 'AgentExecutionError';
// Maintain stack trace (V8 only)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, AgentExecutionError);
}
// Include cause in message for better logging
if (options.cause) {
this.message = `${message} (caused by: ${options.cause.message})`;
}
}AgentExecutionError.toJSON method · typescript · L48-L59 (12 LOC)src/utils/errors.ts
toJSON(): Record<string, unknown> {
return {
name: this.name,
message: this.message,
agent: this.options.agent,
taskId: this.options.taskId,
iteration: this.options.iteration,
recoverable: this.options.recoverable,
cause: this.options.cause?.message,
stack: this.stack,
};
}TimeoutError.constructor method · typescript · L71-L82 (12 LOC)src/utils/errors.ts
constructor(
message: string,
public timeoutMs: number,
public operation?: string
) {
super(message);
this.name = 'TimeoutError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, TimeoutError);
}
}TimeoutError.getTimeoutDuration method · typescript · L87-L95 (9 LOC)src/utils/errors.ts
getTimeoutDuration(): string {
if (this.timeoutMs < 1000) {
return `${this.timeoutMs}ms`;
} else if (this.timeoutMs < 60000) {
return `${(this.timeoutMs / 1000).toFixed(1)}s`;
} else {
return `${(this.timeoutMs / 60000).toFixed(1)}m`;
}
}About: code-quality intelligence by Repobility · https://repobility.com
TimeoutError.toJSON method · typescript · L97-L106 (10 LOC)src/utils/errors.ts
toJSON(): Record<string, unknown> {
return {
name: this.name,
message: this.message,
timeoutMs: this.timeoutMs,
timeoutDuration: this.getTimeoutDuration(),
operation: this.operation,
stack: this.stack,
};
}SDKError.constructor method · typescript · L118-L129 (12 LOC)src/utils/errors.ts
constructor(
message: string,
public sdkDetails: unknown,
public sdkOperation?: string
) {
super(message);
this.name = 'SDKError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, SDKError);
}
}SDKError.isRetryable method · typescript · L137-L154 (18 LOC)src/utils/errors.ts
isRetryable(): boolean {
// Check for common retryable error patterns
const message = this.message.toLowerCase();
const retryablePatterns = [
'timeout',
'network',
'connection',
'econnreset',
'etimedout',
'econnrefused',
'rate limit',
'temporary',
'unavailable',
];
return retryablePatterns.some(pattern => message.includes(pattern));
}SDKError.toJSON method · typescript · L156-L165 (10 LOC)src/utils/errors.ts
toJSON(): Record<string, unknown> {
return {
name: this.name,
message: this.message,
sdkOperation: this.sdkOperation,
isRetryable: this.isRetryable(),
sdkDetails: this.sdkDetails,
stack: this.stack,
};
}FileOperationError.constructor method · typescript · L180-L193 (14 LOC)src/utils/errors.ts
constructor(
message: string,
public filePath: string,
public operation: string,
cause?: Error
) {
super(message);
this.name = 'FileOperationError';
this.cause = cause;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, FileOperationError);
}
}FileOperationError.toJSON method · typescript · L195-L204 (10 LOC)src/utils/errors.ts
toJSON(): Record<string, unknown> {
return {
name: this.name,
message: this.message,
filePath: this.filePath,
operation: this.operation,
cause: this.cause ? this.cause.message : undefined,
stack: this.stack,
};
}ValidationError.constructor method · typescript · L216-L227 (12 LOC)src/utils/errors.ts
constructor(
message: string,
public field?: string,
public value?: unknown
) {
super(message);
this.name = 'ValidationError';
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ValidationError);
}
}ValidationError.toJSON method · typescript · L229-L237 (9 LOC)src/utils/errors.ts
toJSON(): Record<string, unknown> {
return {
name: this.name,
message: this.message,
field: this.field,
value: this.value,
stack: this.stack,
};
}Repobility · open methodology · https://repobility.com/research/
isRetryable function · typescript · L246-L272 (27 LOC)src/utils/errors.ts
export function isRetryable(error: Error): boolean {
if (error instanceof SDKError) {
return error.isRetryable();
}
if (error instanceof AgentExecutionError) {
return error.options.recoverable ?? false;
}
// Timeout errors are generally not retryable at the same timeout
if (error instanceof TimeoutError) {
return false;
}
// File operation errors are not retryable (might succeed on retry if locking issue)
if (error instanceof FileOperationError) {
return true;
}
// Validation errors are never retryable (same input will fail again)
if (error instanceof ValidationError) {
return false;
}
// Default: unknown errors are not retryable
return false;
}formatError function · typescript · L280-L295 (16 LOC)src/utils/errors.ts
export function formatError(error: Error): Record<string, unknown> {
if (error instanceof AgentExecutionError ||
error instanceof TimeoutError ||
error instanceof SDKError ||
error instanceof FileOperationError ||
error instanceof ValidationError) {
return error.toJSON();
}
// Generic error
return {
name: error.name,
message: error.message,
stack: error.stack,
};
}getDefaultLogLevel function · typescript · L80-L89 (10 LOC)src/utils/logger.ts
function getDefaultLogLevel(): LogLevel {
const envLevel = process.env.LOG_LEVEL?.toLowerCase();
const validLevels: LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
if (envLevel && validLevels.includes(envLevel as LogLevel)) {
return envLevel as LogLevel;
}
return isDevelopment() ? 'debug' : 'info';
}