Skip to content

Kit API ​

UseImport fromAPI
Define an engine@kambium/kitdefineEngine, EngineDefinitionInput, EngineFactory, EngineContext
Initialize and clean up resources@kambium/kitEngineSetupHook, SetupContext, EngineServerHooks, EngineLifecycleHooks
Handle provider events@kambium/kitEngineConnectionBindings, AirtableHooks, SlackHooks, EngineActivationArgs, EngineLifecycleResult
Share engine metadata@kambium/kit/shared/engine-runtime, @kambium/kit/shared/engine-connection-configdefineEngineRuntime, EngineRuntimeConfig, resolveConnectionId, EngineConnectionConfig
Run a server@kambium/kit/servercreateServer, shutdownServer, CreateServerOptions, ServerConfig, ServerContext, EngineRegistration
Configure and build the app@kambium/kit/shared/env, @kambium/kit/builddefineEnv, EnvDefinition, buildServer, ServerBuildOptions
Define a task and its execution policy@kambium/kitEngineTaskDefinitions, EngineTaskHandlerArgs, TaskExecutionPolicy, EngineTaskInput
Schedule or finish a task@kambium/kitEngineTaskScheduling, TaskScheduling, TaskRun, PermanentError
Register task payloads or Airtable handlers@kambium/kit/shared/types, @kambium/kit/server/tasks/airtableTaskPayloadByOperation, TaskChainPayload, TaskOperation, TaskPayload, createAirtableTasks
Declare and bind HTTP routes@kambium/kit/server/routes/define-route, @kambium/kit/server/routes/endpointdefineRoute, defineEndpointRoute, EndpointReply
Call typed JSON endpoints@kambium/kit/endpoint, @kambium/kit/frontend/ui-clientdefineEndpoint, EndpointCatalog, EndpointArguments, EndpointResponse, createUiClient

See Engine definitions, Task execution, and Server configuration for application wiring and examples. See Kit services for provider APIs and Kit frontend for dashboard components and stores.

Generated for Kit 0.8.0 and Core 0.10.1.

Functions ​

buildServer() ​

ts
function buildServer(options?: ServerBuildOptions): Promise<BuildResult<BuildOptions>>;

Bundle the app's index.ts with the server's TypeScript and Marko configuration.

Remarks ​

The default output is dist/index.js. Supply additional entries and plugins through options.extra so the standard entry and build plugins stay registered.


createAirtableTasks() ​

ts
function createAirtableTasks<Context extends ServerContext = ServerContext>(options?: AirtableTaskOptions<Context>): object;

Supply platform handlers for the standard Airtable event pipeline.

Remarks ​

Spread these definitions into createServer's tasks map. All three operations use the background worker by default. An option set to false omits that operation.


createServer() ​

ts
function createServer<Context extends ServerContext = ServerContext, Services extends object = {
}>(options: CreateServerOptions<Context, Services>): Promise<FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault> & object>;

Construct the Fastify server and initialize its installed engines.

Remarks ​

The returned server is not listening. Register host routes and hooks before calling ready() or listen(). Close the server with app.close() to run engine shutdown hooks and release server-owned resources.

Example ​

ts
import { createServer, type CreateServerOptions } from "@kambium/kit/server";

function createApp(options: CreateServerOptions) {
  return createServer(options).then(app => {
    app.get("/status", async () => ({ ok: true }));
    return app;
  });
}

createUiClient() ​

ts
function createUiClient<Routes>(transport: UiClientTransport): object;

Call JSON endpoints by method and path using their shared endpoint catalog.

Remarks ​

Pass the configured request store for authentication, base URLs, and transport errors. Structured arguments encode path and query values. Pass a signal to cancel the request. Responses are typed as JSON without client-side validation.


defineEndpoint() ​

ts
function defineEndpoint<Response>(): <Definition>(definition: Definition) => TypedEndpoint<Definition, Response>;

Share a browser-safe JSON GET or POST contract between client and server.

Remarks ​

Use a literal path with required named parameters. Query and body schemas describe inputs. The response generic is compile-time, and the route still owns runtime parsing and authorization.


defineEndpointRoute() ​

ts
function defineEndpointRoute<E extends Endpoint, Context extends ServerContext = ServerContext>(endpoint: E, definition: object): (context: Context) => object;

Bind an endpoint contract to a native Fastify route with typed replies.

Remarks ​

Mount the context-bound result with app.route. Parse the raw query or body and check access in the handler or its owning adapter. Use reply.status(...).send(...) so the success payload is checked against the endpoint response type.


defineEngine() ​

ts
function defineEngine<Connections extends ConnectionInputs, Definition extends Omit<EngineDefinitionInput<Connections, unknown>, "hooks">, Resources = void>(definition: Definition & EngineDefinitionInput<Connections, Resources> & {
  connections: Record<Exclude<keyof Definition["connections"], keyof Connections>, never>;
}): NoInfer<Definition & EngineDefinitionInput<Connections, Resources> & object>;

Define a portable engine for a host to register.

Remarks ​

Declare each provider connection in both runtime.connections and connections. Each backend slot can omit integration, which is filled from its runtime slot. Use empty maps for an engine without provider connections. Preserve explicit connection IDs when existing installations depend on them. This checks connection bindings and the Airtable processing declaration. The host registers the definition and runs setup when constructing its server. Activation belongs to each stored engine instance.


defineEngineRuntime() ​

ts
function defineEngineRuntime<Runtime extends EngineRuntimeInput>(runtime: Runtime): Runtime & {
  connections: ResolvedConnections<Runtime["connections"]>;
};

Declare an engine's browser-safe kind and provider connections.

Remarks ​

Share the result between the backend definition and dashboard. A missing connection ID becomes <connectionName>_<engineKind>. Preserve explicit IDs when they identify existing accounts. Keep credentials in the backend.


defineEnv() ​

ts
function defineEnv<Definitions extends Record<string, EnvDefinition>>(definitions: Definitions): object;

Declare app-owned backend settings for runtime validation and Desktop setup.

Remarks ​

Pass metadata in the declaration. Read values explicitly with read(process.env) at the backend boundary. Missing required or invalid values throw with setting names only. Blank optional values resolve to undefined.


defineRoute() ​

ts
function defineRoute<Path extends string, Generic extends RouteGenericInterface = {
  Params: PathParams<Path>;
}, Context extends ServerContext = ServerContext>(definition: object): (context: Context) => NativeRouteOptions<Generic>;

Declare a Fastify route whose handler receives the host context.

Remarks ​

Bind the declaration to the server context and pass its result to app.route. Path parameter inference is compile-time. Supply native Fastify schemas and authorization hooks where the route requires them.


resolveConnectionId() ​

ts
function resolveConnectionId<Id extends string>(connection: EngineConnectionConfig<string, Id>, isDevelopment: boolean): Id;

Read the connection ID for the caller's environment. A shared ID is returned unchanged.


shutdownServer() ​

ts
function shutdownServer<T = void>(
   app: Pick<FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault>, "close"> & {
  log: Pick<FastifyBaseLogger, "error">;
}, 
   signal: Signals, 
   __namedParameters: ShutdownOptions<T>
): Promise<{
  closeFailed: boolean;
  hookResult:   | {
     kind: "timed_out";
   }
     | {
     kind: "completed";
     value: T;
   }
     | {
     error: any;
     kind: "failed";
   }
     | {
     kind: "completed";
     value: undefined;
   };
  hookTimeoutMs: number;
  sentryFailed: boolean;
}>;

Close the server and report the outcome within a shared shutdown deadline.

Remarks ​

Calls app.close(), then the optional host cleanup and configured error flush. The host interprets the result and owns process exit. A timeout can leave cleanup running in the background.

Classes ​

PermanentError ​

Fail the current task as broken without retrying it. Use this for conditions that another attempt with the same payload cannot resolve.

Extends ​

  • Error

Constructors ​

Constructor ​
ts
new PermanentError(message?: string): PermanentError;
Inherited from ​

Error.constructor

Constructor ​
ts
new PermanentError(message?: string, options?: ErrorOptions): PermanentError;
Inherited from ​

Error.constructor

Properties ​

PropertyType
permanenttrue

Interfaces ​

ServerContext ​

Server-scoped services for host routes and platform hooks. Bind authorization to each incoming request. Use an EngineContext for work scoped to a matched engine instance.

Extends ​

  • AccountDeletionHooks
  • RedisResources

Methods ​

advanceAccountDeletion() ​
ts
advanceAccountDeletion(params: object): Promise<Pick<UserDeletionRequestRow, "status" | "phase">>;
beforeDeleteEngine() ​
ts
beforeDeleteEngine(params: object): Promise<void>;
checkEngineAccessUncached() ​
ts
checkEngineAccessUncached(userId: string, engineId: string): Promise<boolean>;
createSupabaseUserClient() ​
ts
createSupabaseUserClient(userToken: string): SupabaseClient<any>;

Scope database reads and writes to the verified caller's bearer token and RLS policies.

deactivateEngine() ​
ts
deactivateEngine(params: object): Promise<void>;
getActivationBaseUrl() ​
ts
getActivationBaseUrl(): Promise<string>;
getEngineAirtableHooks() ​
ts
getEngineAirtableHooks(kind: string): 
  | Omit<AirtableHooks, "enqueueDelayedTasks">
  | undefined;
getEngineConnections() ​
ts
getEngineConnections(kind: string): BuiltinEngineConnectionConfigs;
getEngineLifecycleDefinition() ​
ts
getEngineLifecycleDefinition(kind: string): EngineLifecycleDefinition;
getEngineSlackMentionHandler() ​
ts
getEngineSlackMentionHandler(kind: string): SlackMentionAiHandler | undefined;
getExternalPostgres() ​
ts
getExternalPostgres(sync: Pick<SyncRecord, "id" | "user_id" | "kind">): Promise<ExternalPostgresConnectionService>;
hasEngineKind() ​
ts
hasEngineKind(kind: string): boolean;
initAirtableOAuthService() ​
ts
initAirtableOAuthService(options?: object): AirtableOAuthService;
initAuthService() ​
ts
initAuthService(request?: FastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<FastifyTypeProviderDefault, FastifySchema, RouteGenericInterface>>, options?: {
  cachePermissions?: boolean;
}): AuthService;

Bind identity and engine access checks to the incoming request.

initCredentialService() ​
ts
initCredentialService(): CredentialService;
initDecisionService() ​
ts
initDecisionService(log: EngineLogger): DecisionService;
initEngineContext() ​
ts
initEngineContext(options: EngineContextOptions): EngineContext;
initNangoService() ​
ts
initNangoService(): NangoService;
initPowerService() ​
ts
initPowerService(params: Omit<{
  airtableConnectionLockHeld?: boolean;
  airtableRequestExpirationMs?: number;
  baseUrl?: string;
  deps: PowerServiceDeps<EngineLogger & object & object>;
  log: EngineLogger & object & object;
  syncId: string;
}, "log" | "deps"> & {
  log: FastifyBaseLogger;
}): PowerService<FastifyBaseLogger>;
initSchemaCacheService() ​
ts
initSchemaCacheService(powerService: PowerService): SchemaCacheService;
initSlackOAuthService() ​
ts
initSlackOAuthService(options?: object): SlackOAuthService;
invalidateEngineAccess() ​
ts
invalidateEngineAccess(): Promise<void>;
isDevTarget() ​
ts
isDevTarget(): boolean;
scheduleEngineDisabledNotification() ​
ts
scheduleEngineDisabledNotification(input: object): Promise<void>;
validateEngineConfig() ​
ts
validateEngineConfig(kind: string, value: Json): void;

Properties ​

PropertyTypeDefault valueDescriptionInherited from
accountDeletion?AccountDeletionConfigundefined--
afterEngineActivate?ServerActivationHookundefinedRuns after the engine hook, persistence and lock release; failures propagate without rollback.-
airtableMcpAirtableMcpServiceundefined--
airtableWebhook?AirtableWebhookNotificationsundefined--
airtableWebhookDeletionEmail?() => Pick<EmailService, "sendAdminEmail">undefined--
authorizeAccountDeletion?(input: { userId: string; }) => Promise<void>undefinedEligibility check during request, confirmation preview and confirmation, before cleanup is scheduled.AccountDeletionHooks.authorizeAccountDeletion
authorizeEngineCreation?(input: CreationAuthorizationInput & { data: object; }) => Promise< | void | { message: string; }>undefinedRuns after validation and authentication, before creation reads or writes. Return a message to deny with 403.-
authorizeWorkspaceBootstrap?(input: object) => Promise< | { allowed: boolean; decorateResponse?: (response: WorkspaceBootstrapResponse) => WorkspaceBootstrapResponse; userId: string; } | undefined>undefinedA host gate must authenticate the bearer token when it handles the request.-
authorizeWorkspaceCreation?(input: CreationAuthorizationInput & { name: string; }) => Promise< | void | { message: string; }>undefined--
beforeAccountCleanup?(input: { request: UserDeletionRequestRow; }) => Promise<void>undefinedAwaited before operational cleanup. Must tolerate retries and overlapping attempts for the same request.AccountDeletionHooks.beforeAccountCleanup
beforeEngineActivate?ServerActivationHookundefinedRuns after initial access/state checks and before acquiring the activation lock.-
brokenTaskEmail?false | BrokenTaskEmailConfigundefined--
cronJobs?readonly ScheduledTask[]undefined--
firstEngineEmail?false | FirstEngineEmailConfigundefined--
frontendUrls?FrontendUrlConfigundefined--
getEngineRuntimeConfigs?() => readonly Pick<EngineRuntimeConfig, "connections" | "kind">[]undefined--
getWorkspaceInvitationBaseUrl?(product: string) => string | Promise<string | undefined> | undefinedundefined--
initEmailService?() => EmailServiceundefined--
initLlmService() => LlmServiceundefined--
localAirtable?LocalAirtableConfigundefined--
localSlack?LocalSlackConfigundefined--
maintenance?ServerMaintenanceOptionsundefined--
mcp?McpServiceundefined--
mcpOAuth?McpOAuthServiceundefined--
mode?ServerRuntimeModeundefined--
redisRedisLikeundefined-RedisResources.redis
redisCacheEncryptionKeystring | undefinedoptions.redisCacheEncryptionKey-RedisResources.redisCacheEncryptionKey
reposobjectundefined--
repos.connectedAccountsMasterRepoConnectedAccountsMasterRepo...--
repos.keyRepoKeyRepository...--
repos.lockRepoLockRepository...--
repos.slackAttachmentMasterRepoSlackAttachmentMasterRepo...--
repos.slackMessageRepoSlackMessageRepo...--
repos.slackReactionFlowRecordRepoSlackReactionFlowRecordRepo...--
repos.slackReplyFlowRecordRepoSlackReplyFlowRecordRepo...--
repos.slackThreadAiOperationRepoSlackThreadAiOperationRepo...--
repos.subscriptionsMasterRepoSubscriptionsMasterRepo...--
repos.syncMasterRepoSyncMasterRepo...--
repos.taskEventRepoTaskEventRepo...--
repos.taskMasterRepoTaskMasterRepo...--
repos.usageSnapshotRepoUsageSnapshotRepository...--
repos.userDeletionRequestRepoUserDeletionRequestRepo...--
slackWebhook?SlackWebhookRuntimeundefined--
supabaseAuthHookSecret?stringundefined--
supabaseMasterSupabaseClient<any>undefined--
supabaseUrl?stringundefined--
taskFailureRuntime?TaskFailureRuntimeundefined--
taskManager?TaskDispatcherundefined--
webhookPathPrefix?stringundefined--

TaskPayloadByOperation ​

Persisted payloads keyed by operation. Applications may extend this interface through module augmentation; TaskOperation and task APIs then include those keys.

Properties ​

PropertyType
airtable_webhook_drainAirtableWebhookDrainTaskPayload
delete_engineDeleteEngineTaskPayload
delete_workspaceobject
delete_workspace.requestedByUserIdstring
delete_workspace.workspaceIdstring
engine_disabled_emailEngineDisabledEmailTaskPayload
nango_delete_connectionNangoDeleteConnectionTaskPayload
platform_daily_reportPlatformDailyReportTaskPayload
record_changeRecordChangeTaskPayload
run_slack_flowFlowTaskPayload
schema_changeSchemaChangeTaskPayload
slack_interactionSlackInteractionTaskPayload
slack_thread_messageSlackThreadMessageTaskPayload
webhook_deliveryobject
webhook_delivery.eventIdstring
webhook_delivery.eventTypestring
webhook_delivery.subjectJson
webhook_delivery.webhookIdstring

TaskRun ​

Report progress or finish the worker-owned task attempt passed to a handler. Await finalizing calls after completing the required writes and side effects.

Methods ​

deferEvent() ​
ts
deferEvent(event: TaskEvent): void;
fail() ​
ts
fail(
   err: unknown, 
   message?: string, 
   details?: Json, 
   options?: object
): Promise<void>;

Apply retry classification and record failure. Ordinary handlers can throw instead.

failInactiveEngine() ​
ts
failInactiveEngine(): Promise<void>;
finalizeWithoutEvent() ​
ts
finalizeWithoutEvent(): Promise<void>;
getFinalStatus() ​
ts
getFinalStatus(): "error" | "success" | "skipped" | undefined;
isFinalized() ​
ts
isFinalized(): boolean;
logEvent() ​
ts
logEvent(
   status: "error" | "progress" | "success", 
   message?: string, 
   details?: Json
): Promise<void>;
logMessage() ​
ts
logMessage(message: string, details?: Json): void;

Record a progress event without finalizing the attempt.

reschedule() ​
ts
reschedule(runAt: string): Promise<void>;

Return the task to pending for a later time without consuming the attempt.

skip() ​
ts
skip(message?: string, details?: Json): Promise<void>;

Finish the task as done with a skipped result for this attempt.

success() ​
ts
success(message?: string, details?: Json): Promise<void>;

Mark the task done and clear its payload after required work succeeds.

warn() ​
ts
warn(message: string, details?: Json): void;

Record a progress event with warning severity.

Properties ​

PropertyModifierType
signal?readonlyAbortSignal
taskreadonlyobject
task.attemptspublicnumber
task.claim_tokenpublicstring | null
task.claimed_atpublicstring | null
task.created_atpublicstring
task.detailspublicJson
task.external_record_idpublicstring
task.finished_atpublicstring | null
task.idpublicnumber
task.is_systempublicboolean
task.last_errorpublicstring | null
task.operationpublicstring
task.payloadpublicJson
task.request_idpublicnumber | null
task.run_atpublicstring
task.scheduling_keypublicstring | null
task.scheduling_startedpublicboolean
task.statuspublic"pending" | "processing" | "done" | "broken"
task.sync_idpublicstring

Type Aliases ​

AirtableDefaultHooks ​

ts
type AirtableDefaultHooks = {
  enqueueDelayedTasks?: (args: AirtableDelayedTasksArgs) => Promise<void>;
  handleRecordChange?: (args: AirtableRecordChangeHookArgs) => Promise<void>;
  handleSchemaChange?: (args: AirtableSchemaChangeHookArgs) => Promise<void>;
  preparePayloads?: (args: AirtablePayloadsHookArgs) => Promise<{
     ignoredAutoNumberFieldCount?: number;
     payloads: AirtableWebhookPayloadRaw[];
  }>;
  prepareRecordChangeTask?: (args: AirtablePrepareRecordChangeArgs) => Promise<AirtableRecordChangeTaskPlan | null>;
  prepareSchemaChangeTask?: (args: object) => Promise<AirtableSchemaChangeTaskPlan | null>;
};

Callbacks for the default record and schema task pipeline. Core persists and dispatches the planned work. Use handlePayloads for engine-owned page processing.

Properties ​

enqueueDelayedTasks? ​
ts
enqueueDelayedTasks?: (args: AirtableDelayedTasksArgs) => Promise<void>;
handleRecordChange? ​
ts
handleRecordChange?: (args: AirtableRecordChangeHookArgs) => Promise<void>;
handleSchemaChange? ​
ts
handleSchemaChange?: (args: AirtableSchemaChangeHookArgs) => Promise<void>;
preparePayloads? ​
ts
preparePayloads?: (args: AirtablePayloadsHookArgs) => Promise<{
  ignoredAutoNumberFieldCount?: number;
  payloads: AirtableWebhookPayloadRaw[];
}>;

Prepare one fetched page before default task planning. Does not own persistence.

prepareRecordChangeTask? ​
ts
prepareRecordChangeTask?: (args: AirtablePrepareRecordChangeArgs) => Promise<AirtableRecordChangeTaskPlan | null>;
prepareSchemaChangeTask? ​
ts
prepareSchemaChangeTask?: (args: object) => Promise<AirtableSchemaChangeTaskPlan | null>;

Schema tasks are skipped when both this hook and handleSchemaChange are omitted.


AirtableHooks ​

ts
type AirtableHooks = 
  | AirtableDefaultHooks & {
  handlePayloads?: never;
}
  | {
  handlePayloads: (args: AirtablePayloadsHookArgs) => Promise<AirtablePayloadsResult>;
} & { [Name in keyof AirtableDefaultHooks]?: never };

Choose the default Airtable record and schema hooks, or own a whole fetched page with handlePayloads. With page handling, persisted effects may replay when processing fails before Core advances the cursor.


AirtablePayloadsHookArgs ​

ts
type AirtablePayloadsHookArgs = {
  context: EngineContext;
  payloads: AirtableWebhookPayloadRaw[];
  signal?: AbortSignal;
};

One page fetched by Core under the engine connection's processing scope. Pass the supplied signal to cancellable work and settle only after required persistence finishes. A failed attempt may replay the same page.

Properties ​

context ​
ts
context: EngineContext;
payloads ​
ts
payloads: AirtableWebhookPayloadRaw[];
signal? ​
ts
signal?: AbortSignal;

AirtablePayloadsResult ​

ts
type AirtablePayloadsResult = {
  attemptedImmediateTaskCount?: number;
  delayedTaskCount?: number;
  ignoredAutoNumberFieldCount?: number;
  recordCount: number;
  schemaCount: number;
  suppliedImmediateTaskCount?: number;
  taskCount?: number;
};

Common page counters. Engine-specific persistence and its logs stay in the hook.

Properties ​

attemptedImmediateTaskCount? ​
ts
attemptedImmediateTaskCount?: number;
delayedTaskCount? ​
ts
delayedTaskCount?: number;
ignoredAutoNumberFieldCount? ​
ts
ignoredAutoNumberFieldCount?: number;
recordCount ​
ts
recordCount: number;
schemaCount ​
ts
schemaCount: number;
suppliedImmediateTaskCount? ​
ts
suppliedImmediateTaskCount?: number;
taskCount? ​
ts
taskCount?: number;

AirtableRecordChange ​

ts
type AirtableRecordChange = Omit<AirtablePrepareRecordChangeArgs, "context" | "syncRecord" | "defaultPayload" | "defaultExternalRecordId"> & {
  taskId: number;
};

Record event data passed to an engine hook, without host services or task state.

Type Declaration ​

taskId ​
ts
taskId: number;

AirtableRecordChangeHookArgs ​

ts
type AirtableRecordChangeHookArgs = {
  change: AirtableRecordChange;
  context: EngineContext;
  logWebhook: EngineWebhookLogger;
  signal?: AbortSignal;
  syncRecord: SyncRecord;
  taskRun: TaskRun;
};

One record change delivered by the task pipeline. Fields from Airtable are keyed by field ID. A missing value and an explicit cleared value are distinct.

Properties ​

change ​
ts
change: AirtableRecordChange;
context ​
ts
context: EngineContext;
logWebhook ​
ts
logWebhook: EngineWebhookLogger;
signal? ​
ts
signal?: AbortSignal;

The task's cancellation signal, when the hook runs through a worker.

syncRecord ​
ts
syncRecord: SyncRecord;
taskRun ​
ts
taskRun: TaskRun;

CreateServerOptions ​

ts
type CreateServerOptions<Context extends ServerContext = ServerContext, Services extends object = {
}> = object & (ServerContext extends Context ? {
  extendContext?: (context: Readonly<RuntimeServerContext<Context>>) => RuntimeContextServices<Context, Services>;
} : {
  extendContext: (context: Readonly<RuntimeServerContext<Context>>) => RuntimeContextServices<Context, Services>;
});

Compose the host's services, engine registrations, and platform tasks.

Type Declaration ​

config ​
ts
config: ServerConfig<Context>;
cronJobs? ​
ts
cronJobs?: readonly EngineCronJobFactory<Context>[];
engines ​
ts
engines: Readonly<Record<string, EngineRegistration<Context>>>;
hooks? ​
ts
hooks?: RuntimeHooks<Context> & object;
Type Declaration ​
afterEngineActivate? ​
ts
afterEngineActivate?: (input: Parameters<NonNullable<Context["afterEngineActivate"]>>[0] & {
  context: Context;
}) => Promise<void>;
authorizeAccountDeletion? ​
ts
authorizeAccountDeletion?: (input: Parameters<NonNullable<Context["authorizeAccountDeletion"]>>[0] & {
  context: Context;
}) => Promise<void>;
authorizeEngineCreation? ​
ts
authorizeEngineCreation?: (input: Parameters<NonNullable<Context["authorizeEngineCreation"]>>[0] & {
  context: Context;
}) => ReturnType<NonNullable<Context["authorizeEngineCreation"]>>;
authorizeWorkspaceBootstrap? ​
ts
authorizeWorkspaceBootstrap?: (input: Parameters<NonNullable<Context["authorizeWorkspaceBootstrap"]>>[0] & {
  context: Context;
}) => ReturnType<NonNullable<Context["authorizeWorkspaceBootstrap"]>>;
authorizeWorkspaceCreation? ​
ts
authorizeWorkspaceCreation?: (input: Parameters<NonNullable<Context["authorizeWorkspaceCreation"]>>[0] & {
  context: Context;
}) => ReturnType<NonNullable<Context["authorizeWorkspaceCreation"]>>;
beforeAccountCleanup? ​
ts
beforeAccountCleanup?: (input: Parameters<NonNullable<Context["beforeAccountCleanup"]>>[0] & {
  context: Context;
}) => Promise<void>;
beforeEngineActivate? ​
ts
beforeEngineActivate?: (input: Parameters<NonNullable<Context["beforeEngineActivate"]>>[0] & {
  context: Context;
}) => Promise<void>;
brokenTask? ​
ts
brokenTask?: BrokenTaskHook<Context>;
onEvent? ​
ts
onEvent?: ServerEventHook;
reportError? ​
ts
reportError?: ErrorReportHook;
tasks ​
ts
tasks: TaskDefinitions<Context>;
testing? ​
ts
testing?: {
  dependencies?: RuntimeDependencies;
};
testing.dependencies? ​
ts
dependencies?: RuntimeDependencies;

Remarks ​

Key each engine by its runtime kind. Put engine-owned tasks on their engine definitions. Use extendContext to supply additional host services to server hooks and platform tasks.


Endpoint ​

ts
type Endpoint = {
  [response]?: readonly [unknown];
  body?: z.ZodType;
  method: "GET" | "POST";
  query?: z.ZodObject;
  url: string;
};

Browser-safe JSON endpoint metadata. Server adapters own parsing and authorization.

Properties ​

[response]? ​
ts
readonly [response]?: readonly [unknown];
body? ​
ts
body?: z.ZodType;
method ​
ts
method: "GET" | "POST";
query? ​
ts
query?: z.ZodObject;
url ​
ts
url: string;

EndpointArguments ​

ts
type EndpointArguments<E extends Endpoint> = InputProperty<"query", QueryInput<SchemaInput<E, "query">>> & InputProperty<"body", SchemaInput<E, "body">> & (keyof EndpointParams<E> extends never ? {
  params?: never;
} : {
  params: EndpointParams<E>;
}) & {
  signal?: AbortSignal;
};

Type Declaration ​

signal? ​
ts
signal?: AbortSignal;

EndpointCatalog ​

ts
type EndpointCatalog<Endpoints extends readonly Endpoint[]> = { [E in Endpoints[number] as `${E["method"]} ${E["url"]}`]: E };

Maps endpoint declarations by method and path for use with createUiClient.


EndpointReply ​

ts
type EndpointReply<E extends Endpoint, ErrorBody = {
  message: string;
}> = FastifyReply<{
  Params: EndpointParams<E>;
  Reply: EndpointReplies<E, ErrorBody>;
}>;

EndpointResponse ​

ts
type EndpointResponse<E extends Endpoint> = NonNullable<E[typeof response]>[0];

EngineActivationArgs ​

ts
type EngineActivationArgs = {
  context: EngineContext;
  sync: SyncRecord;
  webhooks: Readonly<Record<string, Readonly<DirectWebhookInfo>>>;
};

Instance state and the managed webhooks provisioned for this activation. Use the scoped context for provider requests during the hook.

Properties ​

context ​
ts
context: EngineContext;
sync ​
ts
sync: SyncRecord;
webhooks ​
ts
webhooks: Readonly<Record<string, Readonly<DirectWebhookInfo>>>;

EngineConnectionBindings ​

ts
type EngineConnectionBindings<Configs extends EngineConnectionConfigs = BuiltinEngineConnectionConfigs> = { [Name in keyof Configs]: { hooks?: ConnectionHooks<NonNullable<Configs[Name]>["provider"]>; integration: NonNullable<Configs[Name]>; oauth?: string extends NonNullable<Configs[Name]>["provider"] ? AirtableOAuthConfig : NonNullable<Configs[Name]>["provider"] extends "airtable" ? AirtableOAuthConfig : NonNullable<Configs[Name]>["provider"] extends "slack" ? SlackOAuthConfig : never; resolveMention?: string extends NonNullable<Configs[Name]>["provider"] ? SlackMentionResolver : NonNullable<Configs[Name]>["provider"] extends "slack" ? SlackMentionResolver : never; runMentionAiAction?: string extends NonNullable<Configs[Name]>["provider"] ? SlackMentionAiHandler : NonNullable<Configs[Name]>["provider"] extends "slack" ? SlackMentionAiHandler : never; webhook?: string extends NonNullable<Configs[Name]>["provider"] ? AirtableWebhookDeclaration : NonNullable<Configs[Name]>["provider"] extends "airtable" ? AirtableWebhookDeclaration : never } };

Backend bindings selected by the provider slots in the runtime declaration. Put OAuth configuration and provider hooks here. Match the runtime's slot names and existing connection identities.


EngineConnectionConfig ​

ts
type EngineConnectionConfig<Provider extends string = string, Id extends string = string> = {
  id:   | Id
     | {
     development: Id;
     production: Id;
   };
  provider: Provider;
};

Browser-safe connection identity. A single ID applies in both environments. Use development and production IDs when each environment uses its own app.

Properties ​

id ​
ts
id: 
  | Id
  | {
  development: Id;
  production: Id;
};
provider ​
ts
provider: Provider;

EngineContext ​

ts
type EngineContext = {
  airtable: AirtableService;
  airtableMcp: AirtableMcpService;
  airtableRecordCache: RecordCacheService;
  credentials: CredentialService;
  decision: DecisionService;
  log: EngineLogger;
  power: PowerService;
  repos: Omit<ServerRepositories, "slackAttachmentMasterRepo"> & {
     slackAttachmentRepo: SlackAttachmentRepo;
  };
  schema: SchemaCacheService;
  slack: SlackService;
  supabaseMaster: SupabaseClient<Database>;
  sync: SyncRecord;
  taskManager?: TaskDispatcher;
  tasks: object;
  webhooks: EngineWebhookCapabilities;
  claimSchemaRefresh(): Promise<boolean>;
  collectSchemaEvents(change: AirtableSchemaChange): Promise<SchemaLogEvent[]>;
  deactivateEngine(options: {
     error: string;
  }): Promise<void>;
  getExternalPostgres(): Promise<ExternalPostgresConnectionService>;
  initAuthService(): AuthService;
  initEmailService(): EmailService;
  initLlmService(): LlmService;
  serializeEntries(entries: [string, unknown][]): Record<string, unknown>;
  withAirtableRequestPolicy(policy: {
     requestExpirationMs: number;
  }): object;
};

Services and state for one matched engine instance and invocation.

Remarks ​

Pass the context through helpers. Provider services are initialized lazily and share the operation's PowerService. Use tasks.enqueue to persist work under this instance's identity.

Methods ​

claimSchemaRefresh() ​
ts
claimSchemaRefresh(): Promise<boolean>;
collectSchemaEvents() ​
ts
collectSchemaEvents(change: AirtableSchemaChange): Promise<SchemaLogEvent[]>;
deactivateEngine() ​
ts
deactivateEngine(options: {
  error: string;
}): Promise<void>;
getExternalPostgres() ​
ts
getExternalPostgres(): Promise<ExternalPostgresConnectionService>;
initAuthService() ​
ts
initAuthService(): AuthService;
initEmailService() ​
ts
initEmailService(): EmailService;
initLlmService() ​
ts
initLlmService(): LlmService;
serializeEntries() ​
ts
serializeEntries(entries: [string, unknown][]): Record<string, unknown>;
withAirtableRequestPolicy() ​
ts
withAirtableRequestPolicy(policy: {
  requestExpirationMs: number;
}): object;

Properties ​

airtable ​
ts
readonly airtable: AirtableService;

Scoped Airtable client. Fetch one record or use listRecords with its offset for paging.

airtableMcp ​
ts
readonly airtableMcp: AirtableMcpService;
airtableRecordCache ​
ts
readonly airtableRecordCache: RecordCacheService;
credentials ​
ts
readonly credentials: CredentialService;
decision ​
ts
readonly decision: DecisionService;
log ​
ts
log: EngineLogger;
power ​
ts
readonly power: PowerService;
repos ​
ts
readonly repos: Omit<ServerRepositories, "slackAttachmentMasterRepo"> & {
  slackAttachmentRepo: SlackAttachmentRepo;
};
Type Declaration ​
slackAttachmentRepo ​
ts
slackAttachmentRepo: SlackAttachmentRepo;
schema ​
ts
readonly schema: SchemaCacheService;
slack ​
ts
readonly slack: SlackService;

Scoped Slack client. Retain the channel and timestamp returned by createMessage.

supabaseMaster ​
ts
readonly supabaseMaster: SupabaseClient<Database>;
sync ​
ts
readonly sync: SyncRecord;
taskManager? ​
ts
readonly taskManager?: TaskDispatcher;
tasks ​
ts
tasks: object;
localTaskKicksEnabled ​
ts
readonly localTaskKicksEnabled: boolean;
enqueue() ​
ts
enqueue<Operation extends TaskOperation>(operation: Operation, input: EngineTaskInput<Operation>): Promise<
  | Pick<{
  attempts: number;
  claim_token: string | null;
  claimed_at: string | null;
  created_at: string;
  details: Json | null;
  external_record_id: string;
  finished_at: string | null;
  id: number;
  is_system: boolean;
  last_error: string | null;
  operation: string;
  payload: Json | null;
  request_id: number | null;
  run_at: string;
  scheduling_key: string | null;
  scheduling_started: boolean;
  status: Database["public"]["Enums"]["task_status"];
  sync_id: string;
}, "id">
| null>;

Persist work for this instance, with typed payloads selected by operation.

findByTaskIdentity() ​
ts
findByTaskIdentity(params: object): Promise<
  | {
  attempts: number;
  claim_token: string | null;
  claimed_at: string | null;
  created_at: string;
  details: Json | null;
  external_record_id: string;
  finished_at: string | null;
  id: number;
  is_system: boolean;
  last_error: string | null;
  operation: string;
  payload: Json | null;
  request_id: number | null;
  run_at: string;
  scheduling_key: string | null;
  scheduling_started: boolean;
  status: Database["public"]["Enums"]["task_status"];
  sync_id: string;
}
| null>;
findPendingFollowUp() ​
ts
findPendingFollowUp(params: object): Promise<
  | {
  attempts: number;
  claim_token: string | null;
  claimed_at: string | null;
  created_at: string;
  details: Json | null;
  external_record_id: string;
  finished_at: string | null;
  id: number;
  is_system: boolean;
  last_error: string | null;
  operation: string;
  payload: Json | null;
  request_id: number | null;
  run_at: string;
  scheduling_key: string | null;
  scheduling_started: boolean;
  status: Database["public"]["Enums"]["task_status"];
  sync_id: string;
}
| null>;
scheduleDelayedTaskWake() ​
ts
scheduleDelayedTaskWake(task: Pick<TaskInsert, "operation" | "external_record_id" | "run_at">): void;
scheduleLocalTaskKick() ​
ts
scheduleLocalTaskKick(params: object): void;
scheduleTasks() ​
ts
scheduleTasks(tasks: Omit<{
  attempts?: number;
  claim_token?: string | null;
  claimed_at?: string | null;
  created_at?: string;
  details?: Json | null;
  external_record_id: string;
  finished_at?: string | null;
  id?: number;
  is_system?: boolean;
  last_error?: string | null;
  operation: string;
  payload?: Json | null;
  request_id?: number | null;
  run_at?: string;
  scheduling_key?: string | null;
  scheduling_started?: boolean;
  status?: Database["public"]["Enums"]["task_status"];
  sync_id: string;
}, "sync_id">[]): Promise<object[]>;
update() ​
ts
update(id: number, updates: Omit<TaskUpdate, "id" | "sync_id">): Promise<void>;
updatePendingTask() ​
ts
updatePendingTask(id: number, updates: Omit<TaskUpdate, "id" | "sync_id">): Promise<boolean>;
webhooks ​
ts
webhooks: EngineWebhookCapabilities;

EngineContextOptions ​

ts
type EngineContextOptions = {
  kind?: string;
  log: FastifyBaseLogger;
  service?: PowerService<FastifyBaseLogger>;
  sync: SyncRecord;
};

Inputs for an instance-scoped context. Resolve the engine record and enforce request authorization first. Supply a previously configured PowerService when the operation already has one.

Properties ​

kind? ​
ts
kind?: string;

Registered dispatchers can assert the expected engine kind.

log ​
ts
log: FastifyBaseLogger;
service? ​
ts
service?: PowerService<FastifyBaseLogger>;
sync ​
ts
sync: SyncRecord;

EngineDefinitionInput ​

ts
type EngineDefinitionInput<Connections extends ConnectionInputs = ConnectionInputs, Resources = void> = {
  accessTokens?: AccessTokenDefinition;
  airtableEventProcessing?: EngineDefinition["airtableEventProcessing"];
  apiVersion?: 1;
  configSchema?: EngineDefinition["configSchema"];
  connections: ConnectionDeclarations<NoInfer<Connections>>;
  cronJobs?: EngineDefinition["cronJobs"];
  emailNotifications?: readonly EmailNotificationTopic[];
  frontendBaseUrl?: string;
  hooks?: EngineServerHooks<NoInfer<Resources>>;
  lifecycle?: EngineLifecycleHooks;
  mcp?: EngineMcpDefinition;
  onboardingEmail?: EngineDefinition["onboardingEmail"];
  outgoingWebhooks?: OutgoingWebhookDefinition;
  registerAdminRoutes?: EngineDefinition["registerAdminRoutes"];
  registerRoutes?: EngineDefinition["registerRoutes"];
  reportUsage?: EngineUsageReporter;
  runtime: Omit<EngineRuntimeConfig, "connections"> & {
     connections: Connections;
  };
  setup?: EngineSetupHook<Resources>;
  tasks?: EngineTaskDefinitions;
  taskScheduling?: EngineTaskScheduling;
};

Input to defineEngine before Core fills connection identities and binds hooks. Pass the definition through defineEngine before registering it with a host.

Properties ​

accessTokens? ​
ts
accessTokens?: AccessTokenDefinition;
airtableEventProcessing? ​
ts
airtableEventProcessing?: EngineDefinition["airtableEventProcessing"];
apiVersion? ​
ts
apiVersion?: 1;
configSchema? ​
ts
configSchema?: EngineDefinition["configSchema"];
connections ​
ts
connections: ConnectionDeclarations<NoInfer<Connections>>;

Match the runtime slots. The factory fills omitted integration metadata.

cronJobs? ​
ts
cronJobs?: EngineDefinition["cronJobs"];
emailNotifications? ​
ts
emailNotifications?: readonly EmailNotificationTopic[];
frontendBaseUrl? ​
ts
frontendBaseUrl?: string;

Override the application's default frontend URL for this engine kind.

hooks? ​
ts
hooks?: EngineServerHooks<NoInfer<Resources>>;
lifecycle? ​
ts
lifecycle?: EngineLifecycleHooks;
mcp? ​
ts
mcp?: EngineMcpDefinition;
onboardingEmail? ​
ts
onboardingEmail?: EngineDefinition["onboardingEmail"];
outgoingWebhooks? ​
ts
outgoingWebhooks?: OutgoingWebhookDefinition;
registerAdminRoutes? ​
ts
registerAdminRoutes?: EngineDefinition["registerAdminRoutes"];
registerRoutes? ​
ts
registerRoutes?: EngineDefinition["registerRoutes"];
reportUsage? ​
ts
reportUsage?: EngineUsageReporter;
runtime ​
ts
runtime: Omit<EngineRuntimeConfig, "connections"> & {
  connections: Connections;
};
Type Declaration ​
connections ​
ts
connections: Connections;
setup? ​
ts
setup?: EngineSetupHook<Resources>;
tasks? ​
ts
tasks?: EngineTaskDefinitions;
taskScheduling? ​
ts
taskScheduling?: EngineTaskScheduling;

EngineFactory ​

ts
type EngineFactory<Config, Definition extends ReturnType<typeof defineEngine> = ReturnType<typeof defineEngine>> = (config: Config) => Definition;

A package's configured entry point. The host calls it before registering the definition.


EngineLifecycleHooks ​

ts
type EngineLifecycleHooks = {
  activate?: (args: EngineActivationArgs) => Promise<EngineLifecycleResult | void>;
  afterActivate?: (args: EngineLifecycleArgs) => Promise<void>;
  beforeActivate?: (args: EngineLifecycleArgs) => Promise<void>;
  beforeDelete?: (args: EngineLifecycleArgs) => Promise<void>;
  deactivate?: (args: EngineLifecycleArgs) => Promise<EngineLifecycleResult | void>;
};

Customize activation, deactivation, and deletion of a stored engine instance.

Remarks ​

Use EngineSetupHook for resources scoped to a server registration. Activation holds the lifecycle lock through persistence. afterActivate runs after persistence and outside the lock, so its failure leaves the instance active.

Properties ​

activate? ​
ts
activate?: (args: EngineActivationArgs) => Promise<EngineLifecycleResult | void>;

Use provisioned managed webhooks and return any engine-owned fields to persist on activation.

afterActivate? ​
ts
afterActivate?: (args: EngineLifecycleArgs) => Promise<void>;

Run follow-up work after activation is persisted. The supplied record is the pre-update snapshot.

beforeActivate? ​
ts
beforeActivate?: (args: EngineLifecycleArgs) => Promise<void>;

Check activation prerequisites before Core provisions managed resources.

beforeDelete? ​
ts
beforeDelete?: (args: EngineLifecycleArgs) => Promise<void>;

Clean up engine-owned data before the deletion task removes the instance.

deactivate? ​
ts
deactivate?: (args: EngineLifecycleArgs) => Promise<EngineLifecycleResult | void>;

Clean up engine-owned resources before Core removes the managed Airtable webhook.


EngineLifecycleResult ​

ts
type EngineLifecycleResult = {
  payload?: Record<string, unknown>;
  update?: Partial<SyncRecord>;
};

Return engine-owned instance fields to persist and optional data for the caller. Core manages the active state and the fields for managed webhooks.

Properties ​

payload? ​
ts
payload?: Record<string, unknown>;
update? ​
ts
update?: Partial<SyncRecord>;

EngineRegistration ​

ts
type EngineRegistration<Context extends ServerContext = ServerContext> = 
  | PortableEngineDefinition<Context>
| BoundEngineDefinition<Context>;

A definition accepted in the server's engines map. Build new definitions with defineEngine and use the runtime kind as the registration key.


EngineRuntimeConfig ​

ts
type EngineRuntimeConfig = {
  airtableEventProcessing?: {
     maxImmediateTasks: number | null;
  };
  connections: BuiltinEngineConnectionConfigs;
  kind: string;
};

Resolved runtime metadata shared by an engine and its dashboard.

Properties ​

airtableEventProcessing? ​
ts
airtableEventProcessing?: {
  maxImmediateTasks: number | null;
};
maxImmediateTasks ​
ts
maxImmediateTasks: number | null;
Deprecated ​

Backend-only: use defineEngine.airtableEventProcessing.

connections ​
ts
connections: BuiltinEngineConnectionConfigs;
kind ​
ts
kind: string;

EngineServerHooks ​

ts
type EngineServerHooks<Resources = unknown> = {
  beforeServerShutdown?(args: SetupContext & {
     resources: Resources;
  }): void | Promise<void>;
};

Hooks for the lifetime of a server registration.

Methods ​

beforeServerShutdown()? ​
ts
beforeServerShutdown?(args: SetupContext & {
  resources: Resources;
}): void | Promise<void>;

Release resources from setup after workers stop and before Core closes its infrastructure.

Parameters ​
  • args. The resources field is undefined when setup is omitted.

EngineSetupHook ​

ts
type EngineSetupHook<Resources = void> = (context: SetupContext) => Resources | Promise<Resources>;

Initialize resources once per server registration, before worker startup.

Returns ​

Resources passed to hooks.beforeServerShutdown for the same server registration.

Remarks ​

Setup runs even with background jobs disabled. If setup fails, it must clean up resources it acquired before throwing because its shutdown hook has not been registered yet.


EngineTaskDefinition ​

ts
type EngineTaskDefinition<Operation extends TaskOperation> = {
  allowFastExecution?: boolean;
  concurrency?: number;
  executionPolicy?:   | TaskExecutionPolicy
     | ((task: TaskRow) => TaskExecutionPolicy);
  executionTimeoutMs?: number;
  failureContinuation?:   | TaskChainPayload
     | ((task: TaskRow) => TaskChainPayload);
  handler: EngineTaskHandler<Operation>;
  worker: "fast" | "background";
};

Register a handler with its worker lane and attempt limits. The default execution policy requires an active engine instance. Keep policy callbacks read-only. Write durable side effects in the handler.

Properties ​

allowFastExecution? ​
ts
allowFastExecution?: boolean;
concurrency? ​
ts
concurrency?: number;
executionPolicy? ​
ts
executionPolicy?: 
  | TaskExecutionPolicy
  | ((task: TaskRow) => TaskExecutionPolicy);
executionTimeoutMs? ​
ts
executionTimeoutMs?: number;
failureContinuation? ​
ts
failureContinuation?: 
  | TaskChainPayload
  | ((task: TaskRow) => TaskChainPayload);
handler ​
ts
handler: EngineTaskHandler<Operation>;
worker ​
ts
worker: "fast" | "background";

EngineTaskDefinitions ​

ts
type EngineTaskDefinitions = { [Operation in TaskOperation]?: EngineTaskDefinition<Operation> };

Register an engine's executable handlers by operation. Declare app-specific payloads through TaskPayloadByOperation before using those keys here.


EngineTaskHandler ​

ts
type EngineTaskHandler<Operation extends TaskOperation = TaskOperation> = (args: EngineTaskHandlerArgs<Operation>) => Promise<void>;

Process one claimed attempt with the current engine context and abort signal. The worker marks a normally returned, unfinalized attempt successful. Throw failures so the worker can apply retry or terminal handling.


EngineTaskHandlerArgs ​

ts
type EngineTaskHandlerArgs<Operation extends TaskOperation> = {
  context: EngineContext;
  run: TaskRun;
  signal: AbortSignal;
  task: Omit<TaskRow, "operation" | "payload"> & object;
};

Properties ​

context ​
ts
context: EngineContext;
run ​
ts
run: TaskRun;
signal ​
ts
signal: AbortSignal;
task ​
ts
task: Omit<TaskRow, "operation" | "payload"> & object;
Type Declaration ​
operation ​
ts
operation: Operation;
payload ​
ts
payload: TaskPayload<Operation> | null;

EngineTaskInput ​

ts
type EngineTaskInput<Operation extends TaskOperation> = {
  details?: TaskRow["details"];
  external_record_id: string;
  is_system?: TaskRow["is_system"];
  payload: TaskPayload<Operation>;
  reuseExisting?: boolean;
  run_at?: string;
};

Input to context.tasks.enqueue. The context supplies the engine ID. Choose a stable external_record_id within the engine and operation for redelivery.

Properties ​

details? ​
ts
details?: TaskRow["details"];
external_record_id ​
ts
external_record_id: string;
is_system? ​
ts
is_system?: TaskRow["is_system"];
payload ​
ts
payload: TaskPayload<Operation>;
reuseExisting? ​
ts
reuseExisting?: boolean;

Reuse the stored identity and wake due pending work. Broken tasks remain broken.

run_at? ​
ts
run_at?: string;

EngineTaskScheduling ​

ts
type EngineTaskScheduling = { [Operation in TaskOperation]?: TaskScheduling<Operation> };

Attach scheduling by operation to the engine definition. Shared platform handlers can use these policies. Register the handlers separately.


EnvDefinition ​

ts
type EnvDefinition = {
  callbackPath?: string;
  description?: string;
  format?: "url" | "email";
  group?: string;
  label?: string;
  options?: readonly string[];
  providerSetup?: ProviderSetup;
  required?: boolean;
  secret?: boolean;
  setupUrl?: string;
};

Application-owned backend settings. Definitions contain metadata, never values.

Properties ​

callbackPath? ​
ts
callbackPath?: string;
description? ​
ts
description?: string;
format? ​
ts
format?: "url" | "email";
group? ​
ts
group?: string;
label? ​
ts
label?: string;
options? ​
ts
options?: readonly string[];
providerSetup? ​
ts
providerSetup?: ProviderSetup;
required? ​
ts
required?: boolean;
secret? ​
ts
secret?: boolean;
setupUrl? ​
ts
setupUrl?: string;

PortableEngineDefinition ​

ts
type PortableEngineDefinition<Context extends ServerContext = ServerContext> = Omit<EngineDefinition<BuiltinEngineConnectionConfigs, Context>, "connections" | "lifecycle" | "lifecycleDefinition" | "setup" | "tasks"> & object;

Type Declaration ​

apiVersion ​
ts
apiVersion: 1;
connections ​
ts
connections: EngineConnectionBindings;
lifecycle? ​
ts
lifecycle?: EngineLifecycleHooks;
setup? ​
ts
setup?: EngineSetupHook<unknown>;
tasks? ​
ts
tasks?: EngineTaskDefinitions;

RuntimeServiceConfig ​

ts
type RuntimeServiceConfig = {
  auth?:   | AuthDependencies
     | ((supabase: RuntimeServices["supabaseMaster"]) => AuthDependencies);
  branding?: EmailServiceConfig["branding"];
  credentials?: Omit<ConstructorParameters<typeof CredentialService>[0], "keyRepo">;
  decision?: DecisionServiceConfig;
  llm?: LlmServiceDependencies;
  localAirtable?: LocalAirtableConfig;
  localSlack?: LocalSlackConfig;
  mode?: ServerRuntimeMode;
  postmark?: Omit<EmailServiceConfig, "defaultProduct" | "branding">;
  productName?: string;
  supabase?: Parameters<typeof createSupabaseResources>[0] & {
     authHookSecret?: string;
  };
};

Configuration shared by the host's server services. Applications ordinarily set these on ServerConfig and keep provider secrets on the backend.

Properties ​

auth? ​
ts
auth?: 
  | AuthDependencies
  | ((supabase: RuntimeServices["supabaseMaster"]) => AuthDependencies);
branding? ​
ts
branding?: EmailServiceConfig["branding"];
credentials? ​
ts
credentials?: Omit<ConstructorParameters<typeof CredentialService>[0], "keyRepo">;
decision? ​
ts
decision?: DecisionServiceConfig;
llm? ​
ts
llm?: LlmServiceDependencies;
localAirtable? ​
ts
localAirtable?: LocalAirtableConfig;
localSlack? ​
ts
localSlack?: LocalSlackConfig;
mode? ​
ts
mode?: ServerRuntimeMode;
postmark? ​
ts
postmark?: Omit<EmailServiceConfig, "defaultProduct" | "branding">;
productName? ​
ts
productName?: string;
supabase? ​
ts
supabase?: Parameters<typeof createSupabaseResources>[0] & {
  authHookSecret?: string;
};
Type Declaration ​
authHookSecret? ​
ts
authHookSecret?: string;

ServerBuildOptions ​

ts
type ServerBuildOptions = Omit<BuildOptions, "entryPoints" | "plugins"> & object;

Type Declaration ​

extra? ​
ts
extra?: Pick<BuildOptions, "entryPoints" | "plugins">;
validateExternalDependencies? ​
ts
validateExternalDependencies?: boolean;

Require external packages in the invoking app's production dependencies. Defaults to true for workspace apps.


ServerConfig ​

ts
type ServerConfig<Context extends ServerContext = ServerContext> = Omit<RuntimeServiceConfig, "postmark" | "credentials"> & object;

Host settings for one server, including provider credentials and background jobs.

Type Declaration ​

accountDeletion? ​
ts
accountDeletion?: Context["accountDeletion"];
brokenTaskEmail? ​
ts
brokenTaskEmail?: Context["brokenTaskEmail"];
credentials? ​
ts
credentials?: 
  | CredentialConfig & {
  keys?: never;
}
  | {
  activeKeyVersion: CredentialConfig["activeKeyVersion"];
  keys: Partial<Record<CredentialConfig["activeKeyVersion"], string | undefined>>;
  resolveKey?: never;
};
firstEngineEmail? ​
ts
firstEngineEmail?: Context["firstEngineEmail"];
frontendBaseUrl? ​
ts
frontendBaseUrl?: string;
getFrontendBaseUrl? ​
ts
getFrontendBaseUrl?: FrontendUrlConfig["getFrontendBaseUrl"];
getProductForUrl? ​
ts
getProductForUrl?: FrontendUrlConfig["getProductForUrl"];
jobsEnabled? ​
ts
jobsEnabled?: boolean;
localWebhooks? ​
ts
localWebhooks?: boolean;
logger ​
ts
logger: FastifyServerOptions["logger"];
mailpit? ​
ts
mailpit?: boolean;
maintenance? ​
ts
maintenance?: (context: Context, log: FastifyBaseLogger, resources: RedisResources) => ServerMaintenanceOptions;
mcp? ​
ts
mcp?: McpConfig;
mcpOAuth? ​
ts
mcpOAuth?: McpOAuthConfig & {
  createTokenStore: (supabase: ServerContext["supabaseMaster"]) => McpOAuthTokenStore;
};
Type Declaration ​
createTokenStore ​
ts
createTokenStore: (supabase: ServerContext["supabaseMaster"]) => McpOAuthTokenStore;
postmark? ​
ts
postmark?: Omit<PostmarkConfig, "serverToken" | "fromEmail"> & { [Key in "serverToken" | "fromEmail"]?: PostmarkConfig[Key] };
publicApi? ​
ts
publicApi?: PublicApiUrlConfig & {
  baseUrl?: string;
};
Type Declaration ​
baseUrl? ​
ts
baseUrl?: string;
redis? ​
ts
redis?: object;
redis.cacheEncryptionKey? ​
ts
cacheEncryptionKey?: RedisResourceOptions["redisCacheEncryptionKey"];
redis.client? ​
ts
client?: RedisResourceOptions["redis"];
redis.tcpClient? ​
ts
tcpClient?: RedisResourceOptions["redisTcp"];
redis.url? ​
ts
url?: RedisResourceOptions["redisUrl"];
runtime? ​
ts
runtime?: Omit<RuntimeContextConfig, "slackWebhook">;
sentry? ​
ts
sentry?: SentryConfig | false;
slackWebhook? ​
ts
slackWebhook?: RuntimeContextConfig["slackWebhook"];
startupTaskRecovery? ​
ts
startupTaskRecovery?: boolean;
trustProxy? ​
ts
trustProxy?: FastifyServerOptions["trustProxy"];
webhookPathPrefix? ​
ts
webhookPathPrefix?: string;
workerShutdownTimeoutMs? ​
ts
workerShutdownTimeoutMs?: number;

Remarks ​

Resolve environment values in the host before calling createServer. Keep this configuration server-side. jobsEnabled controls cron registration, and startupTaskRecovery controls recovery when the server starts listening.


SetupContext ​

ts
type SetupContext = {
  context: ServerContext;
  getPublicApiBaseUrl?: () => string | Promise<string>;
  jobsEnabled: boolean;
  log: EngineContextOptions["log"];
  redis: RedisLike;
  redisCacheEncryptionKey?: string;
};

Host infrastructure for one-time engine initialization, without an instance.

Properties ​

context ​
ts
readonly context: ServerContext;
getPublicApiBaseUrl? ​
ts
readonly getPublicApiBaseUrl?: () => string | Promise<string>;
jobsEnabled ​
ts
readonly jobsEnabled: boolean;
log ​
ts
readonly log: EngineContextOptions["log"];
redis ​
ts
readonly redis: RedisLike;
redisCacheEncryptionKey? ​
ts
readonly redisCacheEncryptionKey?: string;

SlackEventHookArgs ​

ts
type SlackEventHookArgs = {
  allowMessageEvent?: boolean;
  botUserId?: string;
  context: EngineContext;
  event: SlackEvent;
  parentMessage?: SlackParentMessage;
  slackTeamId?: string;
  syncRecord: SyncRecord;
};

One Slack event already matched to an engine instance. Parent message metadata is available when an earlier message was associated with the instance.

Properties ​

allowMessageEvent? ​
ts
allowMessageEvent?: boolean;
botUserId? ​
ts
botUserId?: string;
context ​
ts
context: EngineContext;
event ​
ts
event: SlackEvent;
parentMessage? ​
ts
parentMessage?: SlackParentMessage;
slackTeamId? ​
ts
slackTeamId?: string;
syncRecord ​
ts
syncRecord: SyncRecord;

Selected by webhook routing before the event hook runs.


SlackFormSubmissionHookArgs ​

ts
type SlackFormSubmissionHookArgs = SlackInteractionHookArgs;

Raw Slack view submission payload and the matched engine context.


SlackFormSubmissionResult ​

ts
type SlackFormSubmissionResult = 
  | Record<string, never>
  | {
  errors: Record<string, string>;
  response_action: "errors";
}
  | {
  response_action: "update";
  view: Record<string, unknown>;
};

Response used to acknowledge a Slack view submission or report field errors.


SlackHooks ​

ts
type SlackHooks = {
  handleEvent?: (args: SlackEventHookArgs) => Promise<boolean>;
  handleFormSubmission?: (args: SlackFormSubmissionHookArgs) => Promise<SlackFormSubmissionResult>;
  handleInteraction?: (args: SlackInteractionHookArgs) => Promise<void>;
  handleThreadMessage?: (args: SlackThreadMessageHookArgs) => Promise<void>;
};

Handle Slack events and interactions after Core matches the installed engine instance. Use the supplied context for its provider services. Validate the fields your hook reads from raw interaction payloads.

Properties ​

handleEvent? ​
ts
handleEvent?: (args: SlackEventHookArgs) => Promise<boolean>;
handleFormSubmission? ​
ts
handleFormSubmission?: (args: SlackFormSubmissionHookArgs) => Promise<SlackFormSubmissionResult>;
handleInteraction? ​
ts
handleInteraction?: (args: SlackInteractionHookArgs) => Promise<void>;
handleThreadMessage? ​
ts
handleThreadMessage?: (args: SlackThreadMessageHookArgs) => Promise<void>;

TaskChainPayload ​

ts
type TaskChainPayload = {
  chain_failure_policy?: TaskChainFailurePolicy;
  next_task?: TaskChainNextTask;
};

Properties ​

chain_failure_policy? ​
ts
chain_failure_policy?: TaskChainFailurePolicy;
next_task? ​
ts
next_task?: TaskChainNextTask;

TaskExecutionPolicy ​

ts
type TaskExecutionPolicy = {
  allowInactiveEngine?: boolean;
  forceBroken?: boolean;
  requiresEngineRecord?: boolean;
};

Properties ​

allowInactiveEngine? ​
ts
allowInactiveEngine?: boolean;

Allow a task to run for an inactive engine. Defaults to false.

forceBroken? ​
ts
forceBroken?: boolean;

Mark the task broken when the worker handles an error. Defaults to false.

requiresEngineRecord? ​
ts
requiresEngineRecord?: boolean;

Require the engine record to exist. Defaults to true.


TaskOperation ​

ts
type TaskOperation = Extract<keyof TaskPayloadByOperation, string>;

TaskPayload ​

ts
type TaskPayload<T extends TaskOperation> = TaskPayloadByOperation[T];

TaskScheduling ​

ts
type TaskScheduling<Operation extends TaskOperation> = {
  delayMs?: number | ((input: TaskSchedulingInput<Operation>) => number);
  key: (payload: TaskPayload<Operation>) => string;
  policy: "keepLatest";
};

Schedule the latest pending payload per engine, operation and key. New arrivals replace the pending successor and reset its deadline. Running attempts and retries keep their own identity and payload.

Properties ​

delayMs? ​
ts
delayMs?: number | ((input: TaskSchedulingInput<Operation>) => number);
key ​
ts
key: (payload: TaskPayload<Operation>) => string;
policy ​
ts
policy: "keepLatest";