Agent DocsDeveloper documentation
Reference

Data Models & Types

All TypeScript types, database schemas, and enums

Data Models Reference

Types are defined in packages/types/src/ and the database schema in services/api-gateway/src/db/schema.ts.


Agents

Source: packages/types/src/agent.ts

type ExecutionMode = 'platform-managed' | 'external-procode' | 'external-n8n';
type AgentStatus = 'draft' | 'active' | 'canary' | 'suspended' | 'deprecated';
type RiskClassification = 'assistive' | 'semi-autonomous' | 'autonomous';

interface Agent {
  id: string;
  name: string;
  description: string;
  version: string;                       // Semantic version
  runtime: 'procode' | 'n8n';
  executionMode: ExecutionMode;
  status: AgentStatus;
  owner: string;                         // Builder user ID
  tenantId: string;
  capabilities: string[];
  tags?: AgentTag[];                     // { name: string; source: 'user' | 'platform' }
  riskClassification: RiskClassification;
  defaultInputModes?: string[];          // MIME types (e.g., ['text/plain', 'image/jpeg'])
  defaultOutputModes?: string[];
  mcpEndpoint?: string;
  createdAt: string;
  updatedAt: string;
  config: AgentConfig;
  metrics?: AgentMetrics;                // successRate, latencyP95, costPerDay, totalExecutions, hitlEscalationRate
}

interface AgentConfig {
  systemPrompt: string;
  model: { primary: string; fallback?: string; temperature: number; maxTokens: number };
  tools: { id: string; name: string; mcpEndpoint: string }[];
  memory: MemoryConfig;
  hitl: { enabled: boolean; riskThreshold: number; escalationChain: string[] };
  guardrails: { inputPolicies: string[]; outputPolicies: string[] };
  entitlements: AgentEntitlements;             // Dim 1: User -> Agent
  toolGrants: AgentToolGrants;                // Dim 2: Agent -> Tool
  interactionPolicy: AgentInteractionPolicy;  // Dim 3: Agent -> Agent
  modelAccess: AgentModelAccess;              // Dim 4: Agent -> Model
  externalConfig?: ExternalConfig;
  knowledge?: AgentKnowledgeConfig;
}

Access Control (4 Dimensions)

// Dim 1: Who can SEE and USE this agent
interface AgentEntitlements {
  visibility: 'public' | 'restricted' | 'private';
  allowedGroups?: string[];  allowedUsers?: string[];  allowedRoles?: string[];
  owners: string[];  ownerGroups?: string[];
}

// Dim 2: Which TOOLS this agent can invoke
interface AgentToolGrants {
  tools: ToolGrant[];  dynamicDiscovery: boolean;  maxToolCallsPerExecution: number;
}
interface ToolGrant {
  toolId: string;
  permissions: ('read' | 'write' | 'execute')[];
  conditions?: { maxCallsPerHour?: number; requireApproval?: boolean;
                 timeWindow?: { start: string; end: string };
                 approvalPolicy?: { approvers?: string[]; approverGroups?: string[]; allowSelfApproval?: boolean } };
}

// Dim 3: Which AGENTS this agent can call
interface AgentInteractionPolicy {
  canInvoke: AgentInvokeGrant[];  invocableBy: { agentId: string }[];  discoverable: boolean;
}
interface AgentInvokeGrant {
  agentId: string;  maxDelegationsPerExecution: number;  requireApproval?: boolean;
  delegationMode?: 'delegate-and-return' | 'handoff';
  capabilityMode?: 'full' | 'readwrite' | 'readonly';
  budgetAllocation?: number | null;
  subagentConfig?: { tokenBudget?: number; costBudget?: number; timeoutMs?: number };
}

// Dim 4: Which MODELS this agent can use
interface AgentModelAccess {
  allowedModels?: string[];  allowedModelTags?: string[];  deniedModels?: string[];
  maxCostPerRequest?: number;  maxCostPerDay?: number;  maxTokensPerRequest?: number;
}

ExternalConfig

interface ExternalConfig {
  endpointUrl: string;
  authType: 'bearer' | 'api-key' | 'mtls' | 'none';
  authHeaderName?: string;
  authSecretRef?: string;                    // Vault reference (e.g., 'vault:tenant-1/agent-xyz')
  inputFormat: 'a2a' | 'langserve' | 'openai-compatible' | 'n8n-webhook' | 'custom';
  responseExtractor?: string;  healthCheckUrl?: string;  timeoutMs?: number;
  n8nWorkflowId?: string;  costModel?: string;
  streamingEnabled?: boolean;  streamingTimeoutMs?: number;
  turnBasedEnabled?: boolean;  turnEndpointUrl?: string;  maxTurns?: number;
  agUiEnabled?: boolean;  agUiEndpointUrl?: string;      // AG-UI = recommended protocol
}

Conversations & Messages

Source: packages/types/src/conversation.ts

interface Conversation {
  id: string;  agentId: string;  userId: string;  tenantId: string;
  status: 'active' | 'closed';  createdAt: string;  messages: Message[];
}

interface Message {
  id: string;
  role: 'user' | 'agent' | 'system';
  content: string;
  timestamp: string;
  toolCalls?: { id: string; name: string; status: 'pending'|'success'|'error';
                input: Record<string,unknown>; output?: Record<string,unknown>; durationMs?: number }[];
  citations?: { id: string; source: string; text: string; relevanceScore: number }[];
  approval?: { id: string; action: string; riskScore: number; impact: string;
               status: 'pending'|'approved'|'rejected'|'modified'; reasoning: string };
  confidence?: number;
  tokenUsage?: { input: number; output: number; cost: number };
  attachments?: { id: string; mimeType: string; name?: string; uri?: string; sizeBytes?: number }[];
}

Tools & MCP

Source: packages/types/src/common.ts

type ToolRiskLevel = 'low' | 'medium' | 'high' | 'critical';
type ToolCategory = 'read-only' | 'write' | 'external-comms' | 'financial' | 'destructive';

interface Tool {
  id: string;  name: string;  description: string;  mcpEndpoint: string;
  runtime: 'procode' | 'n8n' | 'both';
  riskLevel: ToolRiskLevel;  category: ToolCategory;
  inputSchema: Record<string, unknown>;  outputSchema: Record<string, unknown>;
  usageCount: number;  lastUsed?: string;  grantedAgentIds?: string[];
  authRequirements?: { type: 'none'|'oauth'|'api-key'|'bearer'; provider?: string; scopes?: string[]; credentialRef?: string };
  serverId?: string;
  signatureStatus?: 'signed' | 'unsigned' | 'expired' | 'invalid';
  signedAt?: string;  signedBy?: string;
}

interface McpServer {
  id: string;  name: string;  tenantId: string;
  transport: 'stdio' | 'sse';
  command?: string;  args?: string[];        // stdio transport
  endpoint?: string;                         // SSE transport
  status: 'active' | 'inactive' | 'error' | 'connecting';
  toolCount: number;  lastHealthCheck?: string;  createdAt: string;
}

interface N8nWorkflow {
  id: string;  name: string;  description: string;  active: boolean;
  mcpEnabled: boolean;  nodeCount: number;  triggerType: string;
  lastExecution?: string;  executionsPerDay: number;
  publishedAsAgentId?: string;  tags: string[];
  createdAt: string;  updatedAt: string;
}

Tool Sets

Source: packages/types/src/tool-set.ts -- Reusable tool authorization bundles.

type ToolSetStatus = 'active' | 'deprecated' | 'disabled' | 'pending_review';

interface ToolSet {
  id: string;  name: string;  description: string;  instructions: string;
  riskLevel: 'low' | 'medium' | 'high' | 'critical';
  category: string;  toolIds: string[];  tenantId: string;
  status: ToolSetStatus;  createdBy: string;  createdAt: string;  updatedAt: string;
}

interface ToolSetGrant {
  id?: number;  toolSetId: string;  agentId: string;
  conditions?: { maxCallsPerHour?: number; requireApproval?: boolean; timeWindow?: { start: string; end: string } };
  grantedAt?: string;  grantedBy?: string;
}

Skills

Source: packages/types/src/skill.ts -- Portable knowledge bundles (instructions, scripts, references).

type SkillVisibility = 'private' | 'tenant' | 'published';
type SkillContentStatus = 'draft' | 'pending_review' | 'active' | 'deprecated' | 'disabled';

interface Skill {
  id: string;  name: string;  description: string;  version: number;
  contentHash?: string;                          // SHA-256 of instructions
  frontmatter: Record<string, unknown>;          // Parsed YAML metadata
  instructions: string;                          // Markdown body (SKILL.md)
  category: string;  tags: string[];  tenantId: string;
  visibility: SkillVisibility;  status: SkillContentStatus;
  allowedTools: string[];                        // Informational (not grants)
  requiredToolSetIds: string[];                  // Prerequisites (advisory)
  files?: SkillFile[];  createdBy: string;  createdAt: string;  updatedAt: string;
}

interface SkillFile {
  id: string;  skillId: string;  filePath: string;   // e.g., "scripts/validate.py"
  fileType: 'script' | 'reference' | 'asset';
  mimeType?: string;  content?: string;  storageKey?: string;  sizeBytes: number;  createdAt: string;
}

interface AgentSkillAssignment {
  agentId: string;  skillId: string;  skillName?: string;
  enabled: boolean;  priority: number;  addedAt: string;  addedBy: string;
}

Memory

Source: packages/types/src/memory.ts

type MemoryType = 'short-term' | 'long-term' | 'graph' | 'procedural';
type MemoryNamespace = 'user' | 'team' | 'agent' | 'global';
type MemoryConsentCategory = 'preferences' | 'facts' | 'history' | 'procedures';
type MemoryAuditAction = 'create'|'read'|'update'|'delete'|'consolidate'|'export'|'gdpr-forget';

interface MemoryEntry {
  id: string;  agentId: string;  agentName: string;
  type: MemoryType;  namespace: MemoryNamespace;
  userId?: string;  userName?: string;
  key: string;  content: string;  metadata: Record<string, unknown>;
  embedding?: number[];  ttlDays: number;
  createdAt: string;  expiresAt?: string;
  accessCount: number;  lastAccessed?: string;
  consolidated?: boolean;  sourceEntryIds?: string[];  pendingReview?: boolean;
}

interface MemoryConsent {
  id: string;  userId: string;  agentId: string;     // '*' = global
  consentGiven: boolean;  categories: MemoryConsentCategory[];
  consentDate: string;  updatedAt: string;
}

// GDPR Data Subject Access Request (Art. 15/17)
interface DSARRequest {
  id: string;  userId: string;  userEmail: string;
  type: 'export' | 'forget';
  status: 'pending' | 'in-progress' | 'completed' | 'failed';
  agentId?: string;  entriesAffected?: number;  completedAt?: string;  createdAt: string;
}

interface MemoryAuditEntry {
  id: string;  memoryId?: string;  action: MemoryAuditAction;
  actorType: 'agent' | 'user' | 'system';  actorId: string;
  agentId?: string;  userId?: string;  details?: string;  timestamp: string;
}

Knowledge

Source: packages/types/src/knowledge.ts

type EmbeddingStatus = 'pending' | 'processing' | 'complete' | 'error';
type DocumentFormat = 'pdf' | 'docx' | 'txt' | 'md' | 'html' | 'csv';
type ResourceVisibility = 'public' | 'restricted' | 'private';

interface KnowledgeBase {
  id: string;  name: string;  description: string;  tenantId: string;  owner: string;
  visibility: ResourceVisibility;
  allowedUsers?: string[];  allowedGroups?: string[];  allowedRoles?: string[];
  documentCount: number;  totalChunks: number;  totalSizeMB: number;
  embeddingModel: string;
  chunkStrategy: 'fixed' | 'semantic' | 'recursive';
  chunkSize: number;  chunkOverlap: number;
  customPipeline?: CustomPipelineConfig;  parsingConfig?: ParsingPipelineConfig;
  createdAt: string;  updatedAt: string;
}

interface KnowledgeDocument {
  id: string;  knowledgeBaseId: string;  filename: string;  format: DocumentFormat;
  sizeMB: number;  chunkCount: number;  embeddingStatus: EmbeddingStatus;
  uploadedAt: string;  processedAt?: string;  errorMessage?: string;
  metadata: Record<string, string>;
}

interface KnowledgeChunk {
  id: string;  documentId: string;  index: number;  content: string;
  tokenCount: number;  embedding?: number[];
  metadata: { page?: number; section?: string; startOffset: number; endOffset: number };
}

// Agent retrieval config (stored in AgentConfig.knowledge)
interface RetrievalConfig {
  strategy: 'semantic' | 'keyword' | 'hybrid';
  topK: number;  relevanceThreshold: number;  rerank: boolean;  rerankModel?: string;
  graphRAG: boolean;  graphHops?: number;  maxContextTokens: number;
}

Deployments & Executions

Source: packages/types/src/deployment.ts

interface Deployment {
  id: string;  agentId: string;  agentName: string;  version: string;
  environment: 'dev' | 'staging' | 'production';
  status: 'pending' | 'running' | 'succeeded' | 'failed' | 'rolled_back';
  canaryPercent: number;  triggeredBy: string;
  stages: DeploymentStage[];  accessReview?: AccessReviewResult[];
  createdAt: string;  completedAt?: string;
}

interface DeploymentStage {
  name: string;  status: 'pending'|'running'|'passed'|'failed'|'skipped';
  startedAt?: string;  completedAt?: string;  durationMs?: number;
  details?: string;  warnings?: string[];  errors?: string[];
}

interface Execution {
  id: string;  agentId: string;  conversationId?: string;
  status: 'success' | 'error' | 'timeout';  durationMs: number;
  tokenUsage: { input: number; output: number; cost: number };
  toolCalls: number;  hitlTriggered: boolean;  model: string;
  timestamp: string;  errorMessage?: string;
}

Models

Source: packages/types/src/model.ts

type ModelProvider = 'anthropic'|'openai'|'google'|'meta'|'mistral'|'cohere'|'deepseek'|'alibaba'|'jina';
type HostingType = 'de-hosted' | 'eu-hosted' | 'external';
type ModelTier = 'budget' | 'standard' | 'premium';
type ModelType = 'llm' | 'embedding' | 'speech' | 'nlp';
type ModelCapability = 'chat'|'vision'|'audio-input'|'audio-output'|'speech-to-text'
                     |'text-to-speech'|'function-calling'|'embeddings'|'reasoning'|'code-generation';

interface ModelInfo {
  id: string;  name: string;  provider: ModelProvider;
  hostingType: HostingType;  euHosted: boolean;  openSource: boolean;
  tier: ModelTier;  contextWindow: number;  maxOutputTokens: number;
  costPer1kInput: number;  costPer1kOutput: number;     // USD
  latencyP50: number;  latencyP95: number;               // ms
  qualityScore: number;                                   // 0-100
  capabilities: ModelCapability[];
  dataSovereignty: 'de' | 'eu' | 'us' | 'global';
  modelType?: ModelType;
  availability: 'available' | 'restricted' | 'denied';
  restrictionReason?: string;  usageCount?: number;  lastUsed?: string;
}

interface RoutingRule {
  id: string;  name: string;  condition: string;
  conditionType: 'risk-level' | 'token-count' | 'cost-threshold' | 'custom';
  targetModelId: string;  targetModelName: string;  priority: number;  active: boolean;
}

interface FallbackChain {
  id: string;  name: string;
  models: { modelId: string; modelName: string; order: number }[];
}

Evaluations

Source: packages/types/src/eval.ts

interface EvalSuite {
  id: string;  name: string;  description: string;  agentId: string;  agentName?: string;
  testCount: number;  passRate: number | null;  lastRun: string | null;
  status: string;  avgLatency: number | null;  tags: string[];
  judgeConfig?: JudgeConfig;  metricsConfig?: { semanticSimilarity: boolean; faithfulness: boolean; toxicity: boolean };
}

interface JudgeConfig {
  judgeModel: string;  temperature: number;  passThreshold: number;  scale: [number, number];
  rubric?: string;
  fewShotExamples?: { input: string; output: string; score: number; reasoning: string }[];
}

interface EvalRun {
  id: string;  suiteId: string;  startedAt: string;  completedAt?: string;
  status: 'running' | 'completed' | 'failed' | 'passed';
  totalTests: number;  passed: number;  failed: number;
  passRate: number;  avgLatency: number;  aggregateMetrics?: Record<string, number>;
}

interface EvalTestCase {
  id: string;  suiteId: string;  input: string;  expectedOutput: string | null;
  assertion: string;  rubric?: string;  context?: string;  tags?: string[];
  sortOrder: number;  createdAt: string;
}

interface EvalRunResult {
  id: string;  runId: string;  suiteId: string;  testCaseIndex: number;
  input: string;  output: string;  passed: boolean;  score: number | null;
  latencyMs: number;  reason: string;  assertion: string;
  judgeModel?: string;  metrics?: Record<string, number>;  createdAt: string;
}

Users & Identity

Source: packages/types/src/user.ts

type IdpSource = 'keycloak' | 'azure-ad' | 'oidc-generic' | 'scim' | 'invitation';
type ProvisioningMode = 'scim' | 'jit' | 'local' | 'service-account' | 'manual';
type UserStatus = 'active' | 'suspended' | 'deprovisioned';
type UserRole = 'consumer' | 'builder' | 'admin';

interface PlatformUser {
  id: string;  externalId: string;  email: string;  displayName: string;
  tenantId: string;  role: UserRole;  groups: string[];
  idpSource: IdpSource;  provisioningMode: ProvisioningMode;  status: UserStatus;
  lastLogin?: string;  createdAt: string;  updatedAt: string;
  metadata?: { costAttributed?: number; agentEntitlementCount?: number; conversationCount?: number };
}

interface TenantIdpConfig {
  tenantId: string;  provider: IdpSource;
  provisioningMode: 'scim' | 'jit' | 'bundled-keycloak';
  oidcConfig: { issuerUrl: string; clientId: string; scopes: string[];
    claimMappings: { groups: string; roles: string; tenantId: string } };
  roleMappingStrategy: 'idp-groups' | 'idp-roles' | 'manual';
  roleMappings?: { group: string; role: UserRole }[];
  sessionConfig: { maxDurationMinutes: number; concurrentSessionLimit?: number };
  scimEndpoint?: string;
}

interface UserInvitation {
  id: string;  email: string;  displayName?: string;  tenantId: string;
  role: UserRole;  groups: string[];  invitedBy: string;
  status: 'pending' | 'accepted' | 'expired';  createdAt: string;  expiresAt: string;
}

Tenants & Credentials

Source: packages/types/src/tenant.ts

interface Tenant {
  id: string;  name: string;  plan?: string;  status: 'active' | 'suspended';
  quotas?: { maxAgents: number; maxTokensPerMonth: number; maxCostPerMonth: number; maxConcurrentExecutions: number };
  agentCount?: number;  userCount?: number;  monthlyBudget?: number;
  usagePercent?: number;  budgetPercent?: number;
  createdAt?: string;  updatedAt?: string;
  idpConfig?: TenantIdpConfig;
  modelPolicy?: TenantModelPolicy;
}

interface TenantModelPolicy {
  allowedModels?: string[];  deniedModels?: string[];  euHostedOnly: boolean;
  defaultMaxCostPerRequest: number;  defaultMaxCostPerDay: number;
  preset: 'data-sovereign' | 'budget' | 'standard' | 'full-access';
}

type CredentialType = 'aifs-api-key'|'n8n-api-key'|'scim-bearer-token'|'custom'
                    |'oauth-slack'|'oauth-github'|'oauth-google'|'oauth-jira'|'oauth-microsoft'|'oauth-custom';

interface TenantCredential {
  id: string;  tenantId: string;  credentialType: CredentialType;  name: string;
  scope: 'tenant' | 'agent-override' | 'user';
  agentId?: string;  userId?: string;  metadata?: Record<string, string>;
  status: 'active' | 'rotated' | 'revoked';
  expiresAt?: string;  lastUsed?: string;  createdBy: string;  createdAt: string;
}

type OAuthProviderType = 'slack' | 'github' | 'google' | 'jira' | 'microsoft' | 'custom';

interface OAuthProvider {
  id: string;  tenantId: string;  provider: OAuthProviderType;  displayName: string;
  clientId: string;  authUrl: string;  tokenUrl: string;  revokeUrl?: string;
  scopes: string[];  redirectUri: string;  iconUrl?: string;
  metadata?: Record<string, unknown>;  status: 'active' | 'inactive';
  createdAt: string;  updatedAt: string;
}

Approvals (HITL)

Source: packages/types/src/approval.ts

interface Approval {
  id: string;  agentId: string;  agentName: string;
  action: string;  riskScore: number;
  impact: 'financial' | 'data' | 'external-comms' | 'irreversible';
  status: 'pending' | 'approved' | 'rejected';
  reasoning: string;  createdAt: string;  slaDeadline: string;
  requestedBy?: string;  toolId?: string;  workflowId?: string;
  decidedBy?: string;  decidedAt?: string;  decisionReason?: string;
}

type ApprovalDecision = {
  decision: 'approved' | 'rejected' | 'modified';
  reason: string;  modifications?: Record<string, unknown>;
};

Traces & Observability

Source: packages/types/src/trace.ts, packages/types/src/common.ts

interface Trace {
  id: string;  agentId: string;  agentName: string;  tenantId: string;
  startTime: string;  endTime: string;  durationMs: number;
  status: 'success' | 'error';  totalCost: number;  spanCount: number;  spans: Span[];
}

interface Span {
  id: string;  parentId?: string;  name: string;
  type: 'orchestration'|'llm'|'tool'|'memory'|'guardrail'|'hitl'|'access-control'|'auth';
  startTime: string;  durationMs: number;  attributes: Record<string, unknown>;
}

interface AuditEntry {
  id: string;  agentId: string;  agentName?: string;  tenantId: string;
  action: string;  outcome: 'success' | 'blocked' | 'escalated';
  riskLevel: 'low'|'medium'|'high'|'critical';  dimension?: 1|2|3|4;
  reasoning: string;  policyId?: string;  principalId?: string;  resourceId?: string;  timestamp: string;
}

interface GuardrailEvent {
  id: string;  agentId: string;  agentName: string;  type: 'input' | 'output';
  trigger: 'pii-detection'|'prompt-injection'|'jailbreak'|'hallucination'|'toxicity'|'off-topic';
  severity: 'low'|'medium'|'high'|'critical';
  contentPreview: string;  blocked: boolean;  falsePositive?: boolean;  timestamp: string;
}

Orchestration

Source: packages/types/src/orchestration.ts

type OrchestrationPattern = 'sequential'|'parallel'|'router'|'evaluator_optimizer'|'orchestrator_workers';
type OrchestrationStatus = 'planning'|'executing'|'evaluating'|'completed'|'failed'|'cancelled'|'paused';
type SubTaskStatus = 'pending'|'queued'|'running'|'completed'|'failed'|'skipped'|'cancelled';

interface OrchestrationPlan {
  id: string;  goal: OrchestrationGoal;  pattern: OrchestrationPattern;
  subTasks: SubTask[];  planningRationale: string;
  estimatedTotalDurationSeconds?: number;  createdAt: string;
}

interface SubTask {
  id: string;  name: string;  description: string;  dependsOn: string[];
  runtime: 'procode' | 'n8n' | 'auto';  agentId?: string | null;
  toolIds?: string[];  expectedInput?: string;  expectedOutput?: string;
  priority?: number;  estimatedDurationSeconds?: number;
}

interface OrchestrationResult {
  planId: string;  status: OrchestrationStatus;
  subTaskResults: SubTaskResult[];  aggregatedOutput?: unknown;
  qualityEvaluations?: QualityEvaluation[];
  totalDurationMs: number;  totalTokensUsed: number;  totalCostUsd: number;
  startedAt: string;  completedAt?: string;  error?: string;
}

Agent Workflows (Durable Execution)

Source: packages/types/src/agent-workflow.ts

type WorkflowStepType = 'llm_call'|'tool_execution'|'guardrail'|'hitl_wait'
  |'memory_extraction'|'agent_turn'|'skill_execution'|'ag_ui_step'|'ag_ui_activity';
type WorkflowStepStatus = 'pending'|'running'|'completed'|'failed'|'skipped'|'waiting_approval';
type AgentWorkflowStatus = 'running'|'completed'|'failed'|'paused'|'cancelled';

interface AgentWorkflow {
  id: string;  temporalRunId?: string;  agentId: string;  conversationId: string;
  tenantId: string;  userId: string;  status: AgentWorkflowStatus;
  steps: WorkflowStep[];  currentStepIndex: number;  totalSteps: number;  error?: string;
  totalDurationMs: number;  totalInputTokens: number;  totalOutputTokens: number;
  totalCost: number;  toolCallCount: number;
  startedAt: string;  completedAt?: string;  lastCheckpointAt?: string;
  restartFromStep?: number;  parentWorkflowId?: string;
}

interface WorkflowStep {
  index: number;  type: WorkflowStepType;  name: string;  status: WorkflowStepStatus;
  startedAt?: string;  completedAt?: string;  durationMs?: number;  error?: string;
  input?: Record<string, unknown>;  output?: Record<string, unknown>;
  toolCall?: { toolId: string; toolName: string; arguments: Record<string, unknown>; result?: Record<string, unknown> };
  llmCall?: { model: string; inputTokens: number; outputTokens: number; finishReason: string };
  approvalId?: string;
}

// Subagent lifecycle tracking
type SubagentStatus = 'running'|'completed'|'failed'|'suspended'|'terminated'|'budget_exhausted';

interface SubagentInstance {
  id: string;  parentWorkflowId: string;  childWorkflowId: string;
  parentAgentId: string;  childAgentId: string;  childAgentName?: string;
  status: SubagentStatus;  delegationMode: 'delegate-and-return' | 'handoff';
  tokenBudget: number|null;  tokenUsed: number;  costBudget: number|null;  costUsed: number;
  timeoutMs: number|null;  depth: number;  tenantId: string;
  spawnedAt: string;  completedAt: string|null;
}

Sandbox & Isolation

Source: packages/types/src/sandbox.ts

interface SandboxConfig {
  runtimeClass: 'standard' | 'gvisor';
  resources: { cpuLimit: string; memoryLimit: string; cpuRequest?: string; memoryRequest?: string; ephemeralStorageLimit?: string };
  timeoutSeconds: number;
  networkPolicy: { allowEgress: boolean; allowedDomains?: string[]; blockedDomains?: string[];
                   allowedCidrs?: string[]; blockedCidrs?: string[]; allowedPorts?: number[] };
  readOnlyFilesystem?: boolean;  runAsNonRoot?: boolean;
  seccompProfile?: 'strict' | 'standard' | 'runtime/default' | 'unconfined';
  dropAllCapabilities?: boolean;
  allowedLanguages?: ('python'|'javascript'|'typescript'|'bash')[];
  maxCodeSizeBytes?: number;  maxOutputSizeBytes?: number;
}

Compliance

Source: packages/types/src/compliance.ts

type ComplianceFramework = 'eu-ai-act' | 'nist-ai-rmf' | 'iso-42001' | 'soc-2' | 'gdpr';
type ComplianceStatus = 'compliant' | 'partial' | 'non-compliant' | 'not-assessed';

interface ComplianceReport {
  id: string;  framework: ComplianceFramework;  frameworkName: string;
  generatedAt: string;  overallStatus: ComplianceStatus;  overallScore: number;
  sections: ComplianceSection[];  flaggedAgents: ComplianceFlaggedAgent[];
}

API Keys

Source: packages/types/src/api-key.ts

interface ApiKey {
  id: string;  name: string;  keyPrefix: string;  tenantId: string;  createdBy: string;
  ownerType: 'user' | 'service-account' | 'tenant';  ownerId: string | null;
  agentScopes: string[];  permissions: ('chat'|'read'|'manage')[];
  rateLimitPerMinute: number;  dailyCostCap: number;
  status: 'active' | 'revoked' | 'expired';
  lastUsed: string|null;  usageCount: number;  totalCost: number;
  expiresAt: string|null;  createdAt: string;
}

Database Schema Summary

PostgreSQL via Drizzle ORM. All tables are multi-tenant (tenant_id column).

#TablePurpose
1agentsAgent definitions with JSONB config and metrics
2conversationsChat sessions (user + agent + tenant)
3messagesMessages with role, tool calls, token usage
4approvalsHITL requests with SLA deadlines and decisions
5mcp_toolsTool registry with risk, auth, and signatures
6tool_grantsPer-tool agent grants with conditions
7platform_usersUser identities synced from IdP
8idp_group_cacheCached IdP group memberships
9deploymentsDeployment records with stage tracking
10executionsAgent execution records (latency, cost)
11tracesOTel traces with embedded span arrays
12n8n_workflowsn8n workflow sync with webhook paths
13modelsModel pricing registry (all providers)
14tenantsTenant config (quotas, IdP, model policies)
15audit_eventsImmutable access control audit log
16alertsPlatform alerts with severity
17guardrail_eventsInput/output guardrail triggers
18policiesCedar/OPA policy definitions
19memory_entriesScoped memory with embeddings
20memory_statsPer-agent memory aggregates
21memory_graphGraph memory nodes/edges
22memory_consentUser opt-in/opt-out (GDPR)
23memory_audit_logMemory CRUD audit trail
24dsar_requestsGDPR Art. 15/17 requests
25consolidation_runsMemory consolidation tracking
26eval_suitesEvaluation suite definitions
27eval_runsEvaluation run results
28eval_historyTime-series pass rate data
29eval_test_casesStored test cases
30eval_run_resultsPer-test-case results with scores
31eval_pipelinesMulti-stage eval pipeline definitions
32knowledge_basesKB definitions with chunking config
33knowledge_documentsUploaded documents with status
34knowledge_chunksDocument chunks with embeddings
35data_catalogExternal data source registry
36mcp_serversMCP server registry (stdio/SSE)
37api_keysAPI keys with scopes and rate limits
38api_key_usageDaily aggregate key usage
39tenant_credentialsEncrypted credential storage (AES-256-GCM)
40user_invitationsPending invitations with token hashes
41agent_workflowsTemporal workflow state and steps
42a2a_registration_tokensSingle-use agent registration tokens
43oauth_providersPer-tenant OAuth 2.0 config
44prompt_versionsPlayground prompt version history
45compliance_snapshotsCompliance score trend data
46routing_rulesCondition-based model routing
47fallback_chainsOrdered model fallback lists
48subagent_instancesSubagent lifecycle with budgets
49tool_setsReusable tool authorization bundles
50tool_set_toolsTool set to tool mapping
51agent_tool_set_grantsTool set grants to agents
52skillsKnowledge bundles with versioning
53skill_filesSkill attached files
54skill_versionsSkill version history
55agent_skillsAgent to skill assignments
56agent_behavioral_baselinesAnomaly detection baselines
57marketplace_listingsAgent marketplace entries
58user_feedbackThumbs-up/down on messages
59memory_ttl_configsPer-tenant retention policies

Database Enums

EnumValues
runtimeprocode, n8n
execution_modeplatform-managed, external-procode, external-n8n
agent_statusdraft, active, canary, suspended, deprecated
risk_classificationassistive, semi-autonomous, autonomous
conversation_statusactive, closed
message_roleuser, agent, system
approval_statuspending, approved, rejected
impact_typefinancial, data, external-comms, irreversible
tool_risklow, medium, high, critical
tool_categoryread-only, write, external-comms, financial, destructive
tool_runtimeprocode, n8n, both
user_roleconsumer, builder, admin
user_statusactive, suspended, deprovisioned
idp_sourcekeycloak, azure-ad, oidc-generic, scim, invitation
provisioning_modescim, jit, local, service-account, manual
deployment_statuspending, running, succeeded, failed, rolled_back
deployment_envdev, staging, production
execution_statussuccess, error, timeout
trace_statussuccess, error
model_provideranthropic, openai, google, meta, mistral, cohere, deepseek, alibaba, jina
hosting_typede-hosted, eu-hosted, external
model_tierbudget, standard, premium
model_availabilityavailable, restricted, denied
agent_workflow_statusrunning, completed, failed, paused, cancelled
subagent_statusrunning, completed, failed, suspended, terminated, budget_exhausted
delegation_modedelegate-and-return, handoff
tool_set_statusactive, deprecated, disabled, pending_review
skill_visibilityprivate, tenant, published
skill_content_statusdraft, pending_review, active, deprecated, disabled
skill_file_typescript, reference, asset
marketplace_listing_statusdraft, pending_review, certified, published, rejected, delisted