API Reference
Complete API documentation for the five core CoFounder packages. Every function, class, type, and option is documented here with signatures, parameters, defaults, return types, and examples.
@waymakerai/aicofounder-guard
PII detection, prompt injection blocking, toxicity filtering, budget enforcement, rate limiting, and model gating.
createGuard
Create a guard instance with configurable PII, injection, toxicity, budget, rate limit, and model gating. Returns an object with check(), wrap(), middleware(), report(), and resetBudget() methods.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| pii | 'detect' | 'redact' | 'block' | false | 'detect' |
| injection | 'block' | 'warn' | false | 'block' |
| toxicity | 'block' | 'warn' | false | 'block' |
| budget | BudgetConfig | false | false |
| rateLimit | RateLimitConfig | false | false |
| models | { allowed?: string[]; blocked?: string[] } | false | false |
| reporter | 'console' | 'json' | { webhook: string } | false | false |
Example
const guard = createGuard({
pii: 'redact',
injection: 'block',
toxicity: 'block',
budget: { limit: 50, period: 'day', warningAt: 0.8, action: 'block' },
rateLimit: { maxRequests: 100, windowMs: 60000 },
reporter: 'console',
});guard.check
Run all configured guards on the input text. Returns a CheckResult with safe/blocked status, PII findings, injection findings, toxicity findings, redacted text, warnings, violations, cost estimate, and model name.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| text | string | required |
| opts.model | string | undefined |
| opts.direction | 'input' | 'output' | undefined |
Return Type
interface CheckResult {
safe: boolean;
blocked: boolean;
reason?: string;
warnings: string[];
piiFindings: PIIFinding[];
injectionFindings: InjectionFinding[];
toxicityFindings: ToxicityFinding[];
redacted?: string;
cost?: number;
model?: string;
violations: Violation[];
}guard.wrap
Wrap an Anthropic, OpenAI, or Google client with automatic guarding. All API calls through the wrapped client are intercepted, checked, and guarded transparently.
guard.middleware
Returns an Express-compatible middleware function. POST requests with a body are checked; blocked requests receive a 403 response with violation details.
guard.report
Returns a summary report of all guard activity: total checks, blocked/warned/passed counts, PII redaction stats by type, injection attempts by category, toxicity stats, cost tracking, rate limit hits, and model denials.
detectPII
Standalone PII detection. Returns an array of findings with type, value, redacted label, start/end positions, and confidence score. Detects email, SSN, credit card (with Luhn validation), phone, IP address (v4 and v6), date of birth, address, medical record number, passport, and driver's license.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| text | string | required |
redactPII
Detect and replace all PII in the text with labeled placeholders (e.g., [REDACTED_EMAIL], [REDACTED_SSN]). Returns the redacted text and the list of findings.
detectInjection
Score text for prompt injection risk. Returns a 0-100 score, an array of matched patterns with category/severity/weight, and a blocked boolean based on the sensitivity threshold. Sensitivity thresholds: low=70, medium=45, high=25.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| text | string | required |
| sensitivity | 'low' | 'medium' | 'high' | 'medium' |
detectToxicity
Detect toxic content across 7 categories: profanity (low), hate_speech (critical), violence (high), self_harm (critical), sexual (high), harassment (high), and spam (low). Returns matched patterns with category, severity, matched text, and surrounding context.
hasPII / hasInjection / hasToxicity
Boolean convenience functions. hasPII returns true if any PII is detected. hasInjection returns true if the injection score exceeds the threshold. hasToxicity returns true if any finding meets the minimum severity level.
BudgetEnforcer
Standalone budget enforcement. Track spending against per-period limits. Methods: checkBudget(additionalCost?), isExceeded(), record(cost), reset().
Parameters / Options
| Name | Type | Default |
|---|---|---|
| limit | number | required |
| period | 'hour' | 'day' | 'week' | 'month' | required |
| warningAt | number (0-1) | 0.8 |
| action | 'block' | 'warn' | 'block' |
RateLimiter
Standalone rate limiter using a sliding window. Methods: check() returns { allowed, remaining, resetMs }, record() increments the counter.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| maxRequests | number | required |
| windowMs | number | required |
ModelGate
Restrict which models can be used. check(model) returns { allowed: boolean, reason?: string }. Supports exact names and glob patterns (e.g., "*-preview").
@waymakerai/aicofounder-compliance
Enterprise compliance enforcement with 9 preset rules for HIPAA, SEC/FINRA, GDPR, CCPA, legal, safety, and security.
ComplianceEnforcer
Main compliance engine. Add rules, enforce them on AI input/output pairs, and track violation history.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| rules | ComplianceRule[] | [] |
| enableAllPresets | boolean | false |
| strictMode | boolean | false |
| logViolations | boolean | true |
| storeViolations | boolean | true |
| onViolation | (violation) => void | no-op |
| onEnforcement | (result) => void | no-op |
Example
const enforcer = new ComplianceEnforcer({
rules: [
PresetRules.hipaaNoMedicalAdvice(),
PresetRules.secFinancialDisclaimer(),
PresetRules.gdprPIIProtection(),
],
strictMode: true,
});enforcer.enforce
Run all active rules against the AI output. Each rule can allow, block, redact, replace, or append content. Returns the final output, action taken, list of violations, and compliance status.
Return Type
interface ComplianceEnforcementResult {
compliant: boolean;
action: 'allow' | 'block' | 'redact' | 'replace' | 'append';
finalOutput?: string;
violations: ComplianceViolation[];
}enforcer.addRule / removeRule
Dynamically add or remove compliance rules at runtime.
enforcer.getViolations
Returns the full violation history since the enforcer was created.
createComplianceEnforcer
Factory function that creates and returns a ComplianceEnforcer instance.
PresetRules
Factory object with 9 preset compliance rule generators. Each returns a fully configured ComplianceRule ready for use with ComplianceEnforcer.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| hipaaNoMedicalAdvice() | ComplianceRule | Blocks medical diagnoses and treatment advice |
| hipaaPIIProtection() | ComplianceRule | Redacts PHI (SSN, MRN, DOB) from output |
| secFinancialDisclaimer() | ComplianceRule | Appends financial disclaimer to investment content |
| secNoInvestmentAdvice() | ComplianceRule | Blocks specific buy/sell recommendations |
| noLegalAdvice() | ComplianceRule | Appends legal disclaimer to legal content |
| gdprPIIProtection() | ComplianceRule | Redacts PII per GDPR (email, phone, address, IP) |
| ccpaPrivacy() | ComplianceRule | Redacts sensitive data per CCPA (SSN, credit card, passport) |
| ageAppropriate(minAge?) | ComplianceRule | Blocks mature content for underage users (default: 13+) |
| noPasswordRequest() | ComplianceRule | Blocks AI from requesting passwords or credentials |
createComplianceRule
Create a custom compliance rule with a check function that receives (input, output, context) and returns a compliance result.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| id | string | required |
| name | string | required |
| description | string | required |
| category | 'healthcare' | 'finance' | 'legal' | 'privacy' | 'safety' | 'security' | required |
| severity | 'low' | 'medium' | 'high' | 'critical' | required |
| check | ComplianceCheckFn | required |
| tags | string[] | [] |
| enabled | boolean | true |
Example
const customRule = createComplianceRule({
id: 'no-competitor-mention',
name: 'No Competitor Mentions',
description: 'Prevent mentioning competitor products',
category: 'safety',
severity: 'medium',
tags: ['brand', 'marketing'],
check: async (input, output, context) => {
const competitors = ['CompetitorA', 'CompetitorB'];
const mentioned = competitors.filter(c =>
output.toLowerCase().includes(c.toLowerCase())
);
if (mentioned.length > 0) {
return {
compliant: false,
action: 'replace',
message: `Competitor mentioned: ${mentioned.join(', ')}`,
replacement: 'I can help you with our product features.',
issues: mentioned.map(m => `competitor_${m}`),
confidence: 0.9,
};
}
return { compliant: true, action: 'allow' };
},
});detectPII / redactPII
Compliance-focused PII detection and redaction. Supports filtering by type: email, phone, ssn, credit_card, ip_address, medical_record, passport, address, name, date_of_birth.
@waymakerai/aicofounder-agent-sdk
Guardrail wrapper for the Anthropic Agent SDK. Adds PII, injection, compliance, cost tracking, content filtering, audit logging, and rate limiting as interceptors.
createGuardedAgent
Create an agent with a full guard pipeline. The pipeline processes input through interceptors (rate limit, injection, PII, compliance, content, cost, audit), calls the LLM, then guards the output. Returns an agent with run() and getGuardReport() methods.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| model | string | required |
| instructions | string | 'You are a helpful assistant.' |
| guards | GuardConfig | boolean | required |
Example
const agent = createGuardedAgent({
model: 'claude-sonnet-4-20250514',
instructions: 'You are a helpful customer service agent.',
guards: {
pii: { mode: 'redact', onDetection: 'redact' },
injection: { sensitivity: 'medium', onDetection: 'block' },
compliance: { frameworks: ['hipaa', 'gdpr'] },
cost: { budgetPeriod: 'day', warningThreshold: 0.8 },
contentFilter: true,
audit: { destination: 'file', filePath: './audit.log' },
rateLimit: { maxRequests: 100, windowMs: 60000 },
},
});
const result = await agent.run('Help me with my account');
console.log(result.output);
console.log(result.blocked);
console.log(result.violations);
console.log(result.cost);
console.log(result.tokensUsed);
console.log(result.guardsApplied);GuardedAgent.run
Send a message through the guard pipeline, to the LLM, and back through the output guards. Returns the output, block status, violations, cost, token usage, and list of applied guards.
Return Type
interface GuardedAgentResult {
output: string;
blocked: boolean;
violations: Violation[];
cost: number;
tokensUsed: { input: number; output: number };
guardsApplied: string[];
}GuardedAgent.getGuardReport
Returns a comprehensive report: total requests, total cost, PII detections by type, injection attempts, compliance violations by framework, content filtered count, rate limit hits, audit event count, and timestamps.
Pre-built Factories
Pre-configured agent factories with industry-specific guard settings. Each factory creates a GuardedAgent with the appropriate interceptors enabled and configured for its compliance domain.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| createHIPAAAgent | GuardedAgent | PII redaction + HIPAA compliance + audit logging |
| createFinancialAgent | GuardedAgent | SEC/FINRA compliance + cost controls + audit |
| createGDPRAgent | GuardedAgent | GDPR PII protection + data minimization + audit |
| createSafeAgent | GuardedAgent | Full guard stack: PII + injection + toxicity + rate limit |
Example
import { createHIPAAAgent } from '@waymakerai/aicofounder-agent-sdk';
const agent = createHIPAAAgent({
model: 'claude-sonnet-4-20250514',
instructions: 'You are a healthcare information assistant.',
});
const result = await agent.run('Tell me about diabetes management');Interceptors (7 total)
Individual interceptor classes that implement the Interceptor interface with processInput() and processOutput() methods. Can be composed into a custom GuardPipeline for advanced use cases.
GuardPipeline
Low-level pipeline that chains interceptors. Add interceptors with use(), then process input/output text through the full chain. Order matters: rate limit, injection, PII, compliance, content, cost, audit.
guardTool
Wrap an individual tool definition with guards. The tool's handler is intercepted and guarded before and after execution.
Reporting
Generate structured or human-readable reports from a GuardedAgent's activity. Cost reports include per-model token usage and spending. Compliance reports include violation counts by framework.
@waymakerai/aicofounder-policies
Declarative policy engine for PII rules, content rules, model rules, cost rules, and data retention. Includes 9 industry presets and a composable policy builder.
PolicyEngine
Load one or more policies and evaluate text/context against all active rules. Supports PII patterns, content patterns, model restrictions, cost limits, and data retention rules.
Example
import { PolicyEngine, hipaaPolicy, gdprPolicy } from '@waymakerai/aicofounder-policies';
const engine = new PolicyEngine([hipaaPolicy, gdprPolicy]);
const result = engine.evaluate('Patient SSN: 123-45-6789', {
model: 'claude-sonnet-4-20250514',
direction: 'output',
});
console.log(result.allowed); // false
console.log(result.violations); // [{ rule: 'pii', pattern: 'ssn', ... }]compose
Merge multiple policies into a single composite policy. Strategies: "merge" (union of all rules), "override" (last policy wins), "strict" (most restrictive rule wins). Conflict resolution: "most-restrictive", "least-restrictive", "first-wins", "last-wins".
Parameters / Options
| Name | Type | Default |
|---|---|---|
| policies | Policy[] | required |
| strategy | 'merge' | 'override' | 'strict' | 'merge' |
| conflictResolution | 'most-restrictive' | 'least-restrictive' | 'first-wins' | 'last-wins' | 'most-restrictive' |
evaluatePolicy / evaluatePolicies
Evaluate text against one or multiple policies. Returns allowed/blocked status, violations with rule details, and the applicable action.
parsePolicy
Parse a policy from YAML string or JavaScript object. Useful for loading policies from configuration files.
validatePolicy
Validate a policy structure. Returns { valid: boolean, errors: ValidationError[] } with details about any structural issues.
Policy Presets (9 total)
Pre-built policies for common regulatory frameworks. Each includes appropriate PII rules, content rules, model restrictions, cost controls, and data retention settings.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| hipaaPolicy | Policy | HIPAA healthcare compliance |
| gdprPolicy | Policy | EU General Data Protection Regulation |
| ccpaPolicy | Policy | California Consumer Privacy Act |
| secPolicy | Policy | SEC/FINRA financial regulations |
| pciPolicy | Policy | PCI-DSS payment card security |
| ferpaPolicy | Policy | FERPA student data protection |
| soxPolicy | Policy | Sarbanes-Oxley financial reporting |
| safetyPolicy | Policy | General AI safety (harmful content, jailbreaks) |
| enterprisePolicy | Policy | Combined enterprise baseline |
PII Pattern Constants
Pre-defined regex patterns for 20+ PII types. Use these to build custom policy rules. Includes: EMAIL, PHONE, SSN, CREDIT_CARD, CREDIT_CARD_FORMATTED, IPV4, IPV6, DOB, ADDRESS, MEDICAL_RECORD, PASSPORT, DRIVERS_LICENSE, BANK_ACCOUNT, ZIP_CODE, FULL_NAME, AGE, VIN, DEA, NPI.
Content Pattern Constants
Pre-defined content detection patterns for harmful instructions, suicide/self-harm, child exploitation, violence threats, jailbreak attempts, prompt injection, and required disclaimers (investment, medical, legal, AI disclosure).
Cost Rule Presets
Pre-configured cost limits by tier. FREE_TIER: $1/day, STANDARD: $50/day, ENTERPRISE: $500/day. Use createCostRules() to define custom limits.
Model Rule Presets
Model restriction presets. OPENAI_ONLY and ANTHROPIC_ONLY lock to a single provider. MAJOR_PROVIDERS_ONLY allows OpenAI, Anthropic, and Google. NO_DEPRECATED blocks known deprecated models.
PolicyBuilder
Fluent builder for constructing policies programmatically. Chain methods like .pii(patterns).content(rules).model(rules).cost(rules).data(rules).build().
@waymakerai/aicofounder-core
Core SDK with the main CoFounder client, cost tracking, provider management, rate limiting, retry logic, and fallback system.
createCoFounder
Create the main CoFounder client. Configure providers, default model, caching, optimization strategy, and plugins. Supports fluent API chaining.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| providers | Record<string, string> | required (API keys) |
| defaultModel | string | 'claude-sonnet-4-20250514' |
| cache | boolean | CacheConfig | false |
| optimize | 'cost' | 'speed' | 'quality' | 'cost' |
| budget | BudgetConfig | undefined |
| plugins | RanaPlugin[] | [] |
Example
import { createCoFounder } from '@waymakerai/aicofounder-core';
const cofounder = createCoFounder({
providers: {
anthropic: process.env.ANTHROPIC_API_KEY!,
openai: process.env.OPENAI_API_KEY!,
},
defaultModel: 'claude-sonnet-4-20250514',
cache: true,
optimize: 'cost',
});
// Simple usage
const response = await cofounder.chat('Hello!');
// Fluent API
const response2 = await cofounder
.provider('anthropic')
.model('claude-sonnet-4-20250514')
.optimize('quality')
.cache(true)
.chat({ messages: [{ role: 'user', content: 'Hello!' }] });CostTracker
Track spending across all providers and models. Supports budget limits with configurable periods and warning thresholds. Methods: record(model, inputTokens, outputTokens), getStats(), getCostBreakdown(), isOverBudget(), reset().
Parameters / Options
| Name | Type | Default |
|---|---|---|
| budget | BudgetConfig | undefined |
| onBudgetWarning | (stats: CostStats) => void | undefined |
| onBudgetExceeded | (stats: CostStats) => void | undefined |
withRetry
Retry a function with exponential backoff and jitter. Classifies errors (rate_limit, server_error, network_error, timeout) and only retries retryable failures. Returns the result with retry metadata.
Parameters / Options
| Name | Type | Default |
|---|---|---|
| maxRetries | number | 3 |
| baseDelay | number (ms) | 1000 |
| maxDelay | number (ms) | 30000 |
| backoffMultiplier | number | 2 |
| jitter | boolean | true |
RateLimiter
Provider-aware rate limiter that respects API rate limit headers. Configure per-provider limits and automatic backoff.
Error Classes
Typed error classes for different failure modes. Each extends RanaError with provider, model, and context information for debugging.