Engine definitions
An engine definition describes an integration kind. Registering it makes that kind available to the server; it does not create, connect or activate a stored engine instance. Follow Create your first engine for a complete exercise. See the Kit API for the declaration and hook contracts.
Runtime and backend definitions
import { defineEngineRuntime } from "@kambium/kit/shared/engine-runtime";
import { defineEngine } from "@kambium/kit";
export const runtime = defineEngineRuntime({
kind: "heartbeat",
connections: {},
});
export const heartbeatEngine = defineEngine({
runtime,
connections: {},
});Keep the runtime in a browser-safe module when a dashboard also imports it. The backend can add tasks, lifecycle, configSchema, provider hooks and server setup. A configured engine factory takes host inputs and returns that definition.
The app derives EngineKind from its runtime map and registers backend definitions with createServer({ engines: ... }). Those kinds must agree. A frontend catalog may expose only a subset; omitting a page does not unregister the backend engine. Adding a kind requires no core enum or database migration.
Connections
Declare only the connections the engine uses. Each runtime connection needs a matching backend binding. Omitting a connection ID generates ${connectionName}_${engineKind}; explicit IDs preserve existing installations. Treat persisted connection IDs as identities, not display labels.
For direct Airtable and Slack OAuth, put credentials, scopes and callbacks on the backend binding. Runtime metadata describes capabilities and can be sent to the browser. Provider-free engines use empty connection maps. For an optional example, follow Add an Airtable connection.
For Airtable processing, choose a supported mode:
- Record/schema hooks use core's task planning and execution path.
handlePayloadsreceives a fetched page and lets the engine own its persistence. Core still owns fetching, locking, continuation and cursor advancement. A rejected hook leaves the cursor unadvanced, so partial writes may replay.
Page handling cannot be combined with record/schema execution, preparation or delayed-task hooks on the same connection. Definition validation rejects mixed modes.
Connect another provider through Nango
Kambium Kit includes an optional Nango connection flow for providers such as HubSpot. Kit links the Nango connection to the engine instance. Nango stores provider credentials and refreshes OAuth tokens. Your engine owns its API calls and business logic. Nango auth overview
Configure a separate Nango environment that can send auth webhooks to your app. In the Kit dashboard, add a Connect button to your engine's setup component to open Nango's authorization UI.
In the engine definition, set the connection id to the integration ID in the host's Nango environment. The matching backend binding can be empty because the host configures provider credentials and scopes in Nango.
import { defineEngine } from "@kambium/kit";
export const crmEngine = defineEngine({
runtime: {
kind: "crm-contacts",
connections: { hubspot: { provider: "hubspot", id: "hubspot-contacts" } },
},
connections: { hubspot: {} },
});- In the host's
createServeroptions, supply a configured Nango client throughconfig.runtime.createNangoClient. Keep its credentials server-side. In the Nango environment, point the auth webhook at the public URL for Kit's/ui/connect-callback-nangoroute. Kit's callback expectsX-Nango-Signatureand the auth event'sendUser.endUserId. - In the engine's custom setup component, call
useConnectionStore()from@kambium/kit/frontend. Wire the Connect button toconnectNangoTask.perform({ syncId: engineId, appName: "hubspot-contacts" }). Kit restricts the Connect session to the declared integration and saves the connection ID for the engine when the signed callback succeeds. - In trusted server code, look up the saved connection by engine ID and integration ID. Use the saved Nango connection ID with the configured client for provider calls. Verify setup by authorizing a test account, confirming the connection was saved, and making a read-only provider API call.
Nango error reconciliation is a separate host maintenance option. It can deactivate engines with errored connections.
Lifecycle and configuration
Lifecycle hooks validate and implement activation/deactivation behavior. Use beforeActivate for activation requirements even when a custom frontend checks them too. Managed resources follow this sequence:
An Airtable connection can declare webhook: { filters, includes } directly, or provide webhook: ({ sync }) => specification when the scope depends on configuration. The declaration is server-only and stays outside the shared runtime configuration.
The activation coordinator runs optional lifecycle.beforeActivate, creates the webhook using the service's default notification URL, runs optional lifecycle.activate, and persists the webhook identity and active status under the existing activation lock. The activation hook receives webhooks.airtable alongside its scoped EngineContext and sync record. Hooks may return nothing; core persists managed webhook fields without an engine-specific database patch.
If setup or persistence fails, the coordinator attempts to delete only the webhook created by that attempt. A cleanup error is logged and the original error is rethrown. afterActivate still runs after persistence and lock release; its failures do not roll back an active engine. Deactivation runs optional engine cleanup and deletes the declared webhook, preserving the existing best-effort deletion behavior.
Managed webhook declarations require the primary airtable connection because an instance stores one set of Airtable webhook fields. Unsupported connection slots are rejected at definition/registration time.
Host hooks, lifecycle ordering and failure behavior
The optional server-level createServer.hooks.beforeEngineActivate receives { context, sync, user, log } after initial access and active-state checks. The app uses it to check product eligibility and resolve the subscription or trial, in that order. A rejection stops activation before taking the lock. Core reloads the record and rechecks access and active state inside the lock, where it runs the engine's own lifecycle.beforeActivate. It constructs one PowerService and shares one EngineContext between validation and activation. Managed provisioning uses the service's configured notification URL. Hook or persistence failure deletes only that attempt's new webhook, preserving the original error even if cleanup fails.
Post-activation runs after persistence and lock release, with the locked pre-update snapshot and a fresh context without the operation service. Core then sends the standard first-engine email using config.firstEngineEmail names, links and billing policy. It preserves the existing rule: send to the activating user when they have an email and no other active engine of that kind. The check reads at most one ID. Delivery errors are logged without failing activation. An engine can declare an onboardingEmail Marko body on its definition; core supplies branding/layout and uses its generic body when none is declared.
The optional createServer.hooks.afterEngineActivate runs after standard email handling with { context, sync, user, log } and the same pre-update snapshot. It adds custom work and is not required for email delivery. Its failures still propagate without rolling back activation or deleting the webhook. The engine's own lifecycle.afterActivate runs before standard email handling and retains its existing failure behavior.
Deactivation passes through airtableConnectionLockHeld, runs optional portable cleanup, deletes the managed webhook, persists inactive/reset fields, then schedules the configured disabled notification. Already-inactive instances return without cleanup or notifications. Shared deletion skips missing IDs and tolerates provider/reporting/email failures. Persistence failures remain visible.
configSchema accepts a synchronous parse(value) contract. It validates non-null configuration patches before supported HTTP/repository writes. Support partial updates in the schema; parsed/transformed output does not replace the submitted JSON. TypeScript types alone do not validate stored or external data.
Engine context
An EngineContext lasts for one invocation against one engine instance. context.sync is the instance record. Use context.tasks to enqueue scoped work, context.repos for persistence and context.log for operation logs.
Pass the context or its configured services to helpers. Provider services are created on demand. Call initLlmService() once per operation and reuse it for multiple requests. Kit services
Installed backend engines are trusted code. The privileged Supabase client and repository access are not a tenant sandbox. Custom routes must enforce access before invoking privileged operations.
Authenticate a custom route
Bind auth to the current Fastify request. A verified identity tells you who is calling. Check engine access before starting provider work, and use a caller-scoped database client when the database should enforce row-level security (RLS). For writes, enforce the operation's write policy as well as engine access. For supported configuration changes, use Core's configuration route, which applies the ownership and revision checks.
Define a browser-safe endpoint in engine-status.ts:
import { defineEndpoint, type EndpointCatalog } from "@kambium/kit/endpoint";
export const engineStatus = defineEndpoint<{ id: string; active: boolean }>()({
method: "GET",
url: "/example/engines/:id/status",
});
export type StatusEndpoints = EndpointCatalog<[typeof engineStatus]>;Bind the handler on the server. The lookup uses the same caller's credentials. Only construct an instance scope after the access and engine-kind checks.
import { defineEndpointRoute } from "@kambium/kit/server/routes/endpoint";
import { z } from "zod/v4";
import { engineStatus } from "./engine-status";
const params = z.object({ id: z.string().uuid() });
export const engineStatusRoute = defineEndpointRoute(engineStatus, {
async handler(context, request, reply) {
const parsed = params.safeParse(request.params);
if (!parsed.success) return reply.status(400).send({ message: "Invalid engine ID" });
const auth = context.initAuthService(request);
if (!await auth.getUserClaims()) {
return reply.status(401).send({ message: "Sign in required" });
}
const id = parsed.data.id;
if (!await auth.canAccessEngine(id)) {
return reply.status(404).send({ message: "Engine not found" });
}
const db = context.createSupabaseUserClient(auth.getTokenFromHeader(request));
const { data: sync, error } = await db.from("syncs").select("*").eq("id", id).maybeSingle();
if (error) throw error;
if (!sync || sync.kind !== "heartbeat") {
return reply.status(404).send({ message: "Engine not found" });
}
const engine = context.initEngineContext({ sync, log: request.log });
return reply.status(200).send({ id: engine.sync.id, active: engine.sync.active === true });
},
});Before server readiness, mount engineStatusRoute(app.context) in the host's /ui Fastify scope. The generated dashboard maps /api to that scope through its configured request store. In Vue setup, call the path from the shared catalog:
import { createUiClient, useRequestStore } from "@kambium/kit/frontend";
import type { StatusEndpoints } from "./engine-status";
const status = createUiClient<StatusEndpoints>(useRequestStore());
const engine = await status.get("/example/engines/:id/status", { params: { id: engineId } });See Supabase row-level security for enforcement by the bearer-scoped database client.
Tasks and frontend pages
A declared task receives { context, task, run, signal }. The worker owns claims, retry and completion. Use Task execution for payload registration, scoped enqueueing and failure semantics.
The default EnginePage uses public runtime capabilities for connection setup. A custom setup slot replaces that UI, while backend lifecycle validation still applies. See Dashboard integration.
Optional source contracts (repository access may be required): definition validation, context and callback types and scoped context construction.