diff --git a/packages/core/src/cache.ts b/packages/core/src/cache.ts index 4bb5ab0fbc4..43246b581ce 100644 --- a/packages/core/src/cache.ts +++ b/packages/core/src/cache.ts @@ -7,35 +7,80 @@ import type { UUID, } from "./types"; +/** + * Interface for defining a cache adapter that can get, set, and delete key-value pairs. + * @interface + */ export interface ICacheAdapter { get(key: string): Promise; set(key: string, value: string): Promise; delete(key: string): Promise; } +/** + * Memory cache adapter class that implements the ICacheAdapter interface. + */ + export class MemoryCacheAdapter implements ICacheAdapter { data: Map; +/** + * Constructor for creating an instance of the class with optional initial data. + * @param {Map} [initalData] - The initial data to initialize the instance with. + */ constructor(initalData?: Map) { this.data = initalData ?? new Map(); } +/** + * Retrieves the value stored in the data structure with the specified key. + * + * @param {string} key - The key to lookup in the data structure. + * @returns {Promise} The value associated with the specified key, or undefined if the key is not found. + */ async get(key: string): Promise { return this.data.get(key); } +/** + * Sets a key-value pair in the data store. + * + * @param {string} key - The key for the data entry. + * @param {string} value - The value to store. + * @returns {Promise} + */ async set(key: string, value: string): Promise { this.data.set(key, value); } +/** + * Asynchronously deletes the value associated with the given key from the data. + * + * @param {string} key - The key of the value to be deleted. + * @returns {Promise} A promise that resolves once the value is deleted. + */ async delete(key: string): Promise { this.data.delete(key); } } +/** + * Class representing a file system cache adapter. + * Implements the ICacheAdapter interface. + */ + export class FsCacheAdapter implements ICacheAdapter { +/** + * Constructor for creating an instance with a specified data directory. + * @param {string} dataDir - The directory where data will be stored. + */ constructor(private dataDir: string) {} +/** + * Asynchronously retrieves the value associated with the given key from the file system. + * @param {string} key - The key used to fetch the value. + * @returns {Promise} The value associated with the key, or undefined if an error occurs. + */ async get(key: string): Promise { try { return await fs.readFile(path.join(this.dataDir, key), "utf8"); @@ -45,6 +90,13 @@ export class FsCacheAdapter implements ICacheAdapter { } } +/** + * Asynchronously sets a key-value pair in the data directory. + * + * @param {string} key - The key of the data to be set. + * @param {string} value - The value of the data to be set. + * @returns {Promise} A Promise that resolves once the key-value pair is successfully set. + */ async set(key: string, value: string): Promise { try { const filePath = path.join(this.dataDir, key); @@ -56,6 +108,11 @@ export class FsCacheAdapter implements ICacheAdapter { } } +/** + * Deletes a file from the data directory using the given key. + * @param {string} key - The key to identify the file to be deleted. + * @returns {Promise} A Promise that resolves once the file is deleted. + */ async delete(key: string): Promise { try { const filePath = path.join(this.dataDir, key); @@ -66,34 +123,75 @@ export class FsCacheAdapter implements ICacheAdapter { } } +/** + * A class representing a cache adapter that interacts with a database cache. + * @implements {ICacheAdapter} + */ + export class DbCacheAdapter implements ICacheAdapter { +/** + * Constructor for creating a new instance of a class. + * @param {IDatabaseCacheAdapter} db - The database cache adapter used for data storage. + * @param {UUID} agentId - The unique identifier for the agent. + */ constructor( private db: IDatabaseCacheAdapter, private agentId: UUID ) {} +/** + * Retrieves a value from cache based on the provided key. + * @param {string} key - The key to search for in the cache. + * @returns {Promise} The value associated with the key, or undefined if not found. + */ async get(key: string): Promise { return this.db.getCache({ agentId: this.agentId, key }); } +/** + * Asynchronously sets a key-value pair in the cache for the current agent. + * + * @param {string} key - The key to set in the cache. + * @param {string} value - The value to associate with the key in the cache. + * @returns {Promise} A Promise that resolves when the key-value pair has been successfully set in the cache. + */ async set(key: string, value: string): Promise { await this.db.setCache({ agentId: this.agentId, key, value }); } +/** + * Deletes a cache entry with the specified key. + * @param {string} key - The key of the cache entry to be deleted. + * @returns {Promise} A Promise that resolves once the cache entry is deleted. + */ async delete(key: string): Promise { await this.db.deleteCache({ agentId: this.agentId, key }); } } +/** + * A class representing a Cache Manager. + */ export class CacheManager implements ICacheManager { adapter: CacheAdapter; +/** + * Constructor for creating an instance of the class, with a specified cache adapter. + * @param {CacheAdapter} adapter - The cache adapter to be used by the instance. + */ constructor(adapter: CacheAdapter) { this.adapter = adapter; } +/** + * Asynchronously retrieves a value from the cache based on the provided key. + * + * @template T - The type of value being retrieved from the cache. + * @param {string} key - The key to look up in the cache. + * @returns {Promise} A promise that resolves to the value associated with the key, or undefined if the key is not found or the value has expired. + */ async get(key: string): Promise { const data = await this.adapter.get(key); @@ -113,6 +211,13 @@ export class CacheManager return undefined; } +/** + * Set a key-value pair in the cache with optional expiration time. + * @param {string} key - The key to set the value for. + * @param {T} value - The value to store in the cache. + * @param {CacheOptions} [opts] - Optional additional options for caching. + * @returns {Promise} - A Promise that resolves when the value is set in the cache. + */ async set(key: string, value: T, opts?: CacheOptions): Promise { return this.adapter.set( key, @@ -120,6 +225,12 @@ export class CacheManager ); } +/** + * Asynchronously deletes a key from the storage adapter. + * + * @param {string} key - The key to be deleted. + * @returns {Promise} A Promise that resolves once the key is successfully deleted. + */ async delete(key: string): Promise { return this.adapter.delete(key); } diff --git a/packages/core/src/database.ts b/packages/core/src/database.ts index 9e8cbfa1b51..c7cf28f029a 100644 --- a/packages/core/src/database.ts +++ b/packages/core/src/database.ts @@ -16,6 +16,12 @@ import { elizaLogger } from "./logger"; * An abstract class representing a database adapter for managing various entities * like accounts, memories, actors, goals, and rooms. */ +/** + * Database adapter interface for interacting with a database. + * Contains methods for database operations like account retrieval, memory management, goal manipulation, and room management. + * Implements circuit breaker pattern for fault tolerance. + * @interface + */ export abstract class DatabaseAdapter implements IDatabaseAdapter { /** * The database instance. diff --git a/packages/core/src/database/CircuitBreaker.ts b/packages/core/src/database/CircuitBreaker.ts index b79b08daff0..252d9bdb1ef 100644 --- a/packages/core/src/database/CircuitBreaker.ts +++ b/packages/core/src/database/CircuitBreaker.ts @@ -1,5 +1,13 @@ +/** + * Defines a type representing the state of a circuit breaker. + * Possible values are "CLOSED", "OPEN", or "HALF_OPEN". + */ export type CircuitBreakerState = "CLOSED" | "OPEN" | "HALF_OPEN"; +/** + * Represents a Circuit Breaker that can monitor the status of a system and prevent overload. + * @class + */ export class CircuitBreaker { private state: CircuitBreakerState = "CLOSED"; private failureCount: number = 0; @@ -10,6 +18,13 @@ export class CircuitBreaker { private readonly resetTimeout: number; private readonly halfOpenMaxAttempts: number; +/** + * Constructor for the Circuit Breaker class. + * @param {Object} config - Configuration object with optional properties: + * @param {number} [config.failureThreshold] - Number of failures allowed before opening the circuit. + * @param {number} [config.resetTimeout] - Time in milliseconds before attempting to half-open the circuit. + * @param {number} [config.halfOpenMaxAttempts] - Maximum number of attempts in half-open state. + */ constructor( private readonly config: { failureThreshold?: number; @@ -22,6 +37,13 @@ export class CircuitBreaker { this.halfOpenMaxAttempts = config.halfOpenMaxAttempts ?? 3; } +/** + * Executes the provided asynchronous operation while respecting the state of the circuit breaker. + * If the circuit breaker is OPEN, it will transition to HALF_OPEN after a specified resetTimeout. + * Counts successful operation calls in the HALF_OPEN state and resets the circuit breaker if a maximum number of attempts is reached. + * @param {() => Promise} operation - The asynchronous operation to execute. + * @returns {Promise} A Promise that resolves with the result of the operation. + */ async execute(operation: () => Promise): Promise { if (this.state === "OPEN") { if (Date.now() - (this.lastFailureTime || 0) > this.resetTimeout) { @@ -49,6 +71,10 @@ export class CircuitBreaker { } } +/** + * Increments the failure count and updates the last failure time. + * If the failure count exceeds the failure threshold, changes the state to "OPEN". + */ private handleFailure(): void { this.failureCount++; this.lastFailureTime = Date.now(); @@ -58,12 +84,19 @@ export class CircuitBreaker { } } +/** + * Resets the state to 'CLOSED', sets the failure count to 0, and clears the last failure time. + */ private reset(): void { this.state = "CLOSED"; this.failureCount = 0; this.lastFailureTime = undefined; } +/** + * Get the current state of the object. + * @returns {"CLOSED" | "OPEN" | "HALF_OPEN"} The state of the object, which can be "CLOSED", "OPEN", or "HALF_OPEN". + */ getState(): "CLOSED" | "OPEN" | "HALF_OPEN" { return this.state; } diff --git a/packages/core/src/embedding.ts b/packages/core/src/embedding.ts index dc51432387f..91556b6f024 100644 --- a/packages/core/src/embedding.ts +++ b/packages/core/src/embedding.ts @@ -4,6 +4,18 @@ import { IAgentRuntime, ModelProviderName } from "./types.ts"; import settings from "./settings.ts"; import elizaLogger from "./logger.ts"; +/** + * Interface for embedding options. + * + * @typedef {Object} EmbeddingOptions + * @property {string} model - The name of the model to use for embedding. + * @property {string} endpoint - The API endpoint to use for embedding. + * @property {string} [apiKey] - Optional API key for authentication. + * @property {number} [length] - Optional length parameter for embedding. + * @property {boolean} [isOllama] - Optional flag for indicating if Ollama should be used. + * @property {number} [dimensions] - Optional number of dimensions for embedding. + * @property {string} [provider] - Optional provider for embedding. + */ interface EmbeddingOptions { model: string; endpoint: string; @@ -21,9 +33,19 @@ export const EmbeddingProvider = { BGE: "BGE", } as const; +/** + * Type definition for embedding provider type. + */ export type EmbeddingProviderType = (typeof EmbeddingProvider)[keyof typeof EmbeddingProvider]; +/** + * Represents the configuration for an embedding, specifying the dimensions, model, and provider. + * @typedef {Object} EmbeddingConfig + * @property {number} dimensions - The number of dimensions in the embedding. + * @property {string} model - The specific model being used for the embedding. + * @property {EmbeddingProviderType} provider - The type of provider supplying the embedding. + */ export type EmbeddingConfig = { readonly dimensions: number; readonly model: string; @@ -57,6 +79,12 @@ export const getEmbeddingConfig = (): EmbeddingConfig => ({ : "BGE", }); +/** + * Fetches remote embeddings for the given input using the specified options. + * @param {string} input - The input text to generate embeddings for. + * @param {EmbeddingOptions} options - The options object containing endpoint, apiKey, model, dimensions, length, and isOllama. + * @returns {Promise} - A promise that resolves to an array of numbers representing the embeddings. + */ async function getRemoteEmbedding( input: string, options: EmbeddingOptions @@ -111,6 +139,11 @@ async function getRemoteEmbedding( } } +/** + * Determines the embedding type based on the runtime environment and configuration settings. + * @param {IAgentRuntime} runtime - The runtime information for the agent. + * @returns {"local" | "remote"} - The type of embedding to use: "local" for Node.js or custom embeddings, "remote" for OpenAI embeddings. + */ export function getEmbeddingType(runtime: IAgentRuntime): "local" | "remote" { const isNode = typeof process !== "undefined" && @@ -130,6 +163,10 @@ export function getEmbeddingType(runtime: IAgentRuntime): "local" | "remote" { return isLocal ? "local" : "remote"; } +/** + * Retrieves a zero vector for embeddings based on the configured embedding dimension. + * @returns {number[]} A zero vector with the specified embedding dimension filled with zeros. + */ export function getEmbeddingZeroVector(): number[] { let embeddingDimension = 384; // Default BGE dimension @@ -157,6 +194,14 @@ export function getEmbeddingZeroVector(): number[] { * @throws {Error} If the API request fails */ +/** + * Embeds the provided input string using the specified provider and model. + * + * @async + * @param {IAgentRuntime} runtime - The agent runtime object. + * @param {string} input - The input string to embed. + * @returns {Promise} The embedding array for the input string. + */ export async function embed(runtime: IAgentRuntime, input: string) { elizaLogger.debug("Embedding request:", { modelProvider: runtime.character.modelProvider, diff --git a/packages/core/src/environment.ts b/packages/core/src/environment.ts index 0758d0d31d9..f12564bf63f 100644 --- a/packages/core/src/environment.ts +++ b/packages/core/src/environment.ts @@ -20,9 +20,17 @@ export const envSchema = z.object({ }); // Type inference +/** + * Represents the inferred type of the 'envSchema' variable, which is used to define environmental configurations. + */ export type EnvConfig = z.infer; // Validation function +/** + * Validates the environment variables based on the schema defined in envSchema. + * + * @returns {EnvConfig} The validated environment configuration. + */ export function validateEnv(): EnvConfig { try { return envSchema.parse(process.env); @@ -132,9 +140,19 @@ export const CharacterSchema = z.object({ }); // Type inference +/** + * Type definition for CharacterConfig, inferred from CharacterSchema + */ export type CharacterConfig = z.infer; // Validation function +/** + * Validates the character configuration object against the CharacterSchema. + * + * @param {unknown} json - The JSON object representing the character configuration. + * @returns {CharacterConfig} - The validated CharacterConfig object. + * @throws {Error} - If the validation fails, an error with detailed error messages is thrown. + */ export function validateCharacterConfig(json: unknown): CharacterConfig { try { return CharacterSchema.parse(json); diff --git a/packages/core/src/generation.ts b/packages/core/src/generation.ts index 67ed1b664a0..4628a5f773d 100644 --- a/packages/core/src/generation.ts +++ b/packages/core/src/generation.ts @@ -50,6 +50,16 @@ import { fal } from "@fal-ai/client"; * @returns The completed message. */ +/** + * Generates text using the specified runtime, context, modelClass, stop words, and custom system prompt. + * @param {Object} params - The parameters for generating text. + * @param {IAgentRuntime} params.runtime - The runtime for the agent. + * @param {string} params.context - The context for generating text. + * @param {string} params.modelClass - The class of the model to be used. + * @param {string[]} [params.stop] - Optional additional stop words. + * @param {string} [params.customSystemPrompt] - Optional custom system prompt. + * @returns {Promise} A promise that resolves to the generated text. + */ export async function generateText({ runtime, context, diff --git a/packages/core/src/knowledge.ts b/packages/core/src/knowledge.ts index 96a78514c67..f28c98481d1 100644 --- a/packages/core/src/knowledge.ts +++ b/packages/core/src/knowledge.ts @@ -5,6 +5,13 @@ import { stringToUuid } from "./uuid.ts"; import { splitChunks } from "./generation.ts"; import elizaLogger from "./logger.ts"; +/** + * Retrieves knowledge items based on a provided message content. + * + * @param {AgentRuntime} runtime - The current AgentRuntime. + * @param {Memory} message - The message containing the content to search for knowledge. + * @returns {Promise} - An array of KnowledgeItem objects. + */ async function get( runtime: AgentRuntime, message: Memory @@ -64,6 +71,15 @@ async function get( .map((memory) => ({ id: memory.id, content: memory.content })); } +/** + * Set knowledge item in the memory of the agent. + * + * @param {AgentRuntime} runtime - The agent runtime object. + * @param {KnowledgeItem} item - The knowledge item to be set in memory. + * @param {number} [chunkSize=512] - The size of each chunk to split the content into. + * @param {number} [bleed=20] - The amount of overlap between chunks. + * @returns {Promise} - A Promise that resolves when the knowledge item is successfully set in memory. + */ async function set( runtime: AgentRuntime, item: KnowledgeItem, @@ -102,6 +118,13 @@ async function set( } } +/** + * Preprocesses the given content by removing code blocks, inline code, headers, image links, links, Discord mentions, + * HTML tags, horizontal rules, comments, special characters, and normalizing whitespace. + * + * @param {string} content - The content to preprocess + * @returns {string} The preprocessed content + */ export function preprocess(content: string): string { elizaLogger.debug("Preprocessing text:", { input: content, diff --git a/packages/core/src/logger.ts b/packages/core/src/logger.ts index 70b4a489993..181464483f6 100644 --- a/packages/core/src/logger.ts +++ b/packages/core/src/logger.ts @@ -1,4 +1,15 @@ +/** + * Class representing a custom logging utility. + * + * @class + */ class ElizaLogger { +/** + * Constructor for ElizaLogger class. + * Checks if the code is running in a Node.js environment, + * sets the verbose flag based on the environment, + * and logs the initialization details. + */ constructor() { // Check if we're in Node.js environment this.isNode = @@ -30,6 +41,13 @@ class ElizaLogger { debugsTitle = "DEBUG"; assertsTitle = "ASSERT"; +/** + * Get the CSS styling for foreground and background colors based on the provided color names. + * If running in a browser environment, it returns the CSS styling. If running in a Node.js environment, it returns the ANSI escape codes for console coloring. + * @param {string} foregroundColor - The name of the foreground color. Default is an empty string. + * @param {string} backgroundColor - The name of the background color. Default is an empty string. + * @returns {string} The CSS styling for the colors if in a browser environment, or ANSI escape codes for console coloring if in a Node.js environment. + */ #getColor(foregroundColor = "", backgroundColor = "") { if (!this.isNode) { // Browser console styling @@ -109,14 +127,31 @@ class ElizaLogger { return `${fgc}${bgc}`; } +/** + * Get the color reset code based on the environment. + * + * @returns {string} The color reset code ("\x1b[0m" in Node environment, empty string otherwise). + */ #getColorReset() { return this.isNode ? "\x1b[0m" : ""; } +/** + * Clears the console by calling console.clear() + */ clear() { console.clear(); } +/** + * Prints the provided strings with the specified foreground color and background color. + * If objects are provided in the strings, they are converted to strings using JSON.stringify. + * + * @param {string} foregroundColor - The foreground color for the printed text. Default is "white". + * @param {string} backgroundColor - The background color for the printed text. Default is "black". + * @param {Array.} strings - The strings to be printed. + * @returns {void} + */ print(foregroundColor = "white", backgroundColor = "black", ...strings) { // Convert objects to strings const processedStrings = strings.map((item) => { @@ -139,6 +174,15 @@ class ElizaLogger { if (this.closeByNewLine) console.log(""); } +/** + * Logs the given strings with a specified style, including foreground and background colors, icon, and group title. + * @param {any[]} strings - An array of strings to be logged. + * @param {object} options - An object containing the style options with the following properties: + * @param {string} options.fg - The foreground color for the log. + * @param {string} options.bg - The background color for the log. + * @param {string} options.icon - The icon to display along with the group title. + * @param {string} options.groupTitle - The title for the log group. + */ #logWithStyle( strings: any[], options: { @@ -181,6 +225,12 @@ class ElizaLogger { } } +/** + * Logs the given strings with specified style. + * + * @param {...string} strings - The strings to be logged + * @returns {void} + */ log(...strings) { this.#logWithStyle(strings, { fg: "white", @@ -190,6 +240,11 @@ class ElizaLogger { }); } +/** + * Logs warning messages with a specified style. + * + * @param {...string} strings - The messages to log as warnings. + */ warn(...strings) { this.#logWithStyle(strings, { fg: "yellow", @@ -199,6 +254,10 @@ class ElizaLogger { }); } +/** +* Logs an error message with red foreground color, no background color, and an exclamation icon. +* @param {...string} strings - The error message to log +*/ error(...strings) { this.#logWithStyle(strings, { fg: "red", @@ -208,6 +267,11 @@ class ElizaLogger { }); } +/** + * Logs information with blue foreground color and information icon. + * + * @param {...string} strings - Strings to be logged + */ info(...strings) { this.#logWithStyle(strings, { fg: "blue", @@ -217,6 +281,11 @@ class ElizaLogger { }); } +/** + * Logs debug messages with specified styling if verbose mode is enabled. + * + * @param {...string} strings - The debug messages to log. + */ debug(...strings) { if (!this.verbose) { // for diagnosing verbose logging issues @@ -234,6 +303,10 @@ class ElizaLogger { }); } +/** + * Logs the given strings with a green style and a checkmark icon to indicate success. + * @param {...string} strings - The strings to be logged + */ success(...strings) { this.#logWithStyle(strings, { fg: "green", @@ -243,6 +316,10 @@ class ElizaLogger { }); } +/** + * Asserts the provided strings and logs them with a cyan foreground color, no background color, and an exclamation icon. + * @param {...string} strings - The strings to be logged + */ assert(...strings) { this.#logWithStyle(strings, { fg: "cyan", @@ -252,6 +329,11 @@ class ElizaLogger { }); } +/** + * Displays a progress message either by updating the current line or by logging a new line. + * + * @param {string} message - The message to be displayed as progress. + */ progress(message: string) { if (this.isNode) { // Clear the current line and move cursor to beginning diff --git a/packages/core/src/memory.ts b/packages/core/src/memory.ts index 112352766f1..5ea0b893790 100644 --- a/packages/core/src/memory.ts +++ b/packages/core/src/memory.ts @@ -13,6 +13,10 @@ const defaultMatchCount = 10; /** * Manage memories in the database. */ +/** + * MemoryManager class responsible for managing memories in the database. + * @implements {IMemoryManager} + */ export class MemoryManager implements IMemoryManager { /** * The AgentRuntime instance associated with this manager. diff --git a/packages/core/src/messages.ts b/packages/core/src/messages.ts index b098198c4f6..875366f6867 100644 --- a/packages/core/src/messages.ts +++ b/packages/core/src/messages.ts @@ -9,6 +9,16 @@ import { /** * Get details for a list of actors. */ +/** + * Retrieves details for actors in a given room. + * + * @async + * @function getActorDetails + * @param {Object} params - The parameters object. + * @param {IAgentRuntime} params.runtime - The runtime object. + * @param {UUID} params.roomId - The ID of the room to retrieve actor details for. + * @returns {Promise} A promise that resolves to an array of actor details. + */ export async function getActorDetails({ runtime, roomId, diff --git a/packages/core/src/models.ts b/packages/core/src/models.ts index 76095334256..2413f3e95f5 100644 --- a/packages/core/src/models.ts +++ b/packages/core/src/models.ts @@ -505,10 +505,22 @@ export const models: Models = { }, }; +/** + * Retrieves the model of the specified type from the provided model provider. + * + * @param {ModelProviderName} provider - The name of the model provider. + * @param {ModelClass} type - The type of model to retrieve. + * @returns {Model} The model of the specified type from the model provider. + */ export function getModel(provider: ModelProviderName, type: ModelClass) { return models[provider].model[type]; } +/** + * Retrieves the endpoint URL for a given ModelProviderName. + * @param {ModelProviderName} provider - The name of the model provider. + * @returns {string} The endpoint URL for the specified provider. + */ export function getEndpoint(provider: ModelProviderName) { return models[provider].endpoint; } diff --git a/packages/core/src/providers.ts b/packages/core/src/providers.ts index d6335b97e10..d7287bab4ed 100644 --- a/packages/core/src/providers.ts +++ b/packages/core/src/providers.ts @@ -7,6 +7,14 @@ import { IAgentRuntime, State, type Memory } from "./types.ts"; * @param state The current state object. * @returns A string that concatenates the outputs of each provider. */ +/** + * Asynchronously retrieves data from various providers and filters out any null or empty results. + * + * @param {IAgentRuntime} runtime - The runtime environment in which the providers are being executed. + * @param {Memory} message - The input message data to be processed by the providers. + * @param {State} [state] - Optional additional state data to be passed to the providers. + * @returns {string} - Joined string of non-null and non-empty provider results. + */ export async function getProviders( runtime: IAgentRuntime, message: Memory, diff --git a/packages/core/src/relationships.ts b/packages/core/src/relationships.ts index ac79987ae70..b3c63e6188b 100644 --- a/packages/core/src/relationships.ts +++ b/packages/core/src/relationships.ts @@ -1,5 +1,14 @@ import { IAgentRuntime, type Relationship, type UUID } from "./types.ts"; +/** + * Asynchronously creates a relationship between two users in the database. + * + * @param {Object} params - The parameters for creating the relationship. + * @param {IAgentRuntime} params.runtime - The runtime environment for the operation. + * @param {UUID} params.userA - The ID of the first user in the relationship. + * @param {UUID} params.userB - The ID of the second user in the relationship. + * @returns {Promise} A Promise that resolves to a boolean indicating the success of creating the relationship. + */ export async function createRelationship({ runtime, userA, @@ -15,6 +24,15 @@ export async function createRelationship({ }); } +/** + * Retrieves the relationship between two users from the database. + * + * @param {Object} options - The options for retrieving the relationship. + * @param {IAgentRuntime} options.runtime - The agent runtime. + * @param {UUID} options.userA - The ID of the first user. + * @param {UUID} options.userB - The ID of the second user. + * @returns {Promise} A promise that resolves with the relationship between the two users. + */ export async function getRelationship({ runtime, userA, @@ -30,6 +48,13 @@ export async function getRelationship({ }); } +/** + * Fetches relationships for a user from the database. + * @param {Object} params - The parameters for fetching relationships. + * @param {IAgentRuntime} params.runtime - The agent runtime instance. + * @param {UUID} params.userId - The ID of the user to fetch relationships for. + * @returns {Promise} A promise that resolves with the user's relationships from the database. + */ export async function getRelationships({ runtime, userId, @@ -40,6 +65,14 @@ export async function getRelationships({ return runtime.databaseAdapter.getRelationships({ userId }); } +/** + * Formats relationships for a specific user. + * @async + * @param {Object} options - The options object. + * @param {IAgentRuntime} options.runtime - The runtime interface. + * @param {UUID} options.userId - The ID of the user. + * @returns {Promise>} The formatted relationships. + */ export async function formatRelationships({ runtime, userId, diff --git a/packages/core/src/runtime.ts b/packages/core/src/runtime.ts index 2ba5f016b45..dfb7082c0ce 100644 --- a/packages/core/src/runtime.ts +++ b/packages/core/src/runtime.ts @@ -51,6 +51,11 @@ import { stringToUuid } from "./uuid.ts"; * Represents the runtime environment for an agent, handling message processing, * action registration, and interaction with external services like OpenAI and Supabase. */ +/** + * AgentRuntime class that implements the IAgentRuntime interface. + * Provides various functionalities related to the agent runtime. + * @class + */ export class AgentRuntime implements IAgentRuntime { /** * Default count for recent messages to be kept in memory. diff --git a/packages/core/src/settings.ts b/packages/core/src/settings.ts index f6e42a1add3..a26b640453d 100644 --- a/packages/core/src/settings.ts +++ b/packages/core/src/settings.ts @@ -18,10 +18,18 @@ elizaLogger.info("Loading character settings:", { CWD: process.cwd(), }); +/** + * Interface for storing settings with key-value pairs. + * Keys are strings and values can be either strings or undefined. + */ interface Settings { [key: string]: string | undefined; } +/** + * Interface representing namespaced settings. + * @interface + */ interface NamespacedSettings { [namespace: string]: Settings; } diff --git a/packages/core/src/test_resources/createRuntime.ts b/packages/core/src/test_resources/createRuntime.ts index e4a6f0016b2..6d8a60dc04b 100644 --- a/packages/core/src/test_resources/createRuntime.ts +++ b/packages/core/src/test_resources/createRuntime.ts @@ -17,6 +17,18 @@ import { } from "./constants.ts"; import { User } from "./types.ts"; +/** + * Create a runtime instance for the agent with the specified configuration. + * + * @param {Object} options - The configuration options for creating the runtime. + * @param {Record | NodeJS.ProcessEnv} [options.env] - The environment variables or Node.js process environment. + * @param {number} [options.conversationLength] - The length of the conversation. + * @param {Evaluator[]} [options.evaluators] - The list of evaluators for the runtime. + * @param {Action[]} [options.actions] - The list of actions for the runtime. + * @param {Provider[]} [options.providers] - The list of providers for the runtime. + * + * @returns {Object} - An object containing the user, session, and runtime instances. + */ export async function createRuntime({ env, conversationLength, diff --git a/packages/core/src/test_resources/types.ts b/packages/core/src/test_resources/types.ts index 634e266cbe4..1bee9351c9d 100644 --- a/packages/core/src/test_resources/types.ts +++ b/packages/core/src/test_resources/types.ts @@ -1,3 +1,10 @@ +/** + * Interface representing a User + * @property {string} id - The unique identifier of the user + * @property {string} [email] - The email address of the user (optional) + * @property {string} [phone] - The phone number of the user (optional) + * @property {string} [role] - The role of the user (optional) + */ export interface User { id: string; email?: string; diff --git a/packages/core/src/tests/database.test.ts b/packages/core/src/tests/database.test.ts index cab1b659732..496a82c8058 100644 --- a/packages/core/src/tests/database.test.ts +++ b/packages/core/src/tests/database.test.ts @@ -11,10 +11,33 @@ import { UUID, } from "../types"; // Adjust based on your types location +/** + * Mock implementation of a DatabaseAdapter for testing purposes. + * Extends the DatabaseAdapter class. + * + * @class + * @extends DatabaseAdapter + */ class MockDatabaseAdapter extends DatabaseAdapter { +/** + * Retrieve a Memory object by its unique identifier. + * + * @param {UUID} _id - The unique identifier of the Memory object. + * @returns {Promise} A Promise that resolves with the Memory object found, or null if no Memory is found. + */ getMemoryById(_id: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Logs user activity based on the provided parameters. + * + * @param {object} _params - The parameters for logging the activity. + * @param {object} _params.body - The body of the activity, as a key-value pair object. + * @param {string} _params.userId - The UUID of the user performing the activity. + * @param {string} _params.roomId - The UUID of the room where the activity is occurring. + * @param {string} _params.type - The type of activity being logged. + * @returns {Promise} - A promise that resolves when the logging is complete. + */ log(_params: { body: { [key: string]: unknown }; userId: UUID; @@ -23,9 +46,29 @@ class MockDatabaseAdapter extends DatabaseAdapter { }): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves details of actors present in the specified room. + * @param {Object} _params - The parameters for retrieving actor details. + * @param {UUID} _params.roomId - The unique identifier of the room. + * @returns {Promise} - A promise that resolves to an array of Actor objects. + * @throws {Error} - If the method is not implemented. + */ getActorDetails(_params: { roomId: UUID }): Promise { throw new Error("Method not implemented."); } +/** + * Search memories by embedding. + * + * @param {number[]} _embedding - The embedding to search for. + * @param {Object} _params - The parameters for the search. + * @param {number} [_params.match_threshold] - The threshold for matching. + * @param {number} [_params.count] - The maximum number of memories to return. + * @param {UUID} [_params.roomId] - The room ID to search within. + * @param {UUID} [_params.agentId] - The agent ID to search within. + * @param {boolean} [_params.unique] - Whether to return only unique memories. + * @param {string} _params.tableName - The name of the table to search in. + * @returns {Promise} - A promise that resolves to an array of memories. + */ searchMemoriesByEmbedding( _embedding: number[], _params: { @@ -39,6 +82,15 @@ class MockDatabaseAdapter extends DatabaseAdapter { ): Promise { throw new Error("Method not implemented."); } +/** + * Create a new memory in the specified table. + * + * @param _memory The memory object to be created. + * @param _tableName The name of the table where the memory should be created. + * @param _unique Optional. Specifies whether the memory being created should be unique or not. Default is false. + * + * @returns A Promise that resolves when the memory has been successfully created. + */ createMemory( _memory: Memory, _tableName: string, @@ -46,12 +98,37 @@ class MockDatabaseAdapter extends DatabaseAdapter { ): Promise { throw new Error("Method not implemented."); } +/** + * Removes a memory with the specified ID from the given table. + * + * @param {_memoryId: UUID} _memoryId The ID of the memory to be removed. + * @param {_tableName: string} _tableName The name of the table from which the memory should be removed. + * + * @returns {Promise} A promise that resolves when the memory has been successfully removed. + */ removeMemory(_memoryId: UUID, _tableName: string): Promise { throw new Error("Method not implemented."); } +/** + * Removes all memories associated with a specific room and table. + * + * @param {UUID} _roomId - The unique identifier of the room. + * @param {string} _tableName - The name of the table where memories are stored. + * @returns {Promise} A Promise that resolves once all memories are successfully removed. + * @throws {Error} If the method is not implemented. + */ removeAllMemories(_roomId: UUID, _tableName: string): Promise { throw new Error("Method not implemented."); } +/** + * Counts the memories associated with a given room ID. + * + * @param {UUID} _roomId - The ID of the room to count memories for. + * @param {boolean} [_unique] - Optional. If true, only count unique memories. + * @param {string} [_tableName] - Optional. The name of the table to query for memories. + * + * @returns {Promise} - A Promise that resolves to the number of memories associated with the room ID. + */ countMemories( _roomId: UUID, _unique?: boolean, @@ -59,6 +136,15 @@ class MockDatabaseAdapter extends DatabaseAdapter { ): Promise { throw new Error("Method not implemented."); } +/** + * Retrieve goals based on specified parameters + * @param {Object} _params - The parameters for filtering goals + * @param {UUID} _params.roomId - The room ID to fetch goals from + * @param {UUID|null} [_params.userId] - The user ID to filter goals by (optional) + * @param {boolean} [_params.onlyInProgress] - Flag to indicate if only in-progress goals should be included (optional) + * @param {number} [_params.count] - The maximum number of goals to return (optional) + * @returns {Promise} - A promise that resolves to an array of Goal objects + */ getGoals(_params: { roomId: UUID; userId?: UUID | null; @@ -67,55 +153,162 @@ class MockDatabaseAdapter extends DatabaseAdapter { }): Promise { throw new Error("Method not implemented."); } +/** + * Update a goal. + * + * @param _goal - The goal object to update. + * @returns A promise that resolves when the update is complete. + */ updateGoal(_goal: Goal): Promise { throw new Error("Method not implemented."); } +/** + * Creates a new goal. + * + * @param {Goal} _goal - The goal to create. + * @returns {Promise} A Promise that resolves when the goal is created. + */ createGoal(_goal: Goal): Promise { throw new Error("Method not implemented."); } +/** + * Removes a goal with the specified ID. + * @param {_goalId: UUID} _goalId - The ID of the goal to be removed. + * @returns {Promise} A promise that resolves when the goal is successfully removed. + */ removeGoal(_goalId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Removes all goals associated with a specific room. + * + * @param {_roomId} UUID - The unique identifier of the room to remove goals from. + * @returns {Promise} - A promise that resolves when all goals are successfully removed. + */ removeAllGoals(_roomId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves the room with the specified ID. + * + * @param {UUID} _roomId - The ID of the room to retrieve. + * @returns {Promise} - A promise that resolves with the ID of the room, or null if the room is not found. + */ getRoom(_roomId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Creates a room with the specified room ID. + * + * @param _roomId The optional room ID to be assigned to the newly created room. + * @returns A promise that resolves to the UUID of the created room. + * @throws Error if the method is not implemented. + */ createRoom(_roomId?: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Removes a room based on the provided room ID. + * + * @param {UUID} _roomId - The ID of the room to be removed. + * @returns {Promise} - A promise that resolves once the room is successfully removed. + */ removeRoom(_roomId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Retrieve the list of rooms associated with a participant based on their user ID. + * + * @param {UUID} _userId - The unique identifier of the participant + * @returns {Promise} A Promise that resolves to an array of unique identifiers for the rooms + * @throws {Error} If the method is not implemented + */ getRoomsForParticipant(_userId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves rooms for specified participants. + * + * @param _userIds Array of user IDs to retrieve rooms for + * @returns A Promise that resolves to an array of room IDs + */ getRoomsForParticipants(_userIds: UUID[]): Promise { throw new Error("Method not implemented."); } +/** + * Add a participant to a specific room. + * + * @param _userId The UUID of the user to add as a participant. + * @param _roomId The UUID of the room to add the participant to. + * @returns A Promise that resolves to a boolean indicating if the participant was successfully added. + */ addParticipant(_userId: UUID, _roomId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Remove a participant from a room. + * + * @param {UUID} _userId - The unique identifier of the user to be removed. + * @param {UUID} _roomId - The unique identifier of the room from which the user will be removed. + * @returns {Promise} - A boolean indicating whether the participant removal was successful. + */ removeParticipant(_userId: UUID, _roomId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves the list of participants associated with the provided user ID. + * + * @param {UUID} userId - The unique identifier of the user account. + * @returns {Promise} A promise that resolves with an array of Participant objects. + */ getParticipantsForAccount(userId: UUID): Promise; +/** + * Retrieve participants for a specific account associated with the provided user ID + * @param {UUID} userId - The unique identifier for the user account + * @returns {Promise} - A Promise that resolves with an array of Participant objects + */ getParticipantsForAccount(userId: UUID): Promise; +/** + * Retrieve participants for a specific account based on the user ID. + * + * @param {unknown} _userId - The user ID to retrieve participants for. + * @returns {Promise} - A promise that resolves to an array of participants. + */ getParticipantsForAccount( _userId: unknown ): Promise { throw new Error("Method not implemented."); } +/** + * Get participants for a given room. + * + * @param {_roomId} UUID - The ID of the room to get participants for. + * @returns {Promise} - A promise that resolves with an array of participant UUIDs. + */ + + getParticipantsForRoom(_roomId: UUID): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves the state of the specified user in the given room. + * @param {UUID} _roomId - The unique identifier of the room. + * @param {UUID} _userId - The unique identifier of the user. + * @returns {Promise<"FOLLOWED" | "MUTED" | null>} - The state of the participant user (either "FOLLOWED", "MUTED", or null). + */ getParticipantUserState( _roomId: UUID, _userId: UUID ): Promise<"FOLLOWED" | "MUTED" | null> { throw new Error("Method not implemented."); } +/** + * Set the state of a participant in a specific room. + * @param {UUID} _roomId - The ID of the room where the participant is located. + * @param {UUID} _userId - The ID of the participant whose state is being set. + * @param {"FOLLOWED" | "MUTED" | null} _state - The state to set for the participant: "FOLLOWED", "MUTED", or null. + * @returns {Promise} A Promise that resolves when the state is successfully set. + */ setParticipantUserState( _roomId: UUID, _userId: UUID, @@ -123,24 +316,56 @@ class MockDatabaseAdapter extends DatabaseAdapter { ): Promise { throw new Error("Method not implemented."); } +/** + * Creates a relationship between two users. + * + * @param {Object} _params - The parameters for creating the relationship. + * @param {UUID} _params.userA - The UUID of the first user. + * @param {UUID} _params.userB - The UUID of the second user. + * @returns {Promise} - A promise that resolves to true if the relationship was created successfully. + */ createRelationship(_params: { userA: UUID; userB: UUID; }): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves the relationship between two users. + * + * @param {Object} _params - The parameters object. + * @param {string} _params.userA - The UUID of user A. + * @param {string} _params.userB - The UUID of user B. + * @returns {Promise} - The relationship between user A and user B, or null if none exists. + */ getRelationship(_params: { userA: UUID; userB: UUID; }): Promise { throw new Error("Method not implemented."); } +/** + * Retrieves relationships for a given userId. + * + * @param {Object} _params - The parameters for the request. + * @param {UUID} _params.userId - The unique identifier of the user. + * @returns {Promise} - A promise that resolves to an array of Relationship objects. + */ getRelationships(_params: { userId: UUID }): Promise { throw new Error("Method not implemented."); } db: any = {}; // Mock method for getting memories by room IDs +/** + * Retrieves memories based on room ids. + * + * @param {Object} params - The parameters for retrieving memories. + * @param {string[]} params.roomIds - The room ids to retrieve memories from. + * @param {string} [params.agentId] - The agent id to filter memories by. + * @param {string} params.tableName - The name of the table to query memories from. + * @returns {Promise} The memories retrieved based on the provided room ids. + */ async getMemoriesByRoomIds(params: { roomIds: `${string}-${string}-${string}-${string}-${string}`[]; agentId?: `${string}-${string}-${string}-${string}-${string}`; @@ -158,6 +383,18 @@ class MockDatabaseAdapter extends DatabaseAdapter { } // Mock method for getting cached embeddings +/** + * Retrieves cached embeddings based on specified parameters. + * + * @param {Object} _params - The parameters for retrieving cached embeddings. + * @param {string} _params.query_table_name - The name of the table to query. + * @param {number} _params.query_threshold - The threshold for the query. + * @param {string} _params.query_input - The input for the query. + * @param {string} _params.query_field_name - The name of the field in the table. + * @param {string} _params.query_field_sub_name - The sub name of the field in the table. + * @param {number} _params.query_match_count - The number of matches to retrieve. + * @returns {Promise} An array of objects containing the retrieved embeddings and Levenshtein distances. + */ async getCachedEmbeddings(_params: { query_table_name: string; query_threshold: number; @@ -175,6 +412,17 @@ class MockDatabaseAdapter extends DatabaseAdapter { } // Mock method for searching memories +/** + * Search for memories based on the provided parameters. + * @param {Object} params - The search parameters. + * @param {string} params.tableName - The name of the table to search in. + * @param {string} params.roomId - The ID of the room to search memories for. + * @param {number[]} params.embedding - The embedding to compare with memories. + * @param {number} params.match_threshold - The threshold for similarity matching. + * @param {number} params.match_count - The number of matches to retrieve. + * @param {boolean} params.unique - Flag to indicate if only unique memories should be returned. + * @returns {Promise} The list of memories that match the search criteria. + */ async searchMemories(params: { tableName: string; roomId: `${string}-${string}-${string}-${string}-${string}`; @@ -195,6 +443,11 @@ class MockDatabaseAdapter extends DatabaseAdapter { } // Mock method for getting account by ID +/** + * Get an account by user ID. + * @param {UUID} userId - The ID of the user. + * @returns {Promise} The account object for the given user ID, or null if not found. + */ async getAccountById(userId: UUID): Promise { return { id: userId, @@ -204,10 +457,25 @@ class MockDatabaseAdapter extends DatabaseAdapter { } // Other methods stay the same... +/** + * Asynchronously creates a new account. + * + * @param {Account} _account - The account object to create. + * @returns {Promise} A promise that resolves to a boolean value indicating success of account creation. + */ async createAccount(_account: Account): Promise { return true; } +/** + * Retrieves memories from a specified table based on the provided parameters. + * @param {Object} params - The parameters for retrieving memories. + * @param {UUID} params.roomId - The ID of the room for which memories are being retrieved. + * @param {number} [params.count] - The number of memories to retrieve (optional). + * @param {boolean} [params.unique] - Whether to retrieve unique memories (optional). + * @param {string} params.tableName - The name of the table from which memories are retrieved. + * @returns {Promise} The memories retrieved based on the specified parameters. + */ async getMemories(params: { roomId: UUID; count?: number; @@ -225,6 +493,12 @@ class MockDatabaseAdapter extends DatabaseAdapter { ] as unknown as Memory[]; } +/** + * Asynchronously retrieves actors based on the provided room ID. + * @param {Object} _params - The parameters object. + * @param {UUID} _params.roomId - The ID of the room for which to get actors. + * @returns {Promise} - A promise that resolves to an array of Actor objects. + */ async getActors(_params: { roomId: UUID }): Promise { return [ { @@ -236,6 +510,13 @@ class MockDatabaseAdapter extends DatabaseAdapter { ] as unknown as Actor[]; } +/** + * Updates the status of a goal. + * @param {object} _params - The parameters for updating the goal status. + * @param {UUID} _params.goalId - The unique identifier of the goal to update. + * @param {GoalStatus} _params.status - The new status of the goal. + * @returns {Promise} A Promise that resolves when the status of the goal is updated successfully. + */ async updateGoalStatus(_params: { goalId: UUID; status: GoalStatus; @@ -243,6 +524,12 @@ class MockDatabaseAdapter extends DatabaseAdapter { return Promise.resolve(); } +/** + * Retrieves a goal by its unique identifier. + * + * @param {UUID} goalId - The identifier of the goal to retrieve. + * @returns {Promise} The goal object if found, otherwise null. + */ async getGoalById(goalId: UUID): Promise { return { id: goalId, diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index dfc19c2eb23..837642606a2 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -3,6 +3,9 @@ import { Readable } from "stream"; /** * Represents a UUID string in the format "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" */ +/** + * Represents a universally unique identifier (UUID). + */ export type UUID = `${string}-${string}-${string}-${string}-${string}`; /** diff --git a/packages/core/src/uuid.ts b/packages/core/src/uuid.ts index 2227eca2132..8783381d829 100644 --- a/packages/core/src/uuid.ts +++ b/packages/core/src/uuid.ts @@ -1,6 +1,13 @@ import { sha1 } from "js-sha1"; import { UUID } from "./types.ts"; +/** + * Converts a string or number to a UUID. + * + * @param {string | number} target - The string or number to convert to a UUID. + * @throws {TypeError} If the value is not a string. + * @returns {UUID} The converted UUID. + */ export function stringToUuid(target: string | number): UUID { if (typeof target === "number") { target = (target as number).toString(); diff --git a/scripts/jsdoc-automation/src/JsDocCleaner.ts b/scripts/jsdoc-automation/src/JsDocCleaner.ts new file mode 100644 index 00000000000..f7bdcc587f6 --- /dev/null +++ b/scripts/jsdoc-automation/src/JsDocCleaner.ts @@ -0,0 +1,79 @@ +/** + * Utility class for cleaning and validating JSDoc comments. + */ +export class JsDocCleaner { + /** + * Processes and cleans a JSDoc comment to ensure proper formatting. + * + * @param {string} comment - The JSDoc comment to clean. + * @returns {string} The cleaned JSDoc comment. + */ + public static clean(comment: string): string { + // Remove any empty lines at start/end + let cleaned = comment.trim(); + + // Ensure comment starts with /** + if (!cleaned.startsWith('/**')) { + cleaned = '/**' + cleaned.replace(/^\/\*+/, ''); + } + + // Fix common artifacts: + // 1. Multiple closing patterns + cleaned = cleaned.replace(/\*+\s*\*+\s*\/$/, '*/'); + cleaned = cleaned.replace(/\*+\s*\/$/, '*/'); + + // 2. Fix improper closing + if (!cleaned.endsWith('*/')) { + cleaned = cleaned + ' */'; + } + + // 3. Fix spacing in content + cleaned = cleaned.split('\n').map((line, index) => { + // First line should just have /** + if (index === 0) { + return '/**'; + } + + // Clean up any extra asterisks in the content + line = line.trim().replace(/^\*+\s*/, ' * '); + + // Ensure there's a space after the asterisk if it's a content line + if (line.startsWith(' *') && !line.startsWith(' * ')) { + line = ' * ' + line.substring(2).trimStart(); + } + + return line; + }).join('\n'); + + // 4. Fix final spacing + cleaned = cleaned.replace(/\s*\*\//, '\n */'); + + // Validate basic structure + const isValid = + cleaned.startsWith('/**') && + cleaned.endsWith('*/') && + cleaned.includes('\n'); + + if (!isValid) { + // If validation fails, create a minimal valid structure + cleaned = '/**\n * ' + cleaned.replace(/\/\*+|\*+\//g, '').trim() + '\n */'; + } + + return cleaned; + } + + /** + * Validates if a JSDoc comment has proper structure. + * + * @param {string} comment - The JSDoc comment to validate. + * @returns {boolean} True if the comment has valid structure. + */ + public static isValid(comment: string): boolean { + return ( + comment.startsWith('/**') && + comment.endsWith('*/') && + comment.includes('\n') && + !comment.includes('**/') + ); + } +} diff --git a/scripts/jsdoc-automation/src/JsDocGenerator.ts b/scripts/jsdoc-automation/src/JsDocGenerator.ts index 2aa1e608d38..9cb47f422b8 100644 --- a/scripts/jsdoc-automation/src/JsDocGenerator.ts +++ b/scripts/jsdoc-automation/src/JsDocGenerator.ts @@ -1,5 +1,6 @@ import { AIService } from './AIService.js'; import { ASTQueueItem } from './types/index.js'; +import { JsDocCleaner } from './JsDocCleaner.js'; /** * A class that generates JSDoc comments for code snippets and classes. @@ -9,7 +10,7 @@ export class JsDocGenerator { * Constructor for a class that takes in an AIService instance. * @param {AIService} aiService - The AIService instance to be injected into the class. */ - constructor(public aiService: AIService) { } + constructor(public aiService: AIService) {} /** * Generates a comment based on the given ASTQueueItem. @@ -20,7 +21,7 @@ export class JsDocGenerator { public async generateComment(queueItem: ASTQueueItem): Promise { const prompt = this.buildPrompt(queueItem); const comment = await this.aiService.generateComment(prompt); - return comment; + return JsDocCleaner.clean(comment); } /** @@ -29,29 +30,20 @@ export class JsDocGenerator { * @param {ASTQueueItem} queueItem - The ASTQueueItem to generate the comment for. * @returns {Promise} The generated comment for the class. */ - public async generateClassComment( - queueItem: ASTQueueItem, - ): Promise { + public async generateClassComment(queueItem: ASTQueueItem): Promise { const prompt = this.buildClassPrompt(queueItem); const comment = await this.aiService.generateComment(prompt); - return comment; + return JsDocCleaner.clean(comment); } - /** - * Builds a prompt with the JSDoc comment for the provided ASTQueueItem code. - * - * @param {ASTQueueItem} queueItem The ASTQueueItem object containing the code to extract the JSDoc comment from. - * @returns {string} The JSDoc comment extracted from the code provided in the ASTQueueItem object. - */ private buildPrompt(queueItem: ASTQueueItem): string { return `Generate JSDoc comment for the following code: - \`\`\`typescript ${queueItem.code} \`\`\` - Only return the JSDoc comment, not the code itself. + Only return the JSDoc comment with proper formatting, not the code itself. `; } @@ -59,7 +51,6 @@ export class JsDocGenerator { queueItem: ASTQueueItem, ): string { return `Generate JSDoc comment for the following Class: - Class name: ${queueItem.code.match(/class (\w+)/)?.[1]} Only return the JSDoc for the Class itself, not the methods or anything in the class. @@ -74,4 +65,4 @@ export class JsDocGenerator { \`\`\` `; } -} \ No newline at end of file +}