{t("reportsPage.title")}
; ``` In a component that receives `locale` as a prop, read the namespace: ```tsx import { getMessageNamespace, type Locale } from "@/i18n/messages"; const copy = getMessageNamespace(locale, "reportsPage"); ``` `t()` is typed against the English dictionary, so a misspelt key fails `pnpm typecheck`. At runtime a key that is missing from the Chinese dictionary renders as the key itself. ### Check that both dictionaries have the same keys ```bash pnpm validate:app-i18n ``` The `dictionaries-carry-the-same-keys` check runs `validateLocaleParity()`, which compares every key path. It fails and lists the keys when one locale has a key the other lacks. ## Add a locale-aware route ### Create the file under `{-$locale}` Every page route lives in `src/routes/{-$locale}/`. `{-$locale}` is TanStack Router's optional path segment. The same file serves `/reports` with no `locale` param and `/zh/reports` with `locale: "zh"`. ```tsx title="src/routes/{-$locale}/reports.tsx" import { createFileRoute } from "@tanstack/react-router"; import { normalizeLocale } from "@/i18n/messages"; export const Route = createFileRoute("/{-$locale}/reports")({ component: ReportsPage, }); function ReportsPage() { const { locale } = Route.useParams(); return{feature.title}
{feature.body}
## Verify
1. Verify sandbox readiness after saving.
2. Run a task that uses the script tool and confirm execution produces an artifact.
## Troubleshooting
### A script tool refuses with the sandbox unconfigured
`/admin/config/sandbox` is disabled or its key is missing. There is no environment fallback, so
saving the key there is the only way to configure it.
## Next steps
[Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md)
---
# Crawl4AI
> Connect the agent service to Crawl4AI.
Source: https://kernlift.dev/docs/extensions/agent/crawl4ai
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a service connection the agent can use for a task.
## Set up Crawl4AI
### Start the API service
Open [Crawl4AI](https://docs.crawl4ai.com/core/self-hosting/). Deploy the Crawl4AI Docker API service.
### Check the crawl result
Crawl a public test page using its API and confirm the response contains page content.
Provider documentation · [self-hosting guide](https://docs.crawl4ai.com/core/self-hosting/)
## Configure the application
Open `/admin/config/search` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ----------- |
| Service URL | Base URL |
Enable the service, enter the connection details and save.
## Verify
1. Use **Test connection** from the service panel.
2. Run a search or extraction and inspect the returned content.
## Troubleshooting
### Connection failed
Test the configured URL from the agent service host. Match any proxy authorization header with the value saved in admin.
## Next steps
[Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md)
---
# E2B
> Connect the agent service to E2B.
Source: https://kernlift.dev/docs/extensions/agent/e2b
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a service connection the agent can use for a task.
## Set up E2B
### Create the sandbox key
Open [E2B](https://e2b.dev/dashboard). Create a sandbox API key.
### Build the runner template
Build the runner from `packages/sandbox-adapter/template/Dockerfile` using `pnpm --filter @workspace/sandbox-adapter build:runner-template`. Record the template name.
Provider documentation · [E2B templates](https://e2b.dev/docs)
## Configure the application
Open `/admin/config/sandbox` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | --------------------- |
| API key | Provider API key |
| Runner template | Immutable template ID |
Enable the service, enter the connection details and save.
## Verify
1. Verify sandbox readiness after saving.
2. Run a task that uses the script tool and confirm execution produces an artifact.
## Troubleshooting
### A script tool refuses with the sandbox unconfigured
`/admin/config/sandbox` is disabled or its key is missing. There is no environment fallback, so
saving the key there is the only way to configure it.
## Next steps
[Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md)
---
# Image agent
> Add an image agent to the workbench: requests run an image Skill on the agent runtime, in the frame the reader picks, with a per-run picture limit you set.
Source: https://kernlift.dev/docs/extensions/agent/image-agent
The image agent is a plugin on top of the [agent starter](https://kernlift.dev/docs/extensions/agent/starter.md). It adds an **Images** agent to the workbench composer at `/app/agent`, where its messages run the **Image Studio** Skill, an aspect-ratio picker next to the composer, a viewer for image artifacts, and an **Image Agent** settings page at `/admin/config/image-agent`. The **Images** sidebar entry at `/app/image` is a shortcut that opens the workbench with that agent picked. It adds no tool and no table. Pictures come from `model.generate` on the platform's image scenes.
## Before you begin
* The agent starter installed and the agent service deployed: a model for `agent.general` and a sandbox, as described in its guide. Without the agent service the **Images** entry is hidden.
* An image provider wired so that an `image-creation` task completes. See [Get image and video generation working](https://kernlift.dev/docs/extensions/ai/media-generation.md).
* The `image-agent` plugin, which is part of the repository and requires `agent-starter`. It is listed in **Settings → Plugins** (`/admin/plugins`).
* An admin account with `config.read` to open the settings page and `config.write` to save it.
## Configure the two scenes
The image agent runs on two scenes, both configured in **Settings → AI Config** (`/admin/config/ai`) like any other scene. See [AI scenes](https://kernlift.dev/docs/extensions/ai/scenes.md).
| Scene | Media | What it is for |
| ---------------- | ----- | ----------------------------------------------------------------------------------- |
| `agent.image` | Text | The agent loop of an image run. Needs an OpenAI-compatible chat route with a model. |
| `image-creation` | Image | The pictures themselves. Prices are set on this route. |
A missing `agent.image` route does not affect the agent service. The rest of the workbench keeps working and only the image page reports what is missing.
The Skill also calls `image-editing` to revise an existing picture and `image-understanding` to inspect one. Route those scenes too if you want revisions and visual checks. A picture made on `image-creation` or `image-editing` counts toward the per-run limit. Inspecting a picture does not.
## Publish the Skill
Runs load Skills from the registry, not from disk. The Skill ships in `src/plugins/image-agent/skills/image-studio` and is published with the platform Skills:
```bash
pnpm agent:publish-skills
```
Deploys run the same step. It publishes `platform.image` only when its content changed.
## Check readiness and set the limit
### Open the settings page
Go to **Settings → Image Agent** (`/admin/config/image-agent`). **Readiness** lists the `agent.image` route, the `image-creation` route and the published Skill, each **Ready** or **Missing**.
### Set pictures per run
Enter **Pictures per run**, from 1 to 32 (default 8), and click **Save**. Generations past this number are rejected before they reach a provider, and the model receives an instruction to stop and publish what it has.
## Use the image agent
Open **Images** in the workspace sidebar. The workbench opens at `/app/agent` with **Images** selected in the agent picker; you can also select it there yourself. Pick a frame (1:1, 3:4, 4:3, 9:16 or 16:9) and describe the picture. The frame is stored in the message, so retrying an old message keeps its frame, and the next run in the same thread keeps it too. A generation that states its own frame keeps it.
With the picker on **Auto**, a request that clearly asks for a picture ("draw…", "generate an image of…") is routed to the same Skill, and the workbench switches to the image agent for the rest of the thread. Each published picture is shown inside the message as well as in the panel.
## Verify
1. On `/admin/config/image-agent`, all three **Readiness** items show **Ready**.
2. Open `/app/image`. It lands on `/app/agent` with **Images** picked. Choose **16:9** and send "A wide banner of a mountain lake at dawn".
3. The run generates pictures, publishes them, and the panel opens the last one in the image viewer with its pixel size.
4. Set **Pictures per run** to 1 and send another request. The second generation is rejected and the reply says the budget is spent.
In the repository, `pnpm validate:image-agent` checks the routing, the pinned frame, the picture limit and the wiring without calling a provider.
## Troubleshooting
### The image page says image generation is not ready
Each line names what is missing. An `agent.image` route must be an OpenAI-compatible chat route with a model; an image-only route does not count for the agent loop.
### The Images entry is missing
The entry needs the agent service. It is hidden when the service is not deployed, the database is D1, or `agent-starter` is switched off. See [Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md).
### Requests on Auto are not routed to images
Only requests that clearly ask for a picture are routed. Select **Images** in the picker, which always runs the image Skill.
## Turn it off
Switch **image-agent** off in **Settings → Plugins**. The **Images** and **Image Agent** entries disappear, both pages return not found, its server functions reject calls, and a run on `agent.image` is rejected when it starts. Switching **agent-starter** off turns the image agent off with it.
---
# Agent runtime
> How the optional agent service is deployed, how the web app decides whether it is available, and how a run, its workspace, skills and decisions fit together.
Source: https://kernlift.dev/docs/extensions/agent
The agent is a separate service next to the web application, and it is optional. A deployment without it is a complete web app: AI tasks and chat call the configured channels directly through `/app/ai`, `/app/chat` and `/api/chat`. When the service is deployed, the web app authenticates the user, checks ownership and forwards signed requests to it. The service runs the agent loop, the sandboxes and its own background worker. The browser calls only the web app's `/api/agent/*` routes.
## Two processes, one direction of trust
`apps/agent-service` is a Node process installed by the `agent-starter` template. The web app reaches it in one of two ways:
| Transport | When it is used | How it is configured |
| ----------- | -------------------------------------------------------------------- | -------------------------------------------------------------- |
| `url` | A Node server, a container on another platform, or local development | `AGENT_SERVICE_URL` in the web app's environment |
| `container` | A Cloudflare Worker with the agent as a Cloudflare container | The `AGENT_SERVICE` Durable Object binding in `wrangler.jsonc` |
Both transports send the same signed request. `AGENT_INTERNAL_SIGNING_SECRET` authenticates requests between the two processes, and `AGENT_RESOURCE_GRANT_SECRET` signs the short-lived tokens used to reach a stored file. The service never receives session, OAuth or payment variables and refuses to start when one is present in its environment, because it runs untrusted code in sandboxes.
On Cloudflare every request goes to one named container instance. The service holds stream subscriptions, runs in progress and the sandbox pool in memory, so requests for one run must reach the same process. The Worker's Cron Trigger sends that container one maintenance round when runs are unfinished, which also keeps it awake.
## Availability is one answer
`getAgentAvailability()` returns whether this deployment can run the agent. It reads only plugin state, the environment and the database dialect and does not load the agent runtime, so the console layouts can call it on every navigation.
| Reason | Meaning |
| ---------------------------- | ----------------------------------------------------------------------- |
| `plugin_disabled` | The `agent-starter` plugin is switched off in **Settings → Plugins**. |
| `database_not_transactional` | The database is Cloudflare D1, which has no interactive transactions. |
| `service_not_configured` | Neither `AGENT_SERVICE_URL` nor the `AGENT_SERVICE` binding is present. |
| `signing_secret_missing` | `AGENT_INTERNAL_SIGNING_SECRET` is not set. |
Every agent entry uses that result:
* Navigation entries that carry `requires: "agent"` are hidden.
* `/app/agent` and `/app/image` explain that the agent service is not deployed and what to do next.
* `/api/agent/*` returns `503` with the code `agent_unavailable`.
Available does not mean ready. The readiness checks below report whether the service has a model route and a sandbox.
## The database must have transactions
Accepting a run, answering a question, resolving an approval and claiming a background task are each several statements that must commit together. The agent repositories therefore reject a database without interactive transactions before reading or writing anything, with `agent_requires_transactions`.
| Database | Agent |
| -------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| Postgres | Supported. On a Worker the web app connects through Hyperdrive and the container connects directly. |
| SQLite on Node | Supported. The repository facade wraps the `better-sqlite3` connection so that asynchronous transaction callbacks run one after another. |
| Cloudflare D1 | Not supported. The web app runs; the agent entries do not appear. |
## The engine behind a run
`packages/agent-runtime` composes the run loop from DeepSeek Harness packages (`@deepseek-ai/cordis` and `@deepseek-ai/dsh-*`): the agent loop, sessions persisted as an event log, compaction, a token meter, pruning of old tool results and provider retry. The versions are pinned, and one package carries a patch from `patches/` applied through pnpm `patchedDependencies`.
Host code does not import those packages. It depends on the product-facing contracts in `runtime-contracts.ts`, so the engine can change inside the package without touching `src/server` or `apps/agent-service`. `pnpm validate:dsh-runtime` checks the pins, that business code does not import the engine directly, and runs the engine's contract tests.
No web request path loads the runtime. Routes import runtime helpers through narrow subpath exports and never through the package index. `pnpm validate:optional-agent` checks the built server for it.
## Threads, runs and workspaces
A thread holds conversation history. A run is one attempt to answer a message. `POST /api/agent/runs` supplies the message, an idempotency key and optionally an existing thread, a branch or a selected skill. Each run owns its workspace. Attachments and small workspace files are staged into that run before its first model turn. A later run cannot read an earlier run's workspace. A quote of an artifact is carried into the new run explicitly.
The run pins the primary skill, any capability skills, its scene and tool set. This keeps a resumed run on the same effective configuration even if the registry's latest skill version changes. The service resolves the active AI scene route and settles reserved credits through the server-side ledger. Missing model, sandbox or storage configuration is reported as an error, and the service produces no sample output. The number of runs one user may have in progress comes from the plan's `concurrentAgentTasks` entitlement.
The response to a new run and the thread snapshot carry `routing`: the scene, the primary skill and the plugin the run went to. The workbench uses it to follow a request that was routed automatically.
## States and decisions
| State | Meaning | What happens next |
| ------------------------------------------------ | ------------------------------ | -------------------------------------------------------------------------------- |
| `queued` | Accepted but not yet executing | The worker starts it, or it fails or is cancelled before execution. |
| `running` | Model and tools are executing | It may finish, fail, be interrupted, or wait for a person. |
| `waiting_user` | The run asked for information | The owner answers the specific user request. |
| `waiting_approval` | A tool action requires consent | The owner approves or denies the specific action. |
| `completed`, `failed`, `canceled`, `interrupted` | Terminal outcomes | The same run does not return to `running`; a new run is needed for further work. |
An approval request carries a fingerprint and policy version. The response must return both with the decision, so a changed or expired action cannot be approved using an old button. A user request is a question and uses a different endpoint. Reconnecting a stream resumes the view of a run and does not create a second run. Cancellation is a request to the service. It does not undo an action that has already finished.
## Skills, tools and the sandbox
Platform skills live in `agent-skills/` in the source checkout, and a capability plugin ships its own skill inside its plugin folder. `pnpm agent:publish-skills` packages them in object storage and the skill registry. The runtime reads authorized published versions and does not read local files. A run can choose a skill automatically or pin an authorized version. `agent-skills/` is separate from `skills/`, which provides workflows to coding assistants.
Tools that need code execution use the sandbox configured in `/admin/config/sandbox`. Search and crawl tools use the providers configured in `/admin/config/search`. Connector actions require their own account authorization. Resource previews and downloads use owner-scoped, short-lived grants, so a stored artifact never becomes a public URL.
Capabilities beyond the core set, such as an image agent, are plugins of the one workbench. They declare scenes, skills, cards and operations. The host checks them and switches them off with the plugin. See [Plugins](https://kernlift.dev/docs/core/plugins.md) and [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md).
## Readiness and failure boundaries
`GET /healthz` on the agent service reports process liveness. `GET /readyz` checks database reachability, schema version, object storage and usable provider configuration. It returns `503` while any required check is not ready. The `/app/agent` composer has its own narrower check: an active `agent.general` text route with its referenced secrets, plus a configured sandbox. Search and crawl are needed only for tools that use them. The readiness checks do not simulate a provider call.
The web app's own background work (fulfilment retries and unfinished AI tasks) runs in the web app's scheduled jobs and not in the agent service's loop, so it continues without the agent. See [Background jobs](https://kernlift.dev/docs/core/background-jobs.md).
## Files
- Web app side/
- src/server/agent-host/availability.ts
- src/server/agent-host/repository.ts
- src/server/services/agent-api-bridge.service.ts
- src/server/services/agent-route-readiness.service.ts
- src/server/platform/agent-service-container.ts
- Agent service/
- apps/agent-service/src/main.ts
- apps/agent-service/src/server.ts
- apps/agent-service/Dockerfile
- Runtime and contracts/
- packages/agent-runtime/src/runtime.ts
- packages/agent-runtime/src/runtime-contracts.ts
- packages/agent-contracts/src/run.ts
- packages/agent-contracts/src/api.ts
- Checks/
- scripts/validate/optional-agent.ts
- scripts/validate/dsh-runtime.ts
- scripts/validate/sqlite-transactions.ts
## Next steps
* [Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md): configuration, startup and checks.
* [Plugins](https://kernlift.dev/docs/core/plugins.md): how agent capabilities are installed and switched on and off.
* [Credits](https://kernlift.dev/docs/extensions/credits.md): reservation and settlement.
---
# Novita Sandbox
> Connect the agent service to Novita Sandbox.
Source: https://kernlift.dev/docs/extensions/agent/novita
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a service connection the agent can use for a task.
## Set up Novita Sandbox
### Enable the sandbox
Open [Novita Sandbox](https://novita.ai/docs/guides/sandbox-template). Enable a sandbox in your Novita account.
### Select the runner template
Obtain the control-plane endpoint, API key and a runner-compatible template ID from the same account.
## Configure the application
Open `/admin/config/sandbox` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | --------------------- |
| API key | Provider API key |
| Control plane | Control-plane API URL |
| Runner template | Immutable template ID |
Enable the service, enter the connection details and save.
## Verify
1. Verify sandbox readiness after saving.
2. Run a task that uses the script tool and confirm execution produces an artifact.
## Troubleshooting
### A script tool refuses with the sandbox unconfigured
`/admin/config/sandbox` is disabled or its key is missing. There is no environment fallback, so
saving the key there is the only way to configure it.
## Next steps
[Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md)
---
# Agent plugins
> Build an agent capability as a plugin: it joins the one workbench composer, adds its own cards, panels and operations, and switches on and off at runtime without host changes.
Source: https://kernlift.dev/docs/extensions/agent/plugins
An agent plugin is one folder under `src/plugins/
## Verify
1. Use **Test connection** from the service panel.
2. Run a search or extraction and inspect the returned content.
## Troubleshooting
### Connection failed
Test the configured URL from the agent service host. Match any proxy authorization header with the value saved in admin.
## Next steps
[Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md)
---
# Run the agent starter
> Install the agent template, configure its model channels, sandbox and search providers, start the agent service and open the workbench.
Source: https://kernlift.dev/docs/extensions/agent/starter
The `agent-starter` template adds an Agent workbench and a separate Node service. The service coordinates runs, approvals, user requests, skills, tools and a per-run workspace. Model calls use configured AI channels, and the server reserves and settles credits. The agent is optional. A deployment without the service is still a complete web app, and its agent entries show that the service is not deployed. This guide covers installation and readiness. See [Agent runtime](https://kernlift.dev/docs/extensions/agent.md) for the execution model.
## What the template adds
| Part | Where it lives |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Agent contracts, run loop, tools and browser client | `packages/agent-{contracts,runtime,tools,client}` |
| Sandbox provider and its image | `packages/sandbox-adapter`, `packages/sandbox-adapter/template/Dockerfile` |
| The agent service, a second process | `apps/agent-service` |
| Runs, threads, messages, skills, approvals, workspaces and background tasks | migration `0016_agent_starter`, SQLite and Postgres |
| Authenticated API for the browser | `/api/agent/**` |
| Workbench | `/app/agent` |
| The `agent-starter` plugin: its navigation entries and route ownership | `src/plugins/agent-starter` |
| Provider configuration | `/admin/config/sandbox`, `/admin/config/search` |
| Platform skills and their publisher | `agent-skills/`, `pnpm agent:publish-skills` |
| Its validators | `pnpm validate:agent-starter`, `validate:optional-agent`, `validate:dsh-runtime`, `validate:agent-plugin-contract`, `validate:sqlite-transactions`, `validate:agent-generation` |
The workbench requires a usable `agent.general` model route and configured sandbox. Search and crawl providers are required only for tools that use them. The workbench reports missing configuration and never simulates a provider response.
## Before you begin
* The base repository, or the `image-agent` or `video-agent` business template. The agent stack
is part of each. See [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
* Node 20 or later, and a project that runs locally. See [Quick start](https://kernlift.dev/docs/quick-start.md).
* **Postgres, or SQLite on Node.** Agent runs need interactive transactions, which Cloudflare D1
does not have. On D1 the web application runs as usual, the agent entries are hidden and
`/api/agent/*` answers `503 agent_unavailable`. See
[Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md).
* An administrator account holding `config.read` and `config.write`. The two configuration pages
the template adds use the permissions the console already has, so there is nothing new to grant.
* **Object storage configured in `/admin/config/storage`.** Skill bundles, run artifacts and
workspace files are stored there. Until it is configured `pnpm agent:publish-skills` publishes
nothing and prints the reason. `pnpm dev:agent` prints the same message and still starts both processes, so the
configuration page stays reachable. See
[Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md).
* An E2B-compatible sandbox service, if the agent is to execute scripts, and a SearXNG and
crawl4ai deployment if it is to search and read pages.
## Set up the agent service
### Install packages and migrate
```bash
pnpm install && pnpm db:migrate
```
The agent stack is already in the repository: workspace packages under `packages/agent-*` and a
separate app in `apps/agent-service`. `pnpm install` installs their dependencies, and the migration
creates the Agent tables for the configured dialect. Both are no-ops if you ran them in the quick start.
### Point the two processes at each other
```bash title=".env"
# Infrastructure only. Providers, limits and prices are configured in /admin/config/*.
AGENT_SERVICE_URL=http://127.0.0.1:3001
AGENT_WEB_INTERNAL_URL=http://127.0.0.1:5173
AGENT_INTERNAL_SIGNING_SECRET=
AGENT_RESOURCE_GRANT_SECRET=
```
Run `openssl rand -hex 32` twice. Put the two independently generated values in the blank secret fields and use the same pair in the corresponding fields of both processes.
`AGENT_SERVICE_HOST`, `AGENT_SERVICE_PORT`, `AGENT_SERVICE_REQUEST_TIMEOUT_MS`,
`AGENT_FLOW_LOG_LEVEL` and `AGENT_SANDBOX_ERROR_LOG_ENABLED` are optional, and `.env.example` lists
them with their defaults. No provider credential belongs in either environment. These variables
are needed only when you run the agent. Without `AGENT_SERVICE_URL` and the signing secret the web
app treats the agent as not deployed.
## Two processes
The web application serves the pages, authenticates every `/api/agent/**` request and forwards it.
`apps/agent-service` is a Node process that runs the agent loop, the sandboxes and the background
worker. They communicate over signed HTTP, using the two secrets above. The signing
secret authenticates a request between them, and the resource grant secret signs the short-lived
tokens a sandbox uses to reach a file or a model.
For local work, `pnpm dev` runs the web application alone and one command runs both:
```bash
pnpm dev:agent
```
It migrates the database, publishes the platform skills, builds the attachment parser, then runs
Vite and the agent service together. When either secret is unset or shorter than 32 bytes it
generates one for the session, so a first run needs no secret management. A project that has not
configured object storage yet publishes no skill. The command prints a message and starts both processes
so that `/admin/config/storage` remains available for setup.
## Prepare sandbox and retrieval services
| Provider | Choose it for |
| ------------------------------------------------------ | ------------------------------------- |
| [E2B](https://kernlift.dev/docs/extensions/agent/e2b.md) | Execute scripts in an E2B runner |
| [Alibaba Cloud Sandbox](https://kernlift.dev/docs/extensions/agent/aliyun.md) | Use an Alibaba Cloud runner image |
| [Novita Sandbox](https://kernlift.dev/docs/extensions/agent/novita.md) | Use an existing Novita sandbox |
| [SearXNG](https://kernlift.dev/docs/extensions/agent/searxng.md) | Search through a self-hosted instance |
| [Crawl4AI](https://kernlift.dev/docs/extensions/agent/crawl4ai.md) | Extract content from a web page |
## Configure the providers
### Model channels
Open `/admin/config/ai` and give each agent scene an active route: `agent.general` for ordinary
conversation, `agent.research` for search-led runs, `agent.mail` for the mail assistant and
`agent.audio` for speech. A scene without an active channel is reported as not configured, and a
run that needs it fails with that message. See
[Configure AI scenes](https://kernlift.dev/docs/extensions/ai/scenes.md).
### Sandbox
Open `/admin/config/sandbox`, enable it, choose the provider and its control-plane URL, set the
runner template and the runtime limits, and paste the provider key. The key is write-only. It is
stored in the admin config table and never shown again. There is no `E2B_*` environment fallback.
A sandbox without configuration is reported as unavailable, and script tools return an error.
`packages/sandbox-adapter/template/Dockerfile` is the image the runner template is
built from.
### Search
Open `/admin/config/search` for SearXNG (search) and crawl4ai (page extraction). Each has its own
base URL, authentication header, timeout and enable switch, and a **Test connection** button that
performs a real request against the service you named.
### Platform skills
`agent-skills/` holds the skills the agent may load: `general-chat` and `mail-assistant`. An
installed capability plugin, such as the image agent, keeps its skill in its own plugin folder and
is published by the same command.
```bash
pnpm agent:publish-skills
```
The command bundles each one and publishes it to the skill registry, skipping any whose content is
already the active version. A run loads skills from the registry and does not read the files on disk, so
publish after editing them and as part of every deploy. `agent-skills/` is separate from `skills/`, which is
this repository's documentation for coding agents.
### Open the workbench
With both processes running, sign in and open `/app/agent`. Threads, the streaming conversation,
approvals and the artifacts panel are all on that page. Before the providers above are configured
it shows the missing configuration and disables unavailable actions.
## Deploy
The two processes deploy separately, and the web application must be able to reach the service.
### The agent service
Build the bundle and run it on Node 22 or later, directly or in a container:
```bash
pnpm build:agent-service
node apps/agent-service/dist/main.js
```
Give it the database connection, `AGENT_INTERNAL_SIGNING_SECRET`, `AGENT_RESOURCE_GRANT_SECRET`,
`AGENT_WEB_INTERNAL_URL` and its listen address. The process refuses to start
when an authentication or payment secret is present in its environment (`BETTER_AUTH_*`, `AUTH_*`,
`STRIPE_*`, `PAYMENT_*` and the like), because it runs untrusted code in sandboxes and must not
hold them. The same build writes `dist/publish-skills.mjs`, which a deploy runs for
the skill publish step.
### The web application
Deploy it as you already do, with one constraint: its database must be the one holding the agent
tables, so D1 cannot serve them. Set `AGENT_SERVICE_URL` to the service's internal address and
keep the service off the public internet. The browser never connects to it directly.
On Cloudflare the agent service runs as a container next to the Worker. The Worker reaches
Postgres through Hyperdrive (`DATABASE_DIALECT=postgres`, `DATABASE_ADAPTER=hyperdrive`), the
container connects directly with `AGENT_DATABASE_URL`, and the `AGENT_SERVICE` binding replaces
`AGENT_SERVICE_URL`. The commented blocks in `wrangler.jsonc` list the steps. See
[Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md),
[Deploy to a Node host](https://kernlift.dev/docs/deploy/node.md) and the Fly.io, Railway and Docker guides, each
of which runs the agent as a separate service.
### After each deploy
```bash
pnpm db:migrate
pnpm agent:publish-skills
```
Both are idempotent. A deploy that changed no migration and no skill writes nothing.
## Verify
1. `pnpm db:migrate` reports `0016_agent_starter` applied, in the dialect you deploy.
2. `/admin/config/sandbox` shows the sandbox as configured, with the key held in the admin config
table and not shown on the page.
3. `/admin/config/search` reports a successful test connection for each provider you enabled.
4. `curl -i http://127.0.0.1:5173/api/agent/threads` without a session answers `401`. Signed in, it
returns only your own threads.
5. The agent service answers `GET /healthz` with `status: "ok"`, and `GET /readyz` answers `200`
with `database`, `schema`, `objectStorage` and `providers` all `ready` once the scenes and the
sandbox are configured.
6. `/app/agent` runs a turn end to end, and the run's credit reservation appears as a captured
entry in the credit ledger.
In the repository, run `pnpm validate:agent-starter` and `pnpm validate:optional-agent`.
## Troubleshooting
### The Agent entry is missing, or `/api/agent/*` answers `503`
The web app reports the agent as unavailable. The response carries the code `agent_unavailable`
and an `x-agent-unavailable-reason` header:
| Reason | Fix |
| ---------------------------- | ------------------------------------------------------------------------------------ |
| `plugin_disabled` | Switch **agent-starter** on in **Settings → Plugins**. |
| `database_not_transactional` | The database is D1. Use Postgres, or SQLite on Node. |
| `service_not_configured` | Set `AGENT_SERVICE_URL`, or on Cloudflare add the `AGENT_SERVICE` container binding. |
| `signing_secret_missing` | Set `AGENT_INTERNAL_SIGNING_SECRET` to the same value in both processes. |
`/app/agent` shows the same reason to an administrator.
### An agent script fails with `agent_requires_transactions`
The process is connected to a database without interactive transactions (D1). Point it at
Postgres (`DATABASE_DIALECT=postgres`) or at SQLite on Node. The script fails before it writes anything,
so there is nothing to clean up.
### A run fails saying the model is not configured
The scene the run needs has no active channel route. Configure it in `/admin/config/ai`. `/readyz`
reports `providers: not_ready` until every active route resolves to a channel that has its
credential.
### A script tool refuses with the sandbox unconfigured
`/admin/config/sandbox` is disabled or its key is missing. There is no environment fallback, so
saving the key there is the only way to configure it.
### The service exits with `forbidden_agent_service_configuration`
Its environment carries an authentication or payment secret. Remove it. The service needs only the
database, the two agent secrets and the internal web URL.
### `pnpm agent:publish-skills` reports that object storage is not configured
A bundle is stored in object storage, so nothing can be published until `/admin/config/storage`
has a provider. The command exits non-zero, so a deploy that runs it stops. `pnpm dev:agent` prints
the same message and starts both processes so the page can be reached. Configure it, then run the
publish again.
### A new skill has no effect on a run
The skill was changed on disk but not published. Run `pnpm agent:publish-skills`. Runs read skills from the
registry, not from `agent-skills/`.
## Reference
* [Agent runtime](https://kernlift.dev/docs/extensions/agent.md)
* [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md)
* [AI channels](https://kernlift.dev/docs/extensions/ai.md)
* [E2B sandboxes](https://e2b.dev/docs)
## Next steps
- [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md)
- [Configure AI scenes](https://kernlift.dev/docs/extensions/ai/scenes.md)
- [Credits](https://kernlift.dev/docs/extensions/credits/usage.md)
- [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md)
---
# Receive async results (polling and webhooks)
> Image, video and audio tasks that finish later reach a final status, and their credits are charged or returned.
Source: https://kernlift.dev/docs/extensions/ai/async
Many image, video and audio providers answer with a task ID and deliver the result later. You choose per provider, or per provider scene, whether the app polls for the status or the provider calls back. Text is always a direct response, so skip this guide for chat models.
## Before you begin
* A provider and provider scene for an image, video or audio model, with response parsing set. See [Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md).
* Either a status URL you can query, or a public deployment the provider can call back. A local `127.0.0.1` address cannot receive callbacks.
* An admin account with `ai.read` and `ai.write`.
## Choose how results arrive
**Status polling**
### Select polling
On **Settings → AI Config**, open the provider (or a provider scene) and choose **Status polling** under result handling.
### Set the status URL
Fill in **Status URL template**, **Interval sec** and **Timeout sec**. `{{externalTaskId}}` in the template is the provider's task ID. Click **Save**.
**Webhook push**
### Select webhook push
On **Settings → AI Config**, open the provider (or a provider scene) and choose **Webhook push** under result handling.
### Set the signing secret
Fill in **Webhook signing secret** with a random string you share with the provider or your relay. It is never shown again. The badge shows **Configured** or **Not configured**, and a blank field keeps the stored secret. On a provider scene, the field shows **Inherits provider secret** when the provider already has one.
### Register the callback URL
Register the **Callback URL to register** shown under the field with the provider. It is built from the **Base URL** on **Auth Config** and the provider code:
```text
## Verify
1. Inspect Routing readiness for the model. Resolve any missing setting.
2. Send a message through the assigned chat scene and confirm the model responds.
## Troubleshooting
### Chat fails with "Provider scene chat protocol is not configured"
The provider scene routed from the chat scene has no protocol or model ID. Set both on the provider scene.
## Next steps
[Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md)
---
# AI channels, scenes and task lifecycle
> How providers, provider scenes and scenes fit together, how a price in credits is resolved, and how tasks and chat run from request to settlement.
Source: https://kernlift.dev/docs/extensions/ai
AI in Kernlift is set up through configuration. You describe upstream APIs in the admin console, expose
named scenes to your product, and every call is priced in credits and settled against the ledger. To
set it up, see [Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md) and
[Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md).
## Three layers of configuration
| Concept | What it is | Example |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------ |
| **Provider** (a channel) | One upstream API account: base URL, API key, request templates, how results come back and how responses are parsed | `openai` |
| **Provider scene** | One concrete model or endpoint under a provider, with its own request overrides and price | `gpt-4o-mini` on the OpenAI protocol |
| **Scene** | What your product asks for by code, with an output type, routed to one provider scene | `chat`, `image-creation` |
Callers name only a scene. Because a scene routes to one provider scene, you can switch the
model behind `image-creation` without changing any caller. Chat uses the scene `chat` unless the
request names another, and tasks are started at `POST /api/
## Verify
1. Inspect Routing readiness for the model. Resolve any missing setting.
2. Send a message through the assigned chat scene and confirm the model responds.
## Troubleshooting
### Chat fails with "Provider scene chat protocol is not configured"
The provider scene routed from the chat scene has no protocol or model ID. Set both on the provider scene.
## Next steps
[Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md)
---
# Connect an AI provider
> An upstream AI account and its models are saved in the admin console and ready to be routed to your scenes.
Source: https://kernlift.dev/docs/extensions/ai/providers
A provider is one upstream API account, such as OpenAI, Gemini, Cloudflare Workers AI or any HTTP API that returns JSON. A provider scene is one concrete model or endpoint under it. Both are configured on **Settings → AI Config**, with no code change and no environment variables.
## Before you begin
* An account with the provider, an API key, the API base URL and the model IDs from its documentation.
* An admin account with `ai.read` and `ai.write`.
Pick how you connect the provider by what it serves:
| Provider | Output type | What you configure |
| --------------------------------------------------- | ------------------------- | ------------------------------------------------------------------------------ |
| OpenAI, or any OpenAI-compatible chat API | `text` | **OpenAI protocol**, a base URL, an API key and a model ID |
| Google Gemini | `text` | **Gemini protocol**, a base URL, an API key and a model ID |
| Cloudflare Workers AI | `text` | **Edge inference** and a model ID; works only on Workers with the `ai` binding |
| An HTTP API that returns JSON (image, video, audio) | `image`, `video`, `audio` | The endpoint, request parameters, how results come back, and response parsing |
## Prepare credentials with the model provider
| Provider | Choose it for |
| ------------------------------------------------------- | ------------------------------------------- |
| [OpenAI](https://kernlift.dev/docs/extensions/ai/openai.md) | OpenAI-compatible text generation |
| [Google Gemini](https://kernlift.dev/docs/extensions/ai/gemini.md) | Text generation through the Gemini protocol |
| [Cloudflare Workers AI](https://kernlift.dev/docs/extensions/ai/workers-ai.md) | Run a text model through a Worker binding |
For a custom HTTP image, audio or video API, capture a real provider response before setting the parse paths. The steps below cover endpoint and result handling.
## Add the provider
### Open the form
Go to **Settings → AI Config** (`/admin/config/ai`), open **Providers** and click **Add provider**.
### Identify the provider
Enter a **Display name** and a **Code** such as `openai`. The code is saved in lowercase with hyphens and appears in the webhook callback URL. Set **Status** to **Active**.
### Set the base request
* **Method** and **Base URL**: usually `POST`, and the API base URL. For the OpenAI protocol the chat completions path is appended to it.
* **API key secret**: the key from the provider dashboard. It is stored as a secret and an **Authorization** row referencing it is added to **Request headers**. Leave it blank later to keep the stored key.
* **Request headers** and **Request parameters**: optional headers and body fields sent on every call. Values can use `{{prompt}}`, `{{input}}` and `{{metadata./generate`, for example `/api/image-creation/generate`.
## Verify
### Send a chat message
Sign in as the test user on your site and run this in the browser console:
```js
await fetch("/api/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
messages: [{ id: "m1", role: "user", parts: [{ type: "text", text: "Hello" }] }],
}),
}).then((response) => response.text());
```
The reply streams back, and the conversation appears under **Platform → Chats** (`/admin/chats`).
### Run a task
Call a task scene with an API key that has **Run AI tasks**:
```bash
curl -X POST https://your-domain.example/api/image-creation/generate \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"prompt":"A ceramic mug on a wooden desk","mediaType":"image","size":"1024x1024"}'
```
The response includes `taskId`, `status` and `estimatedPriceCredits`. Fields other than reserved names such as `prompt`, `input` and `mediaType` are passed to pricing rules as metadata, so `size` above can drive a **Parameter rules** price.
### Check the result
* The user's `/app/ai` lists the task, and its detail page shows the credits held, charged or returned.
* **Platform → AI Tasks** (`/admin/ai`) shows the task. Failures are listed at `/admin/ai/failed` with the provider's error.
* `/setup` reports **AI channels** as ready.
`pnpm validate:ai` runs text and video tasks through credits and events. `pnpm validate:ai-channel` checks pricing and routing.
## Troubleshooting
### A task fails with "AI scene is not available" or "AI provider is not available for this scene"
The scene has no active route, or the routed provider has no active provider scene for the requested output type. Route the scene on **Scene routing** and check that both the provider and the provider scene are active. No credits are taken.
### A task fails with "S06 insufficient credits"
The user's available balance is lower than the price. Grant credits from **Overview → Users** or lower the price. No provider call is made.
### Users pay an old price
The credit price changed after the provider scene was saved. Open the provider scene and click **Save** again.
## Reference
* [AI channels](https://kernlift.dev/docs/extensions/ai.md)
* [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md)
* [OpenAI API reference](https://platform.openai.com/docs/api-reference)
## Next steps
- [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md)
- [Issue API keys and set rate limits](https://kernlift.dev/docs/core/auth/api-keys.md)
- [AI channels, scenes and task lifecycle](https://kernlift.dev/docs/extensions/ai.md)
- [Credits ledger](https://kernlift.dev/docs/extensions/credits.md)
---
# Cloudflare Workers AI
> Route text generation to Cloudflare Workers AI.
Source: https://kernlift.dev/docs/extensions/ai/workers-ai
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a text model you can route to chat.
## Set up Cloudflare Workers AI
### Choose a text model
Open [Cloudflare Workers AI](https://developers.cloudflare.com/workers-ai/models/). Select a text model from the Workers AI catalog and copy its full ID.
### Deploy the AI binding
Add the AI binding named `ai` to the Worker configuration and deploy it.
Provider documentation · [model catalog](https://developers.cloudflare.com/workers-ai/models/) · [Workers AI bindings](https://developers.cloudflare.com/workers-ai/configuration/bindings/)
## Configure the application
Open `/admin/config/ai` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ----------- |
| Model ID | Model ID |
Add a provider scene for text, select **Edge inference**, enter the model ID, configure its price, and save. Assign the ready model to the chat scene.
## Verify
1. Inspect Routing readiness for the model. Resolve any missing setting.
2. Send a message through the assigned chat scene and confirm the model responds.
## Troubleshooting
### Edge inference is unavailable
The Workers AI binding only exists on Cloudflare Workers with the `ai` binding in `wrangler.jsonc`. Use the OpenAI or Gemini protocol in other runtimes. See [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md).
## Next steps
[Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md)
---
# Microsoft Clarity
> Connect your website to Microsoft Clarity.
Source: https://kernlift.dev/docs/extensions/analytics/clarity
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — the provider’s tag on a public page.
## Set up Microsoft Clarity
### Create the project
Open [Microsoft Clarity](https://clarity.microsoft.com/projects). Create a project for the website and copy its project ID.
### Enable report exports
For reports, generate a token under Settings → Data Export.
Provider documentation · [Data Export API](https://learn.microsoft.com/en-us/clarity/setup-and-installation/clarity-data-export-api)
## Configure the application
Open `/admin/config/analytics` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------------------------------------------------------------ | ---------------------- |
| Clarity → your project → Settings → Overview. | **Clarity project ID** |
| Clarity → your project → Settings → Data Export → generate an API token. | **Clarity API token** |
Save the form.
## Verify
1. Open a public page in a private window with blockers disabled.
2. Check for `clarity.ms/tag` on the page.
## Troubleshooting
### No script appears on the page
The identifier is empty, the page was not reloaded after saving, or an ad blocker removed it. Check the **Runtime checks** panel, then reload with extensions off.
## Next steps
[Add analytics and support chat](https://kernlift.dev/docs/extensions/analytics.md)
---
# Crisp
> Connect your website to Crisp.
Source: https://kernlift.dev/docs/extensions/analytics/crisp
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — the provider’s tag on a public page.
## Set up Crisp
### Create the website
Open [Crisp](https://app.crisp.chat/). Create a website in your workspace.
### Find the Website ID
Open its setup instructions and copy the Website ID.
Provider documentation · [Crisp Web SDK](https://docs.crisp.chat/guides/chatbox-sdks/web-sdk/npm/)
## Configure the application
Open `/admin/config/analytics` in the Kernlift admin console.
| Value from provider | Admin field |
| --------------------------------------------------------- | -------------------- |
| Crisp → Settings → Website settings → Setup instructions. | **Crisp website ID** |
Save the form.
## Verify
1. Open a public page in a private window with blockers disabled.
2. Check for `client.crisp.chat/l.js` on the page.
## Troubleshooting
### The Crisp widget shows "Invalid website"
The saved **Crisp website ID** does not match a website in your Crisp account. Copy it from Crisp and save again.
## Next steps
[Add analytics and support chat](https://kernlift.dev/docs/extensions/analytics.md)
---
# Google Ads
> Connect your website to Google Ads.
Source: https://kernlift.dev/docs/extensions/analytics/google-ads
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — the provider’s tag on a public page.
## Set up Google Ads
### Create a conversion action
Open [Google Ads](https://ads.google.com/). Create a website conversion action.
### Copy the tag identifiers
In tag setup copy the conversion ID and conversion label.
Provider documentation · [Google Ads](https://support.google.com/google-ads/answer/7548399)
## Configure the application
Open `/admin/config/analytics` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------- |
| Google Ads → Goals → Conversions → tag setup (`AW-…`). | **Google Ads ID** |
| The label next to the conversion action. It is saved and made available to the page, but no conversion is fired automatically. | **Google Ads conversion label** |
Save the form.
## Verify
1. Open a public page in a private window with blockers disabled.
2. Check for `googletagmanager.com/gtag/js` on the page.
This loads the Ads tag. Reporting a conversion still requires an event for your chosen conversion action.
## Troubleshooting
### No script appears on the page
The identifier is empty, the page was not reloaded after saving, or an ad blocker removed it. Check the **Runtime checks** panel, then reload with extensions off.
## Next steps
[Add analytics and support chat](https://kernlift.dev/docs/extensions/analytics.md)
---
# Google Analytics
> Connect your website to Google Analytics.
Source: https://kernlift.dev/docs/extensions/analytics/google-analytics
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — the provider’s tag on a public page.
## Set up Google Analytics
### Set up a web stream
Open [Google Analytics](https://analytics.google.com/). Create a GA4 property and a Web data stream. Copy its measurement ID.
### Enable reporting
For reports, record the numeric property ID and enable the Analytics Data API.
### Authorize report access
Obtain a read-only OAuth access token for an account with property access.
Provider documentation · [GA4 Measurement ID](https://support.google.com/analytics/answer/9311124?hl=en)
## Configure the application
Open `/admin/config/analytics` in the Kernlift admin console.
| Value from provider | Admin field |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
| Google Analytics → Admin → Data streams → your web stream → Measurement ID (`G-…`). | **Google Analytics ID** |
| Google Analytics → Admin → Property details. Digits only. | **GA property ID** |
| An OAuth access token with read access to the property, for example with the `analytics.readonly` scope. Tokens are short-lived, so paste a fresh one before pulling reports. | **GA Data API access token** |
Save the form.
## Verify
1. Open a public page in a private window with blockers disabled.
2. Check for `googletagmanager.com/gtag/js` on the page.
## Troubleshooting
### No script appears on the page
The identifier is empty, the page was not reloaded after saving, or an ad blocker removed it. Check the **Runtime checks** panel, then reload with extensions off.
## Next steps
[Add analytics and support chat](https://kernlift.dev/docs/extensions/analytics.md)
---
# Add analytics and support chat
> Load Google Analytics, Umami, Plausible, Clarity or the Crisp chat widget on every page, check the connection and read statistics by country.
Source: https://kernlift.dev/docs/extensions/analytics
When you save a provider's identifier in the admin console, its script loads on every page. When you also save its API credential, you can pull a report to confirm the connection. Every provider is optional and independent, and none reads environment variables.
## Before you begin
* An account with each provider you want, with a site or project for your domain.
* An admin account with `config.write`. `config.read` opens the page but cannot save, pull reports or send a test event.
* For statistics by country, `countries.read`.
Each provider has two parts: a public identifier that loads the script, and an API credential used only when an admin pulls a report.
| Provider | What it adds | Loads the script | Needed for report pulls |
| ----------------- | ----------------------------------------------- | ----------------------- | --------------------------------------------------- |
| Google Analytics | Page views and events in GA4 | **Google Analytics ID** | **GA property ID** and **GA Data API access token** |
| Google Ads | The Google tag for your Ads account | **Google Ads ID** | Not pulled |
| Umami | Privacy-focused analytics, cloud or self-hosted | **Umami website ID** | **Umami API key** |
| Plausible | Privacy-focused analytics, cloud or self-hosted | **Plausible domain** | **Plausible API key** |
| Microsoft Clarity | Heatmaps and session recordings | **Clarity project ID** | **Clarity API token** |
| Crisp | Live chat widget | **Crisp website ID** | Not pulled |
## Create a site with the analytics provider
| Provider | Choose it for |
| --------------------------------------------------------------- | ------------------------------------------------- |
| [Google Analytics](https://kernlift.dev/docs/extensions/analytics/google-analytics.md) | GA4 page views and report pulls |
| [Google Ads](https://kernlift.dev/docs/extensions/analytics/google-ads.md) | Load the Ads tag and configure a conversion label |
| [Umami](https://kernlift.dev/docs/extensions/analytics/umami.md) | Measure visits in Umami Cloud or on your host |
| [Plausible](https://kernlift.dev/docs/extensions/analytics/plausible.md) | Domain-based traffic statistics |
| [Microsoft Clarity](https://kernlift.dev/docs/extensions/analytics/clarity.md) | Heatmaps and session recordings |
| [Crisp](https://kernlift.dev/docs/extensions/analytics/crisp.md) | Embed the chat widget |
## Connect a provider
### Open Analytics Config
Go to **Settings → Analytics Config** (`/admin/config/analytics`). The form has one section per provider: **Google**, **Umami**, **Plausible** and **Clarity / Crisp**. The **Runtime checks** panel shows whether each identifier is saved.
### Fill in the fields for your provider
Use the field mapping in your provider’s guide above.
Token and API key fields are never shown again. Their placeholder reads **Leave blank to keep current token**. Clearing an identifier removes that provider's script, and clearing a base URL or script URL restores its default.
### Save
Click **Save analytics config**. The page shows **Analytics provider configuration saved.** and the **Runtime checks** panel updates.
**No consent banner**
Once saved, each configured script loads on every page of the site, including the admin console, from the next page load. There is no consent banner or per-page switch. If you need visitor consent before tracking, add it to your application before enabling a provider.
## Pull provider reports
### Pull
On **Analytics Config**, in the **Provider reports** card, click **Pull reports**.
### Read the result
Each of Google Analytics, Umami, Plausible and Clarity shows **Passed** with a returned row count, **Failed** with the provider's HTTP status, or **Not configured** naming the missing fields. A provider is contacted only when both its identifier and its API credential are saved. The current Clarity request asks for 7 days, but its Data Export API accepts only 1–3 days. The provider may therefore reject that report check, which does not show that the script is absent.
## Record your own events
To try it without code, use the **Send a test event** card on **Analytics Config**: keep the defaults or choose a **Category** and **Event name**, and click **Send event**. **Event recorded.** confirms it was stored.
From trusted server code, record product events the same way. The function performs no permission check, so never expose it directly to the browser:
```ts title="src/server/services/example.service.ts"
import { trackAnalyticsEvent } from "@/server/services/analytics-support.service";
await trackAnalyticsEvent({
type: "product",
name: "project_created",
userId: user.id,
path: "/app/projects",
locale: "en",
value: 1,
});
```
`type` is one of `product`, `revenue`, `ai`, `api`, `acquisition`, `support` or `retention`. Events stay in your database and are not sent to external providers.
For the separate account and settled-order breakdown by country, see [Countries and regions](https://kernlift.dev/docs/core/admin/countries.md). That page reads your own account and order records and does not use a provider report.
## Verify
1. Open a public page such as `/` or `/pricing` in a private window, with ad blockers off.
2. View the page source and look for the script: `googletagmanager.com/gtag/js` for Google Analytics or Google Ads, a script with your `data-website-id` for Umami, a script with your `data-domain` for Plausible, `clarity.ms/tag` for Clarity and `client.crisp.chat/l.js` for Crisp.
3. Confirm the visit appears in the provider's real-time view. The Crisp chat bubble appears in the page corner.
4. `/setup` lists **Analytics provider** as ready once a Google Analytics, Umami, Plausible or Clarity identifier is saved.
In the repository, `pnpm validate:analytics` checks the settings, events, report pulls and permissions.
## Troubleshooting
### Saving fails with a format error
The Google Analytics ID must look like `G-XXXXXXXX`, the property ID must be numeric, and the Google Ads ID must look like `AW-XXXXXXXX`. Nothing is saved until all three are valid.
### A provider report shows Failed
The provider rejected the request. The report shows the HTTP status and the start of the response. For Google Analytics, check that the access token has not expired and can read the property.
### No script appears on the page
The identifier is empty, the page was not reloaded after saving, or an ad blocker removed it. Check the **Runtime checks** panel, then reload with extensions off.
### The Crisp widget shows "Invalid website"
The saved **Crisp website ID** does not match a website in your Crisp account. Copy it from Crisp and save again.
## Reference
* [Countries and regions](https://kernlift.dev/docs/core/admin/countries.md)
* [Configuration model](https://kernlift.dev/docs/core/configuration.md)
* [Plausible docs](https://plausible.io/docs)
## Next steps
- [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md)
- [Configuration model](https://kernlift.dev/docs/core/configuration.md)
---
# Plausible
> Connect your website to Plausible.
Source: https://kernlift.dev/docs/extensions/analytics/plausible
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — the provider’s tag on a public page.
## Set up Plausible
### Add the site
Open [Plausible](https://plausible.io/sites). Add your website and copy the registered domain exactly.
### Create the Stats API key
For reports, create a Stats API key in the team that owns the site.
Provider documentation · [Stats API keys](https://plausible.io/docs/stats-api)
## Configure the application
Open `/admin/config/analytics` in the Kernlift admin console.
| Value from provider | Admin field |
| -------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| The site domain exactly as registered in Plausible, for example `example.com`. | **Plausible domain** |
| Plausible → Account settings → API keys (Stats API). | **Plausible API key** |
| Prefilled with `https://plausible.io` and `https://plausible.io/js/script.js`. Change both only if you self-host Plausible or use a custom script. | **Plausible API base URL**, **Plausible script URL** |
Save the form.
## Verify
1. Open a public page in a private window with blockers disabled.
2. Check for `data-domain` on the page.
## Troubleshooting
### No script appears on the page
The identifier is empty, the page was not reloaded after saving, or an ad blocker removed it. Check the **Runtime checks** panel, then reload with extensions off.
## Next steps
[Add analytics and support chat](https://kernlift.dev/docs/extensions/analytics.md)
---
# Umami
> Connect your website to Umami.
Source: https://kernlift.dev/docs/extensions/analytics/umami
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — the provider’s tag on a public page.
## Set up Umami
### Register the domain
Open [Umami](https://cloud.umami.is/). Under Settings → Websites register the public site domain and copy the Website ID.
### Create a reporting key
For Umami Cloud reports, create a key under Settings → API keys.
Provider documentation · [adding a website](https://v2.umami.is/docs/add-a-website) · [Cloud API keys](https://docs.umami.is/docs/cloud/api-key)
## Configure the application
Open `/admin/config/analytics` in the Kernlift admin console.
| Value from provider | Admin field |
| ---------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| Umami → Settings → Websites → your site → Website ID. | **Umami website ID** |
| Umami Cloud → Settings → API keys. | **Umami API key** |
| Prefilled with `https://api.umami.is` and `https://cloud.umami.is/script.js`. Change both only if you self-host Umami. | **Umami API base URL**, **Umami script URL** |
Save the form.
## Verify
1. Open a public page in a private window with blockers disabled.
2. Check for `data-website-id` on the page.
## Troubleshooting
### No script appears on the page
The identifier is empty, the page was not reloaded after saving, or an ad blocker removed it. Check the **Runtime checks** panel, then reload with extensions off.
## Next steps
[Add analytics and support chat](https://kernlift.dev/docs/extensions/analytics.md)
---
# Set up email and password sign-in
> Users can create an account, verify their email address, sign in and reset a forgotten password.
Source: https://kernlift.dev/docs/extensions/auth/email-password
Email and password is the default sign-in method. You set the session secret in the environment, then control sign-up and verification from the admin console.
## Before you begin
* A migrated database and a first administrator. See [First steps after install](https://kernlift.dev/docs/customize/first-steps.md).
* An admin account with `config.read` and `config.write`.
* An email provider, so verification and reset emails can be delivered. See [Send transactional email](https://kernlift.dev/docs/extensions/email.md).
## Set the session secret and base URL
### Set the session secret
Set `BETTER_AUTH_SECRET` to a long random value in the deployment environment, for example the output of `node -e "console.log(crypto.randomUUID()+crypto.randomUUID())"`. It is the only auth setting stored in the environment, because it is needed before the database is read. Outside development the app does not start without it.
### Set the base URL
Sign in as an administrator and go to **Settings → Auth Config** (`/admin/config/auth`). In the **Better Auth** panel, set **Base URL** to the public URL of your deployment, for example `https://`, and click **Save**. The page shows **Configuration saved.**
## Choose the account rules
The **Better Auth** panel on **Auth Config** holds the switches that apply to every account.
### Set the switches
* **Enabled**: turns email and password sign-up and sign-in on or off. Saving here also updates the **Enabled** switch in the **Email Login** panel, so change it here.
* **Delete account**: lets signed-in users delete their own account from `/app/profile`.
* **Email verification**: when on (the default), a user who has not clicked the verification link cannot sign in, and each attempt sends a fresh verification email.
### Leave the secret alone
**Secret** already holds the value from `BETTER_AUTH_SECRET`. Leave it blank to keep it.
### Save
Click **Save**. Each panel on the page saves only its own fields.
**Changing the secret signs everyone out**
Entering a new value in **Secret** replaces the stored one, and every existing session stops working. With **Email verification** on and no email provider, sign-up still succeeds but new users cannot sign in.
The **Allow new users** switch in the **Email Login** panel does not currently restrict email sign-up.
## Verify
### Create an account
In a private browser window, open `/auth/sign-up` and create an account. The form shows that the account was created and asks you to verify your email.
### Verify and sign in
Open the link in the verification email. It lands on `/auth/verify-email`. Then sign in at `/auth/sign-in`. You land on `/app/profile`.
### Reset the password
Sign out, open `/auth/forgot-password` and request a reset for the same address. The reset email is always sent in English, and its link opens `/auth/reset-password`, where you set a new password.
`/setup` reports whether the session secret is set and at least one sign-in method is available. To check the wiring from the command line, run `pnpm validate:auth`.
## Troubleshooting
### Sign-in says the email is not verified
**Email verification** is on, so unverified addresses are rejected and a new verification email is sent on each attempt. Turn it off on **Auth Config** if your product does not need verified email. If no email arrives, check the provider on **Email Config** and the log at `/admin/email/deliveries`.
### The app refuses to start with a session secret error
`APP_ENV` is not `development` and `BETTER_AUTH_SECRET` is unset or still the template value. Set it to a random value.
### Sign-in sends users to `/system/rate-limited`
Sign-in is limited to 10 attempts per 5 minutes for each IP address and email. Wait for the window to pass.
### Signed-in users are sent to `/system/session-expired`
The account's status is **Pending**. Set it to **Active** on the user's page in the admin console. See [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md).
## Reference
* [Authentication](https://kernlift.dev/docs/core/auth.md)
* [Send transactional email](https://kernlift.dev/docs/extensions/email.md)
* [Better Auth](https://better-auth.com/docs)
## Next steps
- [Add Google and GitHub sign-in](https://kernlift.dev/docs/extensions/auth/social.md)
- [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md)
- [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md)
- [Environment variables](https://kernlift.dev/docs/reference/env.md)
---
# GitHub
> Let buyers sign in with GitHub.
Source: https://kernlift.dev/docs/extensions/auth/github
## Before you begin
Copy the full URL ending in `/api/auth/callback/github` from **Callback URLs** on `/admin/config/auth`. It must use the origin where users sign in.
**Expected result** — the provider’s sign-in button on your site.
## Set up GitHub
### Register an OAuth App
Open [GitHub](https://github.com/settings/developers). Create a new OAuth App and enter the site homepage.
### Set the callback URL
Paste the GitHub URL from Callback URLs into Authorization callback URL.
### Generate the client secret
Generate a client secret and copy the Client ID from the same app.
Provider documentation · [GitHub's OAuth app guide](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/creating-an-oauth-app)
## Configure the application
Open `/admin/config/auth` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ------------- |
| Client ID | Client ID |
| Client secret | Client Secret |
Enable this provider. To accept first-time users, enable **Allow new users**, then save.
## Verify
1. In a private window open `/auth/sign-in` and choose GitHub.
2. Complete consent and verify the browser returns to the signed-in workspace.
## Troubleshooting
### The provider rejects the redirect
The callback URL registered with Google or GitHub does not match the one in the **Callback URLs** panel. Copy it again, including the scheme and domain.
## Next steps
[Add Google and GitHub sign-in](https://kernlift.dev/docs/extensions/auth/social.md)
---
# Google
> Let buyers sign in with Google.
Source: https://kernlift.dev/docs/extensions/auth/google
## Before you begin
Copy the full URL ending in `/api/auth/callback/google` from **Callback URLs** on `/admin/config/auth`. It must use the origin where users sign in.
**Expected result** — the provider’s sign-in button on your site.
## Set up Google
### Configure the consent screen
Open [Google](https://console.cloud.google.com/auth/clients). Configure the consent screen. Add test users if the app is in testing.
### Create the web client
Create a Web application client.
### Register the redirect URI
Register the Google URL from the Callback URLs panel. Copy the Client ID and secret.
Provider documentation · [Google's web OAuth guide](https://developers.google.com/identity/protocols/oauth2/web-server)
## Configure the application
Open `/admin/config/auth` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ------------- |
| Client ID | Client ID |
| Client secret | Client Secret |
Enable this provider. To accept first-time users, enable **Allow new users**, then save.
## Turn on Google One Tap (optional)
One Tap shows Google's "Continue as …" prompt on the sign-in and sign-up pages, so a visitor already signed in to Google signs in or signs up with one click. It reuses the Google client above.
1. In the Google client, add your site origin, for example `https://`, under **Authorized JavaScript origins**. One Tap is refused from an origin that is not listed.
2. On `/admin/config/auth`, turn on **Google One Tap** in the Google panel and save. It takes effect only while Google sign-in is enabled and its client ID and secret are saved.
While it is on, Better Auth serves `POST /api/auth/one-tap/callback`, which verifies Google's ID token against your client ID; while it is off, that endpoint does not exist. A first-time user can sign up through One Tap only when **Allow new users** is on, and a banned user is still refused.
## Verify
1. In a private window open `/auth/sign-in` and choose Google.
2. Complete consent and verify the browser returns to the signed-in workspace.
3. With One Tap on, open `/auth/sign-in` in a browser signed in to Google. The prompt appears; choosing your account signs you in and returns you to the page you were going to.
## Troubleshooting
### The One Tap prompt does not appear
Check that Google sign-in is enabled with its client ID and secret, that **Google One Tap** is on, and that the site origin is in **Authorized JavaScript origins**. Google also stops showing the prompt for a while after a visitor dismisses it.
### The provider rejects the redirect
The callback URL registered with Google or GitHub does not match the one in the **Callback URLs** panel. Copy it again, including the scheme and domain.
## Next steps
[Add Google and GitHub sign-in](https://kernlift.dev/docs/extensions/auth/social.md)
---
# Add Google and GitHub sign-in
> The sign-in and sign-up pages show a Google or GitHub button that signs users in through their existing account.
Source: https://kernlift.dev/docs/extensions/auth/social
Google and GitHub sign-in are switched on separately in the admin console. Each needs an OAuth app registered with the provider, and changes apply to the next sign-in without a restart.
## Before you begin
* A deployment with a public URL and **Base URL** set on **Auth Config**. See [Set up email and password sign-in](https://kernlift.dev/docs/extensions/auth/email-password.md).
* An admin account with `config.read` and `config.write`.
* A Google Cloud project or a GitHub account where you can create an OAuth app.
## Register the OAuth app
| Provider | Choose it for |
| -------------------------------------- | --------------------------------------- |
| [Google](https://kernlift.dev/docs/extensions/auth/google.md) | Sign in using a Google web OAuth client |
| [GitHub](https://kernlift.dev/docs/extensions/auth/github.md) | Sign in through a GitHub OAuth App |
## Turn the provider on
### Paste the credentials
In the **Google Login** or **GitHub Login** panel, fill in **Client ID** and **Client Secret** from the OAuth app page. The credential fields are never shown again after saving. Leave one blank to keep the stored value.
### Set the switches
* **Enabled**: shows the provider's button on the sign-in and sign-up pages.
* **Allow new users**: when off, the provider only signs in people who already have an account.
### Save
Click **Save** in that panel. The **Login Channels** panel shows which methods are enabled.
**Buttons without credentials**
An enabled button without both a client ID and a client secret shows a message that the provider needs them, and does not redirect.
## Providers
A provider without credentials resolves to a disabled provider, and the
sign-in page does not offer it.
## Verify
In a private browser window, open `/auth/sign-in` and click **Continue with Google Login** or **Continue with GitHub Login**. After approving on the provider's page you land on `/app/profile`. `pnpm validate:auth` also checks the not-configured state and the **Auth Config** wiring.
## Troubleshooting
### The provider rejects the redirect
The callback URL registered with Google or GitHub does not match the one in the **Callback URLs** panel. Copy it again, including the scheme and domain.
### The user lands on `/auth/error`
The OAuth exchange failed after the redirect. Check that **Client Secret** belongs to the same app as **Client ID**. A secret regenerated with the provider must be pasted again.
### A new user cannot sign in with the provider
**Allow new users** is off for that provider, so only existing accounts can use it. Turn it on and click **Save**.
## Reference
* [Authentication](https://kernlift.dev/docs/core/auth.md)
* [Better Auth social providers](https://better-auth.com/docs/authentication/google)
* [Google OAuth](https://developers.google.com/identity/protocols/oauth2)
## Next steps
- [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md)
- [Set up email and password sign-in](https://kernlift.dev/docs/extensions/auth/email-password.md)
- [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md)
---
# Publish content with the CMS
> Write, publish and organise blog posts, legal pages, a changelog and a roadmap in English and Chinese from the admin console.
Source: https://kernlift.dev/docs/extensions/cms
The CMS module publishes your blog at `/blog` (with an RSS feed at `/blog/rss.xml`), legal pages at `/legal/`, a `/changelog` and a `/roadmap`. Every save keeps a revision and runs SEO checks.
## Before you begin
* A project that runs locally. See [Quick start](https://kernlift.dev/docs/quick-start.md). The `cms` module is part of the base repository and shows as **CMS** under **Content** in the admin sidebar.
* An admin account with `cms.read` to open the pages and `cms.write` to create or save entries and add taxonomy terms. The **Content Manager** role holds both.
**Footer links need published entries**
The public footer links to `/blog`, `/legal/privacy` and `/legal/terms`. Publish the `privacy` and `terms` legal entries after installing, or those links lead to a not-found page.
## Create an entry
### Start a new entry
Go to **Content → CMS** (`/admin/cms`). On the **Posts** tab, click **New entry** and choose the **Type**: **Blog post**, **Page**, **Legal**, **Changelog**, **Roadmap** or **Showcase**. The type cannot be changed later.
### Fill in the fields
* **Title**, **Excerpt** and **Markdown** for the content. Markdown renders `#` and `##` headings and paragraphs.
* **Slug**: saved in lower case with other characters turned into hyphens, so `Launch Notes` becomes `launch-notes`.
* **Locale**: **English** or **中文**. A Chinese entry appears under `/zh`.
* **Category** and **Tags** (comma separated): free text.
* **SEO title** and **SEO description**.
* **OG image**: the social preview image path or URL. Leave it blank to keep the current image.
### Create it
Click **Create entry**. The entry is saved with its first revision and opens in the editor. Type, slug and locale must be unique together; creating never replaces an existing entry.
## Publish an entry
### Open the entry
Click the entry's title on its tab to open the editor. Roadmap entries have no tab; open one at `/admin/cms/editor/cms_roadmap__`.
### Publish
Set **Status** to **Published** and click **Save content**. The entry appears on its public page for that locale.
Setting it back to **Draft** or **Archived** removes it from listings, and its page shows the not-found state. The first publish date is kept and reused when you publish again. Every save records a revision; the **Revisions** card shows the count.
| Tab | Shows |
| ------------- | ---------------------------------------------- |
| **Posts** | Blog posts, published on `/blog` |
| **Pages** | Page and showcase entries |
| **Changelog** | Entries published on `/changelog` |
| **Legal** | Entries published on `/legal/` |
| **Taxonomy** | Categories, tags and modules with usage counts |
| **SEO** | Check results from every save |
## Fix SEO warnings
### Open the SEO tab
Every save adds three checks for the entry: an SEO title between 10 and 70 characters, an SEO description between 50 and 160 characters, and a kebab-case slug.
### Fix and save again
A check that does not pass shows `warn`. Adjust the field in the editor and click **Save content**.
## Add taxonomy terms
### Open Taxonomy
Open the **Taxonomy** tab.
### Fill in Add term
Choose the **Type** (**Category**, **Tag** or **Module**) and the **Locale**, and fill in **Label**, **Slug** and, optionally, **Description**.
### Save
Click **Add term**. The term appears in the table; its usage counts entries whose category or tags match its slug.
## Verify
1. Create a **Blog post**, set **Status** to **Published** and click **Save content**.
2. Open `/blog`: the post is listed, opens at `/blog/`, and appears in `/blog/rss.xml`.
3. In the repository, run `pnpm validate:cms`.
## Troubleshooting
### "An entry with this type, locale and slug already exists."
**New entry** found an entry with the same type, locale and slug. Open the existing entry from its list, or use a different slug.
### "CMS slug, locale, and type must be unique."
Another entry already uses that type, slug and locale. Change the slug.
### A post or legal page shows "not found"
The entry is a draft or archived, or its locale does not match the URL. Set **Status** to **Published** and open a Chinese entry under `/zh`.
### An entry does not appear on `/blog`
Listings show only published entries whose locale matches the URL. A Chinese entry appears on `/zh/blog`, not `/blog`.
### "No CMS entry has this id."
The editor address points at an entry that does not exist. Open the entry from its list.
## Reference
* [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md)
* [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md)
* [MDX](https://mdxjs.com/docs/)
## Next steps
- [Plugins](https://kernlift.dev/docs/core/plugins.md)
- [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md)
---
# Credits ledger
> How credits are stored as an append-only ledger with a balance snapshot, and how hold, capture and refund keep metered charges accurate.
Source: https://kernlift.dev/docs/extensions/credits
Credits are the unit your product charges for metered work such as AI tasks. Every change
is an entry in an append-only ledger, and the balance is a snapshot that can
be rebuilt from it. To configure credits, see [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md).
## Two balances
Each user has two balances.
| Balance | Meaning |
| ------------- | ------------------------------------------------------- |
| **Available** | Credits the user can spend right now |
| **Reserved** | Credits held for work that has started but not finished |
A snapshot row per user stores both, plus lifetime purchased and lifetime used totals. New users start
at zero, unless the sign-up bonus on `/admin/config/auth` is on.
## Every change is a ledger entry
All writes go through one function that, for each entry:
1. Rejects an amount that is not positive.
2. Applies the entry's change to available and reserved.
3. Rejects the write if either balance would become negative.
4. Appends the entry with its deltas and the balances after it.
5. Updates the snapshot: lifetime purchased grows on grants and purchases, lifetime used on captures.
6. Records an audit log entry.
Entries are never edited or deleted, so the ledger holds the full history of a user's credits.
| Operation | Entry type | Available | Reserved |
| ------------------------------------- | ------------ | --------- | --------- |
| Admin grant | `grant` | `+amount` | 0 |
| Sign-up bonus (source `signup.bonus`) | `grant` | `+amount` | 0 |
| Admin deduction | `adjustment` | `-amount` | 0 |
| Purchase (plan credits) | `purchase` | `+amount` | 0 |
| Reserve | `reserve` | `-amount` | `+amount` |
| Capture | `capture` | 0 | `-amount` |
| Refund | `refund` | `+amount` | `-amount` |
## Hold, then capture or refund
Metered work holds the price first, then captures or refunds it:
| Reservation status | Reached when | Ledger effect |
| ------------------ | ---------------------------------------------- | ----------------------------- |
| `reserved` | The work starts and available covers the price | Available moves to reserved |
| `captured` | The work succeeds | Reserved is consumed |
| `refunded` | The work fails | Reserved returns to available |
A reservation settles exactly once. Capturing or refunding a reservation that is already settled, that
does not exist or that belongs to another user throws, so a retry cannot charge twice. When available
does not cover the price, the work does not start and the user is sent to `/system/insufficient-credits`.
## How AI work uses it
* **Tasks** reserve the resolved channel price before the provider is called, capture on success and
refund on failure. Asynchronous tasks settle when their final status arrives by webhook or poll.
* **Chat** reserves an estimate before the model call. When the stream ends it refunds that hold,
reserves the amount priced from actual token usage and captures it immediately. If the capture fails,
it refunds.
How a price is resolved is covered in [AI channels, scenes and task lifecycle](https://kernlift.dev/docs/extensions/ai.md).
## The sign-up bonus is granted once per user
When the bonus is on, the Better Auth user-create hook grants it to every new user, whichever way they sign up. The entry id is fixed per user (`credit_entry_signup_`), so a repeated call finds the existing entry and a concurrent duplicate fails before the balance changes. A failed grant is logged and never blocks sign-up. The switch and amount are admin settings, not environment variables; see [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md).
## Plan credits are granted once per order
When a paid order settles, the plan's included credits are added as a `purchase` entry with source
`billing.order.`. An existing entry with that source for the same user skips the grant, so a
webhook and a callback settling the same order add credits only once. See
[Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md).
## Recompute and repair
The ledger is the source of truth, so the snapshot can be checked at any time. Recomputing sums
every entry's deltas and reports whether they match the snapshot. Users can run this read-only check on
their own balance. Repairing, which needs the `credits.write` permission, writes the recomputed totals
back to the snapshot, rebuilds the lifetime totals and records the before and after values in the
audit log.
## Expiry is not implemented
The schema accepts an `expire` entry type and the admin ledger can filter by it, but nothing writes
`expire` entries and grants carry no expiry date. Credits do not expire. Adding expiry means storing an
expiry per grant, which is a schema change in both dialects, and writing `expire` entries through the
same ledger function.
## Files
- Ledger/
- src/server/services/credits-ledger.service.ts
- src/server/db/repositories/credits-ledger.repository.ts
- src/server/db/repositories/credits-config.repository.ts
- Workspace/
- src/components/credits/credits-workspace.tsx
## Next steps
- [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md)
- [AI channels, scenes and task lifecycle](https://kernlift.dev/docs/extensions/ai.md)
- [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
---
# Charge usage with credits
> Users hold a credit balance from plans or grants, and metered work such as AI tasks is paid from it.
Source: https://kernlift.dev/docs/extensions/credits/usage
Credits are the unit your product charges for metered work. Users get them from paid plans, from an operator, or as a sign-up bonus. Each task reserves its price before it runs, and the credits are deducted only if the work succeeds. Credits need no provider and no environment variables, new users start at zero unless you turn on the sign-up bonus, and credits do not expire.
## Before you begin
* An admin account with `credits.read` and `credits.write`. To put credits on plans you also need `products.write`; the built-in **Commerce Manager** role holds the products and credits permissions.
* For plan credits to reach buyers, a connected payment provider. See [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
## Give users credits
**With a plan**
### Open the plan
Go to **Commerce → Products** (`/admin/products`), click the product key and pick a plan in the **Plans** card.
### Set the number
Enter the number in **Included credits** and click **Save plan**. Leave it at `0` for a plan that adds no credits.
When an order for that plan is paid, the buyer receives the credits once, even if the provider sends the payment event more than once. The grant reads the `en` plan row first, so set **Included credits** on the `en` plan and keep the other locales at the same number.
**By hand**
### Find the user
Go to **Overview → Users** (`/admin/users/dashboard`).
### Enter the change
In the user's **Credit actions** cell, type the amount and write a change note of at least two characters.
### Apply it
Click **Grant** or **Deduct**. A deduction cannot take the available balance below zero.
The change appears in the user's ledger with your note, and in the audit log.
**On sign-up**
### Open the sign-up bonus
Go to **Settings → Auth Config** (`/admin/config/auth`) and find the **Sign-up bonus** panel. Saving it needs `config.write`.
### Set the amount
Turn on **Grant credits on sign-up**, enter **Credits per new user** (a whole number from 0 to 1,000,000) and click **Save**.
Every user created after you save receives the bonus once, whether they sign up with email and password, Google, GitHub or Google One Tap. Users who already exist get nothing. The grant is a `grant` entry with source `signup.bonus`, and a user can never receive a second one. If the grant fails, sign-up still succeeds and the error is logged; grant the credits by hand.
## Set what work costs
AI tasks are priced in credits on **Settings → AI Config**: a fixed price per task, rules by request parameters, or token usage. Follow [Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md). A task that costs more than the available balance is rejected before the provider is called.
## Charge credits for your own feature
Hold the price before the work starts, then settle the hold exactly once: capture it on success, refund it on failure. Call this from server code after you have resolved the user.
```ts title="src/server/services/export.service.ts"
import {
captureAiTaskCredits,
refundAiTaskCredits,
reserveAiTaskCredits,
} from "@/server/services/credits-ledger.service";
const { reservationId } = await reserveAiTaskCredits({
userId,
taskId: `export_${jobId}`,
amount: 5,
});
try {
await runExport(jobId);
await captureAiTaskCredits({ reservationId, userId });
} catch (error) {
await refundAiTaskCredits({ reservationId, userId });
throw error;
}
```
Reserving fails when the available balance is too low, and its error message contains `/system/insufficient-credits` so the UI can redirect. Store the `reservationId` next to your job so a retry or a poller settles the same hold.
**Never let users change balances directly**
Do not add a user-callable server function that grants, reserves, captures, refunds or repairs credits. User-facing functions only read and bind to the session user; `pnpm validate:session-owner` fails otherwise.
## Check or repair a balance
### Open the user
On **Overview → Users**, click **Details** on the user row. The **Credits** card shows the current balance and the latest ledger entries.
### Repair if needed
If the balance no longer matches the ledger, for example after a direct database edit, click **Repair snapshot**. The balance is rebuilt from the ledger, and the before and after values are written to the audit log.
## Verify
### Grant a test user 10 credits
Grant 10 credits by hand, sign in as that user and open `/app/credits`. The available balance shows 10 and the ledger shows your grant.
### Buy a plan
Buy a plan with **Included credits** in the provider's test mode, then reload `/app/credits`. The plan's credits appear as a purchase entry.
### Sign up a new user
With the sign-up bonus on, register a new account and open `/app/credits`. The ledger shows one `signup.bonus` grant of the configured amount.
### Run out of credits
Start an AI task that costs more than the remaining balance. It is not created and the user is sent to `/system/insufficient-credits`.
Users see the full ledger with a balanced or drift indicator at `/app/credits/ledger`, and holds and refunds at `/app/credits/reservations`. `pnpm validate:credits` checks the insufficient-credit path, drift repair and page wiring, and `pnpm validate:signup-credits` checks that the sign-up bonus is granted once and only while it is on.
## Troubleshooting
### A task fails with an insufficient credits error
The available balance is lower than the task's price. Credits held by tasks that are still running are not available. Grant credits or buy a plan with **Included credits**, then retry.
### `Reservation is already settled.`
The hold was already captured or refunded. Settle each reservation once, and check its status before retrying a capture or refund.
### The ledger page shows drift
The stored balance no longer equals the sum of the ledger, usually after a direct database edit. Open the user in the admin console and click **Repair snapshot**.
### A paid plan did not add credits
Check that **Included credits** on the plan's `en` row is above zero and that the order is paid on **Commerce → Orders**. If the order is still pending, see [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
## Reference
* [Credits ledger](https://kernlift.dev/docs/extensions/credits.md)
* [AI channels](https://kernlift.dev/docs/extensions/ai.md)
* [Double-entry bookkeeping](https://en.wikipedia.org/wiki/Double-entry_bookkeeping)
## Next steps
- [Credits ledger](https://kernlift.dev/docs/extensions/credits.md)
- [Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md)
- [Sell products and plans](https://kernlift.dev/docs/extensions/payments/products.md)
---
# Write a custom database adapter
> Register your own connection for the Postgres or SQLite schema family and select it with DATABASE_ADAPTER.
Source: https://kernlift.dev/docs/extensions/database/custom-adapter
Database connections are resolved through an adapter registry. The built-in adapters are `sqlite`, `postgres`, `turso` and `d1`; you can register your own, for example to use a company-specific Postgres driver or connection pool.
## Before you begin
* A Drizzle-compatible database client for an existing schema family: `postgres` or `sqlite`.
* A place in your server code that runs before the first database access.
**Same schema, different connection**
An adapter changes only how the app connects. A completely new SQL dialect, such as MySQL, also needs its own schema file, migration chain and repository branches.
## Register the adapter
### Call `registerDatabaseAdapter`
Register it before the first `getDatabase()` call:
```ts title="src/server/db/my-company-postgres.ts"
import { registerDatabaseAdapter } from "./client";
registerDatabaseAdapter({
id: "my-company-postgres",
dialect: "postgres",
runtime: "my-company-postgres",
canHandle: ({ config }) => Boolean(config.database.url),
create: ({ config }) => ({
adapter: "my-company-postgres",
dialect: "postgres",
runtime: "my-company-postgres",
db: createMyDrizzlePostgresClient(config.database.url),
}),
missingPackageHint: "Set DATABASE_URL to use my-company-postgres.",
});
```
`canHandle` returns whether the adapter can run in this environment. `create` returns the Drizzle database object. `missingPackageHint` is optional and is appended to the error when `canHandle` returns false.
### Select it
```bash title=".env"
DATABASE_DIALECT=postgres
DATABASE_ADAPTER=my-company-postgres
DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/postgres
```
`DATABASE_DIALECT` must match the adapter's `dialect`, so migrations use the right chain.
### Migrate
```bash
pnpm db:migrate
```
The adapter contract and registration flow are in `adapter-registry.ts`: `registerDatabaseAdapter`, `listDatabaseAdapters` and `resolveDatabaseAdapter`.
## Verify
* The app starts and `/admin` loads with the adapter selected.
* `pnpm validate:db-adapters` passes.
## Troubleshooting
### `DATABASE_ADAPTER="…" is not registered.`
The adapter was registered after the first database access, or not at all. The error lists the registered ids. Move the registration earlier.
### `Database adapter "…" cannot run in this environment.`
`canHandle` returned false, for example because `DATABASE_URL` is empty. The message ends with your `missingPackageHint`.
### `Database adapter "…" is already registered`
An adapter with that id exists. Choose a different id.
## Reference
* [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md)
* [Environment variables](https://kernlift.dev/docs/reference/env.md)
* [Drizzle ORM](https://orm.drizzle.team/docs/overview): the client your `create` returns
* [Drizzle migrations](https://orm.drizzle.team/docs/migrations): why the dialect determines the migration chain
## Next steps
- [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md)
- [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md)
- [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md)
---
# Neon
> Run the application database on Neon.
Source: https://kernlift.dev/docs/extensions/database/neon
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a migrated database that the running app can read.
## Set up Neon
### Select the branch and database
Open [Neon](https://console.neon.tech/). Create a project and select the target branch and database.
### Copy the migration URL
Open Connect and copy a non-pooled URL for migrations. Choose a runtime connection compatible with prepared statements.
Provider documentation · [Neon connections](https://neon.com/docs/connect/connect-from-any-app)
## Configure the application
Set these values in the server environment for the migration. Use `postgres` as the database dialect.
| Connection setting | Server variable |
| ------------------ | ----------------- |
| Postgres URL | DATABASE\_URL |
| Database dialect | DATABASE\_DIALECT |
Run `pnpm db:migrate` against the target database. Configure the application with the runtime connection for your deployment.
## Verify
1. Verify the migration completed successfully.
2. Start the application and open `/admin` with an administrator account.
## Troubleshooting
### `DATABASE_URL is required when DATABASE_ADAPTER=postgres`
The connection string is empty. Set `DATABASE_URL`.
## Next steps
[Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md)
---
# Use Postgres and Supabase
> Point the app at any Postgres database, including Supabase and Neon, and build its schema from the migration chain.
Source: https://kernlift.dev/docs/extensions/database/postgres
Any Postgres database works through the generic Drizzle Postgres adapter. Supabase and Neon are hosted Postgres endpoints on the same code path. The app uses no Supabase SDK, auth helper, storage API or row-level security.
## Before you begin
* A Postgres database and its connection string, for example from Supabase **Project Settings → Database**.
* A machine that can reach the database to run migrations.
* An empty database. A schema created by something other than the migration chain cannot be migrated in place.
## Create the database with the host
| Provider | Choose it for |
| ---------------------------------------------- | ----------------------------------- |
| [Supabase](https://kernlift.dev/docs/extensions/database/supabase.md) | Direct connection or session pooler |
| [Neon](https://kernlift.dev/docs/extensions/database/neon.md) | Branch-specific connection strings |
## Connect the database
### Set the connection
```bash title=".env"
DATABASE_DIALECT=postgres
DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/postgres
```
`DATABASE_ADAPTER` can stay unset; it defaults to `postgres`.
### Build the schema
```bash
pnpm db:migrate
```
This applies the Postgres chain under `drizzle/migrations/postgres`.
### Create the administrator
```bash
SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='' pnpm db:bootstrap-super-admin
```
**Keep credentials server-side**
Never expose the connection string or a Supabase service-role key to client code. If Supabase's Data API already exposes these tables, restrict role grants and enable and review row-level security; this application's server permissions do not automatically protect that API.
## Using a hosted Postgres database
Supabase and Neon use the same Postgres adapter and migration chain. Prefer direct connection for migrations and the runtime connection chosen above for the application; no provider SDK is needed. Schema changes require a matching migration in both the Postgres and SQLite chains.
## Where the connection goes in production
How a deployment reaches Postgres depends on the platform recorded in `deploy.config.json`. The steps above cover local use and migrating from a checkout; in production the connection is supplied like this:
| Platform | How the app connects | How the schema is migrated |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| Cloudflare | Through Hyperdrive: `DATABASE_ADAPTER=hyperdrive` and the `HYPERDRIVE` binding in `wrangler.jsonc`. The Worker never holds `DATABASE_URL` | `pnpm db:migrate` from the checkout, with `DATABASE_URL` set to the Postgres URL |
| Fly.io | `DATABASE_URL` as an app secret | `release_command` on each deploy |
| Railway | The Postgres declared in `.railway/railway.ts`; its `DATABASE_URL` is passed to the services | The pre-deploy step of the `web` service |
| Docker | The bundled `postgres` compose service, with `POSTGRES_PASSWORD` from `.env.production` | The `migrate` compose service |
On Workers the Postgres client lives for one request and Hyperdrive pools the connections behind it. See [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md), [Deploy to Fly.io](https://kernlift.dev/docs/deploy/fly.md), [Deploy to Railway](https://kernlift.dev/docs/deploy/railway.md) and [Deploy with Docker Compose](https://kernlift.dev/docs/deploy/docker.md).
## Verify
```bash
pnpm validate:db-adapters
```
Then start the app, sign in as the administrator and open `/admin`.
## Troubleshooting
### `DATABASE_URL is required when DATABASE_ADAPTER=postgres`
The connection string is empty. Set `DATABASE_URL`.
### `pnpm db:migrate` reports an existing schema
Tables exist that the migration chain did not create. Drop and recreate the database, then run `pnpm db:migrate` again.
### Do I run `pnpm db:generate`?
No. Generate writes a new migration for a schema change; it does not prepare a database.
## Reference
* [Environment variables](https://kernlift.dev/docs/reference/env.md)
* [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md)
* [Postgres.js](https://github.com/porsager/postgres): the driver this adapter loads
* [Supabase connection strings](https://supabase.com/docs/guides/database/connecting-to-postgres)
## Next steps
- [Run the Node build](https://kernlift.dev/docs/deploy/node.md)
- [Write a custom database adapter](https://kernlift.dev/docs/extensions/database/custom-adapter.md)
- [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md)
---
# Supabase
> Run the application database on Supabase.
Source: https://kernlift.dev/docs/extensions/database/supabase
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a migrated database that the running app can read.
## Set up Supabase
### Create the project
Open [Supabase](https://supabase.com/dashboard/projects). Create a Postgres project and store its database password.
### Copy the database connection
Open Connect and copy the direct migration URL. For IPv4-only hosts check the session pooler connection.
Provider documentation · [Supabase connection modes](https://supabase.com/docs/guides/database/connecting-to-postgres) · [securing the Data API](https://supabase.com/docs/guides/api/securing-your-api)
## Configure the application
Set these values in the server environment for the migration. Use `postgres` as the database dialect.
| Connection setting | Server variable |
| ------------------ | ----------------- |
| Postgres URL | DATABASE\_URL |
| Database dialect | DATABASE\_DIALECT |
Run `pnpm db:migrate` against the target database. Configure the application with the runtime connection for your deployment.
## Verify
1. Verify the migration completed successfully.
2. Start the application and open `/admin` with an administrator account.
## Troubleshooting
### `DATABASE_URL is required when DATABASE_ADAPTER=postgres`
The connection string is empty. Set `DATABASE_URL`.
## Next steps
[Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md)
---
# Use Turso
> Run the app on a Turso libSQL database through the SQLite schema branch and the turso adapter.
Source: https://kernlift.dev/docs/extensions/database/turso
Turso serves libSQL, which is compatible with SQLite. The app keeps the SQLite schema and the
SQLite migration chain and uses a different client. `DATABASE_DIALECT` stays `sqlite`, and you
set `DATABASE_ADAPTER=turso`.
## Before you begin
* A Turso database with its URL and a token:
`turso db show --url ` and `turso db tokens create `.
* `@libsql/client`, already a dependency of this project. The database layer `require.resolve`s it
and only loads it when the `turso` adapter is selected, so a SQLite or Postgres deployment does not
load it.
* Nothing in the admin console. The database connection is one of the three things that stay in
the environment. See [Configuration model](https://kernlift.dev/docs/core/configuration.md).
## Create the database in Turso
Install and log in to the CLI using the [Turso CLI guide](https://docs.turso.tech/cli/db/create), then run `turso db create `. Copy the `libsql://` URL from `turso db show --url ` and create an application token with `turso db tokens create `. Enter those values as `DATABASE_URL` and `DATABASE_AUTH_TOKEN` below. The CLI login credential is not the application database token. Keep the token server-side and set both values in the deployment environment as well. See [Turso tokens](https://docs.turso.tech/cli/db/tokens/create).
## Connect the database
### Set the connection
```bash title=".env"
DATABASE_DIALECT=sqlite
DATABASE_ADAPTER=turso
DATABASE_URL=libsql://YOUR-DATABASE.turso.io
DATABASE_AUTH_TOKEN=YOUR-TURSO-TOKEN
```
The adapter fails at startup if either value is missing. It does not fall back to a local file,
so a misconfigured deployment cannot write to the wrong database.
### Build the schema
```bash
pnpm db:migrate
```
This applies `drizzle/migrations/sqlite`, the same chain a local SQLite file and a Cloudflare D1
database get. Turso needs no migrations of its own.
### Create the administrator
```bash
SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='' pnpm db:bootstrap-super-admin
```
This also seeds the roles, permissions and the default rate-limit rules. You can re-run it. It
inserts what is missing and does not overwrite what an operator has edited.
## How the adapter is selected
`DATABASE_DIALECT=sqlite` selects the SQLite schema and migrations. `DATABASE_ADAPTER=turso` selects the libSQL client. The adapter fails at startup without a `libsql://` address, token or installed `@libsql/client` package. See [Environment variables](https://kernlift.dev/docs/reference/env.md) for the exact startup fields.
The built-in `sqlite`, `postgres`, `d1` and `turso` adapters are registered through the same `registerDatabaseAdapter` function used by custom adapters.
## Verify
```bash
pnpm validate:db-adapters
```
Then start the app, sign in as the administrator and open `/admin`. Run two more checks
once:
1. Unset `DATABASE_AUTH_TOKEN` and start. It throws `DATABASE_AUTH_TOKEN is required when
DATABASE_ADAPTER=turso` and does not open a local file.
2. Write something from the console, for example grant a licence, then read the row with the
Turso CLI. The CLI shows the row the app wrote.
## Troubleshooting
### `DATABASE_AUTH_TOKEN is required when DATABASE_ADAPTER=turso`
Create a token with `turso db tokens create ` and set it.
### `DATABASE_URL is required when DATABASE_ADAPTER=turso`
Set `DATABASE_URL` to the `libsql://` URL from `turso db show --url `.
### The adapter is not selected at all
`canHandle` also requires `@libsql/client` to resolve. After a fresh clone, run `pnpm install`.
## Reference
* [Environment variables](https://kernlift.dev/docs/reference/env.md)
* [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md)
* [Turso documentation](https://docs.turso.tech/)
* [Drizzle with libSQL](https://orm.drizzle.team/docs/get-started-sqlite#turso)
## Next steps
- [Write a custom database adapter](https://kernlift.dev/docs/extensions/database/custom-adapter.md)
The same interface the four built-in adapters implement.
- [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md)
Which adapter fits which runtime, and why.
- [Use Postgres](https://kernlift.dev/docs/extensions/database/postgres.md)
The other dialect, with its own migration chain.
- [Deploy to a Node host](https://kernlift.dev/docs/deploy/node.md)
Where a Turso deployment usually runs.
---
# Aliyun DirectMail
> Send transactional email with Aliyun DirectMail.
Source: https://kernlift.dev/docs/extensions/email/aliyun
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test message in your inbox and its delivery log.
## Set up Aliyun DirectMail
### Verify the sending domain
Open [Aliyun DirectMail](https://dm.console.aliyun.com/). Choose your Direct Mail region and verify a sending domain.
### Create the sender address
Create a triggered-email sender address in the same region.
### Create the RAM AccessKey
Create an AccessKey for a dedicated RAM identity with Direct Mail permission.
Provider documentation · [API sending setup](https://www.alibabacloud.com/help/en/direct-mail/getting-started/simplified-procedure-of-sending-by-api-and-smtp) · [sender-address setup](https://www.alibabacloud.com/help/en/direct-mail/user-guide/setup-sender-addresses)
## Configure the application
Open `/admin/config/email` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| Aliyun RAM console, for a user with DirectMail permission. | **AccessKey ID**, **AccessKey Secret** |
| The sender address under your verified domain in the DirectMail console. | **Sender account** |
| Optional: display name; endpoint (default `https://dm.aliyuncs.com`, change for a regional one); address type (default `1`); tick to route replies to the sender account. | **From alias**, **Endpoint**, **Address type**, **Reply to sender** |
Tick **Set as active email provider** and click **Save provider**.
## Verify
1. On `/admin/email/test`, choose a template and send it to your own address.
2. Confirm delivery in your inbox and a `sent` entry on `/admin/email/deliveries`.
## Troubleshooting
### Deliveries show `not_configured`
The active provider is missing a credential, or email is off. Resend needs an API key; Cloudflare needs account ID and API token; Aliyun needs AccessKey ID, secret and sender account.
## Next steps
[Send transactional email](https://kernlift.dev/docs/extensions/email.md)
---
# Cloudflare Email
> Send transactional email with Cloudflare Email.
Source: https://kernlift.dev/docs/extensions/email/cloudflare
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test message in your inbox and its delivery log.
## Set up Cloudflare Email
### Enable email sending
Open [Cloudflare Email](https://dash.cloudflare.com/). Enable Email Sending for the sender domain.
### Verify the sender domain
Publish and verify its DNS records.
### Copy the account ID
Copy the Account ID from the account overview.
### Issue the token
Create an API token with email sending permission.
Provider documentation · [Email Sending REST API](https://developers.cloudflare.com/email-service/api/send-emails/rest-api/) · [API-token setup](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)
## Configure the application
Open `/admin/config/email` in the Kernlift admin console.
| Value from provider | Admin field |
| ---------------------------------------------------------------------------------- | ----------------------------- |
| Mailbox on the verified domain | From address |
| Cloudflare account overview; My Profile → API Tokens, a token that can send email. | **Account ID**, **API token** |
Tick **Set as active email provider** and click **Save provider**.
## Verify
1. On `/admin/email/test`, choose a template and send it to your own address.
2. Confirm delivery in your inbox and a `sent` entry on `/admin/email/deliveries`.
## Troubleshooting
### Deliveries show `not_configured`
The active provider is missing a credential, or email is off. Resend needs an API key; Cloudflare needs account ID and API token; Aliyun needs AccessKey ID, secret and sender account.
## Next steps
[Send transactional email](https://kernlift.dev/docs/extensions/email.md)
---
# Send transactional email
> Verification, password reset and your own product emails are delivered through Resend, Cloudflare Email Service or Aliyun DirectMail from templates you can edit.
Source: https://kernlift.dev/docs/extensions/email
Email is sent from templates through one active provider. Every attempt, sent or not, is written to a delivery log. Set it up before launch. Without a provider, users cannot receive verification or password reset mail.
## Before you begin
* A sending domain verified with the provider (SPF, DKIM and similar DNS records). Mail from an unverified domain is rejected.
* The provider's credentials.
* An admin account with `config.read` and `config.write`.
Pick the provider by where your domain and account already live:
| Provider | Credentials | Sender |
| ----------------- | ------------------------ | ---------------------------------------------------------------------------------- |
| Resend | One API key | **From address**, on a domain verified in Resend |
| Cloudflare Email | Account ID and API token | **From address**, on a domain set up for Email Service in Cloudflare |
| Aliyun DirectMail | AccessKey ID and secret | **Sender account** created in the DirectMail console; **From address** is not used |
## Prepare the email provider
| Provider | Choose it for |
| ----------------------------------------------------- | ---------------------------------------------- |
| [Resend](https://kernlift.dev/docs/extensions/email/resend.md) | Send from a verified domain with a sending key |
| [Cloudflare Email](https://kernlift.dev/docs/extensions/email/cloudflare.md) | Send using a Cloudflare account and token |
| [Aliyun DirectMail](https://kernlift.dev/docs/extensions/email/aliyun.md) | Use a regional DirectMail sender account |
## Connect the provider
### Open Email Config
Go to **Settings → Email Config** (`/admin/config/email`). The cards at the top list **Resend**, **Cloudflare Email** and **Aliyun DirectMail**; each shows **Ready** when its credentials are saved, or **Missing**, and the sending provider is marked **Active**. Click the card you want.
### Set the sender
Under **Delivery**, fill in **From address** (for Resend and Cloudflare), for example `Acme `, and **Contact notification to**, the inbox that receives `/contact` form messages. A blank field keeps its current value.
### Paste the credentials
Under **Credentials**, fill in the fields for the selected provider:
Use the field mapping in your provider’s guide above.
Secret fields come back empty after saving; a blank field keeps the stored value.
### Activate and save
Tick **Set as active email provider** and click **Save provider**. The card shows **Active**, and the **Runtime** panel shows the provider and sender.
The effect of saving depends on the checkbox. Ticked, this card's provider becomes the active one. Unticked on the active provider's card, email sending is turned off. Unticked on another card, only that provider's settings are saved. The line under the box reads `Active provider: …` or `Email sending is off: no active provider.`
**Before a provider is configured**
Nothing is sent, and each attempt is logged as `not_configured`. Sign-up still works, but while **Email verification** is on, unverified users cannot sign in. `/setup` lists **Email delivery** as required until a provider is active.
## Know which emails are sent for you
These templates are sent without any code from you:
| Template | When |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `email-verification` | On sign-up, when an unverified user tries to sign in while email verification is required, and when a user asks to resend. |
| `password-reset` | When a user requests a password reset. Always sent in English. |
| `contact-routed` | When someone submits the contact form; sent to **Contact notification to**. |
The template set also includes `registration-success`, `newsletter-welcome`, `billing-receipt`, `payment-success`, `subscription-renewal`, `subscription-canceled`, `payment-failed`, `invoice-ready` and `security-alert`. Nothing sends these automatically; send them from your own code.
## Edit a template
### Open the templates
Open `/admin/email/templates`, part of the **Email** area in the **Settings** group. Each template appears once per locale under **Template configuration**, with its variables listed under the key.
### Change the content
Change the subject, **Text body** or **HTML body**. Use `{{name}}` placeholders for variables; values are HTML-escaped when sent.
### Save and preview
Click **Save template**; **Template saved.** confirms it and the variable list is rebuilt from the placeholders. Then open `/admin/email/preview`, pick the template and click **Render preview**. The preview uses the same layout as real delivery.
## Send an email from your code
Call the email service with a template key, recipient, locale and the template's variables.
```ts title="src/server/services/example.service.ts"
import { sendEmailTest } from "@/server/services/email-notifications.service";
const delivery = await sendEmailTest({
templateKey: "payment-success",
to: user.email,
locale: "en",
variables: {
name: user.name,
planName: "Pro",
amount: "$29.00",
orderId: order.id,
receiptUrl: receiptUrl,
},
});
if (delivery.status !== "sent") {
console.warn("Email not sent", delivery.status, delivery.errorMessage);
}
```
The call returns the delivery log row, with status `sent`, `failed` or `not_configured`. It throws only when the template does not exist. If any variable the template uses is missing, nothing is sent and the row is `failed` with `Missing template variables: ...`.
## Verify
### Send a test email
Open `/admin/email/test`; the header shows **Provider ready**. Choose a **Template** and **Locale**, enter your address as **Recipient**, give every variable a value in **Variables JSON**, and click **Send test email**. The form reports `Email delivery recorded:` and the result.
### Check delivery
The message arrives, `/admin/email/deliveries` lists it as `sent`, and `/auth/forgot-password` sends a reset link to an existing account.
`pnpm validate:email` checks templates, previews, logs and provider wiring. `EXTERNAL_VALIDATE_EMAIL_TO=you@example.com pnpm validate:external` sends a real password-reset email.
## Troubleshooting
### Deliveries show `not_configured`
The active provider is missing a credential, or email is off. Resend needs an API key; Cloudflare needs account ID and API token; Aliyun needs AccessKey ID, secret and sender account.
### Email stopped after saving a provider card
The active provider's card was saved with **Set as active email provider** unticked. Open that card, tick the box and click **Save provider**.
### A delivery is `failed` with a sender or domain error
The provider rejected the sender. Verify the domain with the provider and make sure **From address** (or the Aliyun **Sender account**) is on it.
### "Email template not found"
No template exists for that key and locale. Run `pnpm db:seed-baseline` on a fresh database.
## Reference
* [Notifications](https://kernlift.dev/docs/extensions/notifications.md)
* [Configuration model](https://kernlift.dev/docs/core/configuration.md)
* [Resend API](https://resend.com/docs/api-reference/introduction)
## Next steps
- [Send notifications to Slack, Discord or Feishu](https://kernlift.dev/docs/extensions/notifications.md)
- [Set up email and password sign-in](https://kernlift.dev/docs/extensions/auth/email-password.md)
- [Configuration model](https://kernlift.dev/docs/core/configuration.md)
---
# Resend
> Send transactional email with Resend.
Source: https://kernlift.dev/docs/extensions/email/resend
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test message in your inbox and its delivery log.
## Set up Resend
### Add the sending domain
Open [Resend](https://resend.com/domains). Add the domain used in your From address.
### Verify its DNS records
Publish the DNS records Resend shows and wait for Verified.
### Create a sending key
Create a Sending access key for that domain under API Keys.
Provider documentation · [domain verification](https://resend.com/changelog/domain-verification-events) · [API key permissions](https://resend.com/changelog/new-api-key-permissions)
## Configure the application
Open `/admin/config/email` in the Kernlift admin console.
| Value from provider | Admin field |
| --------------------------------------------------------------- | ------------ |
| Mailbox on the verified domain | From address |
| Resend dashboard → API Keys (`re_…`). Sending access is enough. | **API key** |
Tick **Set as active email provider** and click **Save provider**.
## Verify
1. On `/admin/email/test`, choose a template and send it to your own address.
2. Confirm delivery in your inbox and a `sent` entry on `/admin/email/deliveries`.
## Troubleshooting
### Deliveries show `not_configured`
The active provider is missing a credential, or email is off. Resend needs an API key; Cloudflare needs account ID and API token; Aliyun needs AccessKey ID, secret and sender account.
## Next steps
[Send transactional email](https://kernlift.dev/docs/extensions/email.md)
---
# Beehiiv
> Sync newsletter subscribers with Beehiiv.
Source: https://kernlift.dev/docs/extensions/newsletter/beehiiv
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test subscriber in your provider account.
## Set up Beehiiv
### Create the publication
Open [Beehiiv](https://developers.beehiiv.com/welcome/create-an-api-key). Create a publication and copy its publication ID.
### Authorize subscriber sync
Create a key with subscriber read/write access to the publication.
Provider documentation · [Create an API Key](https://developers.beehiiv.com/welcome/create-an-api-key) · [Publication API](https://developers.beehiiv.com/api-reference/publications/show)
## Configure the application
Open `/admin/waitlist/settings` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ---------------------- |
| API key | Beehiiv API key |
| Publication ID | Beehiiv publication id |
Select Beehiiv as the provider and save.
## Verify
1. Subscribe an address you control at `/newsletter`.
2. Retry the sync in admin and verify the entry is marked `success`.
3. Find the contact in Beehiiv.
## Troubleshooting
### Sync logs show `failed`
The provider rejected the request, and the log message contains its error. Correct the credentials on **Provider settings**, then run **Retry provider sync**.
## Next steps
[Newsletter and waitlist](https://kernlift.dev/docs/extensions/newsletter.md)
---
# Newsletter and waitlist
> Collect newsletter subscribers and a launch waitlist, sync them to Resend or Beehiiv, invite people in batches and retry failed syncs.
Source: https://kernlift.dev/docs/extensions/newsletter
The newsletter module adds public `/newsletter`, `/waitlist` and `/waitlist/status` pages, subscribes every new account, and syncs each subscribe, unsubscribe and invite to Resend or Beehiiv. Sign-ups work without a provider. Syncs stay queued until you connect one.
## Before you begin
* A project that runs locally. See [Quick start](https://kernlift.dev/docs/quick-start.md). The `newsletter` module is part of the base repository and shows as **Waitlist** under **Content** in the admin sidebar.
* An admin account with `newsletter.read` to open the pages and `newsletter.write` to save settings, invite and retry.
* A Resend API key with full access (so it can create contacts), or a Beehiiv API key and your publication ID.
To give a teammate access, assign the **Content Manager** role in **Overview → Users**. The role includes both newsletter permissions and the CMS permissions.
## Prepare the newsletter provider
| Provider | Choose it for |
| ---------------------------------------------- | ------------------------------------ |
| [Resend](https://kernlift.dev/docs/extensions/newsletter/resend.md) | Sync contacts with a full-access key |
| [Beehiiv](https://kernlift.dev/docs/extensions/newsletter/beehiiv.md) | Sync subscribers to one publication |
## Connect a provider
One provider is active at a time.
### Open Provider settings
Go to **Content → Waitlist** (`/admin/waitlist`) and open the **Provider settings** tab (`/admin/waitlist/settings`). The **Newsletter provider** item on `/setup` links here too.
### Choose the provider and enter credentials
Under **Provider**, choose **Resend** or **Beehiiv**, then fill in its fields:
Use the field mapping in your provider’s guide above.
Keys and the publication id are write-only. A field with a stored value shows **Stored. Leave blank to keep it**.
### Save
Click **Save provider settings**. The page shows **Newsletter provider settings saved.** and the next subscribe, unsubscribe or invite uses the provider.
To stop syncing, choose **Not configured** and save. New syncs then stay queued.
**Email Config is separate**
The module sends no email and does not read **Email Config**. A Resend key saved there is used for transactional email only. The newsletter needs its own key here.
## Invite from the waitlist
### Open Invite Batch
Open the **Invite Batch** tab (`/admin/waitlist/invites`).
### Invite a batch
Enter a **Batch size** from 1 to 100 and click **Invite batch**. The oldest waiting entries move to invited, and each email is synced to the provider.
### Tell them
No invitation email is sent. Send one through your own email flow.
## Retry queued and failed syncs
Syncs from before the provider was configured are still queued, and syncs the provider rejected are logged as failed.
### Open Invite Batch
Open the **Invite Batch** tab (`/admin/waitlist/invites`).
### Retry
Enter a **Batch size** under **Retry provider sync** and click **Retry provider sync**. The oldest syncs whose latest attempt is `pending` or `failed` are retried.
## Verify
1. Open `/newsletter` and subscribe an address you control.
2. On **Invite Batch**, click **Retry provider sync**.
3. The log shows a new row with your provider and status `success`, and the contact appears in the Resend or Beehiiv dashboard.
In the repository, `pnpm validate:newsletter` runs these flows. To test a real provider, set `EXTERNAL_VALIDATE_NEWSLETTER_EMAIL` and run `EXTERNAL_VALIDATE_STRICT=true pnpm validate:external`.
## Troubleshooting
### Sync logs stay `pending`
No provider is configured, so nothing was sent. [Connect a provider](#connect-a-provider), then run **Retry provider sync**.
### Sync logs show `failed`
The provider rejected the request, and the log message contains its error. Correct the credentials on **Provider settings**, then run **Retry provider sync**.
### Saving provider settings shows an error
The message names the problem: `Resend needs an API key before it can be selected.`, `Beehiiv needs an API key and a publication id before it can be selected.` or `The Beehiiv API base URL must be an https URL.` Nothing is saved until the form is complete.
### A waitlist entry got no invitation email
Invites only change the status and sync the contact. Send the email yourself.
## Reference
* [Send transactional email](https://kernlift.dev/docs/extensions/email.md)
* [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md)
* [Resend audiences](https://resend.com/docs/dashboard/audiences/introduction)
## Next steps
- [Send transactional email](https://kernlift.dev/docs/extensions/email.md)
- [Plugins](https://kernlift.dev/docs/core/plugins.md)
---
# Resend
> Sync newsletter subscribers with Resend.
Source: https://kernlift.dev/docs/extensions/newsletter/resend
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test subscriber in your provider account.
## Set up Resend
### Create a Contacts API key
Open [Resend](https://resend.com/api-keys). Create a separate Full access API key for contact sync.
### Store the contact-sync credential
Keep the key for this audience integration separate from the Sending access key for email.
Provider documentation · [key permissions](https://resend.com/changelog/new-api-key-permissions) · [Contacts model](https://resend.com/blog/new-contacts-experience)
## Configure the application
Open `/admin/waitlist/settings` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | -------------- |
| API key | Resend API key |
Select Resend as the provider and save.
## Verify
1. Subscribe an address you control at `/newsletter`.
2. Retry the sync in admin and verify the entry is marked `success`.
3. Find the contact in Resend.
## Troubleshooting
### Sync logs show `failed`
The provider rejected the request, and the log message contains its error. Correct the credentials on **Provider settings**, then run **Retry provider sync**.
## Next steps
[Newsletter and waitlist](https://kernlift.dev/docs/extensions/newsletter.md)
---
# Discord
> Send team notifications to Discord.
Source: https://kernlift.dev/docs/extensions/notifications/discord
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test notification in the selected channel.
## Set up Discord
### Open server integrations
Open [Discord](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks). Open the target server’s Settings → Integrations → Webhooks.
### Create the channel webhook
Create a webhook for the target text channel and copy its URL.
Provider documentation · [Discord Webhooks](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks)
## Configure the application
Open `/admin/config/email` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ------------------- |
| Webhook URL | Discord webhook URL |
Save the provider card, preserving the active mail provider setting.
## Verify
1. On `/admin/notifications` select `discord-alerts` and send a test notification.
2. Confirm the message in the channel and the `sent` entry in Deliveries.
## Troubleshooting
### Deliveries show `not_configured`
The channel's webhook URL is empty. Save it on **Email Config** and send another test.
## Next steps
[Send notifications to Slack, Discord or Feishu](https://kernlift.dev/docs/extensions/notifications.md)
---
# Feishu
> Send team notifications to Feishu.
Source: https://kernlift.dev/docs/extensions/notifications/feishu
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test notification in the selected channel.
## Set up Feishu
### Add a custom bot
Open [Feishu](https://open.feishu.cn/document/client-docs/bot-v3/add-custom-bot). Add a Custom Bot to the target group.
### Copy the bot webhook
Copy its webhook URL. Check that the group permits unsigned bot requests from this integration.
Provider documentation · [Feishu's custom-bot guide](https://www.feishu.cn/content/7271149634339422210)
## Configure the application
Open `/admin/config/email` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ------------------ |
| Webhook URL | Feishu webhook URL |
Save the provider card, preserving the active mail provider setting.
## Verify
1. On `/admin/notifications` select `feishu-alerts` and send a test notification.
2. Confirm the message in the channel and the `sent` entry in Deliveries.
## Troubleshooting
### Deliveries show `not_configured`
The channel's webhook URL is empty. Save it on **Email Config** and send another test.
## Next steps
[Send notifications to Slack, Discord or Feishu](https://kernlift.dev/docs/extensions/notifications.md)
---
# Send notifications to Slack, Discord or Feishu
> Operations alerts from your product arrive in a team chat channel, with every attempt recorded in a delivery log.
Source: https://kernlift.dev/docs/extensions/notifications
Operations notifications are sent to your team's chat. They are not sent to users. The console ships three channels: Slack, Discord and Feishu. Each channel posts to an incoming webhook URL that you save in the admin console.
## Before you begin
* A Slack workspace, Discord server or Feishu group where you can add an incoming webhook or bot.
* An admin account with `config.read` and `config.write`.
## Create a webhook with the chat provider
| Provider | Choose it for |
| ------------------------------------------------- | ----------------------------- |
| [Slack](https://kernlift.dev/docs/extensions/notifications/slack.md) | Send to a workspace channel |
| [Discord](https://kernlift.dev/docs/extensions/notifications/discord.md) | Send to a server text channel |
| [Feishu](https://kernlift.dev/docs/extensions/notifications/feishu.md) | Send to a group bot |
## Save the webhook URL
### Create the incoming webhook
Create a Slack app with incoming webhooks enabled, a webhook under a Discord channel's **Integrations** settings, or a custom bot in a Feishu group. Copy the URL.
### Paste it on Email Config
Go to **Settings → Email Config** (`/admin/config/email`). Under **Notification webhooks**, paste the URL into **Slack webhook URL**, **Discord webhook URL** or **Feishu webhook URL**. The fields show saved URLs. Clearing one removes that webhook.
### Save
Click **Save provider**. The same button saves the selected email card, so if you are on the active email provider's card, keep **Set as active email provider** ticked, or email is turned off.
**The URL is the credential**
Each notification is a JSON `POST` with no signature header. Keep the webhook URL private, and do not turn on signature verification on the receiving bot, or its requests will be rejected.
## Send a test notification
### Open Notifications
Go to **Settings → Notifications** (`/admin/notifications`).
### Fill in the test
Under **Test notification**, choose a **Channel**, keep or change the **Event key** and **Message**, and click **Send notification**. The form reports `Notification delivery recorded:` and the result.
## Send notifications from your code
The template does not send operations notifications by itself. Call the service where your product needs an alert. Name the channel by its key: `slack-alerts`, `discord-alerts` or `feishu-alerts`.
```ts title="src/server/services/example.service.ts"
import { sendNotificationTest } from "@/server/services/email-notifications.service";
await sendNotificationTest({
channelKey: "slack-alerts",
eventKey: "billing.refund.requested",
message: "Refund requested for order ord_123",
metadata: { orderId: "ord_123" },
});
```
The call returns the delivery log row with status `sent`, `failed`, `not_configured` or `disabled`. It throws only when the channel key does not exist.
## Categories
Every delivery attempt, successful or failed, is recorded alongside an audit entry, so a failed notification appears in the delivery log.
## Verify
* The message arrives in the chat channel.
* **Deliveries** (`/admin/notifications/deliveries`) lists the attempt as `sent`, or shows the **Error** from the chat service.
* `/admin/notifications/channels` shows each channel's status, taken from the URLs saved on **Email Config**.
`pnpm validate:email` checks the notification log and the admin routes.
## Troubleshooting
### Deliveries show `not_configured`
The channel's webhook URL is empty. Save it on **Email Config** and send another test.
### Deliveries show `failed`
The chat service rejected the request, and **Error** holds its response. Check that the URL is complete and still active, and that the Feishu bot has no signature verification turned on.
### Deliveries show `disabled`
The channel is switched off in the database, so nothing is sent even with a URL saved.
### Email stopped after saving a webhook
The webhook was saved from the active email provider's card with **Set as active email provider** unticked. Open that card, tick the box and click **Save provider**.
## Reference
* [Send transactional email](https://kernlift.dev/docs/extensions/email.md)
* [Audit log](https://kernlift.dev/docs/core/admin/audit-log.md)
* [Web push](https://developer.mozilla.org/en-US/docs/Web/API/Push_API)
## Next steps
- [Send transactional email](https://kernlift.dev/docs/extensions/email.md)
- [Run the admin console](https://kernlift.dev/docs/core/admin.md)
- [Configuration model](https://kernlift.dev/docs/core/configuration.md)
---
# Slack
> Send team notifications to Slack.
Source: https://kernlift.dev/docs/extensions/notifications/slack
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — a test notification in the selected channel.
## Set up Slack
### Enable incoming webhooks
Open [Slack](https://api.slack.com/apps). Create an app and enable Incoming Webhooks.
### Choose the destination channel
Select Add New Webhook to Workspace and authorize the target channel. Copy its URL.
Provider documentation · [Slack Incoming Webhooks](https://api.slack.com/messaging/webhooks)
## Configure the application
Open `/admin/config/email` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ----------------- |
| Incoming webhook | Slack webhook URL |
Save the provider card, preserving the active mail provider setting.
## Verify
1. On `/admin/notifications` select `slack-alerts` and send a test notification.
2. Confirm the message in the channel and the `sent` entry in Deliveries.
## Troubleshooting
### Deliveries show `not_configured`
The channel's webhook URL is empty. Save it on **Email Config** and send another test.
## Next steps
[Send notifications to Slack, Discord or Feishu](https://kernlift.dev/docs/extensions/notifications.md)
---
# Alipay
> Accept CNY payments on Alipay's computer-website cashier.
Source: https://kernlift.dev/docs/extensions/payments/alipay
* **Checkout** Alipay's computer-website cashier (`alipay.trade.page.pay`), CNY one-time payments only
* **Subscriptions** No
* **Portal** No
* **Refunds** Yes
* **Promotion codes** No
Plans priced in CNY go to WeChat Pay when it is enabled and complete, and to Alipay otherwise. A plan in another currency, or a subscription plan, is refused before Alipay is called.
## Before you begin
A public HTTPS site, an active one-time plan priced in `CNY` on `/admin/plans` (see [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md)), and an Alipay Open Platform account. Start with the sandbox app, which the gateway field points at by default.
**Expected result** — an order settled by a verified asynchronous notification, and refunded from the console.
## Set up Alipay
### Open the sandbox app
Open the [Alipay Open Platform](https://open.alipay.com/develop/sandbox/app) and use the sandbox application. For production, create a web application and sign the 电脑网站支付 (computer website payment) product for it.
### Generate the app key pair
Generate an RSA2 (2048-bit) key pair with Alipay's key tool. Keep the app private key; PKCS#1 and PKCS#8 both work.
### Choose public key mode
Under 接口加签方式 choose public key mode (公钥模式, not certificate mode), upload the app public key and copy the **Alipay public key** it shows.
### Record the identifiers
Record the APPID. Optionally record your account's PID, the user id starting with `2088`, so notifications from another seller are rejected.
No notification URL is registered with Alipay. Each cashier address carries `notify_url`: the origin of your **Success URL** followed by `/api/billing/webhook/alipay`.
Provider documentation · [Computer website payment](https://opendocs.alipay.com/open/028r8t) · [Asynchronous notifications](https://opendocs.alipay.com/open/00dn7l) · [Signing and verification](https://opendocs.alipay.com/common/057k53)
## Configure the application
Open `/admin/config/payment` in the Kernlift admin console. Select **Alipay**. Enter your public Success URL and Cancel URL. Leave **API base URL** at the sandbox gateway, `https://openapi-sandbox.dl.alipaydev.com/gateway.do`, while testing.
| Value from provider | Admin field |
| --------------------------------------------------------------- | --------------------------------- |
| The application's APPID | **App ID** |
| Account PID (`2088…`), optional | **Seller ID (2088..., optional)** |
| The private key of the pair you generated | **App private key** |
| The Alipay public key shown after uploading your app public key | **Alipay public key** |
Enable the provider and click **Save provider**. The card shows **Ready** once the App ID and both keys are saved, and **Webhook ready** once the Alipay public key is saved.
**Two different public keys**
Paste the Alipay public key, not your app public key. A notification verified against the wrong key fails, and the order stays pending. Keys may be PEM or bare base64; leaving a key field blank keeps the saved key.
## Verify
1. Sign in as an ordinary user, open `/pricing` and buy the CNY one-time plan. **Expected**: you are sent to the Alipay cashier.
2. Pay with the sandbox buyer account. **Expected**: you return through `/api/billing/callback/alipay`, which queries the trade with `alipay.trade.query` before the order is marked paid.
3. Open `/admin/billing-webhooks`. **Expected**: a `TRADE_SUCCESS` event from Alipay with a valid signature.
4. On `/admin/orders`, refund the order. **Expected**: the refund succeeds at once.
## Go live
1. Set **API base URL** to `https://openapi.alipay.com/gateway.do`.
2. Save the production APPID, its app private key and the production Alipay public key. Sandbox keys do not verify production notifications.
3. Make one real purchase and refund it.
## Troubleshooting
### Alipay checkout is refused with `provider_unsupported`
Alipay charges CNY one-time payments only. On `/admin/plans`, price the plan in `CNY` with the one-time or lifetime interval, or use another provider for that plan.
### CNY plans go to WeChat Pay instead of Alipay
WeChat Pay takes CNY plans first whenever it is enabled and complete. Untick it on `/admin/config/payment` if Alipay should take them.
### The notification is stored with a `.mismatch` type
The signature verified, but the `app_id`, `seller_id` or `total_amount` does not match. Check the App ID and Seller ID you saved, and that the plan price was not changed after the order was created.
## Next steps
- [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
Compare the providers and the settings they share.
---
# Creem
> Accept payments with Creem.
Source: https://kernlift.dev/docs/extensions/payments/creem
* **Checkout** Hosted checkout
* **Subscriptions** Cancel and resume
* **Portal** Yes
* **Refunds** In the Creem dashboard only
**Checkout compatibility**
Creem’s documented checkout API requires `product_id`. The current adapter sends `product_data` and has no product-ID field. Treat checkout as unverified until the adapter sends a real Creem product ID and a sandbox order succeeds. [Creem API](https://docs.creem.io/skills/creem-api/REFERENCE)
## Before you begin
A public HTTPS site, an active plan on `/admin/plans`, and access to the merchant dashboard.
**Expected result** — a configured test store, verification secret and webhook endpoint.
## Set up Creem
### Choose the test store
Open [Creem](https://www.creem.io/dashboard). Switch the store to test mode.
### Create the API key
Create an API key under Developers.
### Register the webhook
Register the public HTTPS endpoint ending in `/api/billing/webhook/creem` under Webhooks. Subscribe to `checkout.completed` and copy the signing secret.
Provider documentation · [Creem's webhook guide](https://docs.creem.io/code/webhooks)
## Configure the application
Open `/admin/config/payment` in the Kernlift admin console. Select **Creem**. Enter your public Success URL and Cancel URL, then set **API base URL** to `https://test-api.creem.io`.
| Value from provider | Admin field |
| ------------------- | -------------- |
| API key | API key |
| Webhook secret | Webhook secret |
| Test API | API base URL |
Enable the provider and click **Save provider**.
## Verify
Once the adapter supplies a sandbox product ID, verify the payment flow.
1. Buy a plan on `/pricing` as a sandbox buyer.
2. Check the signed event on `/admin/billing-webhooks`.
3. Find the same order on `/admin/orders` and confirm it is paid.
## Go live
Create live credentials and register the production webhook in the live account. Save its verification value with the matching credentials and `https://api.creem.io`.
## Troubleshooting
### Webhooks fail the signature check
Check that the secret belongs to this store’s webhook in the same mode as the API key.
## Next steps
[Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
---
# DodoPayments
> Accept payments with DodoPayments.
Source: https://kernlift.dev/docs/extensions/payments/dodopayments
* **Checkout** Hosted checkout, needs a DodoPayments product
* **Subscriptions** No lifecycle actions
* **Portal** No
* **Refunds** No
## Before you begin
A public HTTPS site, an active plan on `/admin/plans`, and access to the merchant dashboard.
**Expected result** — an order reconciled with a signed payment notification.
## Set up DodoPayments
### Create the test product
Open [DodoPayments](https://app.dodopayments.com). Select Test Mode and create a product under Products. Copy its product ID.
### Issue the API key
Generate an API key under Developer → API Keys.
### Register payment events
Add your HTTPS endpoint ending in `/api/billing/webhook/dodopayments` under Webhooks. Select `payment.succeeded` and `payment.failed`, then copy the entire signing secret.
Provider documentation · [Dodo products](https://docs.dodopayments.com/features/products) · [official integration example](https://docs.dodopayments.com/developer-resources/nextjs-boilerplate)
## Configure the application
Open `/admin/config/payment` in the Kernlift admin console. Select **DodoPayments**. Enter your public Success URL and Cancel URL, then set **API base URL** to `https://test.dodopayments.com`.
| Value from provider | Admin field |
| ------------------------------------- | ---------------- |
| API key | API key |
| Product ID | Dodo product ID |
| Signing secret | Webhook secret |
| Optional plan-to-product JSON mapping | Plan product IDs |
Enable the provider and click **Save provider**.
## Verify
1. Buy a plan on `/pricing` as a sandbox buyer.
2. Check the signed event on `/admin/billing-webhooks`.
3. Find the same order on `/admin/orders` and confirm it is paid.
## Go live
Create live credentials and register the production webhook in the live account. Save its verification value with the matching credentials and `https://live.dodopayments.com`.
## Troubleshooting
### Webhooks fail the signature check
Paste the full signing secret including its prefix. Check that the server clock is accurate and the request body reaches the app intact.
## Next steps
[Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
---
# Write a fulfilment plugin
> Deliver what a paid order buys from your own plugin, refuse checkouts you cannot fulfil, and see a failed delivery retried.
Source: https://kernlift.dev/docs/extensions/payments/fulfilment
After billing settles an order, it calls every enabled `billing.fulfilment` plugin. This guide adds a fulfiller of your own in a local plugin. It runs once per paid order and once per refund, and it can refuse a checkout before any payment is taken. The built-in `plan-credits` fulfiller in `src/server/billing/plan-credits-fulfiller.ts` is the reference implementation.
## Before you begin
* A project that runs locally with a migrated database, and an active plan to buy. See [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md).
* A payment provider in test mode if you want to see a real order settle. See [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
* The [scheduled jobs](https://kernlift.dev/docs/core/background-jobs/run.md) running, because they perform the retries.
* An idea of what your order delivers and a key that makes delivering it twice harmless, for example a row keyed by the order id.
## Add the fulfiller
### Write the fulfiller
Create `src/server/billing/seat-fulfiller.ts`. A fulfiller is an object with an `id` and any of three hooks. The types are in `src/server/billing/fulfilment-types.ts`.
```ts
import type { BillingFulfiller } from "./fulfilment-types";
export const seatFulfiller: BillingFulfiller = Object.freeze({
id: "seats",
async canCheckout({ userId, planKey }) {
if (planKey !== "team") return { ok: true };
const allowed = await userMayBuySeats(userId);
return allowed
? { ok: true }
: { ok: false, code: "seats_unavailable", reason: "This account cannot buy seats." };
},
async onOrderPaid(order) {
if (order.planKey !== "team") return;
await grantSeatsOnce({ orderId: order.id, userId: order.userId });
},
async onOrderRefunded(order, refund) {
if (refund.fullRefund) await revokeSeats(order.id);
},
});
```
`userMayBuySeats`, `grantSeatsOnce` and `revokeSeats` are functions you write, in a repository under `src/server/db/repositories/`. The rules the hooks must follow:
| Hook | Receives | Rule |
| ----------------- | --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| `canCheckout` | `userId`, `planKey`, `productKey`, `checkoutMode` | Runs before an order exists. Returning `ok: false` stops the checkout with HTTP 409 and your `code` |
| `onOrderPaid` | The order: `id`, `userId`, `provider`, `planKey`, `productKey`, `checkoutMode`, `amountCents`, `currency` | Must be idempotent. A retry may follow a call that half-succeeded |
| `onOrderRefunded` | The order and `refundId`, `amountCents`, `fullRefund` | Same retry rules; called once per refund that succeeded at the provider |
Throw when delivery fails. Billing records the failure and retries. The payment is not reversed.
### Give the plugin a manifest
A plugin that belongs to your project has kind `local`. It can be switched off on `/admin/plugins`. Create `src/plugins/seats/manifest.ts`:
```ts
import { defineManifest } from "../kernel/types";
export const seatsManifest = defineManifest({
id: "seats",
version: "0.1.0",
kind: "local",
});
```
### Create the two halves
Every plugin has a browser-safe half. The fulfiller goes in the server half. Create `src/plugins/seats/plugin.ts`:
```ts
import { definePlugin } from "../kernel/types";
import { seatsManifest } from "./manifest";
export const seatsPlugin = definePlugin({ manifest: seatsManifest });
```
and `src/plugins/seats/plugin.server.ts`:
```ts
import { seatFulfiller } from "../../server/billing/seat-fulfiller";
import { defineServerPlugin } from "../kernel/types";
import { seatsManifest } from "./manifest";
export const seatsServerPlugin = defineServerPlugin({
manifest: seatsManifest,
contributes: { "billing.fulfilment": [seatFulfiller] },
});
```
Use relative imports in the server half. The Agent service loads the same list, so nothing reachable from it may import React, icons or `@/` aliases.
### Register both halves
Add `seatsPlugin` to `installedPlugins` in `src/plugins/installed.ts` and `seatsServerPlugin` to `installedServerPlugins` in `src/plugins/installed.server.ts`. Put both outside the `// @module:` marker regions. Those regions belong to the shipped modules.
### Explain your refusal code
If `canCheckout` can refuse, the buyer lands on the payment-failed page with your `code`. Add a sentence for it under `checkoutFailure.reasons` and `checkoutFailure.nextActions` in both `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts`.
## See a failure retried
1. Make `onOrderPaid` throw, for example `throw new Error("seat service down")`, and buy the plan with the provider's test card.
2. The order is still `paid` on `/admin/orders`. `/admin/audit` has a `billing.fulfilment.failed` entry whose target is the order id and whose metadata names your fulfiller, the event `paid`, the attempt number and the error.
3. Remove the `throw`. Wait a minute, then run a round by hand:
```bash
pnpm jobs:run
```
The `billing-fulfilments` job in the report shows `"attempted": 1, "succeeded": 1`. If the report is `"skipped"`, the in-process loop already took that round. Look at the row instead.
Retries follow a fixed schedule from each failure:
| Attempt | Runs |
| ------- | ------------------------------------------------------------------------------ |
| 1 | When the order is settled |
| 2 | 1 minute after attempt 1 failed |
| 3 | 5 minutes later |
| 4 | 30 minutes later |
| 5 | 2 hours later |
| 6 | 12 hours later; a failure here writes `billing.fulfilment.abandoned` and stops |
A `paid` delivery whose order has been refunded or canceled in the meantime is abandoned. If you switch the plugin off, its failed rows are kept and rechecked each hour without using up attempts.
## Verify it works
* `pnpm validate:plugins` passes: the registry accepts the new plugin and both halves are installed.
* `pnpm validate:billing-fulfilment` passes: billing still notifies fulfillers once, records failures and retries them.
* After a test purchase, `billing_fulfilments` holds one row per fulfiller for the order with event `paid` and status `succeeded`. Open the table with `pnpm db:studio`.
* Refund the order from `/admin/orders`. A second row appears with event `refunded:`.
## Next steps
- [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
Where fulfilment sits between settlement and refunds.
- [Run background jobs](https://kernlift.dev/docs/core/background-jobs/run.md)
Make sure the retries run on your platform.
- [Audit log](https://kernlift.dev/docs/core/admin/audit-log.md)
Find failed and abandoned fulfilments.
---
# Payment lifecycle
> How a checkout becomes a paid order: server-side pricing, provider confirmation by webhook or callback, idempotent settlement and refunds.
Source: https://kernlift.dev/docs/extensions/payments
A payment in Kernlift moves through four stages: the server creates an order at the plan's price,
the buyer pays on the provider's hosted checkout, the provider confirms the payment, and settlement
turns the order into an invoice and notifies the fulfilment plugins, which deliver what the plan
sells. To connect a provider, see
[Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
## The lifecycle at a glance
| Stage | Triggered by | Result |
| ------------ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
| Checkout | `POST /api/billing/checkout` from a signed-in buyer | A `pending` order and a hosted checkout URL |
| Payment | The buyer, on the provider's page | Nothing changes locally yet |
| Confirmation | A signed webhook, or the return callback querying the provider | The order becomes `paid`, `failed` or `canceled` |
| Settlement | A `paid` confirmation | Invoice and subscription, committed first |
| Fulfilment | Settlement, after the order is committed | Every enabled `billing.fulfilment` plugin is notified once; the built-in one grants the plan's credits |
| Refund | An administrator | A refund record; fulfilment plugins are notified when it succeeds |
One provider is active at a time and charges every plan, with one exception: a plan priced in CNY goes
to a mainland wallet when one is enabled and fully configured, WeChat Pay first and Alipay when WeChat
Pay is not ready, and every other currency stays with the active provider. A request may also name a provider explicitly. The providers share this
lifecycle. They differ in what they support after checkout.
| Provider | Subscriptions | Customer portal | Refunds from the admin console |
| ------------ | ----------------------------------------------------------------------------- | --------------- | ------------------------------- |
| Stripe | Yes, renewing monthly or yearly by the plan's interval | Yes | Yes |
| Creem | Cancel and resume | Yes | No, in the Creem dashboard only |
| PayPal | No, one-time payments only | No | No |
| DodoPayments | No lifecycle actions | No | No |
| WeChat Pay | No, CNY one-time payments only | No | Yes |
| Alipay | No, CNY one-time payments only | No | Yes |
| Waffo | Yes, through one monthly and one yearly subscription product created in Waffo | No | No, in the Waffo dashboard only |
Stripe and Waffo can also show a promotion code field at checkout when **Allow promotion codes at checkout** is on. The invoice then records what the buyer actually paid. See [Offer promotion codes](https://kernlift.dev/docs/extensions/payments/setup.md).
## Checkout is priced on the server
The request names a plan key. The server loads that plan and compares the amount, currency and checkout
mode the client sent against it. The server rejects any difference before it calls a
provider.
| Rejection (HTTP 409) | Cause |
| ------------------------ | ----------------------------------------------------------------------------------------- |
| `unknown_plan` | No plan has that key |
| `plan_inactive` | The plan is not active |
| `amount_mismatch` | Amount, currency or checkout mode differs from the plan |
| `product_mismatch` | The request names a different product than the plan sells |
| `plan_interval_mismatch` | The plan bills as a subscription but does not renew monthly or yearly, or the reverse |
| `provider_unsupported` | WeChat Pay or Alipay would charge the plan, but it is a subscription or not priced in CNY |
| A fulfiller's own code | An enabled fulfilment plugin refused the purchase in `canCheckout` |
When the checks pass, a `pending` order is stored with the plan's price. If the active provider is not
configured, the order is marked `failed`, a not-configured event is recorded and the request returns
409\. Otherwise the provider creates a hosted checkout, and its success and cancel URLs point back at
`/api/billing/callback/:provider`.
WeChat Pay has no hosted checkout. Its Native order returns a `weixin://` code URL, which is stored on
the order, and the buyer is sent to `/app/billing/pay/` on your own site. That page draws the
QR code for the signed-in owner of a pending order, polls the server for the order's state every three
seconds, and moves on to the success URL once it is paid. The code expires after two hours.
Alipay sends the buyer straight to its computer-website cashier with an RSA2-signed address that expires after two hours. Waffo creates a hosted checkout session priced from the plan (tax included) on the Waffo product that matches it: the one-time product, or the monthly or yearly subscription product.
## Only the provider can mark an order paid
The return URL a buyer lands on is not proof of payment, because anyone can open it. Payment state changes only
through one of two server-side confirmations.
**The signed webhook.** `/api/billing/webhook/:provider` verifies the provider's signature on the raw
request body before reading anything. It finds the local order id in the event, then maps the event
type to paid, failed or canceled. Each event id is stored, so a repeated delivery returns the stored
result and has no further effect. An event with an invalid signature is stored as failed and changes
nothing. Registering the webhook for each provider is covered in [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
**The return callback.** `/api/billing/callback/:provider` ignores the `status` query parameter except
for logging. It queries the provider for the stored checkout and settles only when the provider reports
it paid. Otherwise the order is left for the webhook. The buyer is then redirected to the success or
cancel URL.
Whichever arrives first settles the order, and the other makes no further change. A failed webhook can be
retried from the admin console, which re-applies a validly signed payload under a new event id.
WeChat Pay follows the same rule with two differences. Its notification is verified with the WeChat
Pay public key and then decrypted with the APIv3 key, and both the notification and the server-side
order query settle only when the amount in fen equals the order amount and the currency is CNY.
Alipay's notification carries its signature in the form body and is verified with the Alipay public
key; it settles only when the app id, the seller id (when saved) and the amount match the order. Its
server-side `alipay.trade.query` settles only when the signature over the raw response verifies and the
amount matches. Waffo's webhook is verified with the saved webhook public key, and its server-side
check looks up the payments recorded for the order. Both record the amount actually charged, so a
promotion code shows on the invoice.
## Settlement is idempotent
Settlement runs from both the webhook and the callback, so every step is safe to repeat:
1. The order status becomes `paid`.
2. An invoice `invoice_` is written.
3. For a subscription, `subscription_` is written with the provider subscription id. If the
callback settled first, a later webhook fills the id in.
4. Once those writes are committed, every enabled fulfilment plugin is notified of the paid order.
## Fulfilment comes after the commit
Billing owns orders, payments and refunds. What a paid order entitles the buyer to is defined by the plugin that
sells it, which contributes a fulfiller to the `billing.fulfilment` server slot. Billing code
does not reference any fulfiller by name.
| Hook | Called | Purpose |
| ----------------- | -------------------------------------------------------- | ------------------------------------------ |
| `canCheckout` | Before an order or a payment session is created | Refuse a purchase with a code and a reason |
| `onOrderPaid` | After the order is committed as paid, once per order | Deliver what the plan sells |
| `onOrderRefunded` | After a refund succeeds at the provider, once per refund | Take back what the refund covers |
Each call is recorded in `billing_fulfilments`, one row per order, fulfiller and event. Inserting the
row is the claim, so a webhook and a callback that settle the same order at the same moment still run
each fulfiller once. A fulfiller that throws does not undo the payment. The row is marked `failed`, an
audit entry is written, and the [scheduled jobs](https://kernlift.dev/docs/core/background-jobs.md) retry it after 1
minute, 5 minutes, 30 minutes, 2 hours and 12 hours. After the sixth attempt the row is abandoned and
left for the operator. A paid event whose order has since been refunded or canceled is abandoned
and not delivered. Fulfillers of switched-off plugins are not called.
The template ships one fulfiller, `plan-credits`, contributed by the foundation plugin. It grants the
plan's included credits once, as a purchase with source `billing.order.`. See
[Credits ledger](https://kernlift.dev/docs/extensions/credits.md) and [Write a fulfilment plugin](https://kernlift.dev/docs/extensions/payments/fulfilment.md).
## Refunds and subscription changes
Refunds are created from the admin console and recorded as `pending`, `succeeded`, `failed` or
`not_configured`. Stripe refunds against a PaymentIntent or Charge, resolving a Checkout Session to its
PaymentIntent first. WeChat Pay refunds through its refund API. A synchronous `SUCCESS` succeeds at
once, and `PROCESSING` stays `pending` until the signed `REFUND.SUCCESS` notification arrives. Alipay refunds
through `alipay.trade.refund` with the local refund id as `out_request_no`, so a repeated request refunds
once. The other adapters report refunds as unsupported; for Waffo, refunds and subscription changes are
made in the Waffo dashboard. Whether a refund is full is judged against the amount the buyer paid. When a refund succeeds, fulfilment plugins receive
`onOrderRefunded` with the amount and whether it covers the whole order. Each plugin determines what a
refund takes back.
Cancelling a subscription sets it to end at the period end, and resuming clears that flag. Both need the
provider subscription id that settlement stored.
## What is recorded
Every checkout, webhook, callback and not-configured attempt is stored with its signature result, status
and raw payload, and administrators can inspect each one. Orders, invoices, subscriptions, refunds and
fulfilments are separate records.
## Files
- Settlement/
- src/server/db/repositories/billing-payment.repository.ts
- src/server/functions/billing-payment.ts
- src/server/payments/wechatpay.ts
- src/server/payments/alipay.ts
- src/server/payments/waffo.ts
- Fulfilment/
- src/server/billing/fulfilment.ts
- src/server/billing/fulfilment-types.ts
- src/server/billing/plan-credits-fulfiller.ts
- src/server/db/repositories/billing-fulfilment.repository.ts
- Console and workspace/
- src/components/billing/app-billing-pages.tsx
- src/components/billing/billing-workspace.tsx
- src/components/billing/wechat-pay-checkout.tsx
## Next steps
- [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
- [Write a fulfilment plugin](https://kernlift.dev/docs/extensions/payments/fulfilment.md)
- [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md)
- [Manage orders, refunds and subscriptions](https://kernlift.dev/docs/extensions/payments/subscriptions.md)
- [Credits ledger](https://kernlift.dev/docs/extensions/credits.md)
---
# PayPal
> Accept payments with PayPal.
Source: https://kernlift.dev/docs/extensions/payments/paypal
* **Checkout** Orders, one-time payments only
* **Subscriptions** No
* **Portal** No
* **Refunds** No
## Before you begin
A public HTTPS site, an active plan on `/admin/plans`, and access to the merchant dashboard.
**Expected result** — an order reconciled with a signed payment notification.
## Set up PayPal
### Create a sandbox app
Open [PayPal](https://developer.paypal.com/dashboard/applications/sandbox). Create a REST app under Apps & Credentials → Sandbox.
### Copy the app credentials
Open the app and copy its Client ID and secret.
### Subscribe to order events
Add your HTTPS endpoint ending in `/api/billing/webhook/paypal` under Webhooks. Select `CHECKOUT.ORDER.APPROVED`, `CHECKOUT.ORDER.COMPLETED` and `CHECKOUT.ORDER.VOIDED`.
### Copy the Webhook ID
Open the saved endpoint and copy its Webhook ID.
Provider documentation · [REST app setup](https://developer.paypal.com/api/get-started/) · [webhook subscription](https://developer.paypal.com/api/rest/webhooks/rest/)
## Configure the application
Open `/admin/config/payment` in the Kernlift admin console. Select **PayPal**. Enter your public Success URL and Cancel URL, then set **API base URL** to `https://api-m.sandbox.paypal.com`.
| Value from provider | Admin field |
| ------------------- | ------------- |
| Client ID | Client ID |
| Secret | Client secret |
| Webhook ID | Webhook ID |
Enable the provider and click **Save provider**.
**Webhook ID**
Use the endpoint ID from the same REST app and mode as the client credentials.
## Verify
1. Buy a plan on `/pricing` as a sandbox buyer.
2. Check the signed event on `/admin/billing-webhooks`.
3. Find the same order on `/admin/orders` and confirm it is paid.
## Go live
Create live credentials and register the production webhook in the live account. Save its verification value with the matching credentials and `https://api-m.paypal.com`.
## Troubleshooting
### Webhooks fail the signature check
Confirm the saved Webhook ID belongs to this REST app and environment. PayPal verifies events with that ID and the app credentials.
## Next steps
[Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
---
# Manage pricing plans
> Create and edit the plans the pricing page lists and checkout sells, in every language, from the admin console.
Source: https://kernlift.dev/docs/extensions/payments/pricing-plans
`/pricing` shows the active plans, and checkout charges the price saved on the plan. You manage plans at `/admin/plans`. Price, currency, interval, credits, status and order belong to the plan and apply to every language. The name, description, button label and feature list are written per language.
## Before you begin
* An admin account with `plans.read` to see the page and `plans.write` to save. The **Commerce Manager** role has both. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md).
* A payment provider, if buyers should be able to pay. See [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
* A decision on the plan key. Orders and subscriptions refer to it, so it cannot change after the plan is created.
## Create a plan
### Open Plans
Go to **Commerce → Plans** (`/admin/plans`). The page counts all plans, those on the pricing page, hidden ones and subscriptions, and lists each plan with its price, credits, languages and status. Click **New plan**, which opens `/admin/plans/new`.
### Fill in the plan
| Field | Rule |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **Plan key** | Lowercase letters and digits separated by single hyphens or underscores, up to 64 characters; `new` is reserved. Fixed after creation |
| **Price** | In the currency's main unit, for example `29` or `29.50`; zero is allowed. Stored in minor units |
| **Currency** | A three-letter code such as `USD` or `CNY` |
| **Billing interval** | Per month, per year, one-time or lifetime |
| **Credits granted** | A whole number of zero or more, added to the buyer's balance when the order is paid |
| **Show on the pricing page** | On makes the plan `active`; off hides it and checkout refuses it with `plan_inactive` |
| **Order** | A whole number; plans are listed in ascending order |
The interval sets how the plan is billed. Monthly and yearly plans are subscriptions. One-time and lifetime plans are a single payment. The form shows which one applies.
### Write the copy for each language
Under each language, fill in **Name**, **Description**, **Button label** and the **Features** list. Tick **Included** for a feature the plan has. An unticked feature is shown as not included. Features without a label are dropped.
English is required. A language whose name is left empty gets no row for the plan. `/pricing` and checkout in that language use the English row, including its feature list. Fill in every language you publish the pricing page in.
### Save
Click **Create plan**. When a save is rejected, the form shows the problem, for example a duplicate plan key or an invalid currency, and nothing is written.
## Edit a plan
Open the plan from the list and click **Save plan** when done. Saving writes the shared fields to every language row and replaces each language's copy and feature list with the form's contents. Clearing a language's name removes that language's row and its features.
A new price affects new checkouts only. Existing subscriptions keep what the payment provider already charges.
If the list warns that some plans have language rows that disagree on price, interval or credits, open each such plan and save it once. Saving writes the same values to every language row.
**Note**
WeChat Pay and Alipay charge a plan only when it is priced in `CNY` and billed as a single payment. With either enabled, CNY plans are charged through it, WeChat Pay first, and other currencies through the active provider. Waffo sells a plan only through the Waffo product that matches it: a one-time plan needs the one-time product, a monthly or yearly plan the subscription product of its interval.
## Verify the plan
* Open `/pricing` in each language. The plan appears in its place with that language's name, price and features. A hidden plan does not appear.
* Sign in as a normal user and buy the plan with the provider's test card. `/admin/orders` shows the order at the plan's price, and the plan's credits appear on the buyer's `/app/credits`.
* `/admin/audit` lists `billing.plan.created` or `billing.plan.updated` with your account as the actor and the plan key as the target.
* `pnpm validate:pricing-plans` passes.
## Troubleshooting
### Checkout answers `amount_mismatch`
The page was loaded before the price changed. Checkout compares the amount, currency and mode the browser sent with the saved plan and rejects the request when they differ. Reload the page.
### Checkout answers `plan_interval_mismatch`
The plan's row bills as a subscription but does not renew monthly or yearly, or the reverse. This happens only to rows written outside the console. Open the plan on `/admin/plans` and save it. The interval then sets the billing mode.
### A plan shows English copy on another language's pricing page
That language has no row for the plan, so the page shows the English row. Open the plan and give it a name in that language.
## Next steps
- [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
Take payment for these plans.
- [Credits](https://kernlift.dev/docs/extensions/credits/usage.md)
What the granted credits pay for.
- [Write a fulfilment plugin](https://kernlift.dev/docs/extensions/payments/fulfilment.md)
Deliver more than credits when a plan is bought.
- [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
How checkout prices an order from the plan.
---
# Sell products and plans
> Your products appear on the storefront with a price; buying one issues a licence the buyer activates with a GitHub username.
Source: https://kernlift.dev/docs/extensions/payments/products
You define what the store sells in the admin console. A product is what a buyer gets a licence for. A plan is one price for a product in one locale. Checkout always charges the price saved on the plan.
## Before you begin
* An admin account with `products.read` and `products.write`. The built-in **Commerce Manager** role holds them.
* A connected payment provider to take real payments. See [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
## Start from the seeded catalogue
A freshly migrated database has no products, so the storefront is empty. Seed the catalogue this store ships with (the Kernlift Premium membership and the business templates) and edit it from there:
```bash
pnpm db:seed-storefront
```
The command only inserts what is missing, so running it again changes nothing and does not overwrite copy or prices you edited. The seeded prices are examples. Set your own on each plan as described below. The catalogue is defined in `scripts/db/storefront-catalog.ts`. Replace it when you sell your own products.
## Create a product
### Open the form
Go to **Commerce → Products** (`/admin/products`) and click **New product**.
### Describe the product
* **Key**: a stable identifier in lowercase letters, digits, hyphens or underscores, such as `cms`. It cannot be changed later.
* **Kind**: **Foundation** is the membership (it comes with the base repository and unlocks member prices); **Template** is a business template sold on its own. **Module** and **Bundle** remain for catalogues that sell that way.
* **Status**: **Active** lists the product on the storefront; **Hidden** and **Retired** do not.
* **Delivery repository (owner/name)**: the private GitHub repository a buyer is invited to when they activate the purchase, for example `kernlift/image-studio`. A product without one is shown as not open yet and cannot be bought.
* **Requires (comma separated keys)** and **All-access bundle (entitles every active product)**: leave empty and unticked for a membership or a template.
* **Name**, **Tagline** and **Description** for each locale.
### Save
Click **Save product**. The page opens the product so you can add plans.
## Add a plan
Each plan is one price in one locale, so a product sold in English and Chinese has one plan row per locale.
A business template has two plans per locale: `-lifetime` is the list price anyone can pay, and `-member` is the member price. A plan whose key ends in `-member` can only be checked out by an account that holds the membership; the server refuses it otherwise.
### Start a plan
On the product page, in the **Plans** card, click **+ Plan key**. To edit an existing plan, click its button, shown as `plan key · locale`.
### Set the price
* **Plan key** (for example `pro_monthly`) and **Locale**. Neither can change after saving.
* **Price (cents)** and **Currency**, for example `4900` and `usd`.
* **Interval**: **Monthly**, **Yearly**, **Lifetime** or **One-time**, shown next to the price.
* **Checkout mode**: `payment` for a one-time charge, `subscription` for a recurring one. Stripe creates subscriptions with a monthly cycle.
* **Included credits**: credits granted once when an order for this plan is paid. See [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md).
* **Plan status**: `active` can be bought; `deferred` cannot.
### Fill in the card copy
Fill in **Name**, **Description**, **CTA label** and **CTA href**, and optionally **AI limit label**. In **Features (one per line, prefix - to mark not included)**, write one feature per line.
### Save
Click **Save plan**. The page shows **Plan saved.** and checkout uses the new price immediately. Repeat for each locale.
**Where products are shown**
Only products with **Status** **Active** are listed. `/pricing` shows the membership as one card and the templates with both prices. A visitor who is a member is offered the member plan; everyone else the list plan. A product without an active plan above zero in the visitor's locale shows **Not priced yet**.
## Understand what a purchase grants
When the provider confirms the payment, the buyer receives:
* An invoice on `/app/billing`, and a subscription for `subscription` plans.
* The plan's **Included credits**, once per order.
* A licence for the plan's product on `/app/licences` (**Purchased templates**).
The licence is not the code yet. The buyer enters their GitHub username on that page and clicks **Activate**; the store then invites that account to the product's delivery repository with read access. The username is fixed by the first activation, and an invitation GitHub expired after 7 days can be sent again from the same page.
Activation counts as delivery: an order whose licence has been activated can no longer be refunded, while an order that was never activated can be, and a full refund revokes its licence. Revoking an activated licence on **Commerce → Licences** removes the account from the repository.
Invitations are sent with a GitHub token you store once under **GitHub delivery** on **Commerce → Products**. It needs admin access to every delivery repository. Without it, activation tells the buyer delivery is not configured and records nothing.
To give someone a licence without a purchase, use **Grant licence** on **Commerce → Licences** (`/admin/licences`, needs `licences.write`). An account cannot buy a product it already holds.
## Add a buy button to your own page
The pricing cards post to the checkout API, and you can do the same from any signed-in page. Send the plan's own price, currency and mode. A request with any other value is rejected.
```ts title="src/components/billing/buy-button.tsx"
const response = await fetch("/api/billing/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
planKey: "growth",
checkoutMode: "subscription",
amountCents: 9900,
currency: "usd",
locale: "en",
}),
});
const result = await response.json();
if (response.status === 409 && result.message) {
// result.status is unknown_plan, plan_inactive, amount_mismatch,
// product_mismatch, membership_required or already_owned
throw new Error(result.message);
}
if (result.checkoutUrl) window.location.assign(result.checkoutUrl);
```
On success the API returns `201` with a `checkoutUrl` on the provider's site. After paying, the buyer returns to your **Success URL** with `billing_order_id`, `billing_status` and `provider` in the query string. Do not treat those parameters as proof of payment. Read the order status.
## Verify
Open `/pricing` in each locale and check that it shows the plan's price. Buy it with a test card, then confirm the order is paid on **Commerce → Orders** and the licence appears on the buyer's `/app/licences`, where it can be activated. `pnpm validate:github-delivery` checks the member price, activation, the refund rule and revocation; `pnpm validate:billing` checks that settlement grants plan credits once.
## Troubleshooting
### A product does not appear on the storefront
The product's **Status** is not **Active**. Set it to **Active** and click **Save product**.
### The card says Not priced yet
The product has no `active` plan with a price above zero in that locale. Add or edit the plan for that locale.
### Checkout returns 409 with `amount_mismatch`
The request sent an amount, currency or mode that differs from the plan. Send the plan's values unchanged. Editing a plan in the admin console changes the expected amount immediately.
### Checkout returns 409 with `membership_required`
The request named a member-price plan (`-member`) and the account does not hold the membership. The buyer either becomes a member first or buys the template with its list plan.
### Checkout returns 409 with `already_owned`
The account already holds an active licence for that product. Send the buyer to `/app/licences` to activate it.
### Activation says delivery is not configured
The product has no **Delivery repository**, or no GitHub token is stored. Set both on **Commerce → Products**, then use **Check the stored token** to confirm GitHub accepts it.
## Reference
* [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
* [Stripe products and prices](https://stripe.com/docs/products-prices/overview)
## Next steps
- [Manage orders, refunds and subscriptions](https://kernlift.dev/docs/extensions/payments/subscriptions.md)
- [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md)
- [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md)
---
# Connect a payment provider
> Buyers pay on Stripe, Creem, PayPal, DodoPayments, WeChat Pay, Alipay or Waffo, and a confirmed payment marks their order paid.
Source: https://kernlift.dev/docs/extensions/payments/setup
Payments run through one active provider at a time. WeChat Pay and Alipay are the exception. Once enabled and complete, they charge every plan priced in CNY, WeChat Pay first and Alipay when WeChat Pay is not ready, and the active provider charges plans in other currencies. You connect providers in the admin console, register the webhook, and take a test payment. Payments need no environment variables.
## Before you begin
* A provider account and API credentials. Start in test mode, except for WeChat Pay, which requires a live merchant account.
* The public URL of your deployment. A local `127.0.0.1` address cannot receive webhooks.
* An admin account with `config.read` and `config.write`.
* At least one active plan on `/admin/plans`. See [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md).
## Create test resources with the payment provider
| Provider | Choose it for |
| ------------------------------------------------------ | --------------------------------------------------------------------------------------------------- |
| [Stripe](https://kernlift.dev/docs/extensions/payments/stripe.md) | Subscription checkout, portal and refunds |
| [Creem](https://kernlift.dev/docs/extensions/payments/creem.md) | Hosted checkout; see adapter compatibility |
| [PayPal](https://kernlift.dev/docs/extensions/payments/paypal.md) | One-time orders with a sandbox buyer |
| [DodoPayments](https://kernlift.dev/docs/extensions/payments/dodopayments.md) | Hosted checkout linked to a product ID |
| [WeChat Pay](https://kernlift.dev/docs/extensions/payments/wechat-pay.md) | CNY one-time payment with a QR code |
| [Alipay](https://kernlift.dev/docs/extensions/payments/alipay.md) | CNY one-time payment on Alipay's computer-website cashier, with refunds |
| [Waffo](https://kernlift.dev/docs/extensions/payments/waffo.md) | Merchant of record: hosted checkout for one-time and subscription plans, sales tax handled by Waffo |
## Enter the provider settings
### Open Payment Config
Go to **Settings → Payment Config** (`/admin/config/payment`). Each provider card shows **Missing credentials** or **Ready**, and **Webhook missing** or **Webhook ready**. Select the provider you want to set up.
### Set the checkout routes
Under **Checkout routes**:
* **Success URL**: where the buyer lands after a confirmed payment, for example `https:///app/billing`.
* **Cancel URL**: where the buyer lands otherwise, for example `https:///pricing`.
* **API base URL**: the provider API to call. Creem, PayPal and DodoPayments default to `https://api.creem.io`, `https://api-m.sandbox.paypal.com` and `https://test.dodopayments.com`. Change it when you move between test and live. Stripe ignores this field, because the key determines test or live. WeChat Pay defaults to `https://api.mch.weixin.qq.com`, its only environment. Alipay defaults to the sandbox gateway; Waffo has one address, `https://api.waffo.ai`, and its key decides test or live.
* **Allow promotion codes at checkout**: see [Offer promotion codes](#offer-promotion-codes).
The buyer returns through your own domain before reaching the success URL, so use your public domain here.
### Paste the API credentials
Under **Credentials**, fill in the fields for the selected provider:
Use the field mapping in your provider’s guide above.
Secret fields are never shown again after saving. Leave one blank to keep the stored value.
## Register the webhook
Follow your provider guide to register its HTTPS endpoint, select the supported events and save its verification credentials. WeChat Pay and Alipay include the notification URL with each order.
## Activate the provider
Tick **Set as active provider** and click **Save provider**. The card shows **Active** and **Webhook ready**, and the **Runtime** panel shows the active provider. Unticking and saving the active provider leaves no provider active. Saving another provider unticked does not change the active one. Ticking WeChat Pay or Alipay turns it on for CNY plans and makes it the active provider only when none is active. The **Capabilities** panel shows whether the portal, subscriptions, refunds and promotion codes are available.
## Offer promotion codes
Turn on **Allow promotion codes at checkout** in **Checkout routes** and click **Save provider**. The switch is stored once (`payment.checkout.allow_promotion_codes`) and is off by default. Stripe and Waffo then show a code field on their hosted checkout; the other providers ignore the switch, and their **Capabilities** panel shows promotion codes as unsupported. Create the codes in the provider's own dashboard.
The invoice records the amount actually paid, taken from the signed webhook or the server-side confirmation, while the amount due stays at the plan price. A refund of everything the buyer paid counts as a full refund.
## Verify
Sign in as a normal user, open `/pricing` and buy a plan with the provider's test card or sandbox buyer. Then check:
* **Security → Webhooks** (`/admin/billing-webhooks`) lists the provider's event with a valid signature.
* **Commerce → Orders** (`/admin/orders`) shows the order as paid.
* The buyer's `/app/billing` shows the invoice, and the plan's credits appear on `/app/credits`. The built-in fulfilment plugin grants credits after the order is committed. If they are missing, look for a `billing.fulfilment.failed` entry on `/admin/audit`.
* For WeChat Pay, the buyer is sent to `/app/billing/pay/`, scans the QR code with WeChat, and the page moves on to the success URL within a few seconds of paying.
* For Alipay, the buyer is sent to Alipay's cashier and comes back through `/api/billing/callback/alipay`, which queries the trade before the order is marked paid.
`pnpm validate:billing` checks the order state machine, not-configured paths and signature handling. `pnpm validate:wechat-pay` checks WeChat Pay signing, decryption, amount checks and routing by currency without calling WeChat Pay. `pnpm validate:alipay`, `pnpm validate:waffo` and `pnpm validate:promotion-codes` do the same for Alipay, Waffo and discounted totals. To test against the real sandbox, run `pnpm validate:external` with the provider credentials saved.
## Troubleshooting
### The buyer is sent to `/system/payment-failed` from the pricing page
Checkout was rejected. Open **Webhooks** for the `checkout.not_configured` or `checkout.failed` event and its error, then complete the credentials on **Payment Config**. DodoPayments also needs a product id.
### Webhooks fail the signature check
Confirm the saved **Webhook secret** is the signing secret of this endpoint, and for DodoPayments the full `whsec_…` value. Stripe and DodoPayments reject events more than 300 seconds away from the server clock, so check the server time. A proxy that rewrites the request body also breaks the signature.
### The buyer lands on a missing page after paying
A database seeded before the default changed can still hold `http://127.0.0.1:5173/app/billing/orders`, which has no route. Set **Success URL** to a page that exists, such as `https:///app/billing`.
### WeChat Pay or Alipay checkout is refused with `provider_unsupported`
WeChat Pay and Alipay charge CNY one-time payments only. On `/admin/plans`, price the plan in `CNY` with the one-time or lifetime interval, or use another provider for that plan.
### The order stays pending
The webhook has not arrived and the buyer did not return to your site. Check that the endpoint is registered for the right events, then resend the event from the provider dashboard.
## Reference
* [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
* [Stripe webhooks](https://stripe.com/docs/webhooks)
## Next steps
- [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md)
- [Write a fulfilment plugin](https://kernlift.dev/docs/extensions/payments/fulfilment.md)
- [Manage orders, refunds and subscriptions](https://kernlift.dev/docs/extensions/payments/subscriptions.md)
- [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
---
# Stripe
> Take one-time payments and monthly or yearly subscriptions through Stripe Checkout, with refunds and the customer portal.
Source: https://kernlift.dev/docs/extensions/payments/stripe
Stripe is the provider with the most complete adapter. The buyer pays on Stripe's hosted Checkout page; the price comes from your plan, so you create no products or prices in Stripe.
## What it supports
| Capability | Supported | Notes |
| ------------------------ | ------------------- | -------------------------------------------- |
| One-time payments | Yes | A plan billed once or for a lifetime |
| Subscriptions | Yes | A plan that renews every month or every year |
| Refunds from the console | Yes | Full or partial, from `/admin/orders` |
| Customer portal | Yes | Buyers open it from `/app/billing/portal` |
| Currencies | The plan's currency | Sent to Stripe as it is saved on the plan |
A renewal is charged by Stripe. This adapter settles the first payment of a subscription; it does not process Stripe's `invoice.*` events, so a renewal does not create a new order or grant the plan's credits again.
## Before you begin
**You need**
* A Stripe account. Use test mode until the whole flow works.
* The site deployed at a public HTTPS address. Stripe cannot deliver a webhook to `127.0.0.1`.
* An admin account with `config.read` and `config.write`.
* At least one active plan in `/admin/plans`. See [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md).
**When you finish you have**
* A secret key (`sk_test_…`) and a webhook signing secret (`whsec_…`) saved in the admin console.
* Stripe set as the active provider, with a test purchase settled as a paid order.
## Set up Stripe
These steps happen in the Stripe Dashboard.
### Open the test API keys
Open [dashboard.stripe.com/test/apikeys](https://dashboard.stripe.com/test/apikeys). The `/test/` address keeps you in test mode.
**Test and live keys do not mix**
A test key only works with a test webhook secret, and a live key with a live one. Finish the whole flow in test mode before you create anything in live mode.
### Copy the secret key
Under **Standard keys**, click **Reveal test key** on the **Secret key** row and copy it. It starts with `sk_test_`.
### Open the webhooks page
Open [dashboard.stripe.com/test/workbench/webhooks](https://dashboard.stripe.com/test/workbench/webhooks) and click **Add destination**.
### Select the events
Select these three events, then continue:
| Event | What it does here |
| --------------------------------------- | --------------------------------------------------- |
| `checkout.session.completed` | Marks the order paid and stores the subscription id |
| `checkout.session.async_payment_failed` | Marks the order failed |
| `checkout.session.expired` | Marks the order canceled |
These checkout events cover the order transitions in the table.
### Enter the endpoint URL
Choose **Webhook endpoint** as the destination type and set the **Endpoint URL** to:
```text
https:///api/billing/webhook/stripe
```
Click **Create destination**.
### Copy the signing secret
On the destination's page, reveal the **Signing secret** and copy it. It starts with `whsec_`.
**One secret per destination**
Each destination has its own signing secret. A secret copied from another destination, or from the Stripe CLI, does not verify these events.
### Activate the customer portal (optional)
To let buyers manage cards and cancel, open [dashboard.stripe.com/test/settings/billing/portal](https://dashboard.stripe.com/test/settings/billing/portal) and click **Activate test link**. If you keep more than one portal configuration, copy the id of the one to use; it starts with `bpc_`.
Stripe's own guides: [Receive Stripe events in your webhook endpoint](https://docs.stripe.com/webhooks) and [Activate the customer portal](https://docs.stripe.com/customer-management/activate-no-code-customer-portal).
## Fill in the admin form
Back in the Kernlift admin console.
### Open Payment Config
Go to **Settings → Payment Config** (`/admin/config/payment`) and select the **Stripe** card.
### Set the return addresses
In **Checkout routes**, set **Success URL** to where a buyer lands after paying, for example `https:///app/billing`, and **Cancel URL** to where a buyer lands otherwise, for example `https:///pricing`. Leave **API base URL** as it is; Stripe does not use it.
### Paste the values from Stripe
In **Credentials**, paste each value into its field:
| In Stripe | Field in the admin form |
| ------------------------------------------- | --------------------------- |
| Secret key (`sk_test_…`) | **Secret key** |
| Signing secret (`whsec_…`) | **Webhook secret** |
| Portal configuration id (`bpc_…`), optional | **Portal configuration ID** |
A secret field is never shown again after saving, and saving it empty keeps the stored value.
### Make Stripe the active provider
Tick **Set as active provider** and click **Save provider**. The card shows **Active**, **Ready** and **Webhook ready**.
## Verify
1. Sign in as an ordinary user, open `/pricing` and buy a plan. **Expected**: you are sent to a Stripe Checkout page.
2. Pay with the test card `4242 4242 4242 4242`, any future expiry date and any CVC (see [Stripe's test cards](https://docs.stripe.com/testing)). **Expected**: you return to the **Success URL**. On the way back, `/api/billing/callback/stripe` asks Stripe whether the session is paid before the order is marked paid.
3. Open **Security → Webhooks** (`/admin/billing-webhooks`). **Expected**: a `checkout.session.completed` event from Stripe with a valid signature.
4. Open **Commerce → Orders** (`/admin/orders`). **Expected**: the order is paid, the buyer sees the invoice on `/app/billing` and the plan's credits on `/app/credits`.
To test a refund, open the order and create a refund. See [Manage orders, refunds and subscriptions](https://kernlift.dev/docs/extensions/payments/subscriptions.md).
## Go live
1. Open [dashboard.stripe.com/apikeys](https://dashboard.stripe.com/apikeys) (no `/test/` in the address) and copy the live **Secret key** (`sk_live_…`).
2. Open [dashboard.stripe.com/workbench/webhooks](https://dashboard.stripe.com/workbench/webhooks) and add the destination again, with the same URL and events. Copy its new signing secret; a test-mode secret does not verify live events.
3. Save both on `/admin/config/payment`, and check that **Success URL** and **Cancel URL** point at the production domain.
4. Make one real purchase and refund it.
## Troubleshooting
### The webhook is listed with a failed signature
The saved **Webhook secret** is not the signing secret of this destination, or it comes from the other mode. Stripe events whose timestamp differs from the server's clock by more than 300 seconds are refused as well, so check the server time. A proxy that rewrites the request body also breaks the signature.
### The order stays pending after a successful payment
Neither the return through `/api/billing/callback/stripe` nor the webhook reached the site. Check that the destination URL is the public address and that `checkout.session.completed` is selected, then resend the event from the Stripe Dashboard.
### Checkout is rejected with `plan_interval_mismatch`
The plan bills as a subscription but its interval is not month or year, or it bills once but has a monthly or yearly interval. Save the plan again in `/admin/plans`; the form keeps the two in step.
### A refund fails with "requires a PaymentIntent or Charge id"
The order has no Stripe payment behind it, which happens when the checkout was never completed. Only a paid order can be refunded.
## Next steps
- [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
Compare the providers and the settings they share.
- [Manage orders, refunds and subscriptions](https://kernlift.dev/docs/extensions/payments/subscriptions.md)
Refund an order, cancel a subscription, open the portal.
---
# Manage orders, refunds and subscriptions
> You can refund an order, cancel or resume a subscription, let buyers manage their billing and re-apply a failed webhook.
Source: https://kernlift.dev/docs/extensions/payments/subscriptions
After a sale, operators work in the **Commerce** and **Security** areas of the admin console, and buyers use their billing pages. Every change goes through the payment provider, so what is available depends on the active provider.
## Before you begin
* A connected provider that has taken at least one payment. See [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md).
* Permissions for what you plan to do: `orders.write` for refunds, `subscriptions.write` for subscription changes, `webhooks.write` to retry webhooks. The matching `.read` permissions open the pages.
* Refunds from the console need Stripe, WeChat Pay or Alipay; Creem and Waffo refunds are made in their own dashboards. Subscription changes and the customer portal need Stripe or Creem.
## Refund an order
### Open the order
Go to **Commerce → Orders** (`/admin/orders`) and open the order.
### Create the refund
Enter the **Amount cents** to return and a **Reason**, then click **Create refund**. The refund is recorded with status pending, succeeded, failed or not configured.
A succeeded refund of the full amount revokes the licences the order issued. A partial refund revokes nothing. A refund does not change the order status or take back credits, so deduct credits by hand if needed. See [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md). Creem refunds are made in the Creem dashboard.
## Cancel or resume a subscription
### Open the subscription
Go to **Commerce → Subscriptions** (`/admin/subscriptions`) and open the subscription.
### Apply the change
Click **Cancel at period end** to stop renewal, or **Resume subscription** to undo it. The change is sent to the provider.
Both actions need the provider's subscription id, which arrives with the paid webhook.
## Let buyers manage their billing
Buyers see their plan, orders and invoices at `/app/billing`, with CSV export. For cards and cancellations they use the provider's customer portal.
### Open the portal page
The buyer opens `/app/billing/portal`.
### Create a session
They leave **Provider** on **Configured default**, enter their **Provider customer ID** (for Stripe, `cus_…`) and click **Create portal session**. When the provider creates the session, the page shows **Portal ready:** followed by the portal URL. Otherwise it shows the status.
**Replace the portal form**
The portal page is a basic form. In your product, replace it with a button that passes the customer id you already store for the buyer.
## Retry a failed webhook
A correctly signed webhook that failed to apply, for example because of a temporary database error, can be applied again.
### Find the event
Go to **Security → Webhooks** (`/admin/billing-webhooks`) and open the event to see its payload, signature result and error.
### Retry
Click **Retry** on a failed event. The stored payload is applied again and the result is recorded as a new event.
Events with an invalid signature cannot be retried. Resend them from the provider dashboard.
## Verify
* After a refund, the order page lists the refund with its status, and a full refund removes the licence from the buyer's `/app/licences`.
* After **Cancel at period end**, the subscription page shows **Cancel at period end** as `yes`. **Resume subscription** sets it back to `no`.
* After a retry, **Webhooks** shows a new event for the same payload.
`pnpm validate:billing` checks the refund, subscription and webhook paths. With sandbox ids set, `pnpm validate:external` calls the real portal, cancel, resume and refund endpoints.
## Troubleshooting
### A Stripe refund fails with "no PaymentIntent to refund"
The message `The Stripe checkout session has no PaymentIntent to refund.` means the checkout session never produced a payment, so there is no charge to return.
### Cancel or resume returns `missing_provider_subscription`
The paid webhook carrying the provider subscription id has not arrived yet. Check **Webhooks** for the event, and register the webhook if it is missing.
### The refund is recorded as not configured or failed
Not configured means the credentials of the provider that took the order are missing on **Payment Config**. For a failed refund, **Webhooks** lists a `refund.failed` event with the error. Providers other than Stripe fail with `This payment provider does not support refunds through this adapter.`, so refund in their dashboard.
### The portal page reports that the portal is not configured
The active provider has no customer portal. Only Stripe and Creem offer one.
## Reference
* [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
* [Stripe subscriptions](https://stripe.com/docs/billing/subscriptions/overview)
## Next steps
- [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md)
- [Sell products and plans](https://kernlift.dev/docs/extensions/payments/products.md)
- [Write a fulfilment plugin](https://kernlift.dev/docs/extensions/payments/fulfilment.md)
---
# Waffo
> Accept payments through Waffo, a merchant of record that collects and remits sales tax.
Source: https://kernlift.dev/docs/extensions/payments/waffo
* **Checkout** Waffo hosted checkout, priced from your plan with tax included
* **Subscriptions** Monthly and yearly, settled on the first payment
* **Portal** No
* **Refunds** In the Waffo dashboard only
* **Promotion codes** Yes
Waffo is the merchant of record: it sells to the buyer and handles sales tax. Checkout needs products that already exist in Waffo, but you create only three, shared by every plan. The price of each session comes from the plan.
## Before you begin
A public HTTPS site, an active plan on `/admin/plans` (see [Manage pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md)), and a Waffo merchant account with a store. Work in the Test environment until the whole flow works.
**Expected result** — a test purchase settled by a signed `order.completed` or `subscription.activated` webhook.
## Set up Waffo
### Create the API key
In the Waffo dashboard open **API & Development → API Keys** and click **Create API Key** with the Test environment. Download the private key at once; it is not shown again. The key's environment decides test or live mode. Record your merchant ID (`MER_…`) as well.
### Create the products
Create one one-time product, one monthly subscription product and one yearly subscription product, and copy their IDs. Each checkout overrides the price, so the product prices do not matter.
### Register the webhook
Under **Settings → Webhooks**, add an HTTP webhook in test mode with the URL `https:///api/billing/webhook/waffo`. Subscribe to `order.completed` and `subscription.activated`.
### Copy the webhook public key
On the same page copy the **Webhook Public Key** for the Test environment. Test and production use different keys.
Provider documentation · [Authentication](https://docs.waffo.ai/api-reference/authentication) · [Create a checkout session](https://docs.waffo.ai/api-reference/endpoints/orders/create-checkout-session) · [Webhooks](https://docs.waffo.ai/api-reference/webhooks)
## Configure the application
Open `/admin/config/payment` in the Kernlift admin console. Select **Waffo**. Enter your public Success URL and Cancel URL, and leave **API base URL** at `https://api.waffo.ai`.
| Value from provider | Admin field |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ |
| Merchant ID (`MER_…`) | **Merchant ID (MER\_...)** |
| The tax category of what you sell: `saas`, `digital_goods`, `software`, `ebook`, `online_course`, `consulting` or `professional_service` | **Tax category (saas, digital\_goods, software...)**; blank keeps `saas` |
| The three product IDs | **One-time product ID**, **Monthly subscription product ID**, **Yearly subscription product ID** |
| The downloaded API private key | **Merchant private key** |
| The Webhook Public Key of the same environment | **Webhook public key** |
Enable the provider and click **Save provider**. The card shows **Ready** once the merchant ID, private key and at least one product ID are saved, and **Webhook ready** once the webhook public key is saved. To let buyers enter a code, turn on **Allow promotion codes at checkout**; create the codes in Waffo.
**A plan needs its product**
A one-time plan needs the one-time product, and a monthly or yearly plan the subscription product of its interval. Without it, checkout is refused. A subscription plan that renews on another interval cannot be sold through Waffo.
## Verify
1. Sign in as an ordinary user, open `/pricing` and buy a plan. **Expected**: you are sent to the Waffo checkout, showing the plan's price.
2. Pay with Waffo's test payment details. **Expected**: you return through `/api/billing/callback/waffo`, which looks up the order's payments in Waffo before marking it paid.
3. Open `/admin/billing-webhooks`. **Expected**: an `order.completed` (one-time) or `subscription.activated` (subscription) event with a valid signature.
4. Open `/admin/orders`. **Expected**: the order is paid, and its invoice shows the amount charged, lower than the plan price if a promotion code was used.
## Go live
1. Create a production API key and production products, and add the webhook again with test mode off.
2. Save the production merchant private key, product IDs and the production webhook public key. A test key cannot verify production events.
3. Make one real purchase and refund it in the Waffo dashboard.
## Troubleshooting
### Webhooks fail the signature check
The saved webhook public key belongs to the other environment, or is missing. Waffo signs `t` in milliseconds and retries reuse it, so events up to 45 minutes old are accepted; older ones are refused. A proxy that rewrites the request body also breaks the signature.
### Checkout fails with "No Waffo subscription product is configured"
The plan is a subscription whose interval has no product ID. Save the monthly or yearly product ID, or change the plan's interval.
### A refund or renewal does not appear on the order
Refunds and subscription changes are made in the Waffo dashboard. Their events, such as `refund.succeeded` and `subscription.renewed`, are stored as ignored: they do not change the local order, create a new order or grant the plan's credits again.
## Next steps
- [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
Compare the providers and the settings they share.
---
# WeChat Pay
> Accept payments with WeChat Pay.
Source: https://kernlift.dev/docs/extensions/payments/wechat-pay
* **Checkout** Native QR code on your own `/app/billing/pay/` page, CNY one-time payments only
* **Subscriptions** No
* **Portal** No
* **Refunds** Yes
## Before you begin
A public HTTPS site, an active plan on `/admin/plans`, and access to the merchant dashboard.
**Expected result** — an order reconciled with a signed payment notification.
## Set up WeChat Pay
### Enable Native payments
Open [WeChat Pay](https://pay.weixin.qq.com/index.php/core/cert/api_cert). Enable Native支付 in the merchant account’s 产品中心.
### Link the AppID
Under AppID账号管理 link your application and record its AppID and merchant ID.
### Request the merchant certificate
Request a merchant API certificate under API安全. Keep the private key and record the certificate serial number.
### Set the decryption key
Set the APIv3 key for decrypting notifications.
### Download the verification key
Download the WeChat Pay public key and copy its public key ID. Each order supplies its own notification URL.
Provider documentation · [Native payments](https://pay.weixin.qq.com/doc/v3/merchant/4012791874) · [verifying with the WeChat Pay public key](https://pay.weixin.qq.com/doc/v3/merchant/4013053249)
## Configure the application
Open `/admin/config/payment` in the Kernlift admin console. Select **WeChat Pay**. Enter your public Success URL and Cancel URL, then set **API base URL** to `https://api.mch.weixin.qq.com`.
| Value from provider | Admin field |
| ---------------------------------------------------------------------- | -------------------------------------------------------------------- |
| Merchant platform → 产品中心 → AppID账号管理, and the account page. | **AppID**, **Merchant ID (mchid)** |
| 账户中心 → API安全 → 商户API证书; paste the whole `apiclient_key.pem`. | **Merchant API certificate serial number**, **Merchant private key** |
| 账户中心 → API安全 → APIv3密钥, the 32-character key you set. | **APIv3 key** |
| 账户中心 → API安全 → 微信支付公钥: the `PUB_KEY_ID_…` and the whole `pub_key.pem`. | **WeChat Pay public key ID**, **WeChat Pay public key** |
Enable the provider and click **Save provider**.
**Preserve the PEM format**
Paste both PEM keys with their header, footer and line breaks. Keep the merchant private key server-side.
## Verify
1. Open a low-value, one-time CNY plan and scan its QR code to pay.
2. Check the signed notification and paid order in admin.
3. Refund the test order before activating delivery and check the provider refund status.
## Troubleshooting
### WeChat Pay checkout is refused with `provider_unsupported`
WeChat Pay charges CNY one-time payments only. On `/admin/plans`, price the plan in `CNY` with the one-time or lifetime interval, or use another provider for that plan.
## Next steps
[Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md)
---
# Amazon S3
> Store uploaded files with Amazon S3.
Source: https://kernlift.dev/docs/extensions/storage/aws-s3
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — an uploaded file you can download again.
## Set up Amazon S3
### Create a private bucket
Open [Amazon S3](https://console.aws.amazon.com/s3/). Create a private bucket in the target region.
### Grant object permissions
Grant an application identity GetObject, PutObject and DeleteObject on its objects.
### Issue the access key
Create an access key and save its secret.
Provider documentation · [creating an S3 bucket](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html) · [IAM access keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)
## Configure the application
Open `/admin/config/storage` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ----------------- |
| Bucket | Bucket name |
| Regional endpoint | S3 endpoint |
| AWS Region | Region |
| Access Key ID | Access Key ID |
| Secret Access Key | Secret Access Key |
Enable uploads and select the S3 driver. Use the bucket’s actual AWS region. Save the configuration.
## Verify
1. Upload a small allowed file at `/app/assets/upload`.
2. Download it from `/app/assets` and check the content.
## Troubleshooting
### S3 upload fails with "Storage upload failed (403)"
The error shows the provider's own code and message. Check the access key, secret and bucket name, and that **Region** matches what the endpoint expects for signing.
## Next steps
[Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md)
---
# Cloudflare R2
> Store uploaded files with Cloudflare R2.
Source: https://kernlift.dev/docs/extensions/storage/cloudflare-r2
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — an uploaded file you can download again.
## Set up Cloudflare R2
### Create the R2 bucket
Open [Cloudflare R2](https://dash.cloudflare.com/). Create an R2 bucket and record its name.
### Workers with an R2 binding
On Workers, bind the bucket as `BUCKET` in `wrangler.jsonc` and deploy.
### S3 access with a scoped token
For S3 access instead, create a bucket-scoped Object Read & Write token. Save the S3 credentials and account endpoint.
Provider documentation · [R2 bucket and credential setup](https://developers.cloudflare.com/r2/get-started/cli/) · [token permissions](https://developers.cloudflare.com/r2/api/tokens/)
## Configure the application
Open `/admin/config/storage` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ----------------- |
| Bucket | Bucket name |
| S3 endpoint | S3 endpoint |
| Signing region | Region |
| Access Key ID | Access Key ID |
| Secret Access Key | Secret Access Key |
Enable uploads and select the S3 driver. For R2 over S3 use region `auto`. With a Worker binding, select **Native bucket binding** instead and skip the S3 fields. Save the configuration.
## Verify
1. Upload a small allowed file at `/app/assets/upload`.
2. Download it from `/app/assets` and check the content.
## Troubleshooting
### S3 upload fails with "Storage upload failed (403)"
The error shows the provider's own code and message. Check the access key, secret and bucket name, and that **Region** matches what the endpoint expects for signing.
## Next steps
[Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md)
---
# Set up file storage and uploads
> Users can upload files and download them through time-limited links, stored in your own S3-compatible bucket or R2 binding.
Source: https://kernlift.dev/docs/extensions/storage
User uploads and AI-generated media are stored in one bucket. The server writes the files, and the browser never uploads to the bucket directly, so the bucket stays private and needs no CORS rule. Storage is configured in the admin console and needs no environment variables.
## Before you begin
* An admin account with `config.read` and `config.write`.
* A bucket, or an app running on Cloudflare Workers with an R2 bucket bound as `BUCKET`.
Choose the driver by where the app runs:
| Driver | Use it when | What you set up |
| -------------------------- | ----------------------------------------------------------------------- | --------------------------- |
| **S3-compatible endpoint** | Any runtime: Node, Docker, Cloudflare Workers. | A bucket and an access key. |
| **Native bucket binding** | The app runs on Cloudflare Workers with an R2 bucket bound as `BUCKET`. | The binding only, no keys. |
## Create the bucket with the storage provider
| Provider | Choose it for |
| ------------------------------------------------------- | ---------------------------------------- |
| [Cloudflare R2](https://kernlift.dev/docs/extensions/storage/cloudflare-r2.md) | A Workers bucket binding or R2 over S3 |
| [Amazon S3](https://kernlift.dev/docs/extensions/storage/aws-s3.md) | Private AWS bucket with regional signing |
| [MinIO](https://kernlift.dev/docs/extensions/storage/minio.md) | Self-hosted object storage |
## Connect the bucket
**S3-compatible endpoint**
### Create the bucket and an access key
In your provider's console, create a bucket and an API key that can read, write and delete objects in it.
Use the field mapping in your provider’s guide above.
Go to **Settings → Storage Config** (`/admin/config/storage`), tick **Enable uploads** and select **S3-compatible endpoint**. Then fill in:
* **Connection → Bucket name**: the bucket you created.
* **Connection → Region**: the signing region in the provider guide. It defaults to `us-east-1`.
* **Connection → S3 endpoint**: the endpoint from the provider guide, without the bucket name.
* **Credentials → Access Key ID** and **Secret Access Key**: the key pair.
On a first setup the S3 option stays greyed out until these fields are saved. Saving still uses it.
### Save
Click **Save storage config**. The page shows **Storage configuration saved.**, and under **Storage driver** in the **Runtime** panel, **Read access** shows `sigv4`.
Credential fields are empty every time the page loads. Leave a field blank to keep the saved value.
**Native bucket binding**
### Bind the bucket
Declare an R2 bucket binding named `BUCKET` in `wrangler.jsonc` and deploy. See [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md).
### Select the driver
On **Settings → Storage Config**, tick **Enable uploads**, select **Native bucket binding** and click **Save storage config**. The connection and credential fields are not used.
**Read access** shows `application`. The binding cannot presign, so signed links point at your own site and the app streams the file. An option this runtime cannot serve is greyed out with the reason underneath.
## Set limits and a public domain
### Limit file size
Under **Limits and MIME types**, set **Max file size bytes**. The default is `10485760` (10 MB).
### Limit file types
Edit **Image MIME types**, **Video MIME types**, **Audio MIME types** and **File MIME types** as comma-separated content types. The defaults are `image/png, image/jpeg, image/webp, image/gif`; `video/mp4, video/webm`; `audio/mpeg, audio/wav, audio/ogg`; and `application/pdf, text/plain`.
### Add a public domain (optional)
If a CDN or custom domain already serves the bucket's objects, fill in **Connection → CDN or public access domain**, for example `https://assets.example.com`. Each new upload records a public link made of this domain and the object path. The app does not make the bucket public, and earlier files keep the link they were saved with.
### Save
Click **Save storage config**.
Unticking **Enable uploads** and saving turns uploads off without removing the saved credentials.
## Upload over the API
Users upload from `/app/assets/upload`. Scripts use a session cookie or an API key with **Upload files**. The endpoint accepts `multipart/form-data` (a `file` field) or JSON (a `base64` field). Without `folderId` the file goes to the user's `/uploads` folder.
```bash
curl -X POST https://your-domain.example/api/assets/upload \
-H "Authorization: Bearer $API_KEY" \
-F "file=@./report.pdf" \
-F "resourceType=file"
# 201 => { "ok": true, "file": { "id": "file_...", "objectKey": "...", "publicUrl": null, ... } }
```
Each user has three folders: `/`, `/uploads` and `/generated`, where AI output goes. Uploads to any other folder are rejected. Signed download links expire after at most 24 hours.
**Before storage is configured**
There is no fallback storage. Uploads fail with `S3-compatible storage credentials are not configured.` (HTTP 503 from `/api/assets/upload`), signed links cannot be created, and `/setup` lists **Object storage** as not ready.
## Verify
### Check the upload page
Open `/app/assets/upload` as any signed-in user. The badge next to the title reads **R2 ready** once a driver is usable (the label is the same for every provider), or **Storage not configured**.
### Upload a file
Pick a **Resource type**, choose a **File** that matches its allowed types, and click **Upload**. The form shows **Uploaded** and the file name, or the provider's error.
### Download it
Open the file from `/app/assets` and click **Generate signed URL**. Open the URL under the button in a new tab. The file loads.
### Check the admin view
**Platform → Assets** (`/admin/assets`) lists the file under its owner, and `/setup` lists **Object storage** as ready.
`pnpm validate:files` checks the wiring for both drivers. `pnpm validate:storage-drivers` writes, reads and deletes real objects in your bucket.
## Troubleshooting
### Upload returns "Content type ... is not allowed"
The file's type is not in the list for the resource type you sent. Add it to the matching MIME list on **Storage Config**, or send the correct resource type.
### Upload returns "Folder does not exist"
The folder id is not one of the caller's own folders. Omit `folderId` on `/api/assets/upload` to use `/uploads`.
### S3 upload fails with "Storage upload failed (403)"
The error shows the provider's own code and message. Check the access key, secret and bucket name, and that **Region** matches what the endpoint expects for signing.
### A signed link from the binding driver returns 503
Links on your own site only serve files while the binding driver is selected and the `BUCKET` binding is present. A link issued before switching drivers cannot be served. Generate a new one.
## Reference
* [Deploy to Cloudflare](https://kernlift.dev/docs/deploy/cloudflare.md)
* [Configuration model](https://kernlift.dev/docs/core/configuration.md)
* [S3 API](https://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html)
## Next steps
- [Issue API keys and set rate limits](https://kernlift.dev/docs/core/auth/api-keys.md)
- [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md)
- [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md)
---
# MinIO
> Store uploaded files with MinIO.
Source: https://kernlift.dev/docs/extensions/storage/minio
## Before you begin
An account with access to the provider and permission to edit the settings below in Kernlift.
**Expected result** — an uploaded file you can download again.
## Set up MinIO
### Create the bucket
Open [MinIO](https://min.io/docs/minio/linux/administration/identity-access-management/minio-user-management.html). Open your MinIO Console and create a bucket.
### Create application keys
Issue application credentials under Access Keys with object access to that bucket.
### Record the S3 endpoint
Record the S3 API endpoint reachable from Kernlift and the signing region.
Provider documentation · [MinIO identity management](https://min.io/docs/minio/linux/administration/identity-access-management/minio-user-management.html)
## Configure the application
Open `/admin/config/storage` in the Kernlift admin console.
| Value from provider | Admin field |
| ------------------- | ----------------- |
| Bucket | Bucket name |
| API address | S3 endpoint |
| Signing region | Region |
| Access Key | Access Key ID |
| Secret Key | Secret Access Key |
Enable uploads and select the S3 driver. Use the S3 API address accessible to the server. Save the configuration.
## Verify
1. Upload a small allowed file at `/app/assets/upload`.
2. Download it from `/app/assets` and check the content.
## Troubleshooting
### S3 upload fails with "Storage upload failed (403)"
The error shows the provider's own code and message. Check the access key, secret and bucket name, and that **Region** matches what the endpoint expects for signing.
## Next steps
[Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md)
---
# Support tickets
> Take support requests from signed-in customers, triage them against an SLA and reply from the admin console.
Source: https://kernlift.dev/docs/extensions/support
A customer opens a ticket from `/app/tickets`. The ticket appears in `/admin/support` with a status, a
priority and an SLA flag, and every reply is written to the same conversation. No third-party
helpdesk is needed. Tickets, conversations and messages are rows in your own database.
## Before you begin
* An account that can reach the console, with the `support.read` permission to read tickets and
`support.write` to reply or reassign. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md).
* Email is optional. Tickets work without it. Connect a provider from
[Send transactional email](https://kernlift.dev/docs/extensions/email.md) if you want the customer notified off-site.
## Set it up
### Give an operator the permissions
Open `/admin/roles`, pick the role your support staff hold and add `support.read` and
`support.write`. A role with only `support.read` sees the queue and the conversation but cannot
reply or reassign, which suits an analyst.
### Open a ticket as a customer
Sign in as an ordinary account, go to `/app/tickets` and submit one. The server takes the
requester's e-mail from the session, not from the form, so a customer cannot submit a ticket under another address.
A new ticket arrives as `triage`, priority `normal`, SLA `within_sla`, assigned to `support`.
### Work the queue
`/admin/support` lists every ticket with its requester, priority, SLA state and assignee. Open one
to read the conversation, reply, and set status, priority, assignee and SLA state together.
A reply from an operator moves the ticket to `waiting`. A reply from the customer moves it back to
`triage`. Closing a ticket also marks its conversation `resolved`, and `/app/tickets/closed` lists
conversations with that status.
## Customer data isolation
The server reads the customer's identity from the session, not from a form field. Before every reply, the server reloads the ticket using both its ID and the requester's email, so another customer's ticket is not returned. Ticket status changes are covered in the steps above.
Conversations, tickets and ticket messages are written in one transaction. Admin changes also create audit entries. See [Audit log](https://kernlift.dev/docs/core/admin/audit-log.md).
## Verify
1. Open a ticket from `/app/tickets`. It appears in `/admin/support` with status `triage`.
2. Reply as an operator. The customer's view shows the reply and the ticket reads `waiting`.
3. Sign in as a different customer and open the first customer's ticket id directly. The page
does not show the conversation.
4. Close the ticket. It moves to `/app/tickets/closed` for the customer.
## Reference
* [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md)
* [Better Auth sessions](https://better-auth.com/docs/concepts/session-management): where the
requester identity comes from
## Next steps
- [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md)
Give support staff a role that can only read and answer tickets.
- [Audit log](https://kernlift.dev/docs/core/admin/audit-log.md)
Every reassignment and reply by an operator is recorded.
- [Notifications](https://kernlift.dev/docs/extensions/notifications.md)
Notify a customer in-app or by e-mail when their ticket changes status.
- [Send transactional email](https://kernlift.dev/docs/extensions/email.md)
Connect a provider so ticket e-mail is delivered.
---
# Architecture
> How the code is layered, why business code never sees a SQL dialect, and the conventions that keep the template forkable.
Source: https://kernlift.dev/docs/guide/architecture
Kernlift is a template other people fork, so its structure is designed to stay predictable as
features are added. Server code is layered, runtime capabilities are detected when the app runs,
and a few conventions apply everywhere. For a map of the directories, see
[Project structure](https://kernlift.dev/docs/core/project-structure.md).
## The layers
```text
routes/ route components and API handlers
└── functions/ server functions callable from routes
└── services/ orchestration across capabilities
└── repositories/ all database access
└── schema/ per-dialect table definitions
platform/ runtime capabilities: cache, storage drivers, edge bindings
jobs/ scheduled work, started by the platform once a minute
agent-host/ the web side of the optional agent service
plugins/ what each installed plugin adds to the console
```
Each layer may call the one below it. Routes stay thin, services coordinate work that spans
capabilities (a settled payment grants credits and issues licences, for example), and repositories
are the only code that reads or writes the database.
| Layer | Lives in | Responsibility |
| ---------------- | ----------------------------- | -------------------------------------------------------------------- |
| Routes | `src/routes/` | Pages, layouts and API handlers; identity is checked at the boundary |
| Server functions | `src/server/functions/` | Calls from loaders and components, each resolving the caller first |
| Services | `src/server/services/` | Orchestration, rate limits and side effects across capabilities |
| Repositories | `src/server/db/repositories/` | Every read and write, behind dialect-neutral contracts |
| Schema | `src/server/db/schema/` | `sqlite.ts` and `postgres.ts`, declaring the same tables |
## Why business code never sees a dialect
Business code calls `repositories/` and never uses a SQL dialect directly, so the same code
runs on SQLite, Cloudflare D1, Turso and Postgres. The two schema files declare the same tables, and
`withRepositoryDialect` passes a repository the schema for the current connection.
Dialect differences stay inside the schema, migration and adapter layers. Migrations are
hand-maintained under `drizzle/migrations/`, so a schema change needs a matching migration
in each. How connections and adapters are chosen is covered in
[Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md).
## Runtime capabilities are facts, not preferences
`src/server/platform/` exposes capabilities the runtime either has or does not: a KV namespace for
cache, a bucket binding for storage, an inference binding for edge AI. Each is detected at runtime. A
capability that is absent is reported as unavailable with the reason, and cannot be selected in admin.
Where a native binding exists, a portable path exists alongside it. Storage has both an
S3-compatible driver and a bucket-binding driver behind one interface, so the template stays
deployable off Cloudflare.
## Caching
Each cache domain keeps its own keys and invalidation timing. Every domain reads its policy
(enable, TTL and backend) from admin config, so a domain can be turned off during triage without a
deploy. The policy is edited at
`/admin/config/cache`.
## Plugins fill the console
The admin sidebar, the workspace sidebar, the dashboard cards and the billing actions are slots,
declared in `src/plugins/slots.ts`, that installed plugins fill.
`src/plugins/installed.ts` is the explicit list of plugins in a build: the builtin `foundation`
plugin, which carries every console entry the foundation ships, and one plugin per installed module.
Server-only contributions are listed separately in `src/plugins/installed.server.ts`.
A plugin can be switched off at `/admin/plugins`. Its entries then disappear and the `/admin` and
`/app` layouts return not found for its pages. Its data stays. See
[Plugins](https://kernlift.dev/docs/core/plugins.md).
## Background work runs in the web app
Recurring work belongs to `runScheduledJobs()` in `src/server/jobs/scheduled.ts`: credit expiry,
billing fulfilment retries and unfinished AI tasks. One round runs a minute, started by whatever
the platform offers: the in-process loop on a Node server, the Worker's Cron Trigger on Cloudflare,
or an external cron calling `pnpm jobs:run`. A lock row in the config table keeps it to one round
even with several replicas, and each round records a heartbeat that `/setup` reads. See
[Background jobs](https://kernlift.dev/docs/core/background-jobs.md).
## The agent is a separate, optional service
The agent workbench runs in `apps/agent-service`, a second process built from the `agent-*`
workspace packages under `packages/`. The web app never loads the agent runtime and no web request
depends on that service. `src/server/agent-host/` is the web side of the boundary:
`getAgentAvailability()` in `availability.ts` returns whether this deployment has an agent,
and navigation, pages and `/api/agent/*` all use that result. A deployment without the
service is a complete web app whose AI goes through the plain channel calls. See
[Agent runtime](https://kernlift.dev/docs/extensions/agent.md).
## One build per deployment target
`deploy.config.json` records the platform (`cloudflare`, `fly`, `railway` or `docker`), the
database and whether the agent is deployed. It is bundled at build time and also picks the build:
the Worker build with `src/server-entry.ts`, or the Node build with `src/server-entry.node.ts`.
`kernlift deploy-target` rewrites it. See [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md).
## Locales
Routes are locale-aware under `src/routes/{-$locale}/`: the same page serves English at `/…` and
Chinese at `/zh/…`. Copy lives in `src/i18n/locales/{en,zh}/messages.ts` with identical keys, and
components read their copy from those dictionaries. Copy that belongs to one console area can sit in
a file of its own under `src/i18n/`, with the same `en` and `zh` keys. See
[Add and change copy](https://kernlift.dev/docs/customize/i18n.md).
## Conventions that apply everywhere
| Convention | What it means |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Spec-driven changes | Every non-trivial change starts as an OpenSpec change in `openspec/changes/` with a proposal, design, specs and tasks, and is archived when done |
| Configuration in the database | Provider credentials and business settings live in `/admin/config/*`; environment variables cover startup and infrastructure only. See [Configuration model](https://kernlift.dev/docs/core/configuration.md) |
| No mock providers | Integrations call real test or sandbox environments. Missing credentials surface as a not-configured state, never as a fake success |
| One identity boundary | Only `src/server/auth/` reads a session. See [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md) |
| A validator per capability | `scripts/validate/*.ts` asserts behaviour and wiring. See [Validators and the release gate](https://kernlift.dev/docs/core/validators.md) |
| One design system everywhere | Admin, workspace, auth, system and public-site pages are all built from beUI (`packages/beui`, `src/components/motion`) with Tailwind utilities on tokens that live on `:root`. No surface opts in and no page carries a prefix of its own. `src/styles/app.css` carries historical `!important` debt that new files must not copy. See [Use the design system](https://kernlift.dev/docs/customize/design-system.md) |
| The agent is optional | No web request path requires the agent service or imports the agent runtime. `pnpm validate:optional-agent` enforces it |
| Agent skills ship with the code | `skills//SKILL.md` holds the skills for working on the project. They name only commands, paths and routes that exist |
## Modules are slices of one repository
The checkout is a single repository. Each module is described by `modules//module.json`,
and shared files carry `@module:` regions. `pnpm registry:build` slices the checkout into a
foundation item plus one item per module, and `pnpm validate:registry` proves the slices reassemble
into the checkout byte for byte and that the foundation compiles without any module. See
[What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md).
## Files
- The layers/
- src/routes
- src/server/functions
- src/server/services
- src/server/db/repositories
- The boundaries/
- src/server/auth
- scripts/validate/auth-boundary.ts
- src/server/agent-host/availability.ts
- scripts/validate/optional-agent.ts
- Plugins and background work/
- src/plugins/installed.ts
- src/plugins/slots.ts
- src/plugins/foundation/plugin.ts
- src/server/jobs/scheduled.ts
- Packages and deployment/
- packages/beui
- apps/agent-service
- deploy.config.json
- src/server/platform/deployment.ts
## Next steps
- [Project structure](https://kernlift.dev/docs/core/project-structure.md)
- [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md)
- [Plugins](https://kernlift.dev/docs/core/plugins.md)
- [Background jobs](https://kernlift.dev/docs/core/background-jobs.md)
- [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md)
---
# FAQ
> Activation, expired invitations, refunds, forking, syncing upstream updates, database changes after a sync, project limits and support.
Source: https://kernlift.dev/docs/guide/faq
Short answers to the questions buyers ask most. If yours is not here, see [Get support](#how-do-i-get-support).
## What do I get when I buy Kernlift Premium?
Premium includes the base repository, Image Studio and Video Studio. Agent products have member pricing. [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
## Are CMS, newsletter and affiliate sold separately?
The base includes these modules. Image Studio and Video Studio come with Premium. Image Agent and Video Agent can be purchased separately.
## Do I need the membership to buy a business template?
Premium includes both Studios and unlocks member pricing on the two Agent templates. Anyone can buy an individual template at list price.
## How do I activate a purchase?
Open **Purchased templates** in your workspace (`/app/licences`), enter your **GitHub username** next to the purchase and click **Activate**. The store invites that account to the product's private repository as a read-only collaborator.
> Enter the username, not an email address. Open `https://github.com/` first and check that it is your profile.
Accept the invitation from your GitHub notifications or the email GitHub sends.
## My invitation expired. What now?
GitHub invitations expire after 7 days. Go back to **Purchased templates** and click **Send the invitation again** on that purchase. The username stays the same; only the invitation is sent again.
## Can I change the GitHub username after activating?
No. A purchase is activated for one GitHub account and cannot be moved to another. Check the username before you click **Activate**.
## Can I get a refund?
Only before activation. An order can be refunded while none of its purchases has been activated. Activation counts as delivery, because the repository can be cloned from that moment, so an order with an activated purchase is not refundable.
To ask for a refund, open a ticket under **Tickets** (`/app/tickets`) with the order number from **Billing** (`/app/billing`).
## Can I fork the repository?
No. The repositories are private and forking is not allowed. Clone the repository and push it to a private repository of your own:
```bash
git clone git@github.com:kernlift/kernlift.git my-app
cd my-app
git remote set-url origin git@github.com:YOUR-ACCOUNT/my-app.git
git push origin main
```
Create the empty private repository `/my-app` on GitHub before you push. Keep it private: the code is licensed to you, not to the public.
## How do I sync upstream updates?
Add the template repository as a second remote named `upstream`, then merge from it.
1. Add the remote once:
```bash
git remote add upstream git@github.com:kernlift/kernlift.git
```
For a business template, use that template's repository (`kernlift/`) instead.
2. Fetch and merge on a clean working tree:
```bash
git fetch upstream
git merge upstream/main
```
3. Resolve any conflicts, then install dependencies and apply the migrations:
```bash
pnpm install
pnpm db:migrate
```
4. Push to your own repository:
```bash
git push origin main
```
> When upstream has changed a lot since your last sync, do not merge everything at once. Read the changelog and use `git cherry-pick ` to take only the changes you need.
[Sync upstream updates](https://kernlift.dev/docs/guide/upgrading.md) covers the full procedure, including which directories are yours to edit so that merges stay small.
## How do I update the database after syncing?
Run the migrations. They are part of the repository, so there is nothing to generate:
```bash
pnpm db:migrate
```
On Cloudflare D1, apply them to the remote database with `pnpm db:migrate:d1:remote`.
If a new admin page then says "Permission denied", the update added permissions. Run `pnpm db:bootstrap-super-admin` again, with the same `SUPER_ADMIN_EMAIL` and `SUPER_ADMIN_PASSWORD` as in the [quick start](https://kernlift.dev/docs/quick-start.md), so the super admin role receives them.
## How many projects can I build?
As many as you like. The membership is not counted per project or per domain, and the application has no runtime licence check.
## Can a teammate get access?
A purchase is activated for one GitHub account. Push the code to your own private repository, as described in [Can I fork the repository?](#can-i-fork-the-repository), and give your team access there.
## How do I get started after activating?
1. Check the [prerequisites](https://kernlift.dev/docs/guide/prerequisites.md).
2. Follow the [quick start](https://kernlift.dev/docs/quick-start.md).
## How do I get support?
* Open a ticket under **Tickets** in your workspace (`/app/tickets`). Include the order number for anything about a purchase.
* Use the contact page at `/contact` if you cannot sign in.
For errors while installing or running the project, check [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md) first; it lists the common symptoms with their fixes.
## Next steps
- [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md)
Buy, activate and open the repository.
- [Architecture](https://kernlift.dev/docs/guide/architecture.md)
The layers of the application and how a request moves through them.
---
# Get Kernlift
> Buy Kernlift Premium, activate it with your GitHub username, open the private repository, and buy business templates as a member or at list price.
Source: https://kernlift.dev/docs/guide/get-kernlift
Kernlift is delivered as a private GitHub repository. You pay once, tell the store your GitHub username, and the store invites that account to the repository. This page walks through it for a new buyer, for a member buying a business template, and for someone buying a template without a membership.
## New buyers
### Buy Kernlift Premium
Sign in, open the pricing page at `/pricing` and buy **Kernlift Premium**. It is a one-time payment and includes the base, Image Studio and Video Studio repositories.
### Open Purchased templates
After the payment is confirmed, go to **Purchased templates** in your workspace (`/app/licences`). Kernlift Premium is listed there as **Not activated**.
### Activate with your GitHub username
Enter your **GitHub username** and click **Activate**. Enter the account name, not an email address; if you are unsure, open `https://github.com/` and check that it is your profile.
The store invites that account to the private repository as a read-only collaborator.
**Two things are final**
The username cannot be changed after activation. Activation also counts as delivery: an order with an activated purchase can no longer be refunded.
### Accept the invitation
Open [GitHub notifications](https://github.com/notifications) or the invitation email. Accept it. An invitation that is not accepted expires after 7 days; if that happens, click **Send the invitation again** on the same page.
### Open the repository
The purchased-templates page now shows the repository address and the clone command. **Open on GitHub** takes you to the repository.
```bash
git clone git@github.com:kernlift/kernlift.git my-app
```
### Start building
Follow the [quick start](https://kernlift.dev/docs/quick-start.md) to install it and sign in as administrator.
## Members buying a business template
Premium includes the base repository, Image Studio and Video Studio. Image Agent and Video Agent are sold separately with member pricing. Open Purchased templates to activate each included Studio. The following purchase steps apply to Agent templates.
1. Sign in with the account that holds Kernlift Premium. The member price can only be checked out by that account.
2. Buy the template at the member price.
3. Open **Purchased templates** (`/app/licences`). The template appears as its own entry, **Not activated**.
4. Activate it with your GitHub username, exactly as above. Each purchase is activated separately, and each one invites you to its own repository:
```bash
git clone git@github.com:kernlift/.git my-app
```
The purchased-templates page shows the exact address for each template.
5. Follow the [quick start](https://kernlift.dev/docs/quick-start.md). A business template is a complete project that includes everything in the base, so the steps are the same.
## Buying a template without a membership
You do not need Kernlift Premium to buy a business template.
* A non-member pays the template's list price. The member price can only be checked out by an account that holds the membership.
* The purchase is activated and delivered the same way: **Purchased templates**, GitHub username, **Activate**.
* A template bought this way gives you that template's repository. It does not include the base repository on its own or member prices on other templates.
If you plan to buy more than one template, compare the list prices with the membership plus member prices before you pay. Buying the membership later does not change the price of an order you already paid.
## If an order is missing
A paid order that does not show up under **Purchased templates** is almost always on another account.
1. Check that you are signed in with the email you paid with. An account created with Google sign-in and one created with a password under a different email are two accounts.
2. Open **Billing** in your workspace (`/app/billing`) and look for the order there. A payment that is still pending has not been confirmed by the payment provider yet; give it a few minutes and reload.
3. If the order is paid but nothing is listed under **Purchased templates**, open a ticket under **Tickets** (`/app/tickets`) with the email you paid with, the order number and your GitHub username.
Do not pay a second time. An account that already holds a product cannot buy it again, and the checkout tells you so before it charges anything.
## Next steps
- [Quick start](https://kernlift.dev/docs/quick-start.md)
Clone, install, migrate and sign in as administrator.
- [FAQ](https://kernlift.dev/docs/guide/faq.md)
Expired invitations, refunds, forking and syncing updates.
- [Prerequisites](https://kernlift.dev/docs/guide/prerequisites.md)
The tools and accounts to have ready before you clone.
---
# Prerequisites
> The tools, accounts and background knowledge to have ready before you clone Kernlift.
Source: https://kernlift.dev/docs/guide/prerequisites
Have these in place before you start the [quick start](https://kernlift.dev/docs/quick-start.md). Nothing here costs money; the paid services come later, when you connect providers.
## Tools on your machine
| Tool | Version | Used for |
| ------- | ------------------------------------------------- | ------------------------------------------------------- |
| Node.js | 22.12+ in the 22.x line | Running the dev server, the build and the scripts |
| pnpm | The version in `packageManager` in `package.json` | Installing dependencies and running every `pnpm` script |
| git | Any recent version | Cloning the repository and syncing updates |
Check them:
```bash
node --version
pnpm --version
git --version
```
If `pnpm` is missing, install it with `npm install -g pnpm@10.25.0`.
## A GitHub account
The code is delivered through GitHub, so you need an account, and it must be the one you activate your purchase with. See [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
The clone commands in these docs use SSH (`git@github.com:...`). Add your public key in [GitHub SSH keys](https://github.com/settings/keys) first, or clone over HTTPS with the address shown on the repository page.
## What you do not need yet
* **A database server.** Local development runs on a SQLite file that the migration creates.
* **A cloud account.** Cloudflare, Fly.io, Railway or a Docker host is only needed when you [deploy](https://kernlift.dev/docs/deploy.md).
* **Provider accounts.** Payments, email, storage and AI are connected in the admin console after the project runs. Until then each one reports that it is not configured.
## For the agent workbench
The agent is optional; the web app is complete without it. If you plan to run it, or you bought `image-agent` or `video-agent`, you also need Postgres and a sandbox service. See [Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md).
## What you should know
You will be reading and changing TypeScript and React. It helps to know:
* TypeScript and React well enough to follow a component and a server function.
* The basics of TanStack Start and TanStack Router: file routes, loaders and server functions.
* SQL basics. Schema and queries are written with Drizzle.
* Tailwind CSS for styling.
If you work with a coding agent, the repository ships skills that walk it through the common tasks. See [Use coding-agent skills](https://kernlift.dev/docs/core/agent-skills.md).
## Next steps
- [Quick start](https://kernlift.dev/docs/quick-start.md)
Clone, install and run the project locally.
- [Project structure](https://kernlift.dev/docs/core/project-structure.md)
Where things are in the checkout.
---
# Troubleshoot a project
> Match a symptom to its cause and fix: setup gaps, session secret, generated types, migrations, development sign-in, the agent, scheduled jobs and repository access.
Source: https://kernlift.dev/docs/guide/troubleshooting
Most problems in a new project come from missing configuration, which the app reports as not configured. Start with the three checks below, which locate most causes. Then find your symptom in the sections that follow.
## Before you begin
* A terminal in the project directory, and access to the environment the app runs in (`.env` locally, the platform's variables in production).
* An administrator account, for the checks that use `/setup`. See [Run the admin console](https://kernlift.dev/docs/core/admin.md).
* The exact error text or the page you ended on. Several fixes below depend on it.
## Find the cause
1. Open `/setup` as an administrator. It reads live configuration on every load and lists each item as **Ready** or **Not ready** with the reason. The first line states the platform, database and whether the build includes the agent service.
2. Read the server output in the terminal running `pnpm dev`, or in your platform's logs. Startup errors and the development sign-in warning are printed there.
3. Run the gate. It runs every validator expected to pass and compares the result with `scripts/validate/known-failures.json`:
```bash
pnpm validate:gate
```
## A feature says it is not configured
Providers are never mocked. Without credentials a feature reports that it is not configured.
| What you see | Cause | Fix |
| -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `/setup` shows **Email delivery** as Not ready; verification and reset mail never arrive | No active email provider | **Settings → Email Config** (`/admin/config/email`). See [Send transactional email](https://kernlift.dev/docs/extensions/email.md) |
| A plan button on `/pricing` ends on `/system/payment-failed` with `reason=checkout_not_configured` | No payment provider is configured | `/admin/config/payment`. See [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md) |
| `/pricing` says plans have not been published | No plan with status `active` for that locale | `/admin/plans`. See [Pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md) |
| Uploads fail; `/setup` shows **Object storage** as Not ready | No storage driver | `/admin/config/storage`. See [Store files](https://kernlift.dev/docs/extensions/storage.md) |
| AI tasks cannot start; `/setup` shows **AI channels** as Not ready | No active channel, or channels exist but no scene routes to them | `/admin/config/ai`. See [AI providers](https://kernlift.dev/docs/extensions/ai/providers.md) and [Scenes](https://kernlift.dev/docs/extensions/ai/scenes.md) |
Saving a settings page confirms that the values were stored. It does not confirm that the provider accepts them. Use the page's own test action, then go back to `/setup`.
## `/setup` will not open or shows gaps
* **It redirects to `/system/session-expired`:** you are not signed in. Sign in at `/auth/sign-in`.
* **It opens but the checklist does not load:** reading the checklist needs `config.read`. Sign in with the account created by `pnpm db:bootstrap-super-admin`, or grant the permission. See [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md).
* **Required items are Not ready:** the four required items are **Session secret**, **Sign-in method**, **Email delivery** and **Scheduled jobs**. Every item except the session secret and the scheduled jobs has a **Configure** button that opens the page that fixes it.
* **An item shows an error message instead of a reason:** that subsystem could not be read, usually because its table is missing. See [Migrations were not applied](#migrations-were-not-applied).
## The session secret is missing or rejected
`BETTER_AUTH_SECRET` signs sessions. What happens without it depends on `APP_ENV`:
| `APP_ENV` | Behaviour |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `development` (or unset) | The app starts on the secret built into the template. `/setup` shows **Session secret** as Not ready: "BETTER\_AUTH\_SECRET is unset or still the template default." |
| Anything else | The app refuses to start: `Refusing to start with the built-in session secret while APP_ENV is "production".` |
Generate a value and set it in `.env` or your platform's secret store, then restart:
```bash
node -e "console.log(crypto.randomUUID()+crypto.randomUUID())"
```
Use a different secret for production: `kernlift deploy-target` generates one into `.env.production`.
## `pnpm typecheck` fails on Worker types
Errors about `CloudflareEnv` or other Workers types mean `worker-configuration.d.ts` does not exist. The file is generated and is not committed:
```bash
pnpm cf-typegen
```
Run it after cloning and after changing bindings in `wrangler.jsonc`. A project deployed to Fly.io, Railway or Docker has no `wrangler.jsonc`. The same command then generates the types from a reference configuration, because the source still references them.
If the errors mention a route you just added, `src/routeTree.gen.ts` is stale. Start `pnpm dev` once, or run `pnpm build`, to regenerate it.
## Migrations were not applied
Pages that load data fail with database errors that name a missing table or column, right after cloning, upgrading or installing a module.
| Database | Command |
| -------------------------------------- | --------------------------- |
| SQLite or Postgres from `DATABASE_URL` | `pnpm db:migrate` |
| Cloudflare D1, local | `pnpm db:migrate:d1:local` |
| Cloudflare D1, deployed | `pnpm db:migrate:d1:remote` |
`pnpm db:migrate` reads `DATABASE_DIALECT` and `DATABASE_URL` from the environment, so check that they point at the database the app uses. When it fails it prints the dialect, the database, and the counts of migration files and applied records. If it adds "The schema exists but no migration has been recorded", the database was not created by migrations. Start from an empty database. Do not migrate over the existing one.
After merging an upstream update, run `pnpm install && pnpm db:migrate`, then `pnpm db:bootstrap-super-admin` so the Super Admin role receives any permissions the update added.
## Development sign-in bypass does not work
Unauthenticated requests are treated as a chosen user only when both of these are true:
1. `APP_ENV=development`.
2. `AUTH_DEV_IMPERSONATE_USER_ID` is set to a non-empty user id.
When it is active the server logs once: `[auth] AUTH_DEV_IMPERSONATE_USER_ID is set. Unauthenticated requests are being treated as "".` If you do not see that line, one of the two conditions is false or the server was not restarted after editing `.env`. The value must be the id of a user that exists, and that user needs `admin.access` to open `/admin`.
Outside development the variable is ignored. There is no other identity fallback. An unauthenticated caller is rejected and is never mapped to a default user. See [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md).
## The agent says it is not deployed
The agent is optional. Without it, `/app/ai` and `/app/chat` still work, agent entries are hidden from the sidebar, the agent pages say "The agent service is not deployed", and `/api/agent/*` returns 503 with `agent_unavailable`. The page states which of four reasons applies:
| Reason | Fix |
| ------------------------------------------ | ------------------------------------------------------------------------------------------ |
| The agent plugin is switched off | Enable it at `/admin/plugins` |
| The database has no transactions | Agent runs cannot use D1. Deploy on Postgres or SQLite |
| No agent service is configured | Set `AGENT_SERVICE_URL` (or the Cloudflare container binding) and deploy the agent service |
| `AGENT_INTERNAL_SIGNING_SECRET` is not set | Set the same value for the web app and the agent service |
Locally, `pnpm dev` starts the web app alone. `pnpm dev:agent` starts it with the agent service. See [Agent starter](https://kernlift.dev/docs/extensions/agent/starter.md).
## `/setup` warns about scheduled jobs
Background work (credit expiry, billing fulfilment retries, AI task polling) runs once a minute and records each round. **Scheduled jobs** becomes Not ready when no round has been recorded, when the last one is more than five minutes old, or when the last round had a failing job. The message names the failed job.
| Platform | How rounds start | Check |
| ---------- | ------------------------- | --------------------------------------------------------------------------------------------------------- |
| Cloudflare | The Worker's Cron Trigger | `wrangler.jsonc` keeps `"triggers": { "crons": ["* * * * *"] }` and the deployed Worker lists the trigger |
| Fly.io | Inside the web process | `min_machines_running = 1` in `fly.toml`; a stopped machine runs no jobs |
| Railway | Inside the web service | The service is running |
| Docker | Inside the web container | `docker compose ps` shows it up |
On the Node platforms, `JOBS_IN_PROCESS=false` turns the in-process loop off. An external cron must then call `pnpm jobs:run`. Run that command by hand to see one round's report as JSON. A new deployment records its first round within a minute, so wait a minute before investigating the warning. See [Background jobs](https://kernlift.dev/docs/core/background-jobs/run.md).
## git cannot reach the repository
| Message | Cause | Fix |
| --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `Repository not found` on `git clone` or `git fetch upstream` | GitHub answers this for a private repository the account cannot read: the invitation was not accepted, or git is signed in as another account | Accept the invitation in your GitHub notifications, and check which account your SSH key or credential belongs to |
| `Permission denied (publickey)` | No SSH key on this machine is registered with your GitHub account | Add the key to GitHub, or clone over HTTPS with the address on the repository page |
| The invitation link says it has expired | GitHub invitations expire after 7 days | Open **Purchased templates** (`/app/licences`) and click **Send the invitation again** |
| `fatal: refusing to merge unrelated histories` on `git merge upstream/main` | `upstream` points at a different template than the one the project was cloned from | Point `upstream` at the repository you cloned: `git remote set-url upstream ` |
Purchases, activation and refunds are covered in the [FAQ](https://kernlift.dev/docs/guide/faq.md).
## Verify
After a fix, confirm it by running the checks and repeating the failed action. A saved settings page is not enough:
```bash
pnpm typecheck
pnpm validate:gate
```
* `/setup` shows **Nothing required is missing**.
* The action that failed now completes against the real provider: a verification email arrives, a sandbox checkout reaches the provider's page, an upload can be downloaded again.
* Before deploying, `pnpm smoke:node` (after `pnpm build:node`) or `pnpm smoke:worker` (after `pnpm build`) runs the built server on a throwaway database and checks pages, the agent 503 response and one scheduled round.
## Next steps
- [Configure a working project](https://kernlift.dev/docs/core/configuration/project.md)
The order to connect providers in.
- [Environment variables](https://kernlift.dev/docs/reference/env.md)
Every variable the source reads.
- [Validators and the release gate](https://kernlift.dev/docs/core/validators.md)
What the gate checks.
- [Background jobs](https://kernlift.dev/docs/core/background-jobs/run.md)
What each scheduled round does.
---
# Sync upstream updates
> Merge new versions of the template into your project from the upstream remote, and accept them with the project's own checks.
Source: https://kernlift.dev/docs/guide/upgrading
Your project is a clone of a template repository that keeps moving. You take its updates by merging from an `upstream` remote. Merges stay small when you keep your changes in the directories that are yours to edit.
## Before you begin
* A clean working tree, committed or stashed.
* Read access to the template repository on GitHub. See [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
* Your project pushed to a private repository of your own, as `origin`. See [Can I fork the repository?](https://kernlift.dev/docs/guide/faq.md)
* `CHANGELOG.md` from the version you are moving to. Breaking changes are marked `Breaking` and carry migration instructions.
## Keep your changes in your zone
| Zone | Paths |
| ----------------- | --------------------------------------------------------------------------------------------------------------------------- |
| Yours to edit | `src/config/site.ts`, `src/components/marketing/example-landing.tsx`, `src/i18n/locales`, `public` |
| Template skeleton | `src/server`, `src/components/ui`, `scripts`, `drizzle/migrations`, `src/router.tsx`, `src/start.ts`, `src/server-entry.ts` |
The skeleton never imports from your zone, except `src/config/site.ts`. `pnpm validate:template-boundary` enforces that.
## Merge an update
### Add the upstream remote once
```bash
git remote add upstream git@github.com:kernlift/kernlift.git
git fetch upstream
```
For a business template, use that template's repository (`kernlift/`) instead.
### Merge the update on a branch
```bash
git fetch upstream
git checkout -b upgrade/upstream-update main
git merge upstream/main
```
Merge rather than rebase, so your project's commit history is not rewritten. When upstream has changed a lot since your last sync, take only what you need with `git cherry-pick ` instead of merging everything at once.
### Resolve conflicts
* **In your zone**: keep yours, then check whether upstream added a key you also need. This usually happens in the message catalogues.
* **In the skeleton**: take upstream, then reapply your change. If you do this repeatedly in the same file, move your change into a module the skeleton calls.
* **In `drizzle/migrations`**: never edit an existing migration. Take upstream's chain as-is and add your own migration on top.
* **In `package.json`**: take both sides' dependencies, then `pnpm install`.
* **In your deployment files** (`deploy.config.json` and `wrangler.jsonc`, `fly.toml`, `.railway/railway.ts` or `compose.yaml`): keep yours. They record your platform and resource ids. If upstream changed the file for your platform, re-add its change by hand, then run `pnpm cf-typegen`.
### Accept the update
```bash
pnpm install
pnpm cf-typegen
pnpm db:migrate
pnpm typecheck
pnpm build
pnpm validate:all
```
### Push to your repository
```bash
git checkout main
git merge upgrade/upstream-update
git push origin main
```
## Verify
* Open `/setup` and confirm nothing required became **Not ready**.
* `pnpm validate:all` shows no new failures. Compare against `scripts/validate/known-failures.json` on the upstream commit you merged.
* To see which release you are on, run `git describe --tags $(git merge-base HEAD upstream/main)`. Version tags match changelog entries one-to-one.
## Troubleshooting
### A new admin page says "Permission denied"
The update added permissions. Run `pnpm db:bootstrap-super-admin` again, with the same `SUPER_ADMIN_EMAIL` and `SUPER_ADMIN_PASSWORD` as in the [quick start](https://kernlift.dev/docs/quick-start.md), so the Super Admin role receives them.
### `pnpm db:migrate` fails after a merge
An existing migration was edited, or the two chains diverged. Restore upstream's migration files unchanged, add yours on top, and run `pnpm validate:migrations`.
### The same skeleton file conflicts on every merge
You keep a change in a file upstream also edits. Move the change into your own zone, or into a plugin the skeleton calls, so the next merge does not touch it. See [Plugins](https://kernlift.dev/docs/core/plugins.md).
### `git fetch upstream` says "Repository not found"
The GitHub account your git client uses is not the one you activated the purchase with, or the invitation was never accepted. Check **Purchased templates** (`/app/licences`); see [My invitation expired](https://kernlift.dev/docs/guide/faq.md).
## Reference
* [FAQ](https://kernlift.dev/docs/guide/faq.md)
* [Validators](https://kernlift.dev/docs/reference/validators.md)
* [Git merge strategies](https://git-scm.com/docs/merge-strategies)
## Next steps
- [FAQ](https://kernlift.dev/docs/guide/faq.md)
- [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md)
- [Validators and the release gate](https://kernlift.dev/docs/core/validators.md)
- [Project structure](https://kernlift.dev/docs/core/project-structure.md)
---
# Introduction
> What Kernlift is, what the base repository contains, what the business templates add, and where to start.
Source: https://kernlift.dev/docs
## What is Kernlift?
Kernlift is a SaaS starter built on TanStack Start. You buy it once, get access to a private GitHub repository, clone it, and build your product in a repository of your own. There is no runtime licence check and nothing to install from a package feed: the code you clone is the whole application.
One codebase runs on Cloudflare Workers or Node, and on SQLite, Cloudflare D1 or Postgres. Provider credentials and business settings are saved in the admin console, not in environment variables. An integration without credentials reports that it is not configured; nothing is mocked.
## What the base repository contains
The base repository comes with the Kernlift Premium membership. It is a complete web app, organised the same way as these docs.
**Core**
* [Configuration](https://kernlift.dev/docs/core/configuration.md) in the admin console, with environment variables only for startup and infrastructure.
* [Sign-in, roles and permissions](https://kernlift.dev/docs/core/auth.md), [users](https://kernlift.dev/docs/core/auth/users.md) and [API keys](https://kernlift.dev/docs/core/auth/api-keys.md).
* An [admin console](https://kernlift.dev/docs/core/admin.md) with an audit log, rate limits and a setup checklist.
* A [repository layer](https://kernlift.dev/docs/core/data-access.md) that keeps business code independent of the SQL dialect.
* A [plugin kernel](https://kernlift.dev/docs/core/plugins.md) for adding pages and server behaviour without editing the shells.
* [Background jobs](https://kernlift.dev/docs/core/background-jobs.md), [validators](https://kernlift.dev/docs/core/validators.md) and [skills for coding agents](https://kernlift.dev/docs/core/agent-skills.md).
**Extensions**
* [Database](https://kernlift.dev/docs/extensions/database/postgres.md): SQLite, Turso, Cloudflare D1, Postgres (Supabase, Neon).
* [Sign-in providers](https://kernlift.dev/docs/extensions/auth/email-password.md): email and password, Google, GitHub.
* [Payments](https://kernlift.dev/docs/extensions/payments.md): Stripe, Creem, PayPal, Dodo Payments, WeChat Pay, Alipay, Waffo.
* [Storage](https://kernlift.dev/docs/extensions/storage.md): Cloudflare R2 or any S3-compatible bucket.
* [Email](https://kernlift.dev/docs/extensions/email.md): Resend, Cloudflare Email, Aliyun DirectMail.
* [Analytics](https://kernlift.dev/docs/extensions/analytics.md): Google Analytics, Umami, Plausible, Microsoft Clarity, and the Crisp chat widget.
* [AI](https://kernlift.dev/docs/extensions/ai.md): OpenAI-compatible APIs, Google Gemini, Cloudflare Workers AI and custom HTTP APIs for image, video and audio, priced in [credits](https://kernlift.dev/docs/extensions/credits.md).
* [CMS](https://kernlift.dev/docs/extensions/cms.md), [newsletter and waitlist](https://kernlift.dev/docs/extensions/newsletter.md), [affiliate program](https://kernlift.dev/docs/extensions/affiliate.md), [support tickets](https://kernlift.dev/docs/extensions/support.md) and [notifications](https://kernlift.dev/docs/extensions/notifications.md).
* An optional [agent workbench](https://kernlift.dev/docs/extensions/agent.md) that runs as a second service.
The full inventory, with the routes each part adds, is in [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md).
## Business templates
A business template is a finished product built on the base: the same application with one product already in place. Each one is its own private repository and is sold separately.
| Template | What it is |
| -------------- | -------------------------------------------------------------------------------------------------- |
| `image-studio` | An image generation site: a prompt, a frame and a gallery, billed in credits. Runs as one web app. |
| `video-studio` | A video generation site: a prompt, a frame, a length and a gallery of clips. Runs as one web app. |
| `image-agent` | A chat-based image product on the agent workbench. Needs the agent service. |
| `video-agent` | A chat-based video product on the agent workbench. Needs the agent service. |
Premium includes both Studios and unlocks member pricing on the two Agent templates. Anyone can buy an individual template at list price.
## Where to start
- [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md)
Buy the membership, activate it with your GitHub username and open the repository.
- [Quick start](https://kernlift.dev/docs/quick-start.md)
Clone the repository and have it running locally, signed in as administrator.
- [FAQ](https://kernlift.dev/docs/guide/faq.md)
Activation, refunds, forking, syncing updates and support.
- [Architecture](https://kernlift.dev/docs/guide/architecture.md)
How the layers fit together before you change them.
---
# Quick start
> Clone the repository, install it, build the database, create the administrator and run the project locally.
Source: https://kernlift.dev/docs/quick-start
This page takes you from an activated purchase to a local project you are signed in to as administrator. It uses a local SQLite file, so you need no database server and no cloud account. A business template is installed the same way; only the repository address differs.
## Before you begin
* The tools in [Prerequisites](https://kernlift.dev/docs/guide/prerequisites.md): Node 22.12 or later in the 22.x line, pnpm and git.
* An activated purchase and an accepted GitHub invitation. See [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
* About ten minutes. Most of it is `pnpm install`.
## Run it locally
### Clone the repository
```bash
git clone git@github.com:kernlift/kernlift.git my-app
cd my-app
```
For a business template, clone `kernlift/` instead. The exact address is on the **Purchased templates** page (`/app/licences`).
If git answers "Repository not found", the invitation has not been accepted yet, or git is using another GitHub account.
### Install dependencies and generate types
```bash
pnpm install
pnpm cf-typegen
```
`pnpm cf-typegen` writes `worker-configuration.d.ts`, the runtime type declarations. The file is
generated and is not committed, so `pnpm typecheck` fails on a fresh clone until it exists. It works with
or without a `wrangler.jsonc`; on a Cloudflare project, run it again whenever you change a binding.
### Create your `.env`
```bash
cp .env.example .env
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```
Paste the printed value into `BETTER_AUTH_SECRET` in `.env`. For local work this is the only value
you need to set: the file already points `DATABASE_DIALECT` at `sqlite` and `DATABASE_URL` at
`./local.db`.
`.env.example` marks each variable: `[必填]` must be set, `[可选]` has a working default, `[开发]`
applies only to development.
### Build the database
```bash
pnpm db:migrate
```
This applies the migration chain and records each step. When it finishes, `local.db` exists in the
project root. It is the only supported way to build the schema.
### Create the first administrator
```bash
SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='' pnpm db:bootstrap-super-admin
```
You should see `Created the super administrator you@example.com (sqlite).`, then a `Baseline content:` line counting what it
inserted. Running it again is safe: it never overwrites a row an administrator edited.
Besides the administrator, this writes the permission set, the super admin role and the baseline
content (email templates, marketing pages, `/system` state pages, notification channels and
rate-limit rules). There is no demo data.
### Start the app
```bash
pnpm dev
```
Vite prints the local address, `http://localhost:5173` by default. Leave it running.
### Sign in
Open `/auth/sign-in` and sign in with the administrator email and password from the previous step. You are
signed in as the super administrator, so the admin console at `/admin` opens for you.
## What the install produced
- Application/
- src/routes
- src/server
- src/components
- Data/
- drizzle/migrations/sqlite
- drizzle/migrations/postgres
- Modules and checks/
- modules
- scripts/validate
The route generator refreshes `src/routeTree.gen.ts` when you run `pnpm dev` or `pnpm build`.
`pnpm typecheck` fails until one of them has run once.
## Push it to your own repository
The repository you cloned is read-only and cannot be forked. Create an empty private repository on GitHub and make it `origin`:
```bash
git remote set-url origin git@github.com:YOUR-ACCOUNT/my-app.git
git push origin main
```
To take later updates, add the template repository back as `upstream`. See [Sync upstream updates](https://kernlift.dev/docs/guide/upgrading.md).
## Set the deployment target
A clone carries `deploy.config.json` and the deployment files of one platform. You do not need to touch them for local work. To deploy somewhere
else, or to add the agent service, run:
```bash
pnpm kernlift deploy-target fly --no-agent --dialect sqlite
```
Replace `fly` with `cloudflare`, `railway` or `docker`. The command writes that platform's files,
moves the previous ones to `.kernlift/previous-deploy/`, generates the production secrets into
`.env.production` and prints the remaining steps. It creates nothing remote. The platforms and the
databases each allows are listed in the [Deployment configuration](https://kernlift.dev/docs/reference/deploy-config.md).
## Verify
Open `/setup`. **Session secret** and **Sign-in method** show **Ready**; **Email delivery** shows
**Not ready** until you connect a provider. That is the expected state of a fresh project.
## Troubleshooting
### `git clone` says "Repository not found"
GitHub answers this for a private repository you cannot read. Accept the invitation from your GitHub
notifications, and check that the SSH key or credential git uses belongs to the account you activated
the purchase with. If the invitation expired, see [My invitation expired](https://kernlift.dev/docs/guide/faq.md).
### `pnpm typecheck` reports missing routes
The route generator refreshes `src/routeTree.gen.ts` when you run `pnpm dev` or `pnpm build`.
then type-check again.
### `pnpm typecheck` fails on the Cloudflare bindings
`worker-configuration.d.ts` is missing or out of date, for example after you changed `wrangler.jsonc`.
Run `pnpm cf-typegen`.
### The database exists but was not built by `pnpm db:migrate`
The migration runner reads its own history to work out which migrations to apply, so a database created another way
cannot be migrated in place. Delete `local.db` and run `pnpm db:migrate` again. The reasoning is in
[Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md).
## Next steps
- [First steps](https://kernlift.dev/docs/customize/first-steps.md)
Work through the setup checklist, connect email and make the project yours.
- [Project structure](https://kernlift.dev/docs/core/project-structure.md)
Find your way around the checkout.
- [Deploy your project](https://kernlift.dev/docs/deploy.md)
Take the project to production on the platform you chose.
- [Environment variables](https://kernlift.dev/docs/reference/env.md)
Every variable in `.env.example`.
---
# What the base repository contains
> The foundation, the modules that ship with it and the agent stack: what each part adds and what it needs.
Source: https://kernlift.dev/docs/reference/capabilities
This page lists what is in the base repository you clone. Nothing here is installed separately: the foundation and every module below are already in the checkout. A provider-backed feature stays unavailable until its credentials are configured.
## Foundation
| Area | Available interface | Configuration or guide |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
| Accounts and access | Sign-in, sign-up, verification, recovery, profile, sessions, roles, permissions and API keys | [Authentication](https://kernlift.dev/docs/core/auth.md), [roles](https://kernlift.dev/docs/core/auth/roles.md), [API keys](https://kernlift.dev/docs/core/auth/api-keys.md) |
| Billing | Products, pricing plans (`/admin/plans`), checkout, orders, subscriptions, customer billing pages and fulfilment plugins | [Payments](https://kernlift.dev/docs/extensions/payments.md), [products](https://kernlift.dev/docs/extensions/payments/products.md) |
| Credits | Balance, reservations and ledger; settlement is performed by server-side workflows | [Credits](https://kernlift.dev/docs/extensions/credits.md) |
| AI and chat | Provider channels, scenes, text and media tasks, chat, pricing and usage | [AI channels](https://kernlift.dev/docs/extensions/ai.md), [scenes](https://kernlift.dev/docs/extensions/ai/scenes.md), [chat](https://kernlift.dev/docs/extensions/ai/chats.md) |
| Files and messaging | Private assets, uploads, email templates and deliveries, notifications | [Storage](https://kernlift.dev/docs/extensions/storage.md), [email](https://kernlift.dev/docs/extensions/email.md), [notifications](https://kernlift.dev/docs/extensions/notifications.md) |
| Operations | Admin dashboard, users, support, analytics, audit, rate limits, countries and readiness checks | [Admin console](https://kernlift.dev/docs/core/admin.md), [setup](https://kernlift.dev/docs/customize/first-steps.md) |
| Extension | The plugin kernel, the list of installed plugins and `/admin/plugins` to switch them on and off | [Plugins](https://kernlift.dev/docs/core/plugins.md) |
| Tooling | The `kernlift deploy-target` and `kernlift context` commands and the coding-agent skills | [CLI](https://kernlift.dev/docs/reference/deploy-config.md), [skills](https://kernlift.dev/docs/core/agent-skills.md) |
| Deployment | Configuration for Cloudflare, Fly.io, Railway and Docker, written by `kernlift deploy-target` | [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md) |
The example landing page, `/pricing`, about and contact pages are part of the foundation. The blog, editable legal content, changelog and RSS come from the CMS module below. Provider keys and business settings belong in `/admin/config/*` or the corresponding admin page. Environment variables are for startup and infrastructure. See [configuration](https://kernlift.dev/docs/core/configuration.md).
## Modules in the repository
Each module is a self-contained feature with its own pages, server code, tables, copy in both languages and a validator. Its boundary is recorded in `modules//module.json`. The **Requires** column lists what else it depends on.
| Key | Kind | Requires | What it adds | Start here |
| --------------- | -------- | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------- |
| `cms` | Module | — | Content editor, taxonomy, revisions, legal and changelog pages, blog and RSS | [CMS](https://kernlift.dev/docs/extensions/cms.md) |
| `newsletter` | Module | — | Newsletter, waitlist, invite and settings pages | [Newsletter and waitlist](https://kernlift.dev/docs/extensions/newsletter.md) |
| `affiliate` | Module | — | Referral, commission, withdrawal and review operations | [Affiliate](https://kernlift.dev/docs/extensions/affiliate.md) |
| `image-agent` | Module | `agent-starter` | `/app/image`, the Image Studio Skill (`platform.image`), a frame picker, the image viewer and the per-run picture limit, with settings at `/admin/config/image-agent` | [Image agent](https://kernlift.dev/docs/extensions/agent/image-agent.md) |
| `agent-starter` | Template | — | `/app/agent`, Agent API and service, skills, connectors, run workspace, sandbox and search configuration | [Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) |
The Agent template runs a second service beside the web app and needs Postgres. `kernlift deploy-target --agent` accepts no other database. D1 can run the foundation, but cannot store Agent runs. Without the agent service the web app is complete, and the agent entries show that the service is not deployed.
`image-agent` is a module, but it is a plugin of the agent workbench, so it does nothing without `agent-starter`.
The business templates (`image-studio`, `video-studio`, `image-agent`, `video-agent`) are separate repositories, each a complete project built on this base. See [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
## How to verify a project
1. Read the `modules/*/module.json` manifests. Each one defines a boundary through `kind`, `requires`, `files`, `fragments`, `migrations`, `tables`, `configKeys` and `skillPackages`.
2. Open `/setup` for live readiness information. A missing provider is reported as not configured. A page can exist while its external integration is not configured.
3. Run `pnpm validate:gate`. Each capability contributes its validator.
## Next steps
* [Templates and derived products](https://kernlift.dev/docs/core/plugins/templates.md) for how a product is built on the base.
* [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md) for the manifest fields and adding a module of your own.
---
# Deployment configuration
> deploy.config.json and the kernlift deploy-target command that rewrites it: the combinations it allows, the files each platform owns, the keys of .env.production, and how each platform migrates and bootstraps.
Source: https://kernlift.dev/docs/reference/deploy-config
`deploy.config.json` is the committed record of where a project deploys. The repository you clone carries it, `kernlift deploy-target` rewrites it, `vite.config.ts` reads it to pick the build target, and the app bundles it so `/setup` can report it. It holds no secrets. For the reasoning, see [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md).
## Fields
```json title="deploy.config.json"
{
"platform": "cloudflare",
"agent": false,
"database": "d1"
}
```
| Field | Values | Meaning |
| ---------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `platform` | `cloudflare`, `fly`, `railway`, `docker` | The one platform this project deploys to. Decides the build target and which platform files exist |
| `agent` | `true`, `false` | Whether the agent service is deployed beside the web app |
| `database` | `d1`, `postgres`, `sqlite` | The production database. Local development uses a SQLite file whatever this says |
A project without the file builds for Cloudflare. Do not edit the file by hand. The platform files are rendered together with it, so change it with `kernlift deploy-target`. Its flags are [below](#switch-platforms-with-kernlift-deploy-target).
## Switch platforms with kernlift deploy-target
`kernlift deploy-target [flags]` runs in a project directory, one that has `deploy.config.json`. It rewrites the file and the platform files, points the `deploy` script at the platform's deploy command, moves the other platforms' files to `.kernlift/previous-deploy/`, adds missing keys to `.env.production` and prints the next steps. It creates no remote resource and moves no data. It is the only `kernlift` command a cloned project needs; everything else is a [script](https://kernlift.dev/docs/reference/scripts.md).
The CLI has no dependencies and runs on Node 20 or later. Its source is in `tools/kernlift/` of your clone. Run it with `pnpm kernlift deploy-target `. The `kernlift` script in the root `package.json` runs `tools/kernlift/src/kernlift.js`, so nothing is fetched from npm.
| Flag | Meaning |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `--agent` / `--no-agent` | Include or drop the agent service (default: the project's current choice) |
| `--dialect ` | Production database (default: the current one if the new platform allows it, otherwise the platform's first choice) |
| `--region ` | Fly.io primary region (default `iad`) |
| `--cwd ` | Project directory (default: the current directory) |
| `--help` | Print usage |
Flags that take a value accept `--flag value` or `--flag=value`. `--agent` and `--no-agent` take no value.
Exit codes:
| Code | When |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0` | The command completed |
| `1` | Any error (the message is printed on stderr): an unknown platform, a combination the platform does not allow, or a directory without `deploy.config.json` |
## Allowed combinations
| `platform` | `agent: false` | `agent: true` |
| ------------ | -------------------- | ------------- |
| `cloudflare` | `d1`, `postgres` | `postgres` |
| `fly` | `postgres`, `sqlite` | `postgres` |
| `railway` | `postgres` | `postgres` |
| `docker` | `postgres`, `sqlite` | `postgres` |
That is eleven combinations. The CLI rejects any other combination before it writes a file. The agent needs Postgres because its runs need transactions and a database shared by two processes. `sqlite` is a single-machine option, and `d1` exists only on Cloudflare. When `kernlift deploy-target` is run without `--dialect`, it keeps the current database if the new platform allows it and otherwise takes the first value in the row.
## What each platform owns
| `platform` | Files in the project root | Build target | `deploy` script |
| ------------ | ----------------------------------------------- | ------------ | --------------------------------------------------------- |
| `cloudflare` | `wrangler.jsonc` | `cloudflare` | `wrangler deploy` |
| `fly` | `fly.toml`, and `fly.agent.toml` with the agent | `node` | `fly deploy` |
| `railway` | `.railway/railway.ts` | `node` | `railway up` |
| `docker` | `compose.yaml` | `node` | `docker compose --env-file .env.production up -d --build` |
The `node` build target is packaged by the root `Dockerfile`. The agent service uses `apps/agent-service/Dockerfile` on every platform. Both Dockerfiles stay in the repository whatever the platform.
The platform files are rendered from templates that ship with the CLI. When `kernlift deploy-target` renders the platform the project already uses, a file whose content differs from the new render (resource ids filled into `wrangler.jsonc`, hand edits) is moved to `.kernlift/previous-deploy/` before the new one is written. A file that is identical is left alone.
## Per-platform behaviour
| | `cloudflare` | `fly` | `railway` | `docker` |
| ------------------------ | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------- | ---------------------------------------------- |
| Migrations | `pnpm db:migrate:d1:remote` for `d1`; `pnpm db:migrate` against the Postgres URL for `postgres` | `release_command` for `postgres`; at process start for `sqlite` | `preDeploy` of the `web` service | The `migrate` service |
| Migrator | Wrangler D1 migrations, or `scripts/db/migrate.ts` | `scripts/db/migrate-runtime.mjs` | `scripts/db/migrate-runtime.mjs` | `scripts/db/migrate-runtime.mjs` |
| Production administrator | `pnpm db:bootstrap-super-admin --remote` with `DATABASE_DIALECT=d1`; with `DATABASE_URL` for Postgres | `fly ssh console --pty -C "node .output/scripts/bootstrap-super-admin.mjs"` | `railway ssh --service web`, then the same script | `docker compose exec web` with the same script |
| Scheduled jobs | Cron Trigger, once a minute | Loop in the web process; `min_machines_running = 1` | Loop in the web process | Loop in the web process |
| Secret store | `wrangler secret put` | `fly secrets import` | `railway variables` | `--env-file .env.production` |
| Agent service | Container bound as `AGENT_SERVICE` | App `-agent`, `fly.agent.toml` | Service `agent`, one replica | Service `agent` |
| Web reaches the agent at | The container binding | `http://-agent.internal:3001` | `http://agent.railway.internal:3001` | `http://agent:3001` |
| Agent reaches the web at | `AGENT_WEB_INTERNAL_URL`, the Worker's public URL | `http://.internal:3000` | `http://web.railway.internal:3000` | `http://web:3000` |
| Postgres comes from | Your database, through the `HYPERDRIVE` binding | Your database, as the `DATABASE_URL` secret | The `postgres` resource in `.railway/railway.ts` | The `postgres` compose service |
| SQLite file | Not available | `/data/app.db` on the `data` volume | Not available | `/data/app.db` on the `data` volume |
## .env.production
Generated in the project root and completed by `kernlift deploy-target`. The file is written with mode 0600 and is ignored by git and by the Docker build context. An existing file is kept. A later run adds missing keys and never changes or removes a value.
| Key | Generated when | Value |
| ------------------------------- | ------------------------ | ----------------------------------------------------------------------------------- |
| `BETTER_AUTH_SECRET` | Always | 32 random bytes, hex |
| `CONFIG_ENCRYPTION_KEY` | Always | 32 random bytes, hex; encrypts provider secrets in the admin config. Keep it stable |
| `SITE_URL` | Always | The site URL given at creation; set it to the deployed origin |
| `POSTGRES_PASSWORD` | `docker` with `postgres` | 32 random bytes, hex; the bundled Postgres password |
| `AGENT_INTERNAL_SIGNING_SECRET` | `agent` is `true` | 32 random bytes, hex; shared by the web app and the agent service |
| `AGENT_RESOURCE_GRANT_SECRET` | `agent` is `true` | 32 random bytes, hex |
You add `DATABASE_URL` yourself for Postgres on `fly`, and the Fly secret import then includes it. On `cloudflare` the agent container's direct Postgres URL is stored as the `AGENT_DATABASE_URL` secret. Values reach the platform over standard input and are never printed. The file is separate from `.env`, which holds the development values for your machine.
## .kernlift/previous-deploy/
When `kernlift deploy-target` switches platforms, the files of the other platforms that are in the project root move here, keeping their relative path, for example `.kernlift/previous-deploy/wrangler.jsonc`. Nothing is deleted. A copy already there is never overwritten. A later one takes the next free name, `wrangler.jsonc.1`, then `.2`.
Use the directory to recover earlier content, such as the resource ids in an earlier `wrangler.jsonc`. Switching back to a platform renders its files from the template again and does not restore the copy.
## Checks
| Command | What it checks |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `pnpm validate:deploy-targets` | Every allowed combination renders the right files, refused ones are refused, the root files match the renderer, and the Node build starts |
| `pnpm smoke:node` | The Node build, after `pnpm build:node`, on a throwaway SQLite database |
| `pnpm smoke:worker` | The Worker build, after `pnpm build`, on a throwaway D1 database |
## Next steps
- [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md)
- [Deploy your project](https://kernlift.dev/docs/deploy.md)
- [Scripts](https://kernlift.dev/docs/reference/scripts.md)
- [Environment variables](https://kernlift.dev/docs/reference/env.md)
---
# Environment variables
> The six variables a deployment needs, the few optional ones, and the variables only the agent service and the scripts read.
Source: https://kernlift.dev/docs/reference/env
A running site needs six environment variables. Everything else, including provider credentials, sign-in methods, the sender address and payment settings, is set in `/admin/config/*` and stored in the database. `.env.example` lists every variable the source reads, and `pnpm validate:env-example` fails when the two disagree.
## Required
| Variable | Default | Purpose |
| -------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------- |
| `APP_ENV` | `development` | `development` or `production`. Anything other than `development` enables the production guards |
| `BETTER_AUTH_SECRET` | Template secret (development only) | Session signing key. Outside development, an empty value or the template default stops the app |
| `SITE_URL` | `https://kernlift.example.com` | Canonical origin for metadata, the sitemap, the feed and absolute links |
| `DATABASE_DIALECT` | `sqlite` | `sqlite`, `postgres` or `d1`; also selects the migration chain |
| `DATABASE_URL` | `./local.db` (empty for `postgres`) | File path, `postgresql://` or `libsql://` URL |
## Optional
Leave these unset unless you need what they do.
| Variable | Default | Purpose |
| ------------------------------ | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `CONFIG_ENCRYPTION_KEY` | — (credentials stored in plaintext) | At least 32 characters. Encrypts admin config values classified `secret` (payment, email, storage, AI and OAuth credentials) at rest with AES-256-GCM, stored as `enc:v1:…`. Keep it stable: a value written with one key reads as not configured under another. Run `pnpm db:encrypt-config-secrets` once to encrypt credentials saved before the key was set. See [Encrypt stored credentials](https://kernlift.dev/docs/core/configuration.md) |
| `JOBS_IN_PROCESS` | `true` | A Node server runs the [scheduled jobs](https://kernlift.dev/docs/core/background-jobs.md) inside the web process once a minute. Set `false` to leave them to an external cron calling `pnpm jobs:run`. A Cloudflare Worker does not read it and uses the Cron Trigger in `wrangler.jsonc` |
| `ADMIN_CONFIG_CACHE_TTL_MS` | `30000` | Cache lifetime for admin config, the one cache that cannot read its own policy from `/admin/config/cache` |
| `DATABASE_ADAPTER` | The dialect | Registered adapter id: `sqlite`, `postgres`, `turso`, `d1`, `hyperdrive` (Postgres from a Worker) or a custom one |
| `DATABASE_AUTH_TOKEN` | — | libSQL auth token for the `turso` adapter |
| `AUTH_DEV_IMPERSONATE_USER_ID` | — | Treat unauthenticated requests as this user. Works only while `APP_ENV=development` and logs a warning |
## Optional Agent service
Set these only when you deploy the Agent service next to the web app. A site without it needs none of them. Model, sandbox and search settings are configured in `/admin/config/*`. Locally, `pnpm dev:agent` sets the addresses and generates the two secrets for each run; a deployment needs fixed values.
| Variable | Default | Read by | Purpose |
| ------------------------------------------ | ------------ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `AGENT_SERVICE_URL` | — | Web app | Internal URL of the Agent service. Required for the agent on a Node deployment; a Cloudflare deployment reaches its container through the `AGENT_SERVICE` binding instead |
| `AGENT_WEB_INTERNAL_URL` | — | Agent service | Internal URL of the web app. Required |
| `AGENT_INTERNAL_SIGNING_SECRET` | — | Both | Signs requests between the two processes; same value on both, at least 32 bytes. Required |
| `AGENT_RESOURCE_GRANT_SECRET` | — | Web app | Signs short-lived resource grants; at least 32 bytes. Required |
| `AGENT_SERVICE_HOST`, `AGENT_SERVICE_PORT` | `::`, `3001` | Agent service | Listen address and port |
| `AGENT_SERVICE_REQUEST_TIMEOUT_MS` | `120000` | Web app | Timeout for a dispatch to the Agent service |
| `AGENT_FLOW_LOG_LEVEL` | `info` | Both | `debug`, `info`, `warn`, `error` or `silent` |
| `AGENT_SANDBOX_ERROR_LOG_ENABLED` | `true` | Agent service | Logs sandbox error details |
The Agent service refuses to start with web authentication or payment secrets in its environment. Give it the same `CONFIG_ENCRYPTION_KEY` as the web app, because it reads the same config table. Its database must support transactions, so D1 cannot hold Agent data. See [install Agent](https://kernlift.dev/docs/extensions/agent/starter.md).
## Scripts and tooling
Read by command-line scripts and validators only. The web app never reads them.
| Variable | Read by | Purpose |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `SUPER_ADMIN_EMAIL`, `SUPER_ADMIN_PASSWORD` | `pnpm db:bootstrap-super-admin` | Required. First administrator; the password (8+ characters) is used only when the account is created |
| `SUPER_ADMIN_NAME` | `pnpm db:bootstrap-super-admin` | Optional; defaults to `Super Admin` |
| `EXTERNAL_VALIDATE_STRICT` | `pnpm validate:external` | `true` turns skipped provider checks into failures |
| `EXTERNAL_VALIDATE_EMAIL_TO` | `pnpm validate:external` | Recipient for the real email check |
| `EXTERNAL_VALIDATE_NEWSLETTER_EMAIL` | `pnpm validate:external` | Address subscribed and unsubscribed through the newsletter provider |
| `EXTERNAL_VALIDATE_GOOGLE_OAUTH_CONFIRMED` | `pnpm validate:external` | Confirms a manual Google OAuth sign-in was completed |
| `EXTERNAL_VALIDATE_BILLING_CUSTOMER_ID`, `EXTERNAL_VALIDATE_BILLING_PAYMENT_ID`, `EXTERNAL_VALIDATE_BILLING_SUBSCRIPTION_ID` | `pnpm validate:external` | Sandbox ids for portal, refund and subscription checks |
| `KERNLIFT_REGISTRY_URL`, `KERNLIFT_PUBLISH_TOKEN` | `pnpm registry:publish` | Registry to publish to and its publishing key. Not used by a cloned project |
| `KERNLIFT_TOKEN`, `KERNLIFT_CONFIG_DIR` | The CLI's package commands | Registry token and config directory override. Not used by a cloned project |
| `CHROME_PATH` | `pnpm assets:screenshots` | Chrome executable for screenshot capture |
| `NODE_ENV` | Database scripts | Provided by the tooling; selects which `.env` files are loaded |
| `AGENT_DEV_WEB_HOST`, `AGENT_DEV_WEB_PORT` | `pnpm dev:agent` | Web listener for local development; default `127.0.0.1:5173` |
| `AGENT_DEV_SERVICE_HOST`, `AGENT_DEV_SERVICE_PORT` | `pnpm dev:agent` | Agent service listener for local development; default `127.0.0.1:3001` |
| `SKILL_PUBLISH_DRY_RUN` | `pnpm agent:publish-skills` | Any non-empty value reports what would be published and writes nothing |
| `AGENT_SANDBOX_TEMPLATE_DIR` | Sandbox image build | Overrides the sandbox image template directory |
## Cloudflare bindings
These are declared in `wrangler.jsonc`. They do not go in `.env`.
| Binding | Type | Purpose |
| ------------ | ------------- | -------------------------------------------------------------------------------------------------- |
| `EDGE_DB` | D1 database | Database for the `d1` adapter |
| `HYPERDRIVE` | Hyperdrive | Postgres connection for the `hyperdrive` adapter; commented out until you use Postgres on a Worker |
| `BUCKET` | R2 bucket | Storage through the bucket binding driver |
| `CACHE` | KV namespace | The `kv` cache backend |
| `AI` | Workers AI | Edge inference |
| `ASSETS` | Static assets | Serves `dist/client` |
`wrangler.jsonc` also declares `"triggers": { "crons": ["* * * * *"] }`, which starts the scheduled jobs once a minute. When the Agent service runs as a Cloudflare container, its direct Postgres URL is the Worker secret `AGENT_DATABASE_URL`, set with `wrangler secret put`.
## Not environment variables
Provider settings such as `RESEND_API_KEY`, `STRIPE_SECRET_KEY` or `GOOGLE_CLIENT_ID` have no effect: set them in the admin console, as described in [Configure a working project](https://kernlift.dev/docs/core/configuration/project.md). AI channel request templates in `/admin/config/ai` may reference a variable as `{{env.NAME}}`; secrets use `{{secret.KEY}}`.
## Next steps
- [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md)
The settings that are not on this page.
- [Configuration model](https://kernlift.dev/docs/core/configuration.md)
Why so few settings are environment variables.
- [Cache](https://kernlift.dev/docs/core/admin/cache.md)
`ADMIN_CONFIG_CACHE_TTL_MS` and the domain it bootstraps.
- [Deploy to a Node host](https://kernlift.dev/docs/deploy/node.md)
The variables a production host needs.
---
# Scripts
> Every pnpm script in the template's package.json except the individual validators, grouped by what you use it for.
Source: https://kernlift.dev/docs/reference/scripts
Run each with `pnpm ` from the project root. Scripts that touch the database read `DATABASE_DIALECT` and `DATABASE_URL` from `.env` or the shell. The individual `validate:*` scripts are listed in [Validators](https://kernlift.dev/docs/reference/validators.md).
## Develop
| Script | Does |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pnpm dev` | Starts the web app with Vite on port 5173 |
| `pnpm dev:agent` | Starts the web app together with the Agent service (`agent-starter`), with local addresses and temporary signing secrets |
| `pnpm kernlift` | Runs the Kernlift CLI in `tools/kernlift`, for example `pnpm kernlift deploy-target fly`. See [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) |
| `pnpm preview` | Serves the last build with `vite preview` |
| `pnpm cf-typegen` | Generates `worker-configuration.d.ts`, the Workers runtime and binding types the source compiles against |
| `pnpm assets:generate` | Regenerates the placeholder site icons and social share image |
| `pnpm assets:screenshots` | Captures marketing screenshots from a running local instance through Chrome; `CHROME_PATH` picks the executable |
## Build and run
| Script | Does |
| -------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `pnpm build` | Builds for the platform recorded in `deploy.config.json`: the Cloudflare Worker, or the Node server for every other platform |
| `pnpm build:cloudflare` | Builds the Cloudflare Worker regardless of `deploy.config.json` |
| `pnpm build:node` | Builds the Node server and bundles the administrator bootstrap into `.output/scripts/` for production images |
| `pnpm build:agent-service` | Builds the separate Agent service package |
| `pnpm start` | Runs the Node build (`.output/server/index.mjs`) |
| `pnpm deploy` | Runs the chosen platform's deploy command; `wrangler deploy` in a Cloudflare project |
## Database
| Script | Does |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `pnpm db:migrate` | Applies the migration chain of the configured dialect, and prints the database state when it cannot |
| `pnpm db:migrate:runtime` | Applies the same migrations with plain Node and no TypeScript tooling; the release step of production images |
| `pnpm db:migrate:d1:local` | Applies the SQLite chain to the local D1 database through wrangler |
| `pnpm db:migrate:d1:remote` | Applies the SQLite chain to the deployed D1 database |
| `pnpm db:generate` | Runs `drizzle-kit generate` for the dialect in `DATABASE_DIALECT` |
| `pnpm db:generate:sqlite` | Generates a migration for the SQLite schema |
| `pnpm db:generate:postgres` | Generates a migration for the Postgres schema |
| `pnpm db:studio` | Opens Drizzle Studio on the configured database |
| `pnpm db:seed-baseline` | Writes baseline content a fresh database needs: email templates, marketing pages and blocks, rate-limit rules. Existing rows are left alone |
| `pnpm db:bootstrap-super-admin` | Creates the first administrator from `SUPER_ADMIN_EMAIL` and `SUPER_ADMIN_PASSWORD`, writes the permission catalogue and runs the baseline seed |
| `pnpm db:seed` | Seeds nothing; prints that baseline content comes from `pnpm db:seed-baseline` |
| `pnpm db:encrypt-config-secrets` | Encrypts the `secret` admin config values still stored as plaintext, with `CONFIG_ENCRYPTION_KEY` from `.env` or the shell. Values already encrypted are skipped, so a second run changes nothing; without a valid key it exits with an error. On D1 it uses the local state by default, `--remote` for the deployed database and `--persist-to ` for another local state |
## Jobs
| Script | Does |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `pnpm jobs:run` | Runs one round of the scheduled jobs and prints its report, or `"skipped"` when another runner holds the round. Exits non-zero when a job failed |
## Agent
| Script | Does |
| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `pnpm agent:publish-skills` | Publishes every platform Skill whose bundled content changed to the skill registry; `SKILL_PUBLISH_DRY_RUN` previews without writing |
## Registry and skills
`registry:build` checks the module manifests against the code; see [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md). `registry:publish` uploads the result to a registry server, which a project cloned from GitHub does not have.
| Script | Does |
| ----------------------- | ------------------------------------------------------------------------------------------------------------- |
| `pnpm registry:build` | Slices the checkout into a foundation item and one item per `modules//module.json`, into `registry/dist` |
| `pnpm registry:publish` | Pushes `registry/dist` to the registry at `KERNLIFT_REGISTRY_URL` with `KERNLIFT_PUBLISH_TOKEN` |
| `pnpm skills:pack` | Builds `packages/kernlift-skills` from `skills/` and writes its `skills.json` manifest |
## Checks
| Script | Does |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pnpm typecheck` | `tsc --noEmit`, including the unit tests in `tests/` |
| `pnpm test` | Runs the unit tests in `tests/unit/*.test.ts` with Node's test runner (`tsx --test`). They cover signing, verification, amounts and encryption, and need no database or network |
| `pnpm check` | `biome check .`: lint and format check; reports pre-existing violations |
| `pnpm lint` | `biome lint .` |
| `pnpm lint:budget` | Fails when a lint rule has more violations than its recorded budget; `--update` lowers the budget after a real reduction |
| `pnpm format` | `biome format --write .` |
| `pnpm validate:all` | Runs the wired validator chain in order and stops at the first failure |
| `pnpm validate:gate` | Runs every validator except the manual and known-failing ones; what CI gates on |
| `pnpm openspec:validate` | Runs `openspec-cn validate` for every active change with a `tasks.md` |
| `pnpm smoke:node` | Runs the Node build on a throwaway SQLite database without the Agent service; run `pnpm build:node` first |
| `pnpm smoke:worker` | Runs the built Worker under local `wrangler dev` on a throwaway D1 database without the Agent service; run `pnpm build` first |
**Note**
Do not run `biome check --write --unsafe` across the repository. Its fixes strip `!important` from the stylesheet and rewrite React hook dependency arrays, both of which change behaviour.
## Next steps
- [Validators](https://kernlift.dev/docs/reference/validators.md)
The individual `validate:*` scripts.
- [Environment variables](https://kernlift.dev/docs/reference/env.md)
What these scripts read.
- [Run background jobs](https://kernlift.dev/docs/core/background-jobs/run.md)
When to schedule `pnpm jobs:run` yourself.
- [Data access](https://kernlift.dev/docs/core/data-access.md)
Why there is a migration chain per dialect.
---
# Skills
> The SKILL.md workflows in skills/: what each one does, what it asks you for and how it confirms the work is done.
Source: https://kernlift.dev/docs/reference/skills
`skills//SKILL.md` holds the workflows a coding agent such as Claude Code follows when it works on this repository or a project made from it. `.claude/skills/` links each one, so opening the checkout is enough. Every skill has four sections: **Inputs** (what the agent asks you for), **Invariants** (rules it keeps), **Workflow** (the steps) and **Verification** (the commands and pages that prove the task is done). How to install and run them elsewhere is in [Use the coding agent skills](https://kernlift.dev/docs/core/agent-skills.md).
These are not the `agent-skills/` packages that the optional `/app/agent` workbench runs; those are described in [Agent template](https://kernlift.dev/docs/extensions/agent/starter.md).
## At a glance
| Skill | Use it to | You provide |
| --------------------- | ----------------------------------------------------------------- | ------------------------------------------------------------ |
| `project-context` | Learn the project before changing it | The task or the area to understand |
| `quick-start` | Create a project and reach a working admin sign-in | Project name, domain, platform, whether the agent is needed |
| `configure-providers` | Connect sign-in, email, payments, storage, AI, analytics or cache | The capability and the provider's credentials |
| `new-page` | Add one admin or workspace page | Path, what it reads and writes, the permission key |
| `new-module` | Add a capability module end to end | Module key, tables, pages, permission keys, required modules |
| `new-agent-plugin` | Add an agent capability to the one workbench | Plugin id, scene, the Skill it ships, what the reader sees |
| `deploy` | Deploy to Cloudflare, Fly.io, Railway or Docker | Platform, its signed-in CLI, a Postgres URL where needed |
| `add-module` | Install or upgrade a module from a Kernlift registry | Module key |
| `remove-module` | Uninstall a registry module, keeping edits and data | Module key, whether its data goes too |
Ask for the task in plain words, or name the skill: "use the new-page skill to add an admin page for exports".
## Understand
### `project-context`
Has the agent run `pnpm kernlift context` for an overview, read `AGENTS.md`, then narrow to the routes, plugins, settings pages, variables, scripts or validators the task touches, open the files named, and pick the task skill. Done when the overview's plugin list matches `src/plugins/installed.ts` and `pnpm validate:skills` passes.
## Build
### `new-page`
Adds a page under `/admin/` or `/app/` with copy in both locales, server functions gated by a permission key, a navigation entry and the guards of the layout it sits under. Done when `pnpm validate:route-i18n`, `pnpm validate:app-i18n`, `pnpm validate:auth-boundary` and `pnpm validate:beui-console` pass, the page renders in both locales and themes, and the entry is hidden from a user without the permission.
### `new-module`
Adds a capability as a module: repository, service, routes, schema and migrations for both dialects, copy in both locales, a validator, and a manifest with `@module` markers. Done when `pnpm validate:registry` shows the foundation still typechecks on its own, the module's own validator passes, and `pnpm validate:all` turns no check red.
### `new-agent-plugin`
Adds a plugin to the agent workbench: server extension, browser entry, Skill, cards, panels and operations, switched on and off at runtime from `/admin/plugins`. Done when `pnpm validate:agent-plugin-contract` and the plugin's validator pass, `pnpm build:agent-service` still builds, and the plugin appears in the `/app/agent` picker.
## Configure and ship
### `quick-start`
Creates a project, installs it, migrates the local database, creates the super administrator and starts `pnpm dev`. Done when `pnpm typecheck` and `pnpm validate:gate` pass and `/setup` shows the session secret and one sign-in method as ready.
### `configure-providers`
Walks through the `/admin/config/*` page for a capability and keeps provider credentials out of the environment. Done when `/setup` shows the item as ready and `pnpm validate:env-example` passes; `EXTERNAL_VALIDATE_STRICT=true pnpm validate:external` runs the real provider checks.
### `deploy`
Picks or switches the platform recorded in `deploy.config.json`, stores the generated secrets, migrates and deploys. Done when the deploy command prints the URL and `/setup` shows the platform, the session secret and scheduled jobs as ready. `pnpm smoke:node` or `pnpm smoke:worker` checks the build first.
## Modules
These two apply only to projects that install modules from a Kernlift registry. Templates bought from the store arrive as their own GitHub repository and need neither; see [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md).
### `add-module`
Installs or upgrades a module, then runs its install, migrate and validator steps. Done when the module's validator passes, the CLI's health check is clean, and its admin page appears for users with its permission.
### `remove-module`
Uninstalls a module: previews the plan, keeps your local edits and keeps the module's data unless you ask otherwise. Done when the CLI's health check is clean, `pnpm typecheck` and `pnpm build` pass, and the module's pages are gone.
## Checks
| Command | What it checks |
| ---------------------- | -------------------------------------------------------------------------------------- |
| `pnpm validate:skills` | Every skill has the four sections and names only commands, paths and routes that exist |
| `pnpm skills:pack` | Builds `@kernlift/skills` from `skills/` |
## Next steps
- [Use the coding agent skills](https://kernlift.dev/docs/core/agent-skills.md)
Install the skills in another project and run one.
- [Scripts](https://kernlift.dev/docs/reference/scripts.md)
The commands the skills run.
- [Validators](https://kernlift.dev/docs/reference/validators.md)
What each validate:\* check proves.
---
# Validators
> Every validate:* script, what it proves, whether validate:all and the release gate run it, and which ones are known to fail.
Source: https://kernlift.dev/docs/reference/validators
Run one with `pnpm validate:`. `pnpm validate:all` runs the wired chain in order and stops at the first failure. `pnpm validate:gate` runs every `validate:*` script except the manual ones and those listed in `scripts/validate/known-failures.json`, and fails on any regression.
## Features
| Script | Proves |
| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `validate:api-keys` | Keys hashed, scoped and rate-limited; usage recorded; admin inventory and wiring |
| `validate:auth` | Account flows: sign-up, verification, reset, sessions |
| `validate:auth-feedback` | Sign-in errors are translated in both locales and rendered as an alert |
| `validate:auth-boundary` | Every API route guarded or explicitly public with a reason; layout guards; webhook signature verdicts |
| `validate:google-one-tap` | Real requests to the Better Auth handler: with One Tap on, a forged ID token gets 400 and no session; with it off or Google disabled, `/api/auth/one-tap/callback` is 404 |
| `validate:ai` | AI tasks, pricing and credits around real outcomes |
| `validate:ai-channel` | Channel schema, pricing, parsing, webhook signatures and polling, refunds |
| `validate:generation-pipeline` | Channel parser paths that index arrays, a scene's relative status path and virtual-hosted object addressing |
| `validate:analytics` | Analytics providers, events, report pulls and support tickets |
| `validate:billing` | Checkout, webhooks, refunds, portal; a missing provider fails instead of faking success |
| `validate:billing-fulfilment` | Paid orders, refunds and checkout refusals reach `billing.fulfilment` plugins once; failures are recorded and retried by the scheduled round |
| `validate:wechat-pay` | WeChat Pay signing, verification, decryption, amount checks, settlement, refunds, routing by currency and the QR checkout page |
| `validate:alipay` | Alipay RSA2 signing, the cashier address, notification verification with app, seller and amount checks, settlement, duplicate notifications, gateway response verification, routing by currency and the admin form |
| `validate:waffo` | Waffo request signing, the checkout session (product per plan, tax-included price, order id, promotion codes), webhook verification with replay and tamper refusal, settlement at the charged amount |
| `validate:promotion-codes` | The promotion code switch reaches Stripe Checkout only when on, and a signed webhook's discounted total is recorded as the amount paid |
| `validate:pricing-plans` | `/admin/plans` writes every locale row, `/pricing` and checkout read them back, bad input is refused, saves are audited and need `plans.write` |
| `validate:credits` | Reserve, capture and refund ledger |
| `validate:signup-credits` | Sign-up bonus settings round-trip, the grant happens once per user and not at all while off, and the Better Auth user-create hook calls it |
| `validate:cache-policy` | Per-domain cache policy from admin config |
| `validate:config-encryption` | `secret` settings are stored as `enc:v1:` ciphertext and read back as plaintext; a wrong key reads as not configured and is never overwritten by seeding; the encrypt command; secret-holding cache domains stay in memory |
| `validate:email` | Templates, deliveries, notification channels |
| `validate:files` | Uploads, signed downloads, storage config |
| `validate:foundation` | Setup readiness, admin overview, system states |
| `validate:plugins` | Plugin registry conflicts, installed-list wiring, enablement and dependency cascades, the `/admin/plugins` surface |
| `validate:session-owner` | Owner-scoped reads |
| `validate:system` | System state pages, event recording, redirects, maintenance mode |
| `validate:users` | RBAC, roles, permissions, assignment, status changes |
## Modules and the agent
| Script | Proves |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `validate:affiliate` | Referrals, commissions, payout review, program settings |
| `validate:cms` | Content entries, revisions, SEO checks, locale-aware admin routes |
| `validate:newsletter` | Newsletter and waitlist flows and provider sync logs |
| `validate:registry` | Registry slices reassemble the checkout; the foundation typechecks alone; manifests describe real files |
| `validate:kernlift-lifecycle` | The CLI's module install and removal on real registry items: dry runs, refusals, byte-for-byte restore, kept edits, `--purge-data` migrations |
| `validate:optional-agent` | The web app is complete without the agent service: scheduled jobs run in the web app under one lock, agent entries report unavailability, no web path loads the agent runtime |
| `validate:agent-starter` | Agent template isolation, transactional database requirement, owner scopes, API guards, credits and readiness |
| `validate:agent-plugin-contract` | One workbench composer for every agent plugin; plugin cards, panels and server join points; switched-off plugins are never selected |
| `validate:agent-generation` | The agent side of the generation pipeline: raw queries on SQLite, publishing generated media, video artifacts |
| `validate:dsh-runtime` | The agent runtime resolves to the pinned DeepSeek Harness build and nothing outside the runtime package imports it |
| `validate:image-agent` | The image agent reaches the host, the workbench and both consoles only through plugin slots and ships as a module |
## Site and copy
| Script | Proves |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `validate:app-i18n` | Shared, auth, system and marketing copy resolve through the dictionaries |
| `validate:route-i18n` | Locale-aware routes |
| `validate:marketing` | Marketing snapshot, pages and blocks |
| `validate:example-landing` | `/` and `/pricing` are built only from the public shell, page-shell primitives and beUI, and every link reaches a route |
| `validate:beui-console` | Console, workspace, auth and system routes use the shared beUI system without importing `src/components/ui` |
| `validate:admin-surface-polish` | Admin record lists page and window their rows correctly |
| `validate:mobile` | Responsive contract |
| `validate:site-metadata` | Site config, sitemap, robots, `.env.example` drift |
| `validate:project-docs` | The README names only commands and paths that exist; `/setup` readiness is derived from live configuration |
| `validate:skills` | Skills name only commands, paths and routes that exist |
| `validate:project-context` | `pnpm kernlift context` reports what the source contains |
| `validate:store-boundary` | No licences, registry server, storefront catalogue, Kernlift marketing site or documentation site in the template |
## Engineering and deployment
| Script | Proves |
| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `validate:env-example` | `.env.example` matches what the source reads |
| `validate:unit-tests` | `pnpm test` passes, and every payment client in `src/server/payments/` and the config encryption has a unit test |
| `validate:template-boundary` | The skeleton never imports from the editable zone; the upgrade guide covers the flow |
| `validate:init-cli` | The CLI's project initialiser generates the session secret, resumes a partly provisioned project and never deletes a cloud resource |
| `validate:migrations` | Both migration chains replay onto an empty database and end with the same tables |
| `validate:db-adapters` | Adapter registry, bindings and server entry |
| `validate:sqlite-transactions` | Async transaction callbacks commit, roll back, queue and nest correctly on the default SQLite adapter |
| `validate:deploy-targets` | `deploy.config.json` picks the Cloudflare or Node build; the entries, images and migration runner match |
| `validate:openspec-traceability`, `validate:openspec-consistency`, `validate:openspec-remaining-scope` | OpenSpec records, traceability and remaining scope |
| `validate:external` | Real provider checks when credentials exist; `EXTERNAL_VALIDATE_STRICT=true` fails skipped checks |
| `validate:external-readiness` | Runs `validate:external`, then writes the readiness report |
`pnpm openspec:validate`, also chained into `validate:all`, runs `openspec-cn validate` for every active change with a `tasks.md`.
## Run separately
| Script | Why it is not in `validate:all` |
| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `validate:all` | The chain itself; the gate does not run it |
| `validate:gate` | The release gate itself |
| `validate:storage-drivers` | Writes and deletes real objects in a bucket; run it deliberately against a bucket you chose. The gate skips it too |
| `validate:ai-channel`, `validate:auth-feedback`, `validate:external` | Not chained into `validate:all`; the gate still runs them |
| `lint:budget` | A budget for pre-existing lint violations that can only go down; `--update` records a reduction |
## Store project
These validators belong to the store project that sells Kernlift. A project created from the template does not have them.
| Script | Proves |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `validate:products` | Server-side pricing, licences, bundle expansion |
| `validate:module-catalog` | Module pages, pricing pages and home blocks render from products |
| `validate:github-delivery` | Membership and member prices, activation with a GitHub username, repository invitations, the refund rule after activation, revocation |
| `validate:template-marketplace` | Templates render from the real snapshot |
| `validate:landing-blocks` | Home composition, tokens, counts from the checkout |
| `validate:docs` | Bilingual navigation and links resolve; module manifests, Agent API methods, schema tables and environment variables match the docs |
| `validate:deployment-docs` | The deployment docs cover every target |
## Known failures
`scripts/validate/known-failures.json` lists validators that do not yet pass on a database built by `pnpm db:migrate` alone. The list may only shrink. Adding an entry fails CI.
| Script | Reason in short |
| ------------------------------- | ------------------------------------------------------------------- |
| `validate:ai` | Expects AI scenes, channels and pricing rows a fresh database lacks |
| `validate:auth` | Asserts copy that moved into the dictionaries |
| `validate:billing` | Asserts rows of an archived design record |
| `validate:cms` | Needs seed content and asserts old admin markup |
| `validate:credits` | Writes ledger rows for users that do not exist; copy moved |
| `validate:files` | Expects seeded folders, files and usage rows; copy moved |
| `validate:newsletter` | Asserts literals that moved into the dictionaries |
| `validate:openspec-consistency` | Archived changes lack newer policy sections |
| `validate:users` | Needs seed users, roles and permissions |
## Next steps
- [Validators and the release gate](https://kernlift.dev/docs/core/validators.md)
Why each one asserts wiring rather than file existence.
- [Scripts](https://kernlift.dev/docs/reference/scripts.md)
Every other `pnpm` script in the template.
- [Upgrading a fork](https://kernlift.dev/docs/guide/upgrading.md)
Record the pass set before, compare after.
- [Environment variables](https://kernlift.dev/docs/reference/env.md)
What the external checks need before they can run.