Services
Core services and utilities in ElizaOS infrastructure with actual implementation details
ElizaOS provides a comprehensive set of services and utilities that power the infrastructure, including environment management, file operations, process control, and development tools. These services ensure smooth operation across development, testing, and production environments.
Service Architecture
Service Builder Pattern
ElizaOS uses a service builder pattern for type-safe service creation:
import { ServiceBuilder, createService } from "@elizaos/core";
// Create a service with type safety
const myService = createService<MyService>("MY_SERVICE")
.withDescription("Custom service for specific functionality")
.withStart(async (runtime: IAgentRuntime) => {
// Service initialization logic
return new MyService(runtime);
})
.withStop(async () => {
// Service cleanup logic
})
.build();
Service Definition
export interface ServiceDefinition<T extends Service = Service> {
serviceType: ServiceTypeName;
description: string;
start: (runtime: IAgentRuntime) => Promise<T>;
stop?: () => Promise<void>;
}
// Define a service with type safety
export function defineService<T extends Service = Service>(
definition: ServiceDefinition<T>
): new (runtime?: IAgentRuntime) => T {
return createService<T>(definition.serviceType)
.withDescription(definition.description)
.withStart(definition.start)
.withStop(definition.stop || (() => Promise.resolve()))
.build();
}
Environment Services
Environment File Service
The actual EnvFileService
implementation manages .env
files:
import { EnvFileService, getEnvFileService } from "@elizaos/cli/services";
// Get the global instance
const envService = await getEnvFileService();
// Read environment variables
const envVars = await envService.read();
// Update a single variable
await envService.update("API_KEY", "new-value");
// Update multiple variables
await envService.updateMany({
API_KEY: "key1",
DATABASE_URL: "postgres://localhost:5432/db",
});
// Delete a variable
await envService.delete("OLD_VAR");
// Validate environment file
const validation = await envService.validate();
if (!validation.valid) {
console.error("Validation errors:", validation.errors);
}
Environment Variable Management
// Validate required variables
const required = ["API_KEY", "DATABASE_URL"];
const missing = envService.validateRequired(required);
// Get all variables
const allVars = envService.getAll();
// Reset to defaults
await envService.reset();
File System Services
Template Management
Handles project and plugin templates:
import { copyTemplate } from "@/src/utils/copy-template";
// Copy template to target directory
await copyTemplate("plugin-starter", targetDir, {
replacements: {
PLUGINNAME: "my-plugin",
PLUGINDESCRIPTION: "My awesome plugin",
GITHUB_USERNAME: "username",
},
});
Directory Services
import { detectDirectoryType } from "@/src/utils/directory-detection";
// Returns: { type: 'project' | 'plugin' | 'monorepo' | 'non-elizaos-dir', hasPackageJson: boolean }
// Get ElizaOS paths
import { getElizaPaths } from "@/src/utils/eliza-paths";
// Detect project type
const dirInfo = detectDirectoryType(process.cwd());
const paths = getElizaPaths();
// Returns: { root, src, config, data, logs }
Process Management
Process Control
import { cleanupProcesses } from "@/src/utils/process-control";
// Kill all ElizaOS processes
await cleanupProcesses();
// Kill specific process
await killProcess(pid);
Port Management
import { getAvailablePort, validatePort } from "@/src/utils/port-utils";
// Validate port
const isValid = validatePort("3000"); // Returns port or throws
// Find available port
const port = await getAvailablePort(3000);
Build Services
Project Building
import { buildProject } from "@/src/utils/build-project";
// Build TypeScript project
await buildProject(projectPath, {
skipTypeCheck: false,
watch: false,
});
Development Server
import { ServerManager } from "@/src/utils/server-manager";
const manager = new ServerManager();
// Start development server
await manager.start({
port: 3000,
character: "character.json",
watch: true,
});
// Stop server
await manager.stop();
Plugin Services
Plugin Discovery
import { discoverPlugins } from "@/src/utils/plugin-discovery";
// Find all plugins in project
const plugins = await discoverPlugins(projectPath);
// Returns array of plugin metadata
Plugin Loading
import { loadPlugin } from "@/src/utils/load-plugin";
// Load and initialize plugin
const plugin = await loadPlugin("@elizaos/plugin-openai", {
config: { API_KEY: "key" },
});
Plugin Context
import { createPluginContext } from "@/src/utils/plugin-context";
// Create context for plugin execution
const context = createPluginContext({
runtime,
services,
config,
});
Registry Services
Plugin Registry
import { RegistryClient } from "@/src/utils/registry";
const registry = new RegistryClient();
// Search plugins
const results = await registry.search("openai");
// Get plugin details
const plugin = await registry.getPlugin("@elizaos/plugin-openai");
// Publish plugin
await registry.publish(pluginMetadata);
Registry Schema
interface PluginMetadata {
name: string;
version: string;
description: string;
author: string;
repository: string;
keywords: string[];
agentConfig: {
pluginType: string;
pluginParameters: Record<string, ParameterDefinition>;
};
}
Documentation Services
Auto Documentation
import { DocumentationGenerator } from "@elizaos/autodoc";
const generator = new DocumentationGenerator({
aiService,
gitManager,
configuration,
});
// Generate documentation
await generator.generate();
JSDoc Generation
import { JsDocGenerator } from "@elizaos/autodoc";
const jsDocGen = new JsDocGenerator(aiService);
// Generate JSDoc for file
const documented = await jsDocGen.generateForFile(filePath);
Testing Services
Test Runner
import { TestRunner } from "@/src/utils/test-runner";
const runner = new TestRunner();
// Run all tests
await runner.runAll();
// Run specific test type
await runner.runByType("component");
Test Health Monitor
import { TestHealthMonitor } from "@/src/utils/testing/test-health-monitor";
const monitor = new TestHealthMonitor();
// Monitor test execution
monitor.startMonitoring();
const health = monitor.getHealth();
Development Services
File Watcher
import { FileWatcher } from "@/src/utils/file-watcher";
const watcher = new FileWatcher();
// Watch for changes
watcher.watch(projectPath, {
onChange: async (path) => {
console.log(`File changed: ${path}`);
await rebuild();
},
});
// Stop watching
watcher.stop();
Hot Reload
import { HotReloader } from "@/src/utils/hot-reload";
const reloader = new HotReloader();
// Enable hot reload
await reloader.enable({
port: 3000,
watch: ["src/**/*.ts"],
});
Utility Services
Spinner Utils
import { createSpinner } from "@/src/utils/spinner-utils";
const spinner = createSpinner("Loading...");
spinner.start();
// Update text
spinner.text = "Processing...";
// Success
spinner.succeed("Done!");
// Error
spinner.fail("Failed!");
Emoji Handler
import { configureEmojis, getEmoji } from "@/src/utils/emoji-handler";
// Configure emoji support
configureEmojis({ forceDisable: false });
// Get emoji with fallback
const checkmark = getEmoji("✅", "[OK]");
Error Handling
import { handleError } from "@/src/utils/handle-error";
try {
// Operation that might fail
} catch (error) {
handleError(error, {
context: "Plugin installation",
suggestions: ["Check network connection", "Verify plugin name"],
});
}
Configuration Services
Config Manager
import { ConfigManager } from "@/src/utils/config-manager";
const config = new ConfigManager();
// Load configuration
await config.load();
// Get value
const value = config.get("setting.nested.value");
// Set value
config.set("setting.nested.value", "new");
// Save configuration
await config.save();
Project Configuration
import { loadProject } from "@/src/project";
// Load project configuration
const project = await loadProject(projectPath);
// Access configuration
const { name, version, agents, plugins } = project;
Cloud Services
TEE Integration
import { TEEService } from "@/src/services/tee";
const tee = new TEEService();
// Deploy to TEE
await tee.deploy({
project: projectPath,
config: teeConfig,
});
// Get attestation
const attestation = await tee.getAttestation(deploymentId);
Phala Integration
// TEE commands are wrapped through CLI
// elizaos tee phala <command>
// Examples:
// - elizaos tee phala auth login
// - elizaos tee phala cvms create
// - elizaos tee phala cvms list
Package Management
Dependency Resolution
import { DependencyResolver } from "@/src/utils/dependency-resolver";
const resolver = new DependencyResolver();
// Resolve plugin dependencies
const deps = await resolver.resolve(pluginName);
// Install dependencies
await resolver.install(deps);
Version Management
import { VersionUtils } from "@/src/utils/version-utils";
// Check version compatibility
const isCompatible = VersionUtils.isCompatible("1.0.0", "^1.0.0");
// Get latest version
const latest = await VersionUtils.getLatest("@elizaos/core");
Security Services
Authentication
import { AuthService } from "@/src/services/auth";
const auth = new AuthService();
// Authenticate with npm
await auth.npmLogin();
// Authenticate with GitHub
await auth.githubLogin(token);
Validation
import { validatePlugin } from "@/src/utils/validation";
// Validate plugin structure
const validation = await validatePlugin(pluginPath);
if (!validation.isValid) {
console.error(validation.errors);
}
Best Practices
Service Usage
-
Always Handle Errors
try { await service.operation(); } catch (error) { handleError(error); }
-
Use Type Safety
import type { ServiceConfig } from "@/types"; const config: ServiceConfig = { // Type-safe configuration };
-
Clean Up Resources
const service = new Service(); try { await service.start(); } finally { await service.cleanup(); }
Performance Optimization
-
Cache Service Instances
let _instance: Service; export function getService(): Service { if (!_instance) { _instance = new Service(); } return _instance; }
-
Use Lazy Loading
const loadService = async () => { const { Service } = await import("./service"); return new Service(); };