import {
TealEngineV12,
TealGuard,
TealRegistry,
TealReliability,
TealAudit,
BundleExporter,
PolicyMode,
} from 'tealtiger';
// --- Initialize modules ---
const guard = new TealGuard({
promptInjection: { enabled: true, mode: PolicyMode.ENFORCE },
contentModeration: { enabled: true, mode: PolicyMode.ENFORCE },
});
const registry = new TealRegistry({
tools: {
allowlist: [
{
name: 'execute_trade',
riskLevel: 'HIGH',
requireApproval: true,
rateLimit: { maxPerHour: 50 },
},
{
name: 'get_portfolio',
riskLevel: 'LOW',
requireApproval: false,
},
{
name: 'get_market_data',
riskLevel: 'LOW',
requireApproval: false,
},
],
},
});
const reliability = new TealReliability({
circuitBreakers: {
'brokerage-api': {
failureThreshold: 3, // Open after 3 consecutive failures
resetTimeout: 30_000, // Try again after 30 seconds
halfOpenMaxAttempts: 1, // Allow 1 test request in half-open
},
},
retryBudget: {
maxRetries: 2,
backoff: 'exponential',
maxBackoff: 5_000,
},
});
const audit = new TealAudit({
enabled: true,
redactPII: true,
outputs: ['file', 'syslog', 'http'],
retention: { days: 2555 }, // 7 years for financial regulations
evidenceEnvelope: {
enabled: true,
includeModuleResults: true,
},
});
const exporter = new BundleExporter({
format: 'sarif',
version: '2.1.0',
outputDir: './compliance-exports',
includeEvidence: true,
});
const engine = new TealEngineV12({
modules: [guard, registry, reliability, audit],
policies: {
tools: {
execute_trade: {
allowed: true,
conditions: {
requireApprovalAbove: 10_000, // Human review for trades > $10K
denyAbove: 500_000, // Hard deny above $500K
maxTradesPerDay: 100,
requireAuth: true,
},
},
},
cost: {
dailyLimit: 1_000_000, // $1M daily trading limit
perRequestLimit: 500_000, // $500K per single trade
trackCommissions: true,
},
},
mode: PolicyMode.ENFORCE,
failClosed: true,
});
// --- Orchestration flow ---
async function handleTradeRequest(
clientRequest: string,
clientId: string,
tradeDetails: {
action: 'buy' | 'sell';
symbol: string;
quantity: number;
estimatedPrice: number;
}
) {
const context = engine.createContext({
clientId,
agentId: 'financial-advisor',
environment: 'production',
complianceMode: 'SEC',
});
const estimatedValue = tradeDetails.quantity * tradeDetails.estimatedPrice;
// Step 1: TealGuard scans client request
const guardResult = await guard.scan({
content: clientRequest,
direction: 'input',
context,
});
if (guardResult.action === 'DENY') {
await audit.log({
type: 'input_blocked',
reason: guardResult.reasonCodes,
correlationId: context.correlationId,
});
return { blocked: true, reason: guardResult.reasonCodes };
}
// Step 2: TealRegistry checks tool authorization
const toolCheck = await registry.checkTool({
tool: 'execute_trade',
agentId: 'financial-advisor',
metadata: { riskLevel: 'HIGH', estimatedValue },
context,
});
if (toolCheck.action === 'DENY') {
return { blocked: true, reason: ['TOOL_NOT_ALLOWLISTED'] };
}
// Step 3: TealEngine evaluates trade against financial policies
const decision = await engine.evaluate({
action: 'tool.execute',
tool: 'execute_trade',
arguments: {
...tradeDetails,
estimatedValue,
},
context,
});
// Step 4: Handle approval gate
if (decision.action === 'REQUIRE_APPROVAL') {
// Check circuit breaker before queuing (no point approving if API is down)
const circuitState = await reliability.checkCircuit('brokerage-api');
if (circuitState === 'OPEN') {
await audit.log({
type: 'trade_blocked_circuit_open',
correlationId: context.correlationId,
metadata: { circuit: 'brokerage-api', state: 'OPEN' },
});
return {
blocked: true,
reason: ['TRADING_API_UNAVAILABLE'],
message: 'Trading API is currently experiencing issues. Please try again later.',
};
}
const approvalId = await queueForApproval({
clientId,
trade: tradeDetails,
estimatedValue,
correlationId: context.correlationId,
decision,
});
await audit.log({
type: 'trade_approval_requested',
correlationId: context.correlationId,
metadata: {
estimatedValue,
symbol: tradeDetails.symbol,
quantity: tradeDetails.quantity,
approvalId,
},
});
return {
pending: true,
approvalId,
message: `Trade of ${tradeDetails.quantity} ${tradeDetails.symbol} ($${estimatedValue.toLocaleString()}) requires compliance approval.`,
correlationId: context.correlationId,
};
}
if (decision.action === 'DENY') {
await audit.log({
type: 'trade_denied',
reason: decision.reasonCodes,
correlationId: context.correlationId,
});
return { blocked: true, reason: decision.reasonCodes };
}
// Step 5: Execute trade with circuit breaker protection
const tradeResult = await reliability.execute(
'brokerage-api',
() => executeTrade(tradeDetails),
context
);
// Step 6: Track cost
const costEntry = {
tradeValue: estimatedValue,
commission: tradeResult.commission || 4.95,
timestamp: new Date().toISOString(),
};
// Step 7: Full audit trail
const evidenceEnvelope = await audit.createEvidenceEnvelope({
correlationId: context.correlationId,
complianceFramework: 'SEC',
tradeDetails: {
action: tradeDetails.action,
symbol: tradeDetails.symbol,
quantity: tradeDetails.quantity,
executedPrice: tradeResult.executedPrice,
totalValue: tradeResult.totalValue,
commission: tradeResult.commission,
},
moduleResults: {
guard: { action: guardResult.action },
registry: { action: toolCheck.action },
engine: { action: decision.action, mode: 'ENFORCE' },
reliability: { circuitState: 'CLOSED' },
},
cost: costEntry,
});
// Step 8: Export for regulatory compliance
await exporter.export({
envelope: evidenceEnvelope,
correlationId: context.correlationId,
format: 'sarif',
});
return {
success: true,
trade: {
symbol: tradeDetails.symbol,
quantity: tradeDetails.quantity,
executedPrice: tradeResult.executedPrice,
totalValue: tradeResult.totalValue,
commission: tradeResult.commission,
},
evidenceId: evidenceEnvelope.id,
correlationId: context.correlationId,
};
}
// --- Example usage ---
const result = await handleTradeRequest(
'Sell 500 shares of ACME Corp and reinvest into S&P 500 index fund.',
'client-abc-123',
{
action: 'sell',
symbol: 'ACME',
quantity: 500,
estimatedPrice: 25.0,
}
);
// result.pending = true (trade > $10,000 requires approval)
// result.approvalId = 'approval-...'
// result.message = 'Trade of 500 ACME ($12,500) requires compliance approval.'