Developer Implementation Manual
Architecture-grade manual covering flows, automation studio, custom connectors, CDC, AI tool registry, REST API, SDK app development, embedded iPaaS, testing, observability, security engineering, and release standards for building production-grade integrations on DAICISION.
1. Developer Overview
DAICISION is a multi-tenant, AI-assisted enterprise integration platform. The platform is structured across four distinct layers. Each layer has clear ownership, well-defined extension points, and non-negotiable quality constraints.
- API Layer (NestJS + TypeScript)
Strict Zod validation on all external inputs. SWC builds for sub-30s full rebuilds. Module-per-domain architecture with isolated schemas and no direct cross-module imports. EventBus for decoupled inter-module communication. ToolRegistry for exposing business operations to flows and the AI assistant.
- Frontend (Next.js + React)
Zustand stores with slice composition for complex state, React Query for all server state. EU-formatted output enforced everywhere: DD.MM.YYYY for dates, comma as decimal separator, period as thousands separator. Dynamic entity system via DynamicEntityList, RecordDetail, and DynamicEntityForm — custom table components are not permitted for standard CRUD views.
- Database (PostgreSQL)
Row-Level Security is being rolled out as defence in depth and is not yet enforced on every table, so tenantId is required in every query — missing tenantId is a multi-tenant data leak, not a bug. Parameterized queries only via Prisma ORM; never raw string concatenation. Schema changes managed through versioned migrations; no ad-hoc ALTER TABLE in application code.
- AI Layer (model-agnostic orchestrator)
Routes requests to configured LLM providers (model is not hardcoded in application code). Enforces token budgets per tenant and per request. Logs prompts, completions and outcomes; tool calls that change data, and denied or failed calls, are audited with a correlation ID where one is available. Risk-level gating on all tool calls — HIGH and CRITICAL tools require explicit approval or elevated session context before execution.
Ownership Matrix
| Area | Developer Owns | Admin Owns | |---|---|---| | Flow logic | Canvas design, node configuration, data mapping | Execution quota limits, DLQ retention policy | | Connectors | Adapter code, operation mapping, test coverage | Credentials, rotation policy, access control | | AI tools | Handler code, schema definition, risk level | Approval thresholds, blocked action policies | | Security | tenantId in queries, Zod validation, safe errors | Role-permission assignments, AI governance |
Design principle
Optimize for predictability first, then speed. Deterministic automation beats clever automation in production environments. Every design choice should be explainable to a new team member reading the flow canvas for the first time.
2. Core Concepts
Before building any automation, ensure these seven concepts are clear. They underpin every design decision in the platform.
- Flow
A directed graph of nodes executed in sequence. Has a trigger, a canvas of nodes, and a version history. The
canvasJSONB column in theflowstable stores the full node and edge structure as a serialized object. Each published version is immutable — editing a published flow creates a new draft version.- Node
One unit of work in the canvas. Has a
type(node category: trigger / logic / tool / transform / utility / connector) anddata.nodeType(the specific operation, e.g.,trigger:schedule). Each node type has a defined input schema (what it consumes from upstream) and output schema (what it produces for downstream nodes). Refer to Node Types for the complete catalogue.- Tool
A registered business operation callable by both flows and the AI assistant. Defined via
ToolRegistry.registerTool(). Identified by a three-segment ID:{module}.{entity}.{action}— e.g.,crm.contact.create. Tools carry a risk level, required permissions, and a Zod parameter schema. The ToolRegistry enforces permission checks and risk-level gating before the handler is ever called. See Tool Nodes.- Event
A typed message emitted to the platform EventBus when a mutation occurs. Naming convention:
{module}.{entity}.{past-tense}— e.g.,crm.contact.created. Every event carriestenantId,correlationId,sourceModule, and a typed payload. Events are the primary mechanism for decoupled communication between modules — never call another module's service directly.- Connector
An integration adapter to an external system. 200+ available in the connector library. Each connector exposes a set of operations (list, get, create, update, delete, and provider-specific variants) and a credential binding. Connector nodes in a flow reference a connector by its provider slug and an operation name. Credentials are never embedded in flow config. See Browsing Connectors.
- Variable
Scoped key-value storage. Flow-scoped variables live for one execution and are gone when the run ends. Global variables are tenant-wide persistent key-value pairs managed in Settings → Variables. Both types are referenced in node config using the double-brace template syntax:
{{ varName }}. Variable resolution happens at execution time, not at flow-save time.- Credential
Encrypted external service authentication stored in the platform credential vault. Referenced in flow and connector configuration using the pattern
secret.<provider>.<purpose>— e.g.,secret.salesforce.integrationUserorsecret.stripe.apiKey. The platform resolves the reference to the actual secret at execution time. Never embed credential values directly in node JSON. See Managing Credentials.
3. Building Flows — Automation Studio
The Automation Studio is the visual canvas for building flows. See Creating Flows for the UI walkthrough. This section covers the engineering conventions that govern how flows should be structured.
Five-Lane Canvas Convention
Lay out every non-trivial flow across five conceptual lanes from top to bottom:
- Trigger lane — all inbound events, schedules, or webhook receivers
- Normalization lane — parsing, type coercion, and canonical structure transforms
- Decision lane — logic branches, guardrails, and conditional checks
- Execution lane — connector and tool write operations
- Recovery lane — error handlers, retry logic, and notification paths
This convention improves readability, testability, and on-call debuggability. It is not enforced by the flow engine — a flow that violates it will execute correctly but becomes harder to audit and trace under incident conditions. Teams that skip the convention consistently produce flows that are difficult to debug at 2am.
Naming Conventions
| Object | Pattern | Example |
|---|---|---|
| Flow | {domain}-{intent}-{frequency} | crm-lead-sync-hourly |
| Node label | {stage}:{purpose} | transform:normalizeLeadPayload |
| Variables | camelCase with domain prefix | crmLeadOwnerId |
| Secret references | secret.<provider>.<purpose> | secret.salesforce.integrationUser |
Trigger Nodes
Trigger nodes start a flow. A flow must have exactly one trigger. See Triggers.
{ "type": "trigger", "data": { "nodeType": "trigger:schedule", "config": { "cron": "0 8 * * 1-5" } } }
{ "type": "trigger", "data": { "nodeType": "trigger:event", "config": { "eventType": "crm.contact.created" } } }
{ "type": "trigger", "data": { "nodeType": "trigger:webhook", "config": { "method": "POST", "path": "/hooks/lead-capture" } } }
{ "type": "trigger", "data": { "nodeType": "trigger:fieldChange", "config": { "objectApiName": "opportunity", "field": "stage", "from": "qualified", "to": "proposal" } } }
{ "type": "trigger", "data": { "nodeType": "trigger:manual", "config": { "label": "Run manually" } } }
Logic Nodes
Logic nodes control flow branching and iteration. See Logic Nodes.
{ "type": "logic", "data": { "nodeType": "logic:if", "config": { "condition": "{{ deal.value > 10000 }}" } } }
{ "type": "logic", "data": { "nodeType": "logic:forEach", "config": { "items": "{{ leads }}", "itemVar": "lead" } } }
{ "type": "logic", "data": { "nodeType": "logic:switch", "config": { "expression": "{{ contact.region }}", "cases": ["EU", "US", "APAC"] } } }
{ "type": "logic", "data": { "nodeType": "logic:merge", "config": { "strategy": "union" } } }
Tool Nodes
Tool nodes call registered platform tools. The nodeType value is tool:{toolId}. The inputMapping maps upstream flow variables to the tool's parameter schema. The outputMapping promotes tool output into named flow variables. See Tool Nodes.
{
"type": "tool",
"data": {
"nodeType": "tool:crm.contact.create",
"config": {
"parameters": { "tenantId": "{{ tenantId }}" },
"inputMapping": {
"firstName": "{{ lead.name.first }}",
"email": "{{ lead.email }}"
},
"outputMapping": { "contactId": "{{ result.id }}" }
}
}
}
Transform Nodes
Transform nodes reshape data between nodes without writing to any external system.
{
"type": "transform",
"data": {
"nodeType": "transform:mapper",
"config": {
"mappings": [
{ "from": "payload.email", "to": "canonical.email" },
{ "from": "payload.companyName", "to": "canonical.accountName" }
]
}
}
}
{
"type": "transform",
"data": {
"nodeType": "transform:code",
"config": {
"language": "typescript",
"code": "return { fullName: `${input.first} ${input.last}`, email: input.email.toLowerCase().trim() };"
}
}
}
Utility Nodes
Utility nodes send messages, trigger notifications, or pause for human approval.
{ "type": "utility", "data": { "nodeType": "utility:email", "config": { "to": "{{ contact.email }}", "subject": "Your quote is ready", "templateId": "quote-ready" } } }
{ "type": "utility", "data": { "nodeType": "utility:notification", "config": { "channel": "slack", "to": "{{ flow.owner }}", "message": "Deal {{ deal.name }} moved to Proposal" } } }
{ "type": "utility", "data": { "nodeType": "utility:approval", "config": { "approvers": ["{{ deal.owner }}"], "timeoutHours": 48, "message": "Approve discount above 20%?" } } }
Connector Nodes
Connector nodes call external APIs via the platform's connector adapters.
{
"type": "connector",
"data": {
"nodeType": "connector:salesforce",
"config": {
"operation": "createContact",
"credential": "secret.salesforce.integrationUser",
"body": {
"FirstName": "{{ contact.firstName }}",
"Email": "{{ contact.email }}"
}
}
}
}
4. Data Mapping and Transforms
Canonical Payload Pattern
Always transform inbound trigger payloads into a canonical internal structure before branching logic or writing to any system. This produces two benefits: field name changes in the upstream trigger are isolated to the normalization node (not scattered across the entire canvas), and every downstream node operates on a predictable, validated structure.
Never map a raw trigger payload directly into a connector write operation.
Mapper Node
The visual drag-and-drop field mapper. Supports:
- Dot-notation paths:
payload.address.city - Double-brace template interpolation:
{{ contact.firstName }} - Static string literal values
- Simple expressions:
{{ lead.value * 1.2 }}
Use the mapper node when the field transformation is straightforward and the mapping logic should be visible to non-developers reviewing the flow canvas.
Code Node
A TypeScript function body. Receives input typed as the upstream node output. Must return a plain JavaScript object. Hard constraints:
- No
asyncoperations - No external imports or network calls
- 5-second execution timeout — exceeding it kills the node with a timeout error
- Return value must be a serializable plain object (no class instances, no functions, no undefined)
Code nodes run in a sandboxed synchronous VM context. Imports are not available at execution time — they are stripped before the node runs. Attempting to use require() or import inside a code node will result in a ReferenceError at runtime, not a build-time error. Similarly, await and Promise are unavailable. Keep code nodes focused on pure synchronous transformations.
// Code node: normalise a webhook contact payload into canonical structure
return {
firstName: input.name?.split(' ')[0] ?? '',
lastName: input.name?.split(' ').slice(1).join(' ') ?? '',
email: input.email?.toLowerCase().trim() ?? '',
phone: input.phone?.replace(/\D/g, '') ?? null,
source: 'webhook-import',
importedAt: new Date().toISOString(),
};
Input/Output Contracts
Document the expected shape of each node's output in a comment at the start of downstream node config. This creates a "data contract" that makes transform failures visible during code review rather than at runtime.
Validation in Code Nodes
Code nodes cannot import Zod, but validate early with guard clauses:
if (!input.email || !input.email.includes('@')) {
throw new Error('Invalid email received: ' + String(input.email));
}
if (!input.tenantId) {
throw new Error('Missing required tenantId in code node input');
}
return {
email: input.email.toLowerCase().trim(),
tenantId: input.tenantId,
};
Mapping policy
Never write raw trigger payload values directly into a connector write operation. Always pass through a normalization node first. This makes field name changes visible and testable, and prevents silent data corruption when upstream schemas evolve.
5. Connector Engineering
The platform provides 200+ ready-to-use connector adapters. When configuring connector nodes in flows, apply these engineering standards consistently.
Standards Reference
| Topic | Required Practice | Rationale |
|---|---|---|
| Authentication | Use shared service credentials, never personal tokens | Personal tokens break silently when users leave or revoke access |
| Timeouts | 30s default; 120s max for batch operations | Prevent hanging executions from blocking downstream nodes |
| Retries | Retry only 429 / 5xx / network errors; max 3 attempts with exponential back-off | Avoid duplicate writes on 4xx client errors |
| Pagination | Explicit page size; loop until hasMore: false | Prevent partial dataset bugs in large record sets |
| Rate limits | Honour Retry-After header; add throttle delay between batch requests | Avoid API account suspension and integration partner bans |
| Idempotency | Pass operation-specific idempotency key on all write operations | Safe replay on network failure without duplicate records |
| Error classification | Distinguish transient (retry) from terminal (fail fast) errors | Prevent infinite retry loops on permanent errors |
Authentication anti-pattern
Never deploy business-critical flows with personal credentials. Personal tokens create silent outages when users leave the organisation or revoke their access. Use shared service accounts with dedicated credentials. See Managing Credentials and Auth Types.
Credential Management
Credentials are stored in the platform vault and referenced by secret.<provider>.<purpose>. The platform resolves these references at execution time, never exposing the raw value in logs or execution traces.
For OAuth2 connectors, the platform handles token refresh automatically when the stored token is within 5 minutes of expiry. Developers do not need to implement token refresh logic in flow config. See OAuth Setup for provider-specific setup steps.
6. Custom Connector Builder
When an integration target is not in the connector library, build a custom connector using the Connector Generator.
/.well-known/openapi.json or /openapi.yaml path from the base URL.Private vs shared connectors
Published connectors are tenant-private by default. To list a connector in the shared marketplace where all tenants can discover and use it, contact platform support. Shared connectors undergo additional security and compatibility review before listing. See Custom Connector Builder for the full specification reference.
7. Change Data Capture
CDC streams entity-level change events (INSERT / UPDATE / DELETE) from the database layer to subscribed consumers — no polling required, near-real-time delivery. This is the primary mechanism for building reactive integrations that respond to data changes regardless of which surface caused them (UI, API import, flow, or direct DB migration).
Creating a Subscription
Navigate to Connectors → CDC → New Subscription. Configure:
- Source object: the entity to watch (e.g.,
invoice,contact,opportunity) - Operation types: INSERT / UPDATE / DELETE — multi-select
- Field filter (optional): emit events only when specific fields change — useful for high-frequency objects where you only care about status transitions
CDC Event Payload Structure
{
"tenantId": "tenant-abc",
"objectApiName": "invoice",
"recordId": "inv-001",
"operation": "UPDATE",
"before": { "status": "draft" },
"after": { "status": "approved" },
"timestamp": "2026-03-29T09:00:00.000Z",
"correlationId": "corr-xyz"
}
The before field is null for INSERT operations. The after field is null for DELETE operations.
Triggering Flows from CDC Events
Use trigger:event with the eventType pattern cdc.{objectApiName}.{operation}:
{
"type": "trigger",
"data": {
"nodeType": "trigger:event",
"config": {
"eventType": "cdc.invoice.UPDATE"
}
}
}
To filter to specific field changes only, add a condition expression:
{
"type": "trigger",
"data": {
"nodeType": "trigger:event",
"config": {
"eventType": "cdc.invoice.UPDATE",
"condition": "{{ event.after.status === 'approved' && event.before.status !== 'approved' }}"
}
}
}
Monitoring Consumer Lag
Connectors → CDC → Subscriptions shows event lag per subscription in milliseconds. If lag consistently exceeds 60 seconds, reduce the subscription scope with field filters, or increase consumer throughput by splitting high-volume subscriptions into multiple narrower subscriptions.
Delivery guarantee
CDC delivers events at-least-once. Under normal conditions, most events are delivered exactly once. During network partitions or consumer restarts, an event may be delivered more than once. Design CDC-triggered flows to be idempotent: use a deduplication key (correlationId + recordId + operation) and check for existing records before writing.
Note: There is no platform-provided
processedEventtable. Each consuming module must maintain its own deduplication store. A minimal schema is:CREATE TABLE IF NOT EXISTS processed_events ( tenant_id UUID NOT NULL, dedup_key TEXT NOT NULL, processed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (tenant_id, dedup_key) );The deduplication key is typically
correlationId:recordId:operation.
// Idempotency check in a CDC-triggered tool handler
// your module's dedup table — see schema note above
const existing = await prisma.processedEvent.findUnique({
where: { correlationId: context.correlationId },
});
if (existing) {
return { success: true, data: existing.result }; // already processed
}
CDC vs trigger:event
CDC events reflect committed database changes from any source — UI, API, import, or flow. Use CDC when you need to react to changes regardless of origin. Use trigger:event with a named business event when you need to react only to changes made through a specific tool or flow. For example, use CDC to sync invoice status to an ERP; use trigger:event on finance.invoice.approved to trigger an approval-specific notification workflow. See CDC documentation.
8. AI Tool Registry — Platform Extension
The ToolRegistry is the primary extensibility surface for developers adding new AI-callable operations. Registering a tool makes it available to both flow tool nodes (via tool:{toolId}) and the conversational AI assistant.
Tool Registration Pattern
Register tools in your NestJS module's onModuleInit lifecycle hook:
async onModuleInit(): Promise<void> {
for (const tool of MY_MODULE_TOOLS) {
this.toolRegistry.registerTool(tool, this.handleTool.bind(this), MANIFEST.schema);
}
}
Tool Definition Structure
import { z } from 'zod';
import { RiskLevel } from '@/modules/business/core/types';
export const createWidgetTool = {
id: 'widgets.widget.create', // {module}.{entity}.{action}
name: 'Create Widget',
description: 'Creates a new widget record in the widgets module.',
riskLevel: RiskLevel.MEDIUM, // LOW | MEDIUM | HIGH | CRITICAL
requiredPermissions: ['widgets.widget.write'],
parameters: z.object({
name: z.string().min(1).describe('Widget display name'),
category: z.enum(['standard', 'premium']).describe('Widget category'),
tenantId: z.string().uuid().describe('Tenant scope — required on every tool call'),
}),
};
Handler Function Pattern
async handleCreateWidget(
params: z.infer<typeof createWidgetTool.parameters>,
context: ToolExecutionContext,
): Promise<ToolResult> {
// Permission already checked by ToolRegistry before handler is called
// tenantId is always present — use it in every DB query
try {
const widget = await this.prisma.widget.create({
data: {
name: params.name,
category: params.category,
tenantId: params.tenantId,
createdById: context.userId,
},
select: { id: true, name: true, category: true, tenantId: true },
});
this.eventBus.publish({
type: 'widgets.widget.created',
tenantId: params.tenantId,
sourceModule: 'widgets',
payload: widget,
correlationId: context.correlationId,
});
return { success: true, data: widget };
} catch (error) {
this.logger.error('widgets.widget.create failed', {
tenantId: params.tenantId,
correlationId: context.correlationId,
error: error instanceof Error ? error.message : String(error),
});
return {
success: false,
error: 'errors.widgets.widget.createFailed', // i18n key returned to caller
};
}
}
Tool Naming Convention
{module}.{entity}.{action} — e.g., crm.contact.create, finance.invoice.approve, hr.employee.terminate. The module segment matches the NestJS module name. The entity segment matches the Prisma model name (lowercase). The action segment is a present-tense verb.
Risk Level Assignment Guide
| Level | When to Use | Examples |
|---|---|---|
| LOW | Read-only queries, list operations, reporting | crm.contact.list, analytics.report.read |
| MEDIUM | Record creates, non-critical updates, message sends | crm.contact.create, messaging.message.send |
| HIGH | Bulk mutations, financial operations, record deletion | finance.invoice.approve, hr.employee.terminate |
| CRITICAL | Role changes, mass delete, credential operations | admin.role.assign, data.records.bulkDelete |
ToolResult Type
// Import from the platform core types
import type { ToolResult } from '@/modules/business/core/types';
// Defined in @/modules/business/core/types — shown here for reference:
type ToolResult =
| { success: true; data: unknown }
| { success: false; error: string }; // error is always an i18n key
ToolResult.error should always be an i18n key (errors.{module}.{entity}.{errorType}), never a raw error message. The platform surfaces this key to the caller — whether the AI assistant or a flow node — and resolves it through the i18n layer.
Never bypass ToolRegistry
Do not call tool handler functions directly from other services. Always route through ToolRegistry so that permission checks, risk-level gating, token budget enforcement, and audit logging are applied consistently. Direct handler calls produce silent gaps in the audit trail and bypass AI safety guardrails.
9. REST API
The REST API is the primary integration surface for external systems, CLI tooling, and SDK applications.
Base URL: https://{tenant-slug}.daicision.app/api/v1
Authentication
All API requests require a Bearer token: Authorization: Bearer {token}. API keys are generated in Settings → API Keys. For machine-to-machine integrations, use the OAuth2 server to obtain short-lived access tokens. See Authentication, API Keys, and OAuth2 Server.
Response Envelope
All endpoints return a consistent envelope:
{ "success": true, "data": {}, "meta": { "total": 100, "page": 1, "limit": 20 } }
{ "success": false, "error": "Human-readable message", "code": "RESOURCE_NOT_FOUND" }
The meta field is present only on paginated list responses. The code field is a machine-readable error code suitable for programmatic handling. Error messages never expose internal details such as stack traces, table names, or query structure.
Flows API
| Method | Path | Description |
|---|---|---|
| POST | /flows/{flowId}/trigger | Manually trigger a flow with an optional payload |
| GET | /executions | List executions, paginated — filter by flowId, status, fromDate |
| GET | /executions/{id} | Get execution detail including trigger payload and current status |
| GET | /executions/{id}/nodes | Per-node latency, input payload, output payload, and status |
| POST | /executions/{id}/replay | Replay a failed or completed execution with original trigger payload |
| POST | /executions/{id}/cancel | Cancel a running execution |
Cancel is best-effort — nodes already in progress will complete before the flow halts. Cancellation is available for executions with status
runningorwaiting_approval.
See Flows API.
Objects and Records API
| Method | Path | Description |
|---|---|---|
| GET | /objects | List all registered object types for this tenant |
| GET | /objects/{objectId} | Get object definition including field schema and metadata |
| GET | /objects/{objectId}/records | List records — supports filter, sort, page, limit |
| POST | /objects/{objectId}/records | Create a record |
| GET | /objects/{objectId}/records/{id} | Get a single record by ID |
| PATCH | /objects/{objectId}/records/{id} | Partial update of a record |
| DELETE | /objects/{objectId}/records/{id} | Soft-delete a record |
Webhooks API
| Method | Path | Description |
|---|---|---|
| POST | /webhooks | Register a webhook endpoint |
| GET | /webhooks | List registered webhooks |
| GET | /webhooks/{webhookId} | Get a single webhook registration |
| PATCH | /webhooks/{webhookId} | Update webhook URL, events, or active status |
| DELETE | /webhooks/{webhookId} | Delete a webhook |
POST /api/v1/webhooks
Content-Type: application/json
{
"url": "https://your-app.com/hooks/daicision",
"events": ["crm.contact.created", "finance.invoice.approved"],
"secret": "your-webhook-signing-secret",
"active": true
}
The platform signs each delivery with HMAC-SHA256 using your secret. Verify the X-Daicision-Signature header on inbound webhooks to confirm authenticity.
Webhook delivery payload envelope:
{
"event": "crm.contact.created",
"tenantId": "tenant-abc",
"timestamp": "2026-03-29T09:00:00.000Z",
"correlationId": "corr-xyz",
"data": {}
}
Webhook delivery is retried up to 5 times with exponential back-off on non-2xx responses. After 5 failures the webhook is suspended and the endpoint owner is notified. See Webhooks.
Pagination
All list endpoints accept ?page=1&limit=20. Maximum limit is 100. Requests above this limit return a 400 with LIMIT_EXCEEDED. Default limit when omitted is 20.
Rate Limits
| Scope | Limit | Headers |
|---|---|---|
| Per tenant | 1,000 requests/min | X-RateLimit-Limit, X-RateLimit-Remaining |
| Per API key | 100 requests/min | X-RateLimit-Limit, X-RateLimit-Remaining |
| On limit exceeded | HTTP 429 | Retry-After header in seconds |
10. SDK and App Development
Apps are platform-hosted UIs registered with a tenant-scoped slug. They appear in the Apps section of the navigation and have access to tenant data via the Objects API. Apps can also expose their own tools to the ToolRegistry.
App Manifest Structure
export const appManifest = {
slug: 'my-app', // URL: /apps/my-app
name: 'My Application',
description: 'What this app does for this tenant',
icon: 'package', // Lucide icon name
version: '1.0.0',
pages: [
{ path: '/', label: 'Dashboard', component: 'AppDashboard' },
{ path: '/settings', label: 'Settings', component: 'AppSettings' },
],
tools: ['my-app.widget.create'], // ToolRegistry IDs exposed by this app
permissions: ['my-app.widget.read', 'my-app.widget.write'],
};
Routing
Apps render at /apps/{slug}. Subpages render at /apps/{slug}/view/{...page}. The tools overview page at /apps/{slug}/tools lists all registered tools with their risk levels and parameter schemas.
Data Access Pattern
Apps access tenant data via the Objects API and Flows API using the session token. All requests are automatically scoped to the current tenant. Use GET /objects/{objectId}/records as the primary data access pattern — avoid direct database access from app code.
// Correct: data access via Objects API
const response = await fetch(`/api/v1/objects/${objectId}/records?page=1&limit=20`, {
headers: { Authorization: `Bearer ${sessionToken}` },
});
const { data, meta } = await response.json();
Tool Registration from Apps
Apps register tools using the same pattern as module tool registration — call ToolRegistry.registerTool() in the app's initialisation. Tools registered by apps follow the same permission and risk-level model as module tools. Use the app slug as the module segment in the tool ID: my-app.widget.create.
App data access pattern
Apps should read data via GET /objects/{objectId}/records and write via tool calls routed through ToolRegistry. Direct database access bypasses the permission model, audit logging, and tenant isolation guarantees enforced by the platform. Apps that bypass these layers will fail security review.
11. Embedded iPaaS
DAICISION can be embedded inside a host application as a white-label integration layer. Embedded tenants are fully isolated from each other and from the host application's credentials.
Two Embed Modes
| Mode | How | Best For |
|---|---|---|
| iframe embed | Host renders <iframe src="https://{tenant}.daicision.app/embedded?token={signedToken}"> | Quick integration, minimal code, standard UI |
| SDK embed | JavaScript SDK initialises a sandboxed tenant context in the host app, communicates via postMessage | Deep integration, custom UI wrapping the embed, programmatic event handling |
Tenant Provisioning
Provision a new embedded tenant via the admin API:
POST /api/v1/admin/tenants
Content-Type: application/json
Authorization: Bearer {masterAdminToken}
{
"name": "Customer ABC",
"plan": "embedded",
"ownerEmail": "admin@customerabc.com"
}
The response includes the new tenant's tenantId and the initial admin credential set. Store the tenantId in your host application's database — it is required for all subsequent embed token generation.
Credential Isolation
Each embedded tenant has its own credential vault. The host application's master credentials are never accessible to embedded tenants. Embedded tenants can only access credentials they have explicitly configured in their own tenant context.
Signed Token Generation
Generate a signed embed token on the host application's server side. Never generate embed tokens in client-side code.
const embedSecret = process.env.DAICISION_EMBED_SECRET;
if (!embedSecret) {
throw new Error('DAICISION_EMBED_SECRET is not configured');
}
const embedToken = jwt.sign(
{
tenantId: embeddedTenantId,
allowedModules: ['flows', 'connectors'],
exp: Math.floor(Date.now() / 1000) + 3600, // 1 hour
},
embedSecret,
);
allowedModulesvalues:flows,connectors,analytics,crm,finance,hr,payroll,contracts,messaging,data,sales-ai. OmittingallowedModulesgrants access to all modules the embedded tenant has permissions for. Use explicit lists in production to apply least-privilege scoping.
Token expiry
Signed embed tokens expire after 1 hour by default. Implement refresh logic in your host application before expiry to prevent session drops mid-workflow. The SDK embed mode provides an onTokenExpiry callback for seamless background refresh. For the iframe mode, implement a silent re-authentication by regenerating the token and updating the src attribute before expiry.
12. Variables and Secrets Management
Variable Types Reference
| Type | Scope | Lifetime | Reference Syntax |
|---|---|---|---|
| Flow variable | Single execution | Duration of the run only | {{ varName }} in any node config |
| Global variable | Tenant-wide | Persistent until explicitly deleted | {{ varName }} — resolved from Settings → Variables |
| Secret reference | Tenant-wide | Persistent, encrypted in vault | secret.<provider>.<purpose> |
Secret Reference Pattern
secret.salesforce.integrationUser, secret.stripe.apiKey, secret.smtp.password. The platform resolves these references at execution time from the encrypted credential store. The resolved value is never written to logs, execution traces, or audit records.
Rotating Secrets in Live Flows
Global Variables
Use global variables for tenant-wide configuration values that change infrequently — for example, the default CRM owner ID, the fallback notification email address, or the active billing cycle identifier. Manage them in Settings → Variables. Changes take effect on the next execution that references the variable — there is no propagation delay.
13. Payroll Automation Development
Payroll flows integrate with the Payroll module's run lifecycle. The payroll run progresses through a strict status machine: draft → reviewed → approved → paid. Flows should attach to specific lifecycle events rather than polling for status changes.
Payroll Lifecycle Events
| Event | When Fired | Typical Automation |
|---|---|---|
| payroll.run.created | New run drafted | Pre-validate employee data completeness, check for missing tax configurations |
| payroll.run.reviewed | Run sent for approval | Notify designated approvers, attach variance report to approval task |
| payroll.run.approved | Approval confirmed by authorised approver | Trigger bank payment batch API with idempotency key |
| payroll.run.paid | Payment confirmed by bank callback | Generate pay slips, distribute to employees, post to accounting GL |
| payroll.run.completed | Pay run fully settled and closed — terminal state | Archive run artefacts, update reporting snapshots, notify finance team of final totals |
| payroll.run.correctionCreated | Off-cycle adjustment run created | Notify payroll team and affected employees, flag for compliance audit |
Tax Table API
The tax table API is read-only. Use it in pre-validation flows to verify that current employee configurations align with applicable rates before a run is sent for review.
GET /api/v1/payroll/tax-tables?jurisdiction=CZ&effectiveDate=2026-01-01
Returns rate bands, thresholds, deduction rules, and effective date ranges for the specified jurisdiction. Use the effectiveDate parameter matching the pay period start date — not today's date — to ensure historical accuracy for retroactive corrections.
Idempotency Requirement
Payroll flows that write payment records must include a run-scoped idempotency key. This prevents duplicate disbursements if the flow retries after a transient network failure:
{
"type": "connector",
"data": {
"nodeType": "connector:bankPayments",
"config": {
"operation": "submitBatch",
"credential": "secret.bank.paymentService",
"idempotencyKey": "payroll-run-{{ run.id }}-payment",
"body": { "amount": "{{ run.netTotal }}", "reference": "{{ run.id }}" }
}
}
}
14. Testing and Debugging
Three Execution Modes
| Mode | Reads External Data? | Writes External Data? | Use For | |---|---|---|---| | Preview | No | No | Validate path selection and logic branching with static mock input | | Read-Only | Yes | No | Validate transforms and logic against live data without side effects | | Full Rollback | Yes | Yes (rolled back after run) | Validate write operations without permanent mutation |
Always progress through all three modes before promoting a new flow to active. A flow that has only been tested in Preview mode has not been validated against real data shapes. See Testing and Debugging.
Minimum Test Matrix
| Test Type | What to Validate | Execution Mode | |---|---|---| | Happy path | Correct end-to-end output with representative production-like input | Full Rollback | | Validation failure | Missing or invalid required fields reach the error handler | Preview | | Connector failure | API timeout and 4xx/5xx error paths activate recovery lane | Read-Only with simulated error | | Idempotency | Duplicate trigger with same payload produces a single record | Full Rollback × 2 | | Rollback verification | No records persist after Full Rollback completes | Full Rollback; verify record count before and after |
Reading Debug Traces
Monitoring → Executions → [execution ID] → Trace
Each node in the trace shows:
- Input payload — the exact data object that entered this node
- Output payload — the data object this node produced for downstream nodes
- Duration (ms) — actual wall-clock time for this node
- Status —
success/error/skipped
Click any failed node to see: the full error message and stack, the request sent to the external system, and the raw response received. This is sufficient to diagnose the vast majority of connector failures without leaving the platform.
Execution Replay
Monitoring → Executions → [execution ID] → Replay
Replays the flow from the start with the original trigger payload. Use replay to recover failed executions after a transient connector outage — the replay uses the same payload that caused the original run, so the result is deterministic. Replay is not available for executions older than the tenant's DLQ retention window.
Flow Templates and Reuse
Before building a new flow from scratch, check Automation → Templates Marketplace for community and platform-provided templates that cover common patterns. Templates can be imported as a draft and customised. See Templates Marketplace.
15. Observability and Reliability
Production Baseline
Execution tracing enabled
labels.docs.checklist.requiredCorrelation IDs and per-node latency are available for every run. Verify this is active for any flow that writes to an external system — tracing is the only way to diagnose partial failure chains.
Alerting configured
labels.docs.checklist.requiredAlert on repeated failures (3 within 10 minutes), dead-letter queue growth above threshold, and unexpected p95 latency spikes. Configure alerts in Monitoring → Alerts before activating any production flow.
Runbook linked to flow
labels.docs.checklist.requiredEvery critical flow must have a responder-facing incident procedure linked in the flow description. The runbook must include: what the flow does, what a failure means for the business, how to manually replay or bypass, and who to escalate to.
Canary release configured
labels.docs.checklist.recommendedFor schedule-triggered flows, validate the new version on the first N executions before promoting to full active status. Configure in Automation → Flows → [flow] → Settings → Canary.
DLQ monitoring configured
labels.docs.checklist.recommendedAlert when dead-letter queue depth exceeds a defined threshold. Growing DLQ depth is the early warning signal for systematic connector failures or schema drift.
Correlation ID Propagation
Every flow run receives a correlationId at trigger time. Pass it in all outbound connector API calls as the X-Correlation-ID header. Include it in utility node messages and server-side error logs. Return it in webhook response headers. This enables cross-system trace stitching when diagnosing failures that span the platform and external providers.
Per-Node Latency
The execution trace shows durationMs per node. Connector nodes consistently above 2,000ms warrant investigation — common causes are rate limiting, oversized request payloads, or geographic network path issues. Transform:code nodes above 500ms may be processing unnecessarily large arrays — examine the input payload size.
Health Endpoints
| Endpoint | Purpose | Healthy Response |
|---|---|---|
| GET /health | Liveness check — is the process running? | HTTP 200 { "status": "ok" } |
| GET /health/ready | Readiness check — are dependencies healthy? | HTTP 200 only when DB, queue, and connector pool are all healthy |
Structured Log Format
Every structured log entry should include these fields:
logger.log({
tenantId,
entityId,
action: 'invoice.approve',
durationMs,
correlationId,
userId,
result: 'success' | 'error',
});
Never log raw user data, email addresses, or financial amounts in plaintext. Use IDs and status codes in log entries — full record data belongs in audit trails, not application logs.
16. Security Engineering
Security is not a post-implementation concern. Each rule below must be verified before writing code, not after.
Security Rules Reference
| Rule | Correct Pattern |
|---|---|
| tenantId in every query | prisma.contact.findMany({ where: { tenantId: params.tenantId } }) |
| Parameterized queries | Use Prisma typed queries — never prisma.$queryRawUnsafe() or string-concatenated SQL |
| Zod validation at boundaries | const validated = schema.parse(input) before any use of external data |
| Permission check before action | Handled by ToolRegistry — never call a tool handler directly from another service |
| No secrets in source code | process.env.STRIPE_SECRET_KEY — validate presence at module onModuleInit |
| Safe error messages | Return errors.module.entity.errorType i18n key to callers; log full detail server-side only |
| Select only required fields | prisma.contact.findMany({ select: { id: true, email: true } }) — never select all fields |
| Events carry tenantId | Every eventBus.publish() call must include tenantId in the payload object |
Role-Based Access
See Roles and Permissions for the full permission model. Before writing any handler, verify:
- What permission is required to perform this action?
- Is that permission checked before the handler executes?
- Does the ToolRegistry
requiredPermissionsarray include this permission?
SQL injection surface
Prisma's typed query builder prevents SQL injection by default. The only injection risk surfaces are $queryRaw and $executeRaw. When these are genuinely necessary, use Prisma's tagged template literal form — never string concatenation. Never use $queryRawUnsafe. Any PR introducing $queryRawUnsafe will be rejected at review.
Input Validation Pattern
All external inputs — HTTP request bodies, webhook payloads, event payloads received from external systems — must be validated with Zod before use:
const IncomingWebhookSchema = z.object({
tenantId: z.string().uuid(),
email: z.string().email(),
amount: z.number().positive(),
});
// In the handler:
const validated = IncomingWebhookSchema.safeParse(rawBody);
if (!validated.success) {
throw new BadRequestException('errors.webhook.validation.failed');
}
const { tenantId, email, amount } = validated.data;
Environment Variable Validation
Validate all required environment variables at module startup, not at first use:
async onModuleInit(): Promise<void> {
const stripeKey = process.env.STRIPE_SECRET_KEY;
if (!stripeKey) {
throw new Error('STRIPE_SECRET_KEY environment variable is required');
}
}
17. Release and Deployment
Flow Versioning Model
Each click of Publish creates an immutable version numbered sequentially starting at v1. The active version is the one currently executing. Rollback means setting the active version to a previous published version — no re-deployment is required. Navigate to Automation → Flows → [flow] → Versions to manage versions and set the active version.
Draft edits do not affect the active version. A flow can have a published active version and an unpublished draft simultaneously.
Release Sign-Off Template
Include this template in the flow description before publishing. It serves as the living record of the flow's purpose, dependencies, and recovery procedure:
Business objective: [what business problem this flow solves]
Owner: [team or person accountable for this flow's operation]
Linked ticket(s): [ticket IDs that specify the requirements]
Data contract: [trigger input schema; connector operations consumed; objects written to]
Test evidence: [execution IDs from Read-Only and Full Rollback test runs]
Rollback: [version number to revert to; steps to execute rollback; estimated rollback time]
On-call contact: [who to page if this flow fails in production]
Last reviewed: [date of last sign-off]
Canary Rollout
Planned — not yet implemented
Canary rollout (routing a percentage of triggers to a new flow version) is not implemented. This section is retained as forward-looking guidance; do not document or rely on a Settings → Canary UI — it does not exist.
Schedule-triggered flows use the following scheduling behaviour instead (see Automation → Flows → [flow] → Trigger for the cron + timezone configuration):
- Cron + IANA timezone: schedules are standard 5-field cron expressions evaluated in a named IANA timezone (default
UTC). Daylight-saving transitions follow the timezone's wall-clock rules. - Skip-overlap: if the previous scheduled occurrence is still queued, pending, or running, the new occurrence is skipped — no parallel runs of the same flow.
- Skip-missed, no catch-up: occurrences missed while the platform was down (or older than the 5-minute staleness window) are skipped, not replayed.
- Monthly execution quota: every fired occurrence consumes one unit of the tenant's monthly execution quota. When the quota is exhausted, occurrences are skipped and the flow owner receives an in-app notification (at most one per flow per day).
- Pause controls: an active tenant- or flow-level pause suppresses new scheduled runs until it is lifted.
Breaking connector changes
If a connector operation's response schema changes — a field is renamed, removed, or its type changes — update all downstream transform and mapper nodes before deploying the new connector version. Use Connectors → References to find every flow consuming a specific connector operation before making connector changes. Schema drift between connector output and transform node expectations is the most common cause of silent data corruption.
Pre-Deploy Checklist
All three execution modes tested
labels.docs.checklist.requiredPreview, Read-Only, and Full Rollback all completed successfully with representative input data.
Happy path and at least one failure path covered
labels.docs.checklist.requiredThe recovery lane has been exercised, not just the happy path. At minimum, test one connector failure scenario.
Release sign-off template completed
labels.docs.checklist.requiredThe flow description includes the full sign-off template with linked ticket IDs and test evidence execution IDs.
No personal credentials in connector nodes
labels.docs.checklist.requiredAll credential references use the
secret.<provider>.<purpose>pattern pointing to shared service account credentials.tenantId present in all tool handler DB queries
labels.docs.checklist.requiredEvery
prisma.*call in handler functions touched by this release includestenantIdin the where clause.Flow permission holders named
labels.docs.checklist.recommendedThe flow description or linked runbook identifies who can edit, disable, and replay this flow.
Schedule behaviour reviewed for schedule-triggered flows
labels.docs.checklist.recommendedCanary rollout is not yet implemented. Instead, confirm the flow tolerates the real scheduling semantics: skip-overlap, skip-missed (no catch-up), and monthly quota consumption.
18. Performance Standards
Target Metrics
| Metric | Target | Limit | Action if Exceeded |
|---|---|---|---|
| API response (p95) | < 200ms | < 500ms | Run EXPLAIN ANALYZE, add index, add caching layer |
| AI tool response | < 5s | < 60s | Reduce tool chain depth, increase timeout budget, cache intermediate results |
| DB query | < 50ms | < 200ms | Add index on filtered and sorted columns |
| Initial frontend bundle | < 200KB | < 500KB | Code-split routes, lazy-load heavy components |
| Full API rebuild (SWC) | < 30s | > 45s | Review barrel imports, reduce module coupling |
| Code node execution | < 1s | < 5s | Simplify logic, avoid large array iteration in transforms |
| Connector call | < 500ms | < 5s | Check network path, enable connection pooling, reduce payload size |
Pagination Requirement
All list endpoints and ToolRegistry list operations must paginate. No unbounded queries. Default page size: 20. Maximum: 100. Any query that does not include a take / limit clause is a production incident waiting to happen on large tenants.
N+1 Prevention
Use Prisma include for relations in list queries instead of loading relations in a loop:
// WRONG — N+1 queries: one per contact record
const contacts = await this.prisma.contact.findMany({ where: { tenantId } });
for (const c of contacts) {
c.deals = await this.prisma.deal.findMany({ where: { contactId: c.id } });
}
// CORRECT — single query with included relation
const contacts = await this.prisma.contact.findMany({
where: { tenantId },
include: {
deals: { select: { id: true, name: true, value: true } },
},
take: 20,
skip: (page - 1) * 20,
});
Index Requirements
Add indexes on all columns used in WHERE, ORDER BY, or JOIN conditions in frequently-executed queries. Always include tenant_id as the first component of composite indexes — this ensures the database can use the index for tenant-scoped queries without a full table scan.
-- Example: composite index for a common tenant-scoped, date-sorted query
CREATE INDEX idx_invoices_tenant_created
ON invoices (tenant_id, created_at DESC)
WHERE deleted_at IS NULL;
Caching Guidelines
Cache expensive computed results — report aggregations, complex join results — using the platform's Redis-backed cache. Cache keys must include tenantId as the first segment. TTL should reflect the acceptable staleness window for the data type: 60s for near-real-time dashboards, 300s for summary reports, 3600s for reference data.
// Cache key pattern — tenantId always first
const cacheKey = `${tenantId}:reports:monthly:${year}-${month}`;
const cached = await redis.get(cacheKey);
Never cache records that include permission-sensitive fields across tenant boundaries. Cache invalidation must fire on every mutation event for the cached entity type.
Related Documentation
Creating Flows
Step-by-step canvas walkthrough
Learn moreTriggers
All trigger types and configuration
Learn moreNode Types
Complete node catalogue
Learn moreTool Nodes
Calling platform tools from flows
Learn moreLogic Nodes
Branching, looping, and merging
Learn moreTesting and Debugging
Execution modes and trace reading
Learn moreConnector Library
Browsing available connectors
Learn moreManaging Credentials
Credential vault and rotation
Learn moreAuth Types
OAuth2, API Key, Basic, Custom
Learn moreOAuth Setup
Provider-specific OAuth configuration
Learn moreCustom Connectors
Connector generator walkthrough
Learn moreCDC
Change data capture subscriptions
Learn moreAPI Overview
REST API reference
Learn moreAPI Authentication
Tokens, keys, and OAuth2 server
Learn moreWebhooks
Outbound webhook configuration
Learn moreRoles and Permissions
Permission model reference
Learn more