---
url: https://kit.kambium.net/docs/kit-api.md
description: >-
  Kambium Kit API reference for engines, server setup, tasks and typed HTTP
  endpoints.
---

# Kit API

| Use | Import from | API |
| --- | --- | --- |
| Define an engine | `@kambium/kit` | [`defineEngine`](#defineengine), [`EngineDefinitionInput`](#enginedefinitioninput), [`EngineFactory`](#enginefactory), [`EngineContext`](#enginecontext) |
| Initialize and clean up resources | `@kambium/kit` | [`EngineSetupHook`](#enginesetuphook), [`SetupContext`](#setupcontext), [`EngineServerHooks`](#engineserverhooks), [`EngineLifecycleHooks`](#enginelifecyclehooks) |
| Handle provider events | `@kambium/kit` | [`EngineConnectionBindings`](#engineconnectionbindings), [`AirtableHooks`](#airtablehooks), [`SlackHooks`](#slackhooks), [`EngineActivationArgs`](#engineactivationargs), [`EngineLifecycleResult`](#enginelifecycleresult) |
| Share engine metadata | `@kambium/kit/shared/engine-runtime`, `@kambium/kit/shared/engine-connection-config` | [`defineEngineRuntime`](#defineengineruntime), [`EngineRuntimeConfig`](#engineruntimeconfig), [`resolveConnectionId`](#resolveconnectionid), [`EngineConnectionConfig`](#engineconnectionconfig) |
| Run a server | `@kambium/kit/server` | [`createServer`](#createserver), [`shutdownServer`](#shutdownserver), [`CreateServerOptions`](#createserveroptions), [`ServerConfig`](#serverconfig), [ServerContext](#servercontext), [`EngineRegistration`](#engineregistration) |
| Configure and build the app | `@kambium/kit/shared/env`, `@kambium/kit/build` | [`defineEnv`](#defineenv), [EnvDefinition](#envdefinition), [`buildServer`](#buildserver), [`ServerBuildOptions`](#serverbuildoptions) |
| Define a task and its execution policy | `@kambium/kit` | [`EngineTaskDefinitions`](#enginetaskdefinitions), [`EngineTaskHandlerArgs`](#enginetaskhandlerargs), [`TaskExecutionPolicy`](#taskexecutionpolicy), [`EngineTaskInput`](#enginetaskinput) |
| Schedule or finish a task | `@kambium/kit` | [`EngineTaskScheduling`](#enginetaskscheduling), [`TaskScheduling`](#taskscheduling), [`TaskRun`](#taskrun), [`PermanentError`](#permanenterror) |
| Register task payloads or Airtable handlers | `@kambium/kit/shared/types`, `@kambium/kit/server/tasks/airtable` | [`TaskPayloadByOperation`](#taskpayloadbyoperation), [`TaskChainPayload`](#taskchainpayload), [TaskOperation](#taskoperation), [TaskPayload](#taskpayload), [`createAirtableTasks`](#createairtabletasks) |
| Declare and bind HTTP routes | `@kambium/kit/server/routes/define-route`, `@kambium/kit/server/routes/endpoint` | [`defineRoute`](#defineroute), [`defineEndpointRoute`](#defineendpointroute), [`EndpointReply`](#endpointreply) |
| Call typed JSON endpoints | `@kambium/kit/endpoint`, `@kambium/kit/frontend/ui-client` | [`defineEndpoint`](#defineendpoint), [`EndpointCatalog`](#endpointcatalog), [EndpointArguments](#endpointarguments), [EndpointResponse](#endpointresponse), [`createUiClient`](#createuiclient) |

See [Engine definitions](https://kit.kambium.net/docs/engines.md), [Task execution](https://kit.kambium.net/docs/tasks.md), and [Server configuration](https://kit.kambium.net/docs/configuration.md) for application wiring and examples. See [Kit services](https://kit.kambium.net/docs/kit-services.md) for provider APIs and [Kit frontend](https://kit.kambium.net/docs/kit-frontend.md) 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

| Property | Type |
| ------ | ------ |
| <a id="property-permanent"></a> `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

* `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

| Property | Type | Default value | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| <a id="property-accountdeletion"></a> `accountDeletion?` | `AccountDeletionConfig` | `undefined` | - | - |
| <a id="property-afterengineactivate"></a> `afterEngineActivate?` | `ServerActivationHook` | `undefined` | Runs after the engine hook, persistence and lock release; failures propagate without rollback. | - |
| <a id="property-airtablemcp"></a> `airtableMcp` | `AirtableMcpService` | `undefined` | - | - |
| <a id="property-airtablewebhook"></a> `airtableWebhook?` | `AirtableWebhookNotifications` | `undefined` | - | - |
| <a id="property-airtablewebhookdeletionemail"></a> `airtableWebhookDeletionEmail?` | () => `Pick`<`EmailService`, `"sendAdminEmail"`> | `undefined` | - | - |
| <a id="property-authorizeaccountdeletion"></a> `authorizeAccountDeletion?` | (`input`: { `userId`: `string`; }) => `Promise`<`void`> | `undefined` | Eligibility check during request, confirmation preview and confirmation, before cleanup is scheduled. | `AccountDeletionHooks.authorizeAccountDeletion` |
| <a id="property-authorizeenginecreation"></a> `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. | - |
| <a id="property-authorizeworkspacebootstrap"></a> `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. | - |
| <a id="property-authorizeworkspacecreation"></a> `authorizeWorkspaceCreation?` | (`input`: `CreationAuthorizationInput` & { `name`: `string`; }) => `Promise`< | `void` | { `message`: `string`; }> | `undefined` | - | - |
| <a id="property-beforeaccountcleanup"></a> `beforeAccountCleanup?` | (`input`: { `request`: `UserDeletionRequestRow`; }) => `Promise`<`void`> | `undefined` | Awaited before operational cleanup. Must tolerate retries and overlapping attempts for the same request. | `AccountDeletionHooks.beforeAccountCleanup` |
| <a id="property-beforeengineactivate"></a> `beforeEngineActivate?` | `ServerActivationHook` | `undefined` | Runs after initial access/state checks and before acquiring the activation lock. | - |
| <a id="property-brokentaskemail"></a> `brokenTaskEmail?` | `false` | `BrokenTaskEmailConfig` | `undefined` | - | - |
| <a id="property-cronjobs"></a> `cronJobs?` | readonly `ScheduledTask`\[] | `undefined` | - | - |
| <a id="property-firstengineemail"></a> `firstEngineEmail?` | `false` | `FirstEngineEmailConfig` | `undefined` | - | - |
| <a id="property-frontendurls"></a> `frontendUrls?` | `FrontendUrlConfig` | `undefined` | - | - |
| <a id="property-getengineruntimeconfigs"></a> `getEngineRuntimeConfigs?` | () => readonly `Pick`<[`EngineRuntimeConfig`](#engineruntimeconfig), `"connections"` | `"kind"`>\[] | `undefined` | - | - |
| <a id="property-getworkspaceinvitationbaseurl"></a> `getWorkspaceInvitationBaseUrl?` | (`product`: `string`) => `string` | `Promise`<`string` | `undefined`> | `undefined` | `undefined` | - | - |
| <a id="property-initemailservice"></a> `initEmailService?` | () => `EmailService` | `undefined` | - | - |
| <a id="property-initllmservice"></a> `initLlmService` | () => [`LlmService`](https://kit.kambium.net/docs/kit-services.md#llmservice) | `undefined` | - | - |
| <a id="property-localairtable"></a> `localAirtable?` | `LocalAirtableConfig` | `undefined` | - | - |
| <a id="property-localslack"></a> `localSlack?` | `LocalSlackConfig` | `undefined` | - | - |
| <a id="property-maintenance"></a> `maintenance?` | `ServerMaintenanceOptions` | `undefined` | - | - |
| <a id="property-mcp"></a> `mcp?` | `McpService` | `undefined` | - | - |
| <a id="property-mcpoauth"></a> `mcpOAuth?` | `McpOAuthService` | `undefined` | - | - |
| <a id="property-mode"></a> `mode?` | `ServerRuntimeMode` | `undefined` | - | - |
| <a id="property-redis"></a> `redis` | `RedisLike` | `undefined` | - | `RedisResources.redis` |
| <a id="property-rediscacheencryptionkey"></a> `redisCacheEncryptionKey` | `string` | `undefined` | `options.redisCacheEncryptionKey` | - | `RedisResources.redisCacheEncryptionKey` |
| <a id="property-repos"></a> `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` | `...` | - | - |
| <a id="property-slackwebhook"></a> `slackWebhook?` | `SlackWebhookRuntime` | `undefined` | - | - |
| <a id="property-supabaseauthhooksecret"></a> `supabaseAuthHookSecret?` | `string` | `undefined` | - | - |
| <a id="property-supabasemaster"></a> `supabaseMaster` | `SupabaseClient`<`any`> | `undefined` | - | - |
| <a id="property-supabaseurl"></a> `supabaseUrl?` | `string` | `undefined` | - | - |
| <a id="property-taskfailureruntime"></a> `taskFailureRuntime?` | `TaskFailureRuntime` | `undefined` | - | - |
| <a id="property-taskmanager"></a> `taskManager?` | `TaskDispatcher` | `undefined` | - | - |
| <a id="property-webhookpathprefix"></a> `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

| Property | Type |
| ------ | ------ |
| <a id="property-airtable_webhook_drain"></a> `airtable_webhook_drain` | `AirtableWebhookDrainTaskPayload` |
| <a id="property-delete_engine"></a> `delete_engine` | `DeleteEngineTaskPayload` |
| <a id="property-delete_workspace"></a> `delete_workspace` | `object` |
| `delete_workspace.requestedByUserId` | `string` |
| `delete_workspace.workspaceId` | `string` |
| <a id="property-engine_disabled_email"></a> `engine_disabled_email` | `EngineDisabledEmailTaskPayload` |
| <a id="property-nango_delete_connection"></a> `nango_delete_connection` | `NangoDeleteConnectionTaskPayload` |
| <a id="property-platform_daily_report"></a> `platform_daily_report` | `PlatformDailyReportTaskPayload` |
| <a id="property-record_change"></a> `record_change` | `RecordChangeTaskPayload` |
| <a id="property-run_slack_flow"></a> `run_slack_flow` | `FlowTaskPayload` |
| <a id="property-schema_change"></a> `schema_change` | `SchemaChangeTaskPayload` |
| <a id="property-slack_interaction"></a> `slack_interaction` | `SlackInteractionTaskPayload` |
| <a id="property-slack_thread_message"></a> `slack_thread_message` | `SlackThreadMessageTaskPayload` |
| <a id="property-webhook_delivery"></a> `webhook_delivery` | `object` |
| `webhook_delivery.eventId` | `string` |
| `webhook_delivery.eventType` | `string` |
| `webhook_delivery.subject` | `Json` |
| `webhook_delivery.webhookId` | `string` |

***

### 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

| Property | Modifier | Type |
| ------ | ------ | ------ |
| <a id="property-signal"></a> `signal?` | `readonly` | `AbortSignal` |
| <a id="property-task"></a> `task` | `readonly` | `object` |
| `task.attempts` | `public` | `number` |
| `task.claim_token` | `public` | `string` | `null` |
| `task.claimed_at` | `public` | `string` | `null` |
| `task.created_at` | `public` | `string` |
| `task.details` | `public` | `Json` |
| `task.external_record_id` | `public` | `string` |
| `task.finished_at` | `public` | `string` | `null` |
| `task.id` | `public` | `number` |
| `task.is_system` | `public` | `boolean` |
| `task.last_error` | `public` | `string` | `null` |
| `task.operation` | `public` | `string` |
| `task.payload` | `public` | `Json` |
| `task.request_id` | `public` | `number` | `null` |
| `task.run_at` | `public` | `string` |
| `task.scheduling_key` | `public` | `string` | `null` |
| `task.scheduling_started` | `public` | `boolean` |
| `task.status` | `public` | `"pending"` | `"processing"` | `"done"` | `"broken"` |
| `task.sync_id` | `public` | `string` |

## 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](#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";
```
