monora-ai
v1.4.0
Published
Lightweight governance and trace SDK for AI systems
Downloads
452
Maintainers
Readme
Monora SDK for Node.js
Lightweight governance and trace SDK for AI systems.
Features
- Immutable Event Logs: SHA-256 hash chains for tamper-evident audit trails
- Policy Enforcement: Model allowlist/denylist with classification-based rules
- Model Registry: Centralized model and provider metadata
- Tracing: Distributed tracing for AI system observability
- Event Processing: Background event dispatcher with batching and buffering
- Multiple Sinks: Output to stdout, file (JSON-lines), or HTTPS endpoints
- Event Enrichment: Automatic metadata (timestamp, host, process, environment)
Installation
npm install monoraQuick Start
import { init, llmCall, trace } from 'monora';
// Initialize SDK
init({ configPath: './monora.yml' });
const ask = llmCall({ purpose: 'support' })(function ask(
question: string,
model: string = 'gpt-4o-mini'
) {
return { choices: [{ message: { content: 'ok' } }] };
});
// Create a trace
trace('my-ai-task', (span) => {
console.log('Trace ID:', span.traceId);
ask('hello');
});Guided Setup (Wizard)
npx monora-ai init
# or
./node_modules/.bin/monora initThis generates a monora.yml you can load with loadConfig({ configPath: './monora.yml' }).
Reports & Security Review
The runtime automatically generates compliance reports at trace completion (default: ./monora_reports/<trace_id>/compliance.json) and emits a trust_summary event. Configure behavior with the reporting section in monora.yml.
npx monora-ai report --input events.jsonl --output report.json
npx monora-ai report --input events.jsonl --output report.md --format markdown
npx monora-ai security-review --input events.jsonl --output security.json
npx monora-ai security-review --input events.jsonl --output security.json --sign gpg --gpg-key "[email protected]"
npx monora-ai trust-package --input events.jsonl --trace-id trc_123 --output trust.json --config monora.ymlimport { exportTrustPackage } from 'monora-ai';
const trustPackage = exportTrustPackage('trc_123', {
inputPath: 'events.jsonl',
configPath: 'monora.yml',
});Data Handling + Alerts
import { DataHandlingEngine, buildDataViolation, ViolationWebhookDispatcher } from 'monora';
const dataHandling = new DataHandlingEngine({
enabled: true,
mode: 'redact',
rules: [
{ name: 'email', pattern: '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}' }
]
});
const payload = { message: 'Contact me at [email protected]' };
const { value, applied } = dataHandling.sanitizePayload('request', payload, 'confidential');
const dispatcher = new ViolationWebhookDispatcher({
endpoint: 'https://hooks.example.com/monora',
headers: { Authorization: 'Bearer TOKEN' }
});
dispatcher.start();
dispatcher.send({ event_type: 'policy_violation', message: 'Example violation' });High-level Runtime Helpers
import { init, logEvent, toolCall, agentStep, setViolationHandler } from 'monora';
init({ configPath: './monora.yml' });
setViolationHandler((violation) => {
console.error('Violation:', violation.message);
});
const fetchTool = toolCall({ toolName: 'fetch', purpose: 'integration' })(async (url: string) => {
return { ok: true, url };
});
const plan = agentStep({ agentName: 'planner', stepType: 'planning', purpose: 'analysis' })(
(goal: string) => [`step for ${goal}`]
);
logEvent('custom', { message: 'hello' }, { purpose: 'manual' });Configuration
Create a monora.json or monora.yaml file:
{
"defaults": {
"data_classification": "internal",
"environment": "production"
},
"policies": {
"model_allowlist": ["gpt-4*", "claude-3-*"],
"model_denylist": ["deepseek:*"],
"enforce": true
},
"immutability": {
"enabled": true,
"scope": "per_trace",
"hash_algorithm": "sha256"
}
}API Documentation
Policy Engine
import { PolicyEngine } from 'monora';
const engine = new PolicyEngine({
model_allowlist: ['gpt-4*'],
model_denylist: ['deepseek:*'],
enforce: true
});
// Check a model
const violation = engine.checkModel('gpt-4o-mini', 'internal');
// Check without throwing
const isAllowed = engine.isModelAllowed('gpt-4o-mini');Model Registry
import { ModelRegistry } from 'monora';
const registry = new ModelRegistry({
default_provider: 'unknown',
providers: [
{ name: 'openai', model_patterns: ['gpt-*'] },
{ name: 'anthropic', model_patterns: ['claude-*'] }
]
});
// Resolve provider
const [provider, matched] = registry.resolve('gpt-4o');
console.log(provider); // 'openai'Tracing
import { trace, traceAsync, startSpan } from 'monora';
// Synchronous trace
trace('my-operation', (span) => {
span.metadata.custom = 'value';
return 'result';
});
// Async trace
await traceAsync('my-async-operation', async (span) => {
const child = startSpan('child-operation');
await doWork();
return 'result';
});Hash Chain Verification
import { verifyChain, detectTampering, detectSequenceGaps } from 'monora';
// Verify chain integrity
const [isValid, error] = verifyChain(events);
if (!isValid) {
console.error('Chain verification failed:', error);
}
// Detect tampering
const tampered = detectTampering(events);
console.log('Tampered events:', tampered);
// Detect sequence gaps
const gaps = detectSequenceGaps(events);
console.log('Sequence gaps:', gaps);Security Reports
Generate JSON security review reports locally with CLI:
Auth: none (local CLI). Errors: invalid JSONL/config or GPG signing failures.
npx monora-ai security-review --input events.jsonl --output security.json
npx monora-ai security-review --input events.jsonl --output security.json --config monora.ymlData Handling
Use the data handling engine for redaction or blocking decisions (modes: redact, block, allow):
Auth: none. Errors: DataHandlingViolation in block mode or invalid regex patterns.
import { DataHandlingEngine } from 'monora';
const engine = new DataHandlingEngine({
enabled: true,
mode: 'redact',
rules: [{ name: 'email', pattern: '[^@]+@[^@]+\\.[^@]+' }]
});
const { value, applied } = engine.sanitizePayload('request', payload, 'confidential');Webhook Alerts
Send policy violation payloads to a webhook:
Auth: set headers such as Authorization. Errors: network failures, non-2xx responses, or queue overflow.
import { ViolationWebhookDispatcher } from 'monora';
const dispatcher = new ViolationWebhookDispatcher({
endpoint: 'https://hooks.example.com/monora',
headers: { Authorization: 'Bearer TOKEN' }
});
dispatcher.start();
dispatcher.send({ event_type: 'policy_violation', message: 'Blocked model' });{
"alerts": {
"violation_webhook": "https://hooks.example.com/monora",
"headers": { "Authorization": "Bearer YOUR_TOKEN" }
}
}Event Building and Dispatching
Event builder and dispatcher classes are available in the current Node SDK.
import { EventBuilder, EventDispatcher, StdoutSink, FileSink } from 'monora';
// Create event builder
const builder = new EventBuilder({
defaults: {
service_name: 'my-service',
environment: 'production',
data_classification: 'internal',
},
});
// Build events with automatic enrichment
const event = builder.build('llm_call', {
model: 'gpt-4o',
prompt_tokens: 100,
completion_tokens: 50,
});
// Setup event dispatcher with sinks
const sinks = [
new StdoutSink('json'),
new FileSink('./events.jsonl', { batchSize: 100 }),
];
const dispatcher = new EventDispatcher(sinks, config);
dispatcher.start();
// Emit events (buffered and batched automatically)
dispatcher.emit(event);
// Cleanup
dispatcher.close();Sink Options
These sink implementations are exported and ready for use.
// Stdout Sink
const stdoutSink = new StdoutSink('pretty'); // or 'json'
// File Sink with rotation
const fileSink = new FileSink('./logs/events.jsonl', {
batchSize: 100,
flushIntervalSec: 5.0,
rotation: 'daily', // or 'size' or 'none'
maxSizeMb: 100,
});
// HTTPS Sink with retry
const httpsSink = new HttpSink(
'https://api.example.com/events',
{ 'Authorization': 'Bearer token' },
{
batchSize: 50,
timeoutSec: 10.0,
retryAttempts: 3,
backoffBaseSec: 0.5,
}
);License
MIT
Support
For issues and questions, please visit: https://github.com/monora/monora
