@codmir/events
v2.0.0
Published
Event system for UI & backend activity tracking, AI-safe workflows, logging, error detection, and replay
Readme
@codmir/events
Event system SDK for observability, telemetry, AI task scheduling, and workflow automation.
Features
- Telemetry — Batch event reporting to Codmir Events Platform with retries
- Event Bus Client — Publish/subscribe to events across services
- AI Task Scheduler — Schedule and delegate tasks between AI agents
- Workflow Schema — Visual workflow definitions with 8 node types
- Core Event System — Typed events, monitoring, logging, replay
- NestJS Integration — Ready-to-use modules and decorators
Installation
pnpm add @codmir/eventsTelemetry (Recommended)
Track events from any project and report them to the Codmir Events Platform.
import { createTelemetry } from '@codmir/events/telemetry';
const telemetry = createTelemetry({
endpoint: 'https://codmir.com/api/events/ingest',
apiKey: process.env.CODMIR_EVENTS_API_KEY,
projectId: 'proj_123',
source: 'my-app',
environment: 'production',
// Optional
batchSize: 25, // flush after 25 events (default)
flushIntervalMs: 5000, // auto-flush every 5s (default)
maxRetries: 3, // retry on 5xx errors (default)
debug: false, // console logging (default)
});
// Track a simple event
telemetry.track('user/signed-up', { userId: '123', plan: 'pro' });
// Track with options
telemetry.track('order/created', { orderId: 'ord_1', total: 99 }, {
correlationId: 'checkout_abc',
userId: 'user_456',
});
// Track an operation with automatic timing
const op = telemetry.trackOperation('deploy/build', { branch: 'main' });
await runBuild();
op.end(); // records COMPLETED + durationMs
// Handle errors
const op2 = telemetry.trackOperation('email/send');
try {
await sendEmail();
op2.end();
} catch (err) {
op2.end({ error: err.message }); // records FAILED + error
}
// Manual flush
await telemetry.flush();
// Graceful shutdown (flushes remaining queue)
await telemetry.shutdown();Telemetry Config
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| endpoint | string | required | Ingestion API URL |
| apiKey | string | — | Bearer token for auth |
| projectId | string | — | Associate events with a project |
| organizationId | string | — | Associate with an organization |
| source | string | — | Source identifier (e.g. "my-app") |
| environment | string | — | e.g. "production", "staging" |
| batchSize | number | 25 | Events per batch before auto-flush |
| flushIntervalMs | number | 5000 | Auto-flush interval (ms) |
| maxRetries | number | 3 | Retries for server errors |
| debug | boolean | false | Enable console logging |
| headers | object | — | Custom request headers |
Event Bus Client
Publish and subscribe to events via the Codmir event bus.
import { createEventClient } from '@codmir/events/client';
const client = createEventClient({
serviceUrl: 'http://localhost:3000',
agentId: 'my-service',
projectId: 'proj_123',
});
// Publish
await client.publish({
type: 'ticket/created',
data: { ticketId: 't_1', title: 'Fix login bug' },
});
// Subscribe
await client.subscribe(['task.completed', 'task.failed'], (event) => {
console.log('Event:', event.type, event.data);
});
// Cleanup
client.close();AI Task Scheduler
Coordinate AI agents with role-based task queuing.
import { createTaskScheduler } from '@codmir/events/scheduler';
const scheduler = createTaskScheduler({
serviceUrl: 'http://localhost:3000',
projectId: 'proj_123',
});
// Register as an agent
await scheduler.registerAgent({
name: 'Coder AI',
role: 'coder',
capabilities: ['typescript', 'react'],
});
// Process tasks
await scheduler.startProcessing(async (task) => {
const result = await generateCode(task.input);
return { status: 'completed', output: { code: result } };
});Agent Roles
| Role | Description |
|------|-------------|
| coordinator | Orchestrates agents, breaks down tasks |
| coder | Writes and modifies code |
| reviewer | Reviews code and provides feedback |
| tester | Creates and runs tests |
| documenter | Writes documentation |
| researcher | Researches and gathers information |
| planner | Creates plans and architecture |
| debugger | Debugs and fixes issues |
| security | Security analysis and fixes |
| devops | Infrastructure and deployment |
Workflow Schema
Define visual workflows with typed nodes and edges (used in the workflow builder).
import {
WorkflowDefinitionSchema,
WORKFLOW_TEMPLATES,
createWorkflowFromTemplate,
validateWorkflow,
} from '@codmir/events';
// Create from template
const workflow = createWorkflowFromTemplate(
'ticket-to-code', 'proj_123', 'org_456', 'user_789'
);
// Validate
const { valid, errors } = validateWorkflow(workflow);Node Types
| Type | Description | Color |
|------|-------------|-------|
| trigger | Event or schedule start | Amber |
| action | HTTP, DB, integration | Blue |
| ai | LLM call or AI task | Purple |
| condition | Branching logic (true/false) | Orange |
| wait | Delay or timer | Cyan |
| agent | Delegate to AI agent | Indigo |
| transform | Data transformation | Teal |
| output | Workflow result | Emerald |
Subpath Exports
import { ... } from '@codmir/events'; // Core + telemetry re-exports
import { ... } from '@codmir/events/telemetry'; // CodmirTelemetry, createTelemetry
import { ... } from '@codmir/events/client'; // EventClient, createEventClient
import { ... } from '@codmir/events/scheduler'; // TaskScheduler
import { ... } from '@codmir/events/orchestrator'; // Multi-agent orchestrator
import { ... } from '@codmir/events/core'; // Core types and factory
import { ... } from '@codmir/events/monitoring'; // Monitoring system
import { ... } from '@codmir/events/logging'; // Structured logging
import { ... } from '@codmir/events/replay'; // Event replay
import { ... } from '@codmir/events/adapters'; // Transport adapters
import { ... } from '@codmir/events/nestjs'; // NestJS modules
import { ... } from '@codmir/events/preview'; // IDE preview system
import { ... } from '@codmir/events/domains'; // Domain event typesEnvironment Variables
# Telemetry
CODMIR_EVENTS_API_KEY=your-api-key
CODMIR_EVENTS_ENDPOINT=https://codmir.com/api/events/ingest
# Event bus (legacy)
EVENTS_SERVICE_URL=http://localhost:3000
AGENT_ID=unique-agent-id
PROJECT_ID=project-123
ORGANIZATION_ID=org-456License
MIT
