Kit API
| Use | Import from | API |
|---|---|---|
| Define an engine | @kambium/kit | defineEngine, EngineDefinitionInput, EngineFactory, EngineContext |
| Initialize and clean up resources | @kambium/kit | EngineSetupHook, SetupContext, EngineServerHooks, EngineLifecycleHooks |
| Handle provider events | @kambium/kit | EngineConnectionBindings, AirtableHooks, SlackHooks, EngineActivationArgs, EngineLifecycleResult |
| Share engine metadata | @kambium/kit/shared/engine-runtime, @kambium/kit/shared/engine-connection-config | defineEngineRuntime, EngineRuntimeConfig, resolveConnectionId, EngineConnectionConfig |
| Run a server | @kambium/kit/server | createServer, shutdownServer, CreateServerOptions, ServerConfig, ServerContext, EngineRegistration |
| Configure and build the app | @kambium/kit/shared/env, @kambium/kit/build | defineEnv, EnvDefinition, buildServer, ServerBuildOptions |
| Define a task and its execution policy | @kambium/kit | EngineTaskDefinitions, EngineTaskHandlerArgs, TaskExecutionPolicy, EngineTaskInput |
| Schedule or finish a task | @kambium/kit | EngineTaskScheduling, TaskScheduling, TaskRun, PermanentError |
| Register task payloads or Airtable handlers | @kambium/kit/shared/types, @kambium/kit/server/tasks/airtable | TaskPayloadByOperation, TaskChainPayload, TaskOperation, TaskPayload, createAirtableTasks |
| Declare and bind HTTP routes | @kambium/kit/server/routes/define-route, @kambium/kit/server/routes/endpoint | defineRoute, defineEndpointRoute, EndpointReply |
| Call typed JSON endpoints | @kambium/kit/endpoint, @kambium/kit/frontend/ui-client | defineEndpoint, 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()
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()
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()
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
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()
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()
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()
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()
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()
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()
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()
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()
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()
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
new PermanentError(message?: string): PermanentError;Inherited from
Error.constructor
Constructor
new PermanentError(message?: string, options?: ErrorOptions): PermanentError;Inherited from
Error.constructor
Properties
| Property | Type |
|---|---|
permanent | true |
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
AccountDeletionHooksRedisResources
Methods
advanceAccountDeletion()
advanceAccountDeletion(params: object): Promise<Pick<UserDeletionRequestRow, "status" | "phase">>;beforeDeleteEngine()
beforeDeleteEngine(params: object): Promise<void>;checkEngineAccessUncached()
checkEngineAccessUncached(userId: string, engineId: string): Promise<boolean>;createSupabaseUserClient()
createSupabaseUserClient(userToken: string): SupabaseClient<any>;Scope database reads and writes to the verified caller's bearer token and RLS policies.
deactivateEngine()
deactivateEngine(params: object): Promise<void>;getActivationBaseUrl()
getActivationBaseUrl(): Promise<string>;getEngineAirtableHooks()
getEngineAirtableHooks(kind: string):
| Omit<AirtableHooks, "enqueueDelayedTasks">
| undefined;getEngineConnections()
getEngineConnections(kind: string): BuiltinEngineConnectionConfigs;getEngineLifecycleDefinition()
getEngineLifecycleDefinition(kind: string): EngineLifecycleDefinition;getEngineSlackMentionHandler()
getEngineSlackMentionHandler(kind: string): SlackMentionAiHandler | undefined;getExternalPostgres()
getExternalPostgres(sync: Pick<SyncRecord, "id" | "user_id" | "kind">): Promise<ExternalPostgresConnectionService>;hasEngineKind()
hasEngineKind(kind: string): boolean;initAirtableOAuthService()
initAirtableOAuthService(options?: object): AirtableOAuthService;initAuthService()
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()
initCredentialService(): CredentialService;initDecisionService()
initDecisionService(log: EngineLogger): DecisionService;initEngineContext()
initEngineContext(options: EngineContextOptions): EngineContext;initNangoService()
initNangoService(): NangoService;initPowerService()
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()
initSchemaCacheService(powerService: PowerService): SchemaCacheService;initSlackOAuthService()
initSlackOAuthService(options?: object): SlackOAuthService;invalidateEngineAccess()
invalidateEngineAccess(): Promise<void>;isDevTarget()
isDevTarget(): boolean;scheduleEngineDisabledNotification()
scheduleEngineDisabledNotification(input: object): Promise<void>;validateEngineConfig()
validateEngineConfig(kind: string, value: Json): void;Properties
| Property | Type | Default value | Description | Inherited from |
|---|---|---|---|---|
accountDeletion? | AccountDeletionConfig | undefined | - | - |
afterEngineActivate? | ServerActivationHook | undefined | Runs after the engine hook, persistence and lock release; failures propagate without rollback. | - |
airtableMcp | AirtableMcpService | undefined | - | - |
airtableWebhook? | AirtableWebhookNotifications | undefined | - | - |
airtableWebhookDeletionEmail? | () => Pick<EmailService, "sendAdminEmail"> | undefined | - | - |
authorizeAccountDeletion? | (input: { userId: string; }) => Promise<void> | undefined | Eligibility check during request, confirmation preview and confirmation, before cleanup is scheduled. | AccountDeletionHooks.authorizeAccountDeletion |
authorizeEngineCreation? | (input: CreationAuthorizationInput & { data: object; }) => Promise< | void | { message: string; }> | undefined | Runs 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> | undefined | A 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> | undefined | Awaited before operational cleanup. Must tolerate retries and overlapping attempts for the same request. | AccountDeletionHooks.beforeAccountCleanup |
beforeEngineActivate? | ServerActivationHook | undefined | Runs after initial access/state checks and before acquiring the activation lock. | - |
brokenTaskEmail? | false | BrokenTaskEmailConfig | undefined | - | - |
cronJobs? | readonly ScheduledTask[] | undefined | - | - |
firstEngineEmail? | false | FirstEngineEmailConfig | undefined | - | - |
frontendUrls? | FrontendUrlConfig | undefined | - | - |
getEngineRuntimeConfigs? | () => readonly Pick<EngineRuntimeConfig, "connections" | "kind">[] | undefined | - | - |
getWorkspaceInvitationBaseUrl? | (product: string) => string | Promise<string | undefined> | undefined | undefined | - | - |
initEmailService? | () => EmailService | undefined | - | - |
initLlmService | () => LlmService | undefined | - | - |
localAirtable? | LocalAirtableConfig | undefined | - | - |
localSlack? | LocalSlackConfig | undefined | - | - |
maintenance? | ServerMaintenanceOptions | undefined | - | - |
mcp? | McpService | undefined | - | - |
mcpOAuth? | McpOAuthService | undefined | - | - |
mode? | ServerRuntimeMode | undefined | - | - |
redis | RedisLike | undefined | - | RedisResources.redis |
redisCacheEncryptionKey | string | undefined | options.redisCacheEncryptionKey | - | RedisResources.redisCacheEncryptionKey |
repos | object | undefined | - | - |
repos.connectedAccountsMasterRepo | ConnectedAccountsMasterRepo | ... | - | - |
repos.keyRepo | KeyRepository | ... | - | - |
repos.lockRepo | LockRepository | ... | - | - |
repos.slackAttachmentMasterRepo | SlackAttachmentMasterRepo | ... | - | - |
repos.slackMessageRepo | SlackMessageRepo | ... | - | - |
repos.slackReactionFlowRecordRepo | SlackReactionFlowRecordRepo | ... | - | - |
repos.slackReplyFlowRecordRepo | SlackReplyFlowRecordRepo | ... | - | - |
repos.slackThreadAiOperationRepo | SlackThreadAiOperationRepo | ... | - | - |
repos.subscriptionsMasterRepo | SubscriptionsMasterRepo | ... | - | - |
repos.syncMasterRepo | SyncMasterRepo | ... | - | - |
repos.taskEventRepo | TaskEventRepo | ... | - | - |
repos.taskMasterRepo | TaskMasterRepo | ... | - | - |
repos.usageSnapshotRepo | UsageSnapshotRepository | ... | - | - |
repos.userDeletionRequestRepo | UserDeletionRequestRepo | ... | - | - |
slackWebhook? | SlackWebhookRuntime | undefined | - | - |
supabaseAuthHookSecret? | string | undefined | - | - |
supabaseMaster | SupabaseClient<any> | undefined | - | - |
supabaseUrl? | string | undefined | - | - |
taskFailureRuntime? | TaskFailureRuntime | undefined | - | - |
taskManager? | TaskDispatcher | undefined | - | - |
webhookPathPrefix? | string | undefined | - | - |
TaskPayloadByOperation
Persisted payloads keyed by operation. Applications may extend this interface through module augmentation; TaskOperation and task APIs then include those keys.
Properties
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()
deferEvent(event: TaskEvent): void;fail()
fail(
err: unknown,
message?: string,
details?: Json,
options?: object
): Promise<void>;Apply retry classification and record failure. Ordinary handlers can throw instead.
failInactiveEngine()
failInactiveEngine(): Promise<void>;finalizeWithoutEvent()
finalizeWithoutEvent(): Promise<void>;getFinalStatus()
getFinalStatus(): "error" | "success" | "skipped" | undefined;isFinalized()
isFinalized(): boolean;logEvent()
logEvent(
status: "error" | "progress" | "success",
message?: string,
details?: Json
): Promise<void>;logMessage()
logMessage(message: string, details?: Json): void;Record a progress event without finalizing the attempt.
reschedule()
reschedule(runAt: string): Promise<void>;Return the task to pending for a later time without consuming the attempt.
skip()
skip(message?: string, details?: Json): Promise<void>;Finish the task as done with a skipped result for this attempt.
success()
success(message?: string, details?: Json): Promise<void>;Mark the task done and clear its payload after required work succeeds.
warn()
warn(message: string, details?: Json): void;Record a progress event with warning severity.
Properties
Type Aliases
AirtableDefaultHooks
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?
enqueueDelayedTasks?: (args: AirtableDelayedTasksArgs) => Promise<void>;handleRecordChange?
handleRecordChange?: (args: AirtableRecordChangeHookArgs) => Promise<void>;handleSchemaChange?
handleSchemaChange?: (args: AirtableSchemaChangeHookArgs) => Promise<void>;preparePayloads?
preparePayloads?: (args: AirtablePayloadsHookArgs) => Promise<{
ignoredAutoNumberFieldCount?: number;
payloads: AirtableWebhookPayloadRaw[];
}>;Prepare one fetched page before default task planning. Does not own persistence.
prepareRecordChangeTask?
prepareRecordChangeTask?: (args: AirtablePrepareRecordChangeArgs) => Promise<AirtableRecordChangeTaskPlan | null>;prepareSchemaChangeTask?
prepareSchemaChangeTask?: (args: object) => Promise<AirtableSchemaChangeTaskPlan | null>;Schema tasks are skipped when both this hook and handleSchemaChange are omitted.
AirtableHooks
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
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
context: EngineContext;payloads
payloads: AirtableWebhookPayloadRaw[];signal?
signal?: AbortSignal;AirtablePayloadsResult
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?
attemptedImmediateTaskCount?: number;delayedTaskCount?
delayedTaskCount?: number;ignoredAutoNumberFieldCount?
ignoredAutoNumberFieldCount?: number;recordCount
recordCount: number;schemaCount
schemaCount: number;suppliedImmediateTaskCount?
suppliedImmediateTaskCount?: number;taskCount?
taskCount?: number;AirtableRecordChange
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
taskId: number;AirtableRecordChangeHookArgs
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
change: AirtableRecordChange;context
context: EngineContext;logWebhook
logWebhook: EngineWebhookLogger;signal?
signal?: AbortSignal;The task's cancellation signal, when the hook runs through a worker.
syncRecord
syncRecord: SyncRecord;taskRun
taskRun: TaskRun;CreateServerOptions
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
config: ServerConfig<Context>;cronJobs?
cronJobs?: readonly EngineCronJobFactory<Context>[];engines
engines: Readonly<Record<string, EngineRegistration<Context>>>;hooks?
hooks?: RuntimeHooks<Context> & object;Type Declaration
afterEngineActivate?
afterEngineActivate?: (input: Parameters<NonNullable<Context["afterEngineActivate"]>>[0] & {
context: Context;
}) => Promise<void>;authorizeAccountDeletion?
authorizeAccountDeletion?: (input: Parameters<NonNullable<Context["authorizeAccountDeletion"]>>[0] & {
context: Context;
}) => Promise<void>;authorizeEngineCreation?
authorizeEngineCreation?: (input: Parameters<NonNullable<Context["authorizeEngineCreation"]>>[0] & {
context: Context;
}) => ReturnType<NonNullable<Context["authorizeEngineCreation"]>>;authorizeWorkspaceBootstrap?
authorizeWorkspaceBootstrap?: (input: Parameters<NonNullable<Context["authorizeWorkspaceBootstrap"]>>[0] & {
context: Context;
}) => ReturnType<NonNullable<Context["authorizeWorkspaceBootstrap"]>>;authorizeWorkspaceCreation?
authorizeWorkspaceCreation?: (input: Parameters<NonNullable<Context["authorizeWorkspaceCreation"]>>[0] & {
context: Context;
}) => ReturnType<NonNullable<Context["authorizeWorkspaceCreation"]>>;beforeAccountCleanup?
beforeAccountCleanup?: (input: Parameters<NonNullable<Context["beforeAccountCleanup"]>>[0] & {
context: Context;
}) => Promise<void>;beforeEngineActivate?
beforeEngineActivate?: (input: Parameters<NonNullable<Context["beforeEngineActivate"]>>[0] & {
context: Context;
}) => Promise<void>;brokenTask?
brokenTask?: BrokenTaskHook<Context>;onEvent?
onEvent?: ServerEventHook;reportError?
reportError?: ErrorReportHook;tasks
tasks: TaskDefinitions<Context>;testing?
testing?: {
dependencies?: RuntimeDependencies;
};testing.dependencies?
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
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]?
readonly [response]?: readonly [unknown];body?
body?: z.ZodType;method
method: "GET" | "POST";query?
query?: z.ZodObject;url
url: string;EndpointArguments
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?
signal?: AbortSignal;EndpointCatalog
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
type EndpointReply<E extends Endpoint, ErrorBody = {
message: string;
}> = FastifyReply<{
Params: EndpointParams<E>;
Reply: EndpointReplies<E, ErrorBody>;
}>;EndpointResponse
type EndpointResponse<E extends Endpoint> = NonNullable<E[typeof response]>[0];EngineActivationArgs
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
context: EngineContext;sync
sync: SyncRecord;webhooks
webhooks: Readonly<Record<string, Readonly<DirectWebhookInfo>>>;EngineConnectionBindings
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
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
id:
| Id
| {
development: Id;
production: Id;
};provider
provider: Provider;EngineContext
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()
claimSchemaRefresh(): Promise<boolean>;collectSchemaEvents()
collectSchemaEvents(change: AirtableSchemaChange): Promise<SchemaLogEvent[]>;deactivateEngine()
deactivateEngine(options: {
error: string;
}): Promise<void>;getExternalPostgres()
getExternalPostgres(): Promise<ExternalPostgresConnectionService>;initAuthService()
initAuthService(): AuthService;initEmailService()
initEmailService(): EmailService;initLlmService()
initLlmService(): LlmService;serializeEntries()
serializeEntries(entries: [string, unknown][]): Record<string, unknown>;withAirtableRequestPolicy()
withAirtableRequestPolicy(policy: {
requestExpirationMs: number;
}): object;Properties
airtable
readonly airtable: AirtableService;Scoped Airtable client. Fetch one record or use listRecords with its offset for paging.
airtableMcp
readonly airtableMcp: AirtableMcpService;airtableRecordCache
readonly airtableRecordCache: RecordCacheService;credentials
readonly credentials: CredentialService;decision
readonly decision: DecisionService;log
log: EngineLogger;power
readonly power: PowerService;repos
readonly repos: Omit<ServerRepositories, "slackAttachmentMasterRepo"> & {
slackAttachmentRepo: SlackAttachmentRepo;
};Type Declaration
slackAttachmentRepo
slackAttachmentRepo: SlackAttachmentRepo;schema
readonly schema: SchemaCacheService;slack
readonly slack: SlackService;Scoped Slack client. Retain the channel and timestamp returned by createMessage.
supabaseMaster
readonly supabaseMaster: SupabaseClient<Database>;sync
readonly sync: SyncRecord;taskManager?
readonly taskManager?: TaskDispatcher;tasks
tasks: object;localTaskKicksEnabled
readonly localTaskKicksEnabled: boolean;enqueue()
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()
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()
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()
scheduleDelayedTaskWake(task: Pick<TaskInsert, "operation" | "external_record_id" | "run_at">): void;scheduleLocalTaskKick()
scheduleLocalTaskKick(params: object): void;scheduleTasks()
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()
update(id: number, updates: Omit<TaskUpdate, "id" | "sync_id">): Promise<void>;updatePendingTask()
updatePendingTask(id: number, updates: Omit<TaskUpdate, "id" | "sync_id">): Promise<boolean>;webhooks
webhooks: EngineWebhookCapabilities;EngineContextOptions
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?
kind?: string;Registered dispatchers can assert the expected engine kind.
log
log: FastifyBaseLogger;service?
service?: PowerService<FastifyBaseLogger>;sync
sync: SyncRecord;EngineDefinitionInput
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?
accessTokens?: AccessTokenDefinition;airtableEventProcessing?
airtableEventProcessing?: EngineDefinition["airtableEventProcessing"];apiVersion?
apiVersion?: 1;configSchema?
configSchema?: EngineDefinition["configSchema"];connections
connections: ConnectionDeclarations<NoInfer<Connections>>;Match the runtime slots. The factory fills omitted integration metadata.
cronJobs?
cronJobs?: EngineDefinition["cronJobs"];emailNotifications?
emailNotifications?: readonly EmailNotificationTopic[];frontendBaseUrl?
frontendBaseUrl?: string;Override the application's default frontend URL for this engine kind.
hooks?
hooks?: EngineServerHooks<NoInfer<Resources>>;lifecycle?
lifecycle?: EngineLifecycleHooks;mcp?
mcp?: EngineMcpDefinition;onboardingEmail?
onboardingEmail?: EngineDefinition["onboardingEmail"];outgoingWebhooks?
outgoingWebhooks?: OutgoingWebhookDefinition;registerAdminRoutes?
registerAdminRoutes?: EngineDefinition["registerAdminRoutes"];registerRoutes?
registerRoutes?: EngineDefinition["registerRoutes"];reportUsage?
reportUsage?: EngineUsageReporter;runtime
runtime: Omit<EngineRuntimeConfig, "connections"> & {
connections: Connections;
};Type Declaration
connections
connections: Connections;setup?
setup?: EngineSetupHook<Resources>;tasks?
tasks?: EngineTaskDefinitions;taskScheduling?
taskScheduling?: EngineTaskScheduling;EngineFactory
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
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?
activate?: (args: EngineActivationArgs) => Promise<EngineLifecycleResult | void>;Use provisioned managed webhooks and return any engine-owned fields to persist on activation.
afterActivate?
afterActivate?: (args: EngineLifecycleArgs) => Promise<void>;Run follow-up work after activation is persisted. The supplied record is the pre-update snapshot.
beforeActivate?
beforeActivate?: (args: EngineLifecycleArgs) => Promise<void>;Check activation prerequisites before Core provisions managed resources.
beforeDelete?
beforeDelete?: (args: EngineLifecycleArgs) => Promise<void>;Clean up engine-owned data before the deletion task removes the instance.
deactivate?
deactivate?: (args: EngineLifecycleArgs) => Promise<EngineLifecycleResult | void>;Clean up engine-owned resources before Core removes the managed Airtable webhook.
EngineLifecycleResult
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?
payload?: Record<string, unknown>;update?
update?: Partial<SyncRecord>;EngineRegistration
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
type EngineRuntimeConfig = {
airtableEventProcessing?: {
maxImmediateTasks: number | null;
};
connections: BuiltinEngineConnectionConfigs;
kind: string;
};Resolved runtime metadata shared by an engine and its dashboard.
Properties
airtableEventProcessing?
airtableEventProcessing?: {
maxImmediateTasks: number | null;
};maxImmediateTasks
maxImmediateTasks: number | null;Deprecated
Backend-only: use defineEngine.airtableEventProcessing.
connections
connections: BuiltinEngineConnectionConfigs;kind
kind: string;EngineServerHooks
type EngineServerHooks<Resources = unknown> = {
beforeServerShutdown?(args: SetupContext & {
resources: Resources;
}): void | Promise<void>;
};Hooks for the lifetime of a server registration.
Methods
beforeServerShutdown()?
beforeServerShutdown?(args: SetupContext & {
resources: Resources;
}): void | Promise<void>;Release resources from setup after workers stop and before Core closes its infrastructure.
Parameters
args. Theresourcesfield isundefinedwhen setup is omitted.
EngineSetupHook
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
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?
allowFastExecution?: boolean;concurrency?
concurrency?: number;executionPolicy?
executionPolicy?:
| TaskExecutionPolicy
| ((task: TaskRow) => TaskExecutionPolicy);executionTimeoutMs?
executionTimeoutMs?: number;failureContinuation?
failureContinuation?:
| TaskChainPayload
| ((task: TaskRow) => TaskChainPayload);handler
handler: EngineTaskHandler<Operation>;worker
worker: "fast" | "background";EngineTaskDefinitions
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
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
type EngineTaskHandlerArgs<Operation extends TaskOperation> = {
context: EngineContext;
run: TaskRun;
signal: AbortSignal;
task: Omit<TaskRow, "operation" | "payload"> & object;
};Properties
context
context: EngineContext;run
run: TaskRun;signal
signal: AbortSignal;task
task: Omit<TaskRow, "operation" | "payload"> & object;Type Declaration
operation
operation: Operation;payload
payload: TaskPayload<Operation> | null;EngineTaskInput
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?
details?: TaskRow["details"];external_record_id
external_record_id: string;is_system?
is_system?: TaskRow["is_system"];payload
payload: TaskPayload<Operation>;reuseExisting?
reuseExisting?: boolean;Reuse the stored identity and wake due pending work. Broken tasks remain broken.
run_at?
run_at?: string;EngineTaskScheduling
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
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?
callbackPath?: string;description?
description?: string;format?
format?: "url" | "email";group?
group?: string;label?
label?: string;options?
options?: readonly string[];providerSetup?
providerSetup?: ProviderSetup;required?
required?: boolean;secret?
secret?: boolean;setupUrl?
setupUrl?: string;PortableEngineDefinition
type PortableEngineDefinition<Context extends ServerContext = ServerContext> = Omit<EngineDefinition<BuiltinEngineConnectionConfigs, Context>, "connections" | "lifecycle" | "lifecycleDefinition" | "setup" | "tasks"> & object;Type Declaration
apiVersion
apiVersion: 1;connections
connections: EngineConnectionBindings;lifecycle?
lifecycle?: EngineLifecycleHooks;setup?
setup?: EngineSetupHook<unknown>;tasks?
tasks?: EngineTaskDefinitions;RuntimeServiceConfig
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?
auth?:
| AuthDependencies
| ((supabase: RuntimeServices["supabaseMaster"]) => AuthDependencies);branding?
branding?: EmailServiceConfig["branding"];credentials?
credentials?: Omit<ConstructorParameters<typeof CredentialService>[0], "keyRepo">;decision?
decision?: DecisionServiceConfig;llm?
llm?: LlmServiceDependencies;localAirtable?
localAirtable?: LocalAirtableConfig;localSlack?
localSlack?: LocalSlackConfig;mode?
mode?: ServerRuntimeMode;postmark?
postmark?: Omit<EmailServiceConfig, "defaultProduct" | "branding">;productName?
productName?: string;supabase?
supabase?: Parameters<typeof createSupabaseResources>[0] & {
authHookSecret?: string;
};Type Declaration
authHookSecret?
authHookSecret?: string;ServerBuildOptions
type ServerBuildOptions = Omit<BuildOptions, "entryPoints" | "plugins"> & object;Type Declaration
extra?
extra?: Pick<BuildOptions, "entryPoints" | "plugins">;validateExternalDependencies?
validateExternalDependencies?: boolean;Require external packages in the invoking app's production dependencies. Defaults to true for workspace apps.
ServerConfig
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?
accountDeletion?: Context["accountDeletion"];brokenTaskEmail?
brokenTaskEmail?: Context["brokenTaskEmail"];credentials?
credentials?:
| CredentialConfig & {
keys?: never;
}
| {
activeKeyVersion: CredentialConfig["activeKeyVersion"];
keys: Partial<Record<CredentialConfig["activeKeyVersion"], string | undefined>>;
resolveKey?: never;
};firstEngineEmail?
firstEngineEmail?: Context["firstEngineEmail"];frontendBaseUrl?
frontendBaseUrl?: string;getFrontendBaseUrl?
getFrontendBaseUrl?: FrontendUrlConfig["getFrontendBaseUrl"];getProductForUrl?
getProductForUrl?: FrontendUrlConfig["getProductForUrl"];jobsEnabled?
jobsEnabled?: boolean;localWebhooks?
localWebhooks?: boolean;logger
logger: FastifyServerOptions["logger"];mailpit?
mailpit?: boolean;maintenance?
maintenance?: (context: Context, log: FastifyBaseLogger, resources: RedisResources) => ServerMaintenanceOptions;mcp?
mcp?: McpConfig;mcpOAuth?
mcpOAuth?: McpOAuthConfig & {
createTokenStore: (supabase: ServerContext["supabaseMaster"]) => McpOAuthTokenStore;
};Type Declaration
createTokenStore
createTokenStore: (supabase: ServerContext["supabaseMaster"]) => McpOAuthTokenStore;postmark?
postmark?: Omit<PostmarkConfig, "serverToken" | "fromEmail"> & { [Key in "serverToken" | "fromEmail"]?: PostmarkConfig[Key] };publicApi?
publicApi?: PublicApiUrlConfig & {
baseUrl?: string;
};Type Declaration
baseUrl?
baseUrl?: string;redis?
redis?: object;redis.cacheEncryptionKey?
cacheEncryptionKey?: RedisResourceOptions["redisCacheEncryptionKey"];redis.client?
client?: RedisResourceOptions["redis"];redis.tcpClient?
tcpClient?: RedisResourceOptions["redisTcp"];redis.url?
url?: RedisResourceOptions["redisUrl"];runtime?
runtime?: Omit<RuntimeContextConfig, "slackWebhook">;sentry?
sentry?: SentryConfig | false;slackWebhook?
slackWebhook?: RuntimeContextConfig["slackWebhook"];startupTaskRecovery?
startupTaskRecovery?: boolean;trustProxy?
trustProxy?: FastifyServerOptions["trustProxy"];webhookPathPrefix?
webhookPathPrefix?: string;workerShutdownTimeoutMs?
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
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
readonly context: ServerContext;getPublicApiBaseUrl?
readonly getPublicApiBaseUrl?: () => string | Promise<string>;jobsEnabled
readonly jobsEnabled: boolean;log
readonly log: EngineContextOptions["log"];redis
readonly redis: RedisLike;redisCacheEncryptionKey?
readonly redisCacheEncryptionKey?: string;SlackEventHookArgs
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?
allowMessageEvent?: boolean;botUserId?
botUserId?: string;context
context: EngineContext;event
event: SlackEvent;parentMessage?
parentMessage?: SlackParentMessage;slackTeamId?
slackTeamId?: string;syncRecord
syncRecord: SyncRecord;Selected by webhook routing before the event hook runs.
SlackFormSubmissionHookArgs
type SlackFormSubmissionHookArgs = SlackInteractionHookArgs;Raw Slack view submission payload and the matched engine context.
SlackFormSubmissionResult
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
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?
handleEvent?: (args: SlackEventHookArgs) => Promise<boolean>;handleFormSubmission?
handleFormSubmission?: (args: SlackFormSubmissionHookArgs) => Promise<SlackFormSubmissionResult>;handleInteraction?
handleInteraction?: (args: SlackInteractionHookArgs) => Promise<void>;handleThreadMessage?
handleThreadMessage?: (args: SlackThreadMessageHookArgs) => Promise<void>;TaskChainPayload
type TaskChainPayload = {
chain_failure_policy?: TaskChainFailurePolicy;
next_task?: TaskChainNextTask;
};Properties
chain_failure_policy?
chain_failure_policy?: TaskChainFailurePolicy;next_task?
next_task?: TaskChainNextTask;TaskExecutionPolicy
type TaskExecutionPolicy = {
allowInactiveEngine?: boolean;
forceBroken?: boolean;
requiresEngineRecord?: boolean;
};Properties
allowInactiveEngine?
allowInactiveEngine?: boolean;Allow a task to run for an inactive engine. Defaults to false.
forceBroken?
forceBroken?: boolean;Mark the task broken when the worker handles an error. Defaults to false.
requiresEngineRecord?
requiresEngineRecord?: boolean;Require the engine record to exist. Defaults to true.
TaskOperation
type TaskOperation = Extract<keyof TaskPayloadByOperation, string>;TaskPayload
type TaskPayload<T extends TaskOperation> = TaskPayloadByOperation[T];TaskScheduling
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?
delayMs?: number | ((input: TaskSchedulingInput<Operation>) => number);key
key: (payload: TaskPayload<Operation>) => string;policy
policy: "keepLatest";