# Kernlift documentation # Audit log > Read who changed what: 48 write paths record an actor, an action, a target and their metadata. Source: https://kernlift.dev/docs/core/admin/audit-log Writes that need an audit trail (a licence issued, a refund, a config save, a ticket reassigned, a file deleted) append a row to `audit_logs` in the same code path that performs them. The console lists the most recent 500 at `/admin/audit`. You can filter them by action and expand each row's metadata. ## Before you begin * An account with `audit.read`. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). * Nothing to configure. The log records from the first request and has no provider. ## Set it up ### Give an auditor the permission, and only that `audit.read` reads the log. It does not imply `config.read`, `users.write` or anything else, so you can give a compliance reviewer an account that sees every change and cannot make any. ### Read the log `/admin/audit` lists actor, action, target and time. Filter by action to narrow the list. Expand a row to read the metadata the write recorded, such as an order id, a provider name or a permission key. ### Record your own writes When you add a write path, append to the log from the repository that performed it, so the entry is written together with the change: ```ts await recordAudit("billing.refund.created", orderId, { provider, amountCents }); ``` `actor` names the subsystem that wrote the row. Metadata is JSON, so it is searchable later without a migration. ## What the log records today 48 call sites write to it, grouped by the subsystem that owns them: | Prefix | Examples | | ---------------------------- | --------------------------------------------------------------------------------------------- | | `billing.*` | `checkout.created`, `refund.created`, `licences.issued`, `licences.revoked`, `portal.created` | | `support.*` | `ticket.created`, `ticket.replied`, `ticket.assignment.updated` | | `cms.*` | `entry.upserted`, `taxonomy.created` | | `email.*`, `notification.*` | `template.saved`, `delivery.recorded`, `webhooks.saved`, `preferences.updated` | | `affiliate.*` | `referral.created`, `conversion.recorded`, `payout.requested` | | `newsletter.*`, `waitlist.*` | `subscribed`, `unsubscribed`, `joined` | | `file.*` | `uploaded`, `deleted` | | `analytics.*` | `event.recorded` | ## The row The page snapshot also includes rate-limit rules and the 20 most recent webhook verification results, so you can inspect configuration changes and rejected events together. ## Verify 1. Issue a licence by hand from `/admin/licences`. A `billing.licences.issued` row appears at the top of `/admin/audit` with the licence's target id. 2. Filter by that action. Only those rows remain. 3. Expand the row. The metadata shows the product key and the user it was granted to. 4. Sign in as a role without `audit.read`. The page shows permission denied. ## Reference * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [Rate limits](https://kernlift.dev/docs/core/admin/rate-limits.md): the rate-limit rules in the same snapshot * [Drizzle inserts](https://orm.drizzle.team/docs/insert): how a repository appends the row ## Next steps - [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) Create a read-only auditor role. - [Rate limits](https://kernlift.dev/docs/core/admin/rate-limits.md) What was throttled, and by which rule. - [Support tickets](https://kernlift.dev/docs/extensions/support.md) Operator actions on a ticket are audited too. --- # Cache > Ten cache domains with their own TTLs, in memory or in Cloudflare KV, each clearable on its own. Source: https://kernlift.dev/docs/core/admin/cache Every request that touches payments, email, storage or AI reads the provider configuration from the admin config table. Those reads are cached per domain, with a TTL you set at `/admin/config/cache`. You can clear each domain separately when you have changed something and do not want to wait for its TTL to expire. ## Before you begin * `config.read` to see the page, `config.write` to change a TTL or clear a domain. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). * Memory is the default. Cloudflare KV is available only when the runtime has a `CACHE` binding. Redis is listed with an unavailable reason and is not connected to the cache layer. ## Set it up ### Choose a backend Memory caches inside one process. On Workers, each isolate caches separately, and on Node each container does. KV is shared across instances. Unavailable backends remain visible with a reason. The runtime falls back to process memory if a configured backend is unavailable. ### Set a TTL per domain Each domain has its own default. With a short TTL on configuration, a provider change takes effect quickly. With a longer TTL on templates, content that rarely changes is read less often. The save form accepts 1–86,400 seconds. Turn off **Enabled** to bypass caching for that domain. The TTL is retained for later use. ### Clear a domain after a change Saving a provider from `/admin/config/*` clears that domain, so your change takes effect without waiting for the TTL. Clear a domain by hand when you changed a row outside the console. ## Domains and their defaults | Domain | What it holds | Default TTL | | --------------------- | ----------------------------- | ----------- | | `admin_config` | The admin config table itself | 30s | | `auth_config` | Auth providers and options | 30s | | `email_config` | Email provider settings | 30s | | `email_template` | Rendered email templates | 60s | | `payment_config` | Payment provider settings | 30s | | `storage_config` | Object storage settings | 30s | | `analytics_config` | Analytics provider settings | 30s | | `newsletter_config` | Newsletter provider settings | 30s | | `ai_channel_snapshot` | The channel list | 30s | | `ai_channel_resolved` | Scene → channel resolution | 15s | `admin_config` is the bootstrap domain. Every other domain reads its own policy through it, so it cannot read its policy from the table it caches. Its TTL comes from `ADMIN_CONFIG_CACHE_TTL_MS`, one of the few environment variables this project reads. ## Policy To add another cache domain, update `cacheDomains` in `cache-policy.ts`. The admin page then shows its TTL setting and clear action. ## Verify 1. Open `/admin/config/cache`. Ten domains are listed with their TTLs. 2. Change a payment setting at `/admin/config/payment`, then load a checkout. The new setting is in effect immediately, without the 30-second wait. 3. Turn off **Enabled** for `email_template` and save. Template reads stop being cached. 4. On a runtime without the `CACHE` binding, the KV option is shown with the reason it is unavailable. ## Reference * [Configuration model](https://kernlift.dev/docs/core/configuration.md): why settings live in the database * [Environment variables](https://kernlift.dev/docs/reference/env.md): including `ADMIN_CONFIG_CACHE_TTL_MS` * [Deployment](https://kernlift.dev/docs/deploy/runtimes.md): which bindings a runtime has * [Cloudflare KV](https://developers.cloudflare.com/kv/): the shared backend ## Next steps - [Configuration model](https://kernlift.dev/docs/core/configuration.md) What is cached, and where it is edited. - [Rate limits](https://kernlift.dev/docs/core/admin/rate-limits.md) Another setting that behaves differently on one process and on several instances. - [Deploy to Cloudflare](https://kernlift.dev/docs/deploy/cloudflare.md) Create the KV namespace and bind it as CACHE. - [AI channels](https://kernlift.dev/docs/extensions/ai.md) The scene resolution this cache keeps for fifteen seconds. --- # View accounts and paid orders by country > Compare account and settled-order totals by country over a date range. Source: https://kernlift.dev/docs/core/admin/countries `/admin/countries` groups accounts and settled orders by country code in a map and sortable table. It reads your application database and needs no third-party analytics account. ## Before you begin * `countries.read`. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). * Accounts with a country recorded. An account whose country is unknown is counted under `UNKNOWN`, so the totals still add up. ## Set it up ### Open the page Open `/admin/countries`. The page loads a default date range. The range, start and end are URL search parameters, so a copied link preserves the selected window. ### Select a date range Choose **Today**, **Yesterday**, **7 days**, **30 days** or a custom range, then select **Apply**. The map and table update together. Compare **Users**, **Created orders**, **Paid orders** and **Paid amount** for the selected interval. The page shows aggregate country totals only; it does not expose an individual user's location or provide a drill-down into accounts. Country is captured from supported request headers when a user signs in. If the platform provides no country header, that account is counted under `UNKNOWN`. ## Search parameters Country names are localised from the two-letter code in `src/lib/admin-countries.ts`. The database does not store the name. ## Verify 1. Open `/admin/countries`. The map and the table render, and their totals match the summary row. 2. Narrow the range. Both the map and the table change together. 3. Place a test order from an account with a country set. After the webhook settles it, the amount appears against that country. 4. Sign in as a role without `countries.read`. The page denies access. ## Reference * [Analytics](https://kernlift.dev/docs/extensions/analytics.md): page and event analytics * [Payments](https://kernlift.dev/docs/extensions/payments.md): when an order counts as paid * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [MapLibre GL](https://maplibre.org/maplibre-gl-js/docs/): the map this page renders with If every row is `UNKNOWN`, check whether the platform forwards a country header and have a user sign in again. Existing sessions keep the country recorded when they were created. ## Next steps - [Analytics](https://kernlift.dev/docs/extensions/analytics.md) Traffic and events, with or without a third-party provider. - [Payments](https://kernlift.dev/docs/extensions/payments.md) Where the paid amounts on this page come from. - [Users and accounts](https://kernlift.dev/docs/core/auth/users.md) The account rows this page counts. - [Admin console](https://kernlift.dev/docs/core/admin.md) The other operations pages. --- # Run the admin console > Create the first administrator, finish the setup checklist, find your way around the sidebar, and use plugins, caching and the audit log from /admin. Source: https://kernlift.dev/docs/core/admin The admin console at `/admin` is where operators run the product. Use this guide once, right after installation, and come back to it when you tune caching or review the audit log. ## Before you begin * A migrated database (`pnpm db:migrate`). * A shell on a machine that can reach that database. * The email address and password you want for the first administrator. ## Create the first administrator Nobody can open `/admin` until one user holds the `admin.access` permission, and permissions are granted inside the console. The bootstrap script creates the first administrator from the command line. ### Add the administrator to `.env` ```bash title=".env" SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD=at-least-8-characters SUPER_ADMIN_NAME="Super Admin" ``` `SUPER_ADMIN_EMAIL` and `SUPER_ADMIN_PASSWORD` are required. The password must be at least 8 characters and is only used when the account is created. `SUPER_ADMIN_NAME` is optional and defaults to `Super Admin`. ### Run the bootstrap script ```bash pnpm db:bootstrap-super-admin ``` The script creates the account with a verified email, or promotes an existing account with that email without changing its password. It sets the access status to **Active**, writes every permission the template ships, grants them all to a **Super Admin** role and assigns that role. It also writes the baseline email templates, marketing pages and rate-limit rules. ### Remove the password and sign in Delete `SUPER_ADMIN_PASSWORD` from `.env`. Only the script reads these variables. Sign in at `/auth/sign-in` and open `/admin`. Run the script again after an upgrade or a module install that adds permissions, so the Super Admin role receives them. ## Work through the setup checklist ### Open Setup Open **Setup** from the workspace sidebar (`/setup`). It reads the live configuration on every load. ### Fix each item marked Not ready Every item states what is missing and has a **Configure** button that opens the page that fixes it. Required items are **Session secret**, **Sign-in method**, **Email delivery** and **Scheduled jobs**. **Payment provider**, **Object storage**, **AI channels**, **Newsletter provider** (with the newsletter module) and **Analytics provider** are optional. The badge reads **Nothing required is missing** when every required item is ready. Two required items are not set in the console. **Session secret** is `BETTER_AUTH_SECRET` in the environment, because it is needed before the database is read; see [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md). **Scheduled jobs** reports whether the once-a-minute background round is running. It has no **Configure** button, and its message names the platform switch to check. See [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md). ## Find your way around the sidebar The sidebar is grouped, and every entry is hidden from a user who lacks its permission. | Group | Entries | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Overview** | Dashboard (`/admin`), Users, Countries | | **Operations** | Roles, Permissions, Support | | **Commerce** | Plans (`/admin/plans`), Orders, Subscriptions | | **Platform** | AI Tasks, Chats, API Keys, Rate Limits, Assets | | **Content** | CMS, Waitlist and Affiliates, each with its module | | **Security** | Webhooks, Audit | | **Settings** | Auth, Payment, Storage, AI, Analytics and Email Config, Email, Notifications, Plugins (`/admin/plugins`), plus Sandbox, Search and Image Agent settings with the agent modules | **Plans** is where you create the pricing plans that `/pricing` lists and checkout charges. It needs `plans.read`, and `plans.write` to save. See [Pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md). ## Switch a plugin on or off 1. Open **Settings → Plugins** (`/admin/plugins`, needs `config.read`). It lists every plugin installed in this build with what it contributes. 2. Use the switch on a module's row; saving needs `config.write`. The builtin foundation plugin is always on. A disabled plugin's console entries disappear and its `/admin` and `/app` pages return not found. Its data stays. This page does not install plugins; a plugin is installed by adding it to `src/plugins/installed.ts`. See [Console plugins](https://kernlift.dev/docs/core/plugins/console-plugins.md). ## Tune caching ### Open the cache settings Open `/admin/config/cache`. It has no sidebar entry; saving needs `config.write`. ### Set each area For each area, tick **Enabled**, set **Time to live (seconds)** and choose a **Backend** available in this runtime. Click **Save**. ### Clear a cache when needed **Clear this domain** empties that area's cache immediately. ## Review the audit log Open **Security → Audit** (`/admin/audit`, needs `audit.read`). It lists the latest 500 events, such as user status changes, auth and provider settings saves, API key events and rate-limit decisions, and offers them as a CSV download. **Before setup** Without the bootstrap script no one can open the console. A signed-in user without `admin.access` is sent to `/system/permission-denied`, and a visitor without a session to `/system/session-expired`. ## Verify * Sign in as the administrator: `/admin` opens and the sidebar shows every group. * `/setup` shows **Nothing required is missing** once the required items are ready. * In the repository, run: ```bash pnpm validate:users pnpm validate:auth-boundary ``` ## Troubleshooting ### `SUPER_ADMIN_EMAIL is required.` The script found no value. Add both variables to `.env`, or pass them inline: `SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='' pnpm db:bootstrap-super-admin`. ### A page shows `Permission denied: ` The user can open the console but lacks the permission that page checks. The dashboard at `/admin` alone needs `admin.dashboard.read`, `users.read`, `credits.read` and `ai.read`. See [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). ### A new permission does not reach the Super Admin Role permissions are written when `pnpm db:bootstrap-super-admin` runs. Run it again. ### A sidebar entry is missing The sidebar hides entries the user has no permission for. Give the user a role that carries the permission for that page; see [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). ## Reference * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [Base UI](https://base-ui.com) ## Next steps - [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) - [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) - [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md) --- # Rate limits > Set the API-key request limits and choose an in-memory or Redis counter backend. Source: https://kernlift.dev/docs/core/admin/rate-limits `/admin/rate-limits` configures API-key traffic: one default limit and overrides for AI generation, AI status and asset upload. Authentication and webhook protection have separate runtime paths. This page does not edit their rules. ## Before you begin * An account with `config.read` to see the page and `config.write` to change the backend. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). * Memory is the default backend. Configure Redis for shared counters across application instances. ## Set it up ### Look at the rules you already have Open `/admin/rate-limits`. The form shows the default limit and three endpoint overrides. These values are stored in admin config, not in the separate `rate_limit_rules` audit table. ### Pick a backend Memory counts inside one process. Separate Workers isolates or Node containers each keep their own counters. Select Redis and provide a connection URL to share counters across instances. The URL is stored as an admin config secret and is never returned to the browser. The page shows only whether a URL is set. ### Tune a rule Set the default request cap and window, then adjust any endpoint-specific caps and windows. ## API-key limits on this page | Key | Endpoint pattern | Default | | --------------------- | ----------------------------- | ---------------------------------- | | Default API-key limit | Other scoped API-key requests | 100 requests per 1-second window | | `ai_generate` | `/api/{scene}/generate` | Inherits the default until changed | | `ai_status` | `/api/status` | Inherits the default until changed | | `assets_upload` | `/api/assets/upload` | Inherits the default until changed | The form accepts a cap of 1–10,000 requests and a window of 1–3,600 seconds for each entry. ## Backend When adding a default rule, update `defaultRateLimitRules` and run `insertMissingRateLimitRules`. Existing deployments receive the new rule, and operator changes are not overwritten. ## Verify 1. Open `/admin/rate-limits`. Three endpoint overrides and the default API-key limit are listed. 2. Switch the backend to Redis without a URL. The page rejects the save. It does not fall back to memory. 3. Save a Redis URL, reload the page. It reports that a URL is configured and does not display it. ## Reference * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [API keys](https://kernlift.dev/docs/core/auth/api-keys.md): the scopes the verify limit protects * [Redis](https://redis.io/docs/latest/develop/): the shared counter store ## Next steps - [Audit log](https://kernlift.dev/docs/core/admin/audit-log.md) Which rules were triggered and the result of each webhook verification. - [API keys](https://kernlift.dev/docs/core/auth/api-keys.md) Scopes, usage records and the limits that apply per key. - [Cache](https://kernlift.dev/docs/core/admin/cache.md) Another setting that behaves differently with one process or several instances. - [Credits](https://kernlift.dev/docs/extensions/credits/usage.md) What a denied reservation means for the customer's balance. --- # Use coding-agent skills > Use the SKILL.md workflows in skills/ to learn a project, create projects, build, install and remove modules, add pages, configure providers and deploy. Source: https://kernlift.dev/docs/core/agent-skills The `skills/` directory contains workflows for a coding assistant working on this repository or a derived project. These are **not** the published `agent-skills/` packages used by the optional `/app/agent` runtime. For that product, see [Agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) and [Agent runtime](https://kernlift.dev/docs/extensions/agent.md). ## Before you begin * A coding agent that reads `SKILL.md` files, such as Claude Code. * The repository checked out, or a project you want to install the skills into. | Skill | Use it when | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `project-context` | Starting on a project or an area you have not read: what is there and where it lives | | `quick-start` | Creating a project with the CLI and reaching a working admin sign-in | | `new-module` | Adding a module end to end, including its region markers and manifest | | `new-page` | Adding one admin or workspace page with copy, guards and navigation | | `new-agent-plugin` | Adding an agent capability as a plugin of the one workbench: Skill, cards, panels and operations | | `configure-providers` | Wiring real providers through `/admin/config/*` | | `deploy` | Deploying to Cloudflare, Fly.io, Railway or a Docker host: picking or switching the platform, storing the generated secrets, migrating and checking `/setup` | | `add-module` | Installing or upgrading a module through the CLI's package workflow, with a preview first | | `remove-module` | Uninstalling a module through the CLI's package workflow: previewing the plan, keeping edits, deciding about data and retiring its Skills | `quick-start`, `add-module` and `remove-module` drive the CLI's package workflow, which a project cloned from GitHub does not use. In a clone, follow the [quick start](https://kernlift.dev/docs/quick-start.md) instead of `quick-start`; you do not need the other two, because every module is already in the checkout. Every skill has the same four sections: **Inputs**, **Invariants**, **Workflow** and **Verification**. It names only commands, paths and routes that exist in the repository. ## Install the skills **In your clone** Nothing to install. The repository commits a link at `.claude/skills/` for each skill in `skills/`, so Claude Code loads them when you open the clone. On Windows, git checks the links out as plain text files unless symbolic links are enabled (`git config core.symlinks true` before cloning, with Developer Mode on). Without them, use the other tab. **In another project** ```bash npx skills add kernlift/kernlift ``` Run it in the project root. `kernlift/kernlift` is the private repository you were invited to, so your GitHub account needs read access to it. The command installs the skills for Claude Code in `.claude/skills` and for other coding agents in `.agents/skills`. ## Run a skill ### Name the task Ask the agent for the task in plain words, or name the skill, for example "use the new-page skill to add an admin page for exports". ### Provide the inputs Each skill starts with an **Inputs** section, such as a module key or the deployment platform. The agent asks for anything missing. ### Let it follow the workflow The agent works through the **Workflow** steps while keeping the **Invariants**, such as never inventing ids or reading `process.env` from feature code. ### Check the result The agent finishes with the skill's **Verification** section: the commands and pages that confirm the task is done. ## Let an agent read the project Documentation describes Kernlift in general; an agent working on your project needs facts about that project. Two sources give it them. **`pnpm kernlift context`** prints a description of the checkout, read from the source each time it runs, so it stays current as you add routes, plugins and settings. It needs no token, network or database, and writes nothing. ```bash pnpm kernlift context # overview and the topics below pnpm kernlift context routes # every URL and the file that serves it pnpm kernlift context validators --json ``` | Topic | What it lists | | ------------ | ---------------------------------------------------------------------------------------- | | `rules` | The sections of `AGENTS.md`, summarised | | `routes` | URLs by area (public, auth, app, admin, api) with their files | | `plugins` | Plugins in `src/plugins`, whether this build installs them, their routes and nav entries | | `config` | Each `/admin/config/*` page with the server functions and repositories behind it | | `env` | Variables in `.env.example` with their level and description | | `scripts` | `pnpm` scripts other than validators | | `validators` | `pnpm validate:*` checks, which ones `validate:all` runs, and the known failures | | `skills` | The skills in `skills/` | `all` prints every topic at once. The `project-context` skill tells the agent to start here. **The documentation as Markdown.** [`/llms.txt`](https://kernlift.dev/llms.txt) lists every page of this site with a link to its Markdown, [`/llms-full.txt`](https://kernlift.dev/llms-full.txt) is the whole site in one file, and any page is available as Markdown by adding `.md` to its address, for example `/docs/quick-start.md`. The Chinese versions are under `/zh`. Point an agent at `https://kernlift.dev/llms.txt` when it needs a concept or procedure that is not in the code. ## Verify * In Claude Code, the skills from `skills/` appear in the list of available skills. * `pnpm kernlift context` prints an overview whose plugin list matches `src/plugins/installed.ts`. * In the repository, `pnpm validate:skills` confirms every command, path and route a skill names exists. ## Troubleshooting ### The agent does not see the skills Open the agent in the repository root so it finds `.claude/skills`. If `.claude/skills/` is a small text file instead of a link, the clone was made without symbolic links; install with `npx skills add kernlift/kernlift`. ### `pnpm validate:skills` fails after an edit A skill names a command, path or route that no longer exists. Update the skill to match the code. ## Reference * [Skills](https://kernlift.dev/docs/reference/skills.md): what each skill does, asks for and checks * [Agent starter](https://kernlift.dev/docs/extensions/agent/starter.md): the separate runtime product and its published skill packages * [Agent Skills specification](https://agentskills.io/specification): the `SKILL.md` format ## Next steps - [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) - [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md) - [Deploy your project](https://kernlift.dev/docs/deploy.md) - [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md) --- # Issue API keys and set rate limits > Users call the AI and upload endpoints from scripts with scoped keys, and you control how often each key may call them. Source: https://kernlift.dev/docs/core/auth/api-keys API keys let a user call selected `/api/*` endpoints without a browser session. Any signed-in user can create keys for their own account. Operators set the limits. Keys need no provider and no environment variables. ## Before you begin * A signed-in user account to create the key. * To view limits you need `config.read`, to change them `config.write`, and to list every user's keys `api_keys.read`. The built-in **Platform Operator** role can view, and **Settings Manager** adds `config.write`. * For AI calls, a routed scene. See [Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md). ## Create a key ### Open the form Sign in, open **API Keys** in the app sidebar (`/app/api-keys`) and click **Create API Key**. ### Fill in the fields | Field | What to enter | | ------------------------ | ----------------------------------------------------------------------------------------------------- | | **Key name** | A label you will recognise later, at least two characters. | | **Environment** | **Production**, **Staging** or **Development**. A label only; it does not change what the key can do. | | **Rate limit (req/sec)** | Requests allowed per window on endpoints without an API rule. Defaults to 100. | | **Expiry date** | Optional. The key stops working once this date starts (UTC). | | **Allowed origins/IPs** | Optional, one per line. See the warning below. | | **Scopes** | **Run AI tasks**, **Read AI task status**, **Upload files**. The first two are selected by default. | ### Copy the secret Click **Create key**, then **Copy** the **Secret key**. It is shown once and cannot be retrieved later. If it is lost, create a new key. Scopes cannot be changed after creation. **Allowed origins block server-to-server calls** When **Allowed origins/IPs** is filled, a request is accepted only if its `Origin` header matches a line exactly, scheme and port included. IP addresses are not matched, and requests without an `Origin` header, such as curl or server code, are rejected. Leave it blank for server-to-server keys. ## Call the API with the key Send the key as `Authorization: Bearer ` or `x-api-key: `. ```bash curl -X POST "https://your-domain.example/api/$SCENE/generate" \ -H "Authorization: Bearer $KERNLIFT_API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt": "Summarise this changelog"}' curl "https://your-domain.example/api/status?taskId='taskId'" \ -H "x-api-key: $KERNLIFT_API_KEY" ``` `$SCENE` is a scene code from **Scene routing**. The first call needs **Run AI tasks**, the second **Read AI task status**, and `POST /api/assets/upload` needs **Upload files**. Calls run as the key's owner and spend the owner's credits. `GET /api/openapi.json` serves an OpenAPI 3.1 document for these endpoints. ## Set rate limits for all keys ### Open Rate Limits In the admin console, go to **Platform → Rate Limits** (`/admin/rate-limits`). ### Choose the backend **Rate limit backend**: **Memory** counts requests inside each server process. Choose **Redis** when several instances serve the API, and enter **Redis URL** (for example `redis://default:password@host:6379`). If Redis cannot be reached, the request is counted in memory. Switching back to **Memory** clears the saved URL. ### Set the defaults **Default limit (req/sec)** and **Default window (sec)** apply to any endpoint without its own rule. Limits range from 1 to 10,000 and windows from 1 to 3,600 seconds. ### Set the API rules **API rules** has one row each for **AI generate** (`/api/{scene}/generate`), **AI status** (`/api/status`) and **Asset upload** (`/api/assets/upload`). Set **Limit (req)** and **Window (sec)** per row, then click **Save configuration**. API rules apply to every key on those three endpoints and take precedence over the limit a user picks when creating a key. That per-key limit applies to the other key-authenticated endpoints. ## Give one key different limits ### Find the key Go to **Platform → API Keys** (`/admin/api-keys`). **Key inventory** lists every user's keys, masked, with owner, status, expiry, **Last used** and usage event count. Filter with **Search** and **Status**, then click **Apply**. ### Edit its rules Click **API rules** on the row. **API key default** sets the key's own limit and window. Each endpoint row shows the value it currently inherits and lets you set a **Rate limit** and **Window** for this key alone. ### Save Click **Save**. Every row in the dialog is stored for that key, so later changes on **Rate Limits** no longer reach it. ## Revoke a key On `/app/api-keys`, click **Revoke** on the key's row, type the key name and click **Confirm revoke**. Requests with that key fail immediately. Operators cannot create or revoke a user's key, but a banned user's keys stop working until the ban is lifted. ## Verify Call the status endpoint without a `taskId`: ```bash curl -i "https://your-domain.example/api/status" \ -H "Authorization: Bearer $KERNLIFT_API_KEY" ``` * `400` with `taskId is required.`: the key works. * `401` `invalid_api_key`: the key is wrong, revoked or expired, or its allowed origins reject the request. * `403` `insufficient_scope`: the key lacks **Read AI task status**. * `429` `rate_limited`: a limit was hit. Wait for the window to pass. Each attempt appears as accepted or rejected on **Usage stats** (`/app/api-keys/usage`). `pnpm validate:api-keys` checks the key inventory, scopes and the verification limit. ## Troubleshooting ### A request returns `insufficient_scope` The key lacks the scope the endpoint requires. For example, a key with only the default scopes cannot call `POST /api/assets/upload`. Keys cannot be edited, so create a new key with the needed scope. ### Limits reset or differ between servers The **Memory** backend keeps counters in each server process. On **Rate Limits**, set **Rate limit backend** to **Redis** and fill in **Redis URL** so all instances share counters. ### A route ignores the key and asks for a session Some endpoints accept sessions only: `/api/chat`, `/api/chat/conversations` and `/api/billing/checkout`. ### Many `rate_limited` responses from one IP Independently of the limits above, key verification is capped at 120 attempts per 60 seconds for each key prefix and client IP, which slows down guessing. Spread the calls out or stop sending invalid keys. ## Reference * [Rate limits](https://kernlift.dev/docs/core/admin/rate-limits.md) * [Bearer authentication](https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication) ## Next steps - [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md) - [Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md) --- # Authentication and authorization model > Where identity is read, how access is decided at each boundary, and why there is no fallback user. Source: https://kernlift.dev/docs/core/auth Authentication establishes who is calling. Authorization determines whether that caller may perform an action. Kernlift keeps both in one directory, checks them at more than one layer, and has no fallback identity. To set up sign-in methods and roles, see [Set up email and password sign-in](https://kernlift.dev/docs/extensions/auth/email-password.md) and [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). ## One place reads a session `src/server/auth/` is the only code allowed to read a Better Auth session. It has three parts: | File | Decides | Main exports | | ----------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `context.ts` | Who the caller is | `requireAuthContext()` (the default, throws without identity), `getAuthContext()` (returns `null`, for genuinely optional-identity paths) | | `guards.ts` | Whether the caller may act | `requirePermission`, `requireOwnership`, `requireNotBanned`, `hasPermission` | | `api-boundary.ts` | How an API handler authenticates | `withApiAuth`, which accepts a session or, when the route opts in, an API key with a named scope | An `AuthContext` carries `userId`, `roles`, `permissions`, `status`, `sessionId`, `apiKeyId` and `source`. The source is `session`, `api-key` or `dev-impersonation`. Better Auth itself is built in `auth.ts` from settings stored in the admin console, and mounted at `/api/auth/*` for OAuth callbacks and the password reset link. Because Google and GitHub credentials are read per request, saving them needs no restart. ## There is no identity fallback An unauthenticated caller is rejected. No code path maps it to a default user. The only exception is a development sign-in bypass, and it requires both `APP_ENV=development` and an explicit `AUTH_DEV_IMPERSONATE_USER_ID`. Either one alone has no effect, and the server logs a warning the first time the bypass applies. ## Access is checked in layers A request to a protected page passes several checks. Each check alone is enough to reject it. | Layer | Where | What it checks | | ------------------ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------- | | Request middleware | `src/start.ts` | Page requests for `/app/*` and `/admin/*` without a session cookie go to `/auth/sign-in` | | Workspace layout | `app.tsx` | A banned user goes to `/system/permission-denied`; missing identity or an inactive account goes to `/system/session-expired` | | Admin layout | `admin.tsx` | Requires `admin.access`; missing identity goes to `/system/session-expired`, a missing permission to `/system/permission-denied` | | Server function | `requireAdminPermission` | Each admin function checks its own permission key, so a page is never the only gate on its data | | API route | `withApiAuth` | Session or scoped API key; otherwise the route must be on the explicit public list | Guarding at the layout level means a new page under `/app` or `/admin` is protected by default. ## Roles, permissions and status Roles, permissions and status are resolved together from the user's access profile, role assignments and each role's permissions. Profiles are written only when an operator changes a user's access, so a user without one resolves to `active`. | Status | Effect | | --------- | --------------------------------------------------------------------------------------------------------------- | | `active` | Normal access, subject to permissions | | `banned` | Rejected by every guard; a session is refused at creation. A ban whose end date has passed resolves to `active` | | `pending` | Not active, so workspace and admin guards reject it | `requirePermission` and `requireOwnership` both call `requireNotBanned` first, so an inactive account fails before any permission check. Roles group permission keys; see [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). ## Ownership hides existence Owner-scoped reads include the caller's id in the query. A record belonging to someone else is then indistinguishable from one that does not exist, so an endpoint cannot be used to probe for other people's data. Where a record's existence is sensitive, the route answers 404 rather than 403, as `/api/status` does for another user's task. ## Public endpoints are listed, with reasons Every API route either uses `withApiAuth` or appears in an explicit public-endpoint list with a stated reason. Provider webhooks and signed-grant redemption are on that list: they authenticate by signature or by an unguessable credential. ## API keys and scopes API keys are hashed at rest, shown once, and carry scopes: `ai:run`, `ai:read`, `files:write` and `files:read`. Users can put `ai:run`, `ai:read` and `files:write` on their own keys. `files:read` is reserved. With the agent installed, operators can also issue keys with `agent:read` and `agent:run`. ## Sign-in rate limit The `auth.sign-in` rule allows 10 attempts per 300 seconds per IP and email. It is part of the baseline content that `pnpm db:bootstrap-super-admin` writes, and each decision is recorded in the audit log. A blocked caller lands on `/system/rate-limited`. ## How this is enforced `pnpm validate:auth-boundary` checks that sessions are read only in `src/server/auth/`, that the layouts guard their trees, that there is no identity fallback, that impersonation is double-gated, that production refuses the template session secret, and that every API route uses `withApiAuth` or is listed as public. ## Files - The only place a session is read/ - src/server/auth/context.ts - src/server/auth/guards.ts - src/server/auth/api-boundary.ts - src/server/auth/auth.ts - Where the guard runs/ - src/routes/{-$locale}/app.tsx - src/routes/{-$locale}/admin.tsx ## Next steps - [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md) - [Issue API keys and set rate limits](https://kernlift.dev/docs/core/auth/api-keys.md) --- # Manage users, roles and permissions > Each teammate holds a role with only the permissions their job needs, and you can suspend or ban any account. Source: https://kernlift.dev/docs/core/auth/roles Access is role based. A user holds roles, and each role grants permission keys. Opening `/admin` needs `admin.access`. Every admin page then checks its own permission, so a teammate's roles determine which pages they see. ## Before you begin * A first administrator created with `pnpm db:bootstrap-super-admin`. See [First steps after install](https://kernlift.dev/docs/customize/first-steps.md). * To create roles you need `roles.write`. To assign roles or change a user's status you need `users.write`. * The full permission catalog, with a description of each key, is at `/admin/permissions`. ## Create a role As a rule, a `.read` permission opens a page and the matching `.write` permission allows changes on it. ### Open the role form Go to **Operations → Roles** (`/admin/roles`) and open the **Add role** tab. ### Start from a preset (optional) Under **Sidebar role presets**, click a preset to fill the form. The presets are **Admin Overview**, **Admin Operations**, **Commerce Manager**, **Platform Operator**, **Content Manager**, **Security Manager** and **Settings Manager**. Roles with the same keys already exist and can be assigned directly. ### Describe the role Fill in **Key** (a stable identifier such as `support.lead`), **Name** and **Description**. All three are required. ### Pick the permissions Under **Permissions**, tick the permissions to grant. They are grouped by sidebar area: **Overview**, **Operations**, **Commerce**, **Platform**, **Content**, **Security**, **Settings** and **Other**. Always include **admin.access**. ### Save Click **Save role**. To change a role later, open the **Roles & users** tab and click **Edit** on its row in **Role directory**. **Delete** works only while no user holds the role. The full catalog with descriptions is at `/admin/permissions` (**Permission catalog**, no sidebar entry). ## Assign roles to a user ### Find the user Go to **Overview → Users** (`/admin/users/dashboard`), find the user and click their name or **Details**. ### Check the status Under **Access**, **Status** must be **Active**. A pending or banned user gets no permissions from any role. ### Choose the roles In the **Roles** card, click **Roles**. In the **Update user roles** dialog, tick the roles to grant and untick the ones to remove, then click **Save roles**. Users who already hold a role also appear under **Role users** on `/admin/roles`, where **Update roles** opens the same dialog. ## Suspend or ban a user ### Open the user On **Overview → Users**, click **Details** on the user. ### Set the status Set **Status** to **Active**, **Pending** or **Banned**. For a ban, add an optional **Ban reason** and **Ban expires** date. ### Save Click **Save**. The page confirms the change and records it in the audit log. A banned user cannot sign in, their pages send them to `/system/permission-denied`, and their API keys stop working. Once **Ban expires** has passed, the account is treated as active again. A pending user is sent to `/system/session-expired`. **Changes apply without signing out** Role and status changes take effect on the user's next page load. The user does not need to sign in again. ## Verify Sign in as the user in a private window. The sidebar shows only the pages their roles allow, and a page opened by URL without its permission shows `Permission denied: `. **Security → Audit** (`/admin/audit`) lists the status change. From the command line, `pnpm validate:users` checks role saving, assignment and status changes. ## Troubleshooting ### `/admin` redirects to `/system/permission-denied` The user lacks `admin.access`. Assign a role that includes it, or run `pnpm db:bootstrap-super-admin` for the first administrator. ### A page shows `Permission denied: ` The user can open the console but lacks the permission that page checks. The dashboard at `/admin` needs four: `admin.dashboard.read`, `users.read`, `credits.read` and `ai.read`, so a narrow role sees this error there. ### A user with the right role still has no access Their **Status** is pending or banned. Set it to **Active** on the user's page. ### A new permission does not reach the Super Admin Role permissions are written when `pnpm db:bootstrap-super-admin` runs. Run it again after an upgrade that adds permissions. ## Reference * [Users and accounts](https://kernlift.dev/docs/core/auth/users.md) * [Better Auth](https://better-auth.com/docs) ## Next steps - [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md) - [Run the admin console](https://kernlift.dev/docs/core/admin.md) --- # Users and accounts > Find an account, read what it holds, assign roles, ban and restore, and repair a credit balance. Source: https://kernlift.dev/docs/core/auth/users On `/admin/users/dashboard` an operator looks up one account: what it bought, what it holds, and why it cannot sign in. The page is not a CRM. It has no free-text notes about a customer and shows only the rows the product wrote. ## Before you begin * `users.read` to open the directory and a detail page, `users.write` to change a status, and `roles.write` to change which roles an account holds. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). * The three permissions are separate so that you can grant them independently. Support staff usually need the first, rarely the second, and not the third. ## Set it up ### Open the directory `/admin/users/dashboard` lists accounts with their status and roles. Search by name or e-mail. ### Open one account `/admin/users/$userId` shows the account's roles, its access profile status, its licences, its credit balance and its recent activity. These are the same rows the customer sees at `/app`, read from the same repositories. ### Ban or restore A banned account keeps its rows and loses its session. The guards reject it at the layout, so every `/app` and `/admin` page is blocked without a per-page check. Restoring the account lifts the ban. No data is deleted in between. ### Repair a credit balance If the ledger and the cached balance disagree, `adminRepairUserCreditBalance({ userId })` recomputes the balance from the ledger entries. It is the button on the detail page and requires `credits.write`. Users cannot call it, and no self-service path writes a balance. ## Account status Authorization is enforced in `users-rbac.ts` by each server operation through `requireAdminPermission`. Being able to see the page does not grant permission to act. ## Verify 1. Open `/admin/users/dashboard` with a role that has only `users.read`. The list renders and the ban action is rejected. 2. Ban an account, then try to open `/app` as that account. The layout rejects it, so no `/app` page opens. 3. Restore it. The same account signs in again with its licences and credits intact. 4. Add a role to an account and reload its detail page. The permission list is the union of its roles. ## Reference * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [Authentication](https://kernlift.dev/docs/core/auth.md): where identity is resolved * [Better Auth: users and accounts](https://better-auth.com/docs/concepts/users-accounts) ## Next steps - [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) Define the roles this directory assigns. - [Credits](https://kernlift.dev/docs/extensions/credits/usage.md) Grant, deduct and repair a balance from the ledger. - [Audit log](https://kernlift.dev/docs/core/admin/audit-log.md) Every status and role change is recorded. --- # Background jobs > How the web app runs its own periodic work once a minute on every platform, why one lock row is enough, and how /setup detects when it stopped. Source: https://kernlift.dev/docs/core/background-jobs The web app has work that no request triggers: retrying a failed fulfilment, finishing an AI task nobody is polling. That work is in one function, `runScheduledJobs()`, which runs one round of every job. Platforms differ only in what calls it. To check your own deployment, see [Run background jobs](https://kernlift.dev/docs/core/background-jobs/run.md). ## One round, a fixed list of jobs A round runs the jobs in order. A job that throws is recorded as failed and the next one still runs. | Job | Does | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | | `credit-sweep` | An extension point. The template's ledger has nothing to expire or top up, so it reports zero; a project that adds expiring credits implements it here | | `billing-fulfilments` | Retries fulfilments that failed when an order was paid or refunded, with backoff | | `ai-channel-tasks` | Advances asynchronous provider tasks nobody is polling, so they finish and settle credits | | `agent-maintenance` | With `agent-starter` only: gives a Cloudflare agent container with unfinished runs one maintenance round. Does nothing for an agent service reached by URL | These jobs belong to the web app, not to the Agent service. A deployment without the agent runs every one of them except `agent-maintenance`, and the agent service's own loop runs none of them. ## Three ways a round starts | Deployment | Trigger | Switch | | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------- | | Node server (Fly.io, Railway, Docker, a VPS, `pnpm dev`) | A loop inside the web process: first round five seconds after start, then one every minute | `JOBS_IN_PROCESS`, on by default | | Cloudflare Worker | The Cron Trigger `"crons": ["* * * * *"]` in `wrangler.jsonc`, handled by `scheduled` in the Worker entry | The `triggers` block | | Any | `pnpm jobs:run` from a system cron, a Kubernetes CronJob or a platform scheduler | Your scheduler | The Node build starts the loop when the server process loads, so a fresh deployment with no traffic still retries fulfilments. `pnpm dev` does not evaluate the server entry, so there the loop starts with the first request. A Worker is not a long-running process and may not hold a timer, so the loop never starts there. Setting `JOBS_IN_PROCESS=false` turns the loop off and leaves scheduling to `pnpm jobs:run`. ## One lock row keeps it to one round a minute Triggers are allowed to overlap: every replica runs the loop, and a cron may fire next to it. The lock is a single row in `config_settings`, `jobs.next_run_at`, holding an ISO timestamp. 1. A runner claims the round with a conditional update: move `jobs.next_run_at` forward only if it is not in the future. Exactly one caller's update changes the row. The others see zero rows updated and return `"skipped"`. 2. The claim pushes the timestamp five minutes ahead. If the runner dies mid-round, the lock expires after that. 3. When the round ends, `jobs.next_run_at` is set to one minute after the round started, `jobs.last_run_at` to the finish time and `jobs.last_report` to the round's JSON report. The comparison is a string comparison of ISO timestamps, which orders the same way on SQLite, D1 and Postgres, and the claim is one statement, so it needs no transaction. ## The heartbeat on /setup `/setup` stores no status flag for jobs. It reads `jobs.last_run_at` and `jobs.last_report` each time and evaluates them: | State | `/setup` shows | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | | No round recorded | Not ready. A new deployment records its first round within a minute; if the message stays, nothing is starting them | | Last round more than five minutes ago | Not ready, with how long ago it ran | | Last round had a failed job | Not ready, with each failed job's name and error | | Last round recent and clean | Ready | Every message ends with how rounds are started on the platform in `deploy.config.json`: the Cron Trigger on Cloudflare, `min_machines_running = 1` on Fly.io, the web service on Railway, the web container on Docker. The item has no admin page to link to, because it is fixed in the platform. ## Files - The round/ - src/server/jobs/scheduled.ts - src/server/jobs/credit-sweep.ts - src/server/db/repositories/scheduled-jobs.repository.ts - Triggers/ - src/server/jobs/in-process.ts - src/server-entry.ts - src/server-entry.node.ts - scripts/jobs/run.ts - Heartbeat/ - src/server/jobs/heartbeat.ts - src/server/functions/setup-readiness.ts `pnpm validate:optional-agent` runs rounds against the configured database and asserts the lock: a second call inside the minute skips, two concurrent calls run one round, and a crashed runner's lock is taken over. ## Next steps - [Run background jobs](https://kernlift.dev/docs/core/background-jobs/run.md) Check your platform, run a round by hand, read the warning. - [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md) The fulfilment retries these rounds perform. - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) Why each platform starts rounds differently. - [Environment variables](https://kernlift.dev/docs/reference/env.md) `JOBS_IN_PROCESS`. --- # Run background jobs > Make sure the scheduled jobs run on your platform, run a round by hand, and act on the warning /setup shows when they stop. Source: https://kernlift.dev/docs/core/background-jobs/run Fulfilment retries and unfinished AI tasks are handled by a round of scheduled jobs that should run once a minute. On most deployments it already does. This guide confirms that, shows how to run a round yourself, and explains what to do when `/setup` reports that rounds have stopped. For how the lock and the heartbeat work, see [Background jobs](https://kernlift.dev/docs/core/background-jobs.md). ## Before you begin * A deployed project, or a local one with a migrated database. * An admin account with `config.read` to open `/setup`. * The platform the project deploys to, from the `platform` field in `deploy.config.json`. See [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md). ## Make sure rounds run on your platform ### Find your trigger | Platform | What starts a round | What to check | | ---------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | | Cloudflare | The Worker's Cron Trigger | `wrangler.jsonc` keeps `"triggers": { "crons": ["* * * * *"] }` and the deployed Worker lists the trigger | | Fly.io | A loop inside the web process | `fly.toml` keeps `min_machines_running = 1`; a stopped machine runs nothing | | Railway | A loop inside the web service | The web service is running | | Docker | A loop inside the web container | The container is up: `docker compose ps` | | Local | The same loop, started by the first request to `pnpm dev` | Open any page once | On the Node platforms the loop is on unless `JOBS_IN_PROCESS=false` is set. ### Decide whether to use an external cron Keep the in-process loop unless you have a reason to move scheduling out of the web process, for example web machines that scale to zero. In that case set `JOBS_IN_PROCESS=false` in the web app's environment and have your scheduler run this once a minute, with the same database variables as the web app: ```bash pnpm jobs:run ``` Running both the loop and a cron is safe. A lock row lets one runner take each round and the others skip. ### Run a round by hand From a checkout whose `.env` points at the database you want to act on: ```bash pnpm jobs:run ``` It prints the round's report and exits non-zero when a job failed: ```json { "startedAt": "2026-11-17T08:00:00.000Z", "finishedAt": "2026-11-17T08:00:00.412Z", "jobs": [ { "name": "credit-sweep", "ok": true, "counts": { "expiredUsers": 0, "granted": 0 } }, { "name": "billing-fulfilments", "ok": true, "counts": { "attempted": 0, "succeeded": 0 } }, { "name": "ai-channel-tasks", "ok": true, "counts": { "polled": 0 } } ] } ``` If it prints `"skipped"`, another runner took the round within the last minute. This is expected. Wait a minute and run it again. A project with `agent-starter` installed has a fourth job, `agent-maintenance`. ## Read the warning on /setup Open `/setup` and find the scheduled-jobs item. The page evaluates it from the last recorded round on every load. | The item says | Meaning | Do | | ------------------------------------------------------ | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | | No scheduled round has been recorded | Nothing has run since the database was created | On a new deployment wait a minute. If it stays, the trigger in the table above is missing | | The last scheduled round ran N minutes ago | More than five minutes without a round | Check the trigger for your platform; the message names it. Fulfilment retries and AI task polling wait until rounds resume | | The last round had failures | A job threw | Read the job name and error in the message, fix the cause, then run `pnpm jobs:run` and read that job's result | | Last round less than a minute ago, every job succeeded | Rounds are running | Nothing | A failed job does not stop the other jobs in the round, and it is tried again in the next round. ## Verify rounds are running * `/setup` shows the scheduled-jobs item as ready, with a last round at most a few minutes old. * Reload `/setup` two minutes later. The time of the last round has advanced. * In `config_settings`, `jobs.last_run_at` holds a recent ISO timestamp and `jobs.last_report` the report of that round. * `pnpm validate:optional-agent` passes. Before a release, `pnpm smoke:node` (after `pnpm build:node`) or `pnpm smoke:worker` (after `pnpm build`) starts the built app on a throwaway database and checks that a round is recorded. ## Next steps - [Background jobs](https://kernlift.dev/docs/core/background-jobs.md) The lock, the heartbeat and the list of jobs. - [Write a fulfilment plugin](https://kernlift.dev/docs/extensions/payments/fulfilment.md) The retries these rounds perform. - [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md) The AI tasks a round advances. - [Environment variables](https://kernlift.dev/docs/reference/env.md) `JOBS_IN_PROCESS` and the database variables `pnpm jobs:run` reads. --- # Configuration model > Why a few settings live in environment variables and everything else lives in the database, edited in the admin console. Source: https://kernlift.dev/docs/core/configuration Kernlift keeps settings in two places. A handful of environment variables start the app and connect it to the database. Everything else, including every provider credential, is stored in the database and edited in the admin console. To change settings, see [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md). ## The rule | Setting | Where it goes | Why | | --------------------------------------------------------------- | ------------------------------------------------------ | -------------------------------------------------- | | App environment, session secret, database connection, site URL | `.env` or your host's environment | Needed before the app can read the database | | Sign-in methods, email, payments, storage, AI, analytics, cache | Admin console, `/admin/config/*` | Stored in the database, changed without a redeploy | | Products, plans and licences | Admin console, `/admin/products` and `/admin/licences` | Business data, not configuration | The split follows startup order. Anything the process needs before it can open the database comes from the environment. Everything else is stored in the database and managed by the operator. ## Why provider settings are not environment variables * **No redeploy to change a provider.** Rotating a key, switching the active email provider or turning on Google sign-in takes one save in the admin console. * **One source of truth.** The `/setup` checklist, the admin pages and the runtime all read the same rows, so the page reports the configuration the server uses. * **A forkable template.** A project built on the template adds provider settings to the admin surface and adds no environment variable. Feature code does not read `process.env`. ## The environment variables A local project needs only `BETTER_AUTH_SECRET`, which you set in the [quick start](https://kernlift.dev/docs/quick-start.md). Production sets these: | Variable | Role | | ----------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | | `APP_ENV` | `development` or `production`. Production enables stricter checks | | `BETTER_AUTH_SECRET` | Signs sessions. Production refuses to start with the template default | | `CONFIG_ENCRYPTION_KEY` | Optional, strongly recommended. Encrypts the credentials stored in the database; see [Encrypt stored credentials](#encrypt-stored-credentials) | | `DATABASE_DIALECT` | `sqlite`, `postgres` or `d1` | | `DATABASE_ADAPTER` | Optional adapter id such as `turso` or a custom adapter. Defaults to the dialect | | `DATABASE_URL` | File path or connection string | | `SITE_URL` | Canonical origin for metadata, the sitemap, the feed and email links | `.env.example` lists every variable the source reads, and `pnpm validate:env-example` keeps the two in step. Every variable is described in [Environment variables](https://kernlift.dev/docs/reference/env.md). ## The admin settings pages | Page | Covers | | ------------------------- | ---------------------------------------------------------------------------------------------------------- | | `/admin/config/auth` | Email and password rules, Google and GitHub OAuth, Google One Tap, the sign-up bonus | | `/admin/config/email` | Resend, Cloudflare Email or Aliyun DirectMail, and notification webhooks | | `/admin/config/payment` | Stripe, Creem, PayPal, DodoPayments, WeChat Pay, Alipay or Waffo, success and cancel URLs, promotion codes | | `/admin/config/storage` | S3-compatible storage and allowed upload types | | `/admin/config/ai` | AI providers, provider scenes, scenes and credit pricing | | `/admin/config/analytics` | Analytics provider | | `/admin/config/cache` | Cache enable, TTL and backend per domain | | `/admin/config/sandbox` | Agent sandbox provider, image and resource limits; installed with `agent-starter` | | `/admin/config/search` | Agent search and crawl services; installed with `agent-starter` | Newsletter, notification channels and rate limits have separate admin pages. The complete route and permission map is in [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md). ## "Not configured" is a state, not an error A provider without credentials reports "not configured" and does not run. The template never fakes a provider response, simulates a payment or invents usage data. `/setup` turns those states into a checklist: each item is **Ready** or **Not ready**, and **Configure** links to the page that fixes it. Only the session secret, a sign-in method and email delivery are required. ## Encrypt stored credentials Credentials live in the database, so a leaked backup, read replica or database console would expose them. Set `CONFIG_ENCRYPTION_KEY` (at least 32 characters) in the environment of every process that reads the config table, the web app and, when deployed, the Agent service, and every setting classified `secret` is encrypted at rest: * **What is encrypted.** Values classified `secret`: payment, email, storage, AI and OAuth credentials. They are written as `enc:v1::` with AES-256-GCM, the key derived with HKDF-SHA-256 and the setting key bound as additional data, so a ciphertext cannot be moved to another row. `public` and `internal` values stay plaintext. * **Existing credentials.** A credential saved before the key was set stays plaintext until it is saved again. Run `pnpm db:encrypt-config-secrets` once to encrypt them all; on D1 add `--remote` for the deployed database. A second run changes nothing. * **A wrong or missing key.** A value that cannot be decrypted reads as not configured, never as ciphertext, and seeding never overwrites it, so restoring the right key restores the credential. * **Caches.** Cache domains that hold decrypted credentials always use process memory; KV or Redis cannot be chosen for them on `/admin/config/cache`. * **Readiness.** `/setup` has a **Credential encryption** item. It reports a missing or too short key, plaintext credentials left over and credentials that cannot be decrypted; only the last makes it required. Without the key, credentials are stored as plaintext and everything else behaves the same, which suits local development. `kernlift deploy-target` generates the key into `.env.production`. Keep the key stable: there is no rotation, and changing or losing it means entering every credential again. ## How settings are read Most configuration reads are cached. Saving through the console clears the relevant domain. A direct database edit may remain unseen until its TTL expires. The bootstrap `admin_config` cache cannot read its own policy from the table it caches, so its TTL comes from `ADMIN_CONFIG_CACHE_TTL_MS`. `/admin/config/cache` marks that domain as not configurable. ## Variables outside the application The `KERNLIFT_*` variables at the end of `.env.example` are read only by the registry publishing script and the CLI's package commands. The application never reads them, and a project cloned from GitHub can leave them unset. ## Files - Storage and cache/ - src/server/db/repositories/admin-config.repository.ts - src/server/config/config-encryption.ts - scripts/db/encrypt-config-secrets.ts - src/server/platform/cache-policy.ts - The pages/ - src/routes/{-$locale}/admin/config - src/components/admin/config-layout.tsx The pages use shared console patterns, but their data is not all stored alike: ordinary provider settings use classified `config_settings` rows, AI channels and pricing use dedicated tables, and Agent search uses JSON rows classified as `secret`. ## Next steps - [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) The task version of this page. - [Cache](https://kernlift.dev/docs/core/admin/cache.md) How long a setting is held before a read sees your change. - [Environment variables](https://kernlift.dev/docs/reference/env.md) The short list that stays outside the database. - [First steps after install](https://kernlift.dev/docs/customize/first-steps.md) What /setup asks you to configure first. --- # Configure a working project > Set startup variables, make sign-in and email work, then connect and verify the providers your product uses. Source: https://kernlift.dev/docs/core/configuration/project For a new deployment, first make sure the app starts, an administrator can sign in, and verification email is delivered. Enable payments, files, AI and other integrations only when your product needs them. A page being present does not mean its provider is ready. ## Before you begin * Migrate the database, obtain access to the runtime environment, and sign in as an administrator. If no administrator exists, follow [Start the admin console](https://kernlift.dev/docs/core/admin.md). * Have test or sandbox accounts for the providers you intend to use. Provider credentials belong in the admin console, not `.env`. See [Environment variables](https://kernlift.dev/docs/reference/env.md) for the startup list. ## 1. Set the startup environment Use `.env.example` as a checklist. Set `APP_ENV`, `BETTER_AUTH_SECRET`, `SITE_URL` and the database connection in local `.env` or your hosting platform. In production, generate a fresh `BETTER_AUTH_SECRET`; do not use the template value: ```bash node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" ``` In production, also set `CONFIG_ENCRYPTION_KEY` to a value of at least 32 characters, generated the same way, so the provider credentials you enter next are encrypted in the database. Keep it stable once set. If credentials were saved before you set it, run `pnpm db:encrypt-config-secrets` once. See [Encrypt stored credentials](https://kernlift.dev/docs/core/configuration.md). Restart the app after changing environment variables, then run `pnpm db:migrate` and confirm the migrations complete. See [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md) for dialects and Workers bindings. ## 2. Keep a working sign-in method Open **Auth Config** in the admin console. Email/password sign-in is enabled by default. If you turn it off, configure and test Google or GitHub first so users retain a way to sign in. Set verification, sign-up and account-deletion policies as needed. For social sign-in, register the callback URL shown by the page with the provider before saving its client ID and secret. Sign out and test sign-in and new-account registration. See [Email/password sign-in](https://kernlift.dev/docs/extensions/auth/email-password.md) and [Social sign-in](https://kernlift.dev/docs/extensions/auth/social.md) for fields and callback steps. The session-signing `BETTER_AUTH_SECRET` is an environment variable and does not appear on this page. ## 3. Deliver a real email In **Email Config**, select Resend, Cloudflare or Aliyun, enter credentials and a verified sender, enable the provider and save. Complete sender-domain verification at the provider first. Then use **Email → Test send** and confirm success in delivery history. Test registration verification or password reset as well. A successful save confirms that the settings were stored. It does not confirm that mail was delivered. If delivery fails, check the sender domain, credential and provider error in the delivery record. See [Email](https://kernlift.dev/docs/extensions/email.md) for fields and templates. ## 4. Enable only the capabilities you use Configure each integration when needed, and complete its end-to-end check before moving on: | Capability | Configure | Confirm | | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Checkout and subscriptions | Enter sandbox credentials, return URLs and webhook secret in Payment Config; create at least one active plan in **Plans** (`/admin/plans`) | Complete a sandbox checkout. An order changes state only after a signed webhook or server-side provider confirmation. See [Payment providers](https://kernlift.dev/docs/extensions/payments/setup.md) | | Uploads or Agent artifacts | Choose S3-compatible storage or an R2 binding; set the bucket, credentials, size and content-type limits | Upload an allowed file and download it as its owner. See [Storage](https://kernlift.dev/docs/extensions/storage.md) | | AI tasks or Agent models | Create a channel and provider scene; set credentials, model, scene route and pricing | Run a test task, confirm a real provider result and recorded usage. See [AI providers](https://kernlift.dev/docs/extensions/ai/providers.md) and [Scenes](https://kernlift.dev/docs/extensions/ai/scenes.md) | | Analytics and support chat | Set script IDs; add a server-side access token if reports are needed | Confirm the script loads and records a test event; check report pulling separately. See [Analytics](https://kernlift.dev/docs/extensions/analytics.md) | | Agent sandbox and web research | Install `agent-starter`; configure object storage and AI before sandbox, SearXNG and crawl4ai connections and limits | Test search and crawl separately, then run a workbench task using those tools. See [Agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) | Caching works with its defaults. If you need to change it, use **Cache Config** to set enablement, TTL and an available backend per domain. Turn off Enabled to bypass a cache; a zero TTL is not accepted. See [Cache](https://kernlift.dev/docs/core/admin/cache.md). Newsletter, notifications, pricing plans and API-key rate limits have their own business pages; see [Run the admin console](https://kernlift.dev/docs/core/admin.md) for where each one lives. ## Confirm readiness Open `/setup`. Session secret, sign-in method, email delivery and scheduled jobs are required; the page also reports optional payment, storage, AI, newsletter and analytics readiness, and **Credential encryption**, which becomes required when stored credentials cannot be decrypted. It does not check cache, Agent sandbox or search, so complete the functional tests above. Do not infer provider readiness from whether a page opens. ## Troubleshoot * **The app will not start or rejects the session secret:** Check `APP_ENV` and `BETTER_AUTH_SECRET`, then restart. Production rejects an empty or template secret. * **A setting saved, but the capability is not ready:** Check the page's status and test result, then inspect the provider error. Saving and connecting are separate checks. * **AI Config appears in the menu but will not load:** The sidebar uses `config.read`, while the page requires `ai.read`; saving requires `ai.write`. * **A module's pages or menu entries are gone:** Check **Plugins** (`/admin/plugins`); a disabled plugin hides its entries and its pages return not found. * **`/setup` reports that scheduled jobs are not running:** Fix this on the deployment platform. See [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md). * **A change seems stale:** Console saves usually clear their cache domain. A direct database edit may need a TTL expiry or manual clear. See [Cache](https://kernlift.dev/docs/core/admin/cache.md). --- # Data access > How business code reaches the database: repositories only, one contract over SQLite, D1 and Postgres, what a transaction means on each, and why migrations are kept per dialect. Source: https://kernlift.dev/docs/core/data-access Kernlift runs on SQLite, Cloudflare D1 and Postgres from the same business code. All database access goes through `src/server/db/repositories/*`, and everything that differs between databases stays in the schema, migration and adapter layers underneath. To switch databases, see [Use Postgres](https://kernlift.dev/docs/extensions/database/postgres.md). ## Repositories are the only door Server functions, services and API routes call repository functions. They do not import Drizzle tables, write SQL or branch on a dialect. A repository gets its database through `withRepositoryDialect`, which passes it three values: | Value | What it is | | --------- | ----------------------------------------------------------------------------------- | | `db` | The Drizzle database of the active adapter | | `schema` | The table definitions for that database: `schema/postgres.ts` or `schema/sqlite.ts` | | `dialect` | `"postgres"`, `"sqlite"` or `"d1"` | Both schema files define the same tables with the same names and columns, so a repository writes one query against `schema.billingOrders` and it runs on either. Where a column's storage differs, most often a timestamp, the repository converts at that one point by checking `dialect`. Agent tables follow the same pattern in `agent-sqlite.ts` and `agent-postgres.ts`. ## Two schema families, five adapters The adapter determines how the app connects. The schema family determines the SQL it runs. | Adapter | Schema family | Runs on | Connection | | ------------ | ------------- | ------------------ | ---------------------------------------------------- | | `sqlite` | SQLite | Node | A local file through `better-sqlite3` | | `turso` | SQLite | Node | libSQL with `DATABASE_URL` and `DATABASE_AUTH_TOKEN` | | `d1` | SQLite | Cloudflare Workers | The `EDGE_DB` binding | | `postgres` | Postgres | Node | `DATABASE_URL`, one client per process | | `hyperdrive` | Postgres | Cloudflare Workers | The `HYPERDRIVE` binding, one client per request | `DATABASE_ADAPTER` selects one and defaults to `DATABASE_DIALECT`. You can register your own for either family. See [Write a custom database adapter](https://kernlift.dev/docs/extensions/database/custom-adapter.md). A Worker may not reuse a socket that was opened while handling another request. The `hyperdrive` adapter therefore creates its Postgres client inside a per-request scope. The Worker entry wraps each request and each scheduled event in `runInRequestScope`, and the client lives as long as that scope. Hyperdrive pools the real connections behind it. On Node there is no scope and the `postgres` adapter keeps one client. ## What a transaction means on each database Repositories are written once, with async transaction callbacks: `db.transaction(async (tx) => { ... })`. What happens underneath depends on the database. | Database | Behaviour | | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Postgres, Hyperdrive, Turso | The driver runs the callback as an interactive transaction | | SQLite (`better-sqlite3`) | The driver is synchronous and rejects an async callback, so the repository facade runs it as a real transaction on the same connection: `BEGIN IMMEDIATE`, then `COMMIT`, or `ROLLBACK` with the original error. Transactions in one process run one at a time, in order, and a nested call joins the open one | | D1 | No interactive transactions. The repository context reports `d1`, and code that would open a transaction runs the same statements one by one instead | On SQLite a transaction callback should do database work only and stay short, because other queued work in the process can run between its statements. On D1 a multi-step write is not atomic, so it must be safe to repeat or to stop halfway. For the same reason the Agent, which needs transactions for its runs, does not use D1. Where one statement is enough, the code uses one. The scheduled-jobs lock is a single conditional update and the fulfilment claim is a single insert under a unique key, so both behave the same on all three databases. ## Migrations are kept per dialect There are two migration chains, one per schema family, with the same file names: | Chain | Used by | Applied with | | ----------------------------- | -------------------- | ------------------------------------------------------------------------------------ | | `drizzle/migrations/sqlite` | SQLite, Turso, D1 | `pnpm db:migrate`; `pnpm db:migrate:d1:local` and `pnpm db:migrate:d1:remote` for D1 | | `drizzle/migrations/postgres` | Postgres, Hyperdrive | `pnpm db:migrate`, or `pnpm db:migrate:runtime` in a production image | The chains are maintained by hand. A schema change means editing both schema files and adding a migration with the same name to both chains. `pnpm db:generate:sqlite` and `pnpm db:generate:postgres` produce a first draft for each. `pnpm validate:migrations` then checks that the two chains agree: the journals and the files match, each chain replays onto an empty database, each `--> statement-breakpoint` segment holds one statement, and both dialects end with the same tables. `pnpm db:migrate` wraps the migration tool to report the one state it otherwise fails on silently: a database whose tables exist but whose migration bookkeeping is empty, because something other than the chain created it. ## Files - Repositories/ - src/server/db/repositories - src/server/db/repositories/repository-dialect.ts - Schema/ - src/server/db/schema/sqlite.ts - src/server/db/schema/postgres.ts - src/server/db/schema/agent-sqlite.ts - src/server/db/schema/agent-postgres.ts - Adapters and transactions/ - src/server/db/client.ts - src/server/db/adapter-registry.ts - src/server/db/sqlite-transactions.ts - src/server/platform/request-scope.ts - Migrations/ - drizzle/migrations/sqlite - drizzle/migrations/postgres - scripts/db/migrate.ts - scripts/db/migrate-runtime.mjs Three validators cover this layer: `validate:db-adapters` (the registry, the bindings and the server entry), `validate:migrations` (the two chains) and `validate:sqlite-transactions` (commit, rollback, ordering and nesting on the default SQLite adapter). ## Next steps - [Use Postgres](https://kernlift.dev/docs/extensions/database/postgres.md) Switch the dialect and run the second chain. - [Write a custom database adapter](https://kernlift.dev/docs/extensions/database/custom-adapter.md) A different connection for the same schema. - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) Which database each platform allows. --- # Build a module > Add a feature to the repository as a module: code, schema and migrations for both dialects, region markers, a manifest and a validator. Source: https://kernlift.dev/docs/core/plugins/build-a-module A module is a feature whose boundary the repository records exactly: its files, its regions in shared files, its tables and its settings. Keeping a feature of your own in a module keeps it apart from upstream code, so merges stay small, and lets `pnpm validate:registry` prove that the foundation still compiles without it. This guide adds one end to end. The shipped `affiliate` module (`modules/affiliate/module.json`) is a complete example to read alongside it. If you use a coding agent, the `new-module` skill walks through the same steps. See [Use coding-agent skills](https://kernlift.dev/docs/core/agent-skills.md). ## Before you begin * A clone of the repository that passes `pnpm validate:registry`. Record which validators pass before you start, so you can tell afterwards that you turned none red. * A kebab-case key, written `` below, for example `reviews`. It names the manifest directory and the markers. * The tables the module owns, the pages it adds and the permission keys it needs. * The keys of any modules it requires. `image-agent`, for example, requires `agent-starter`. ## Add the module ### Propose the change ```bash openspec-cn new change "" openspec-cn validate "" ``` Fill in `proposal.md`, `design.md`, `specs//spec.md` and `tasks.md` under `openspec/changes//` before you validate. ### Add the tables and a migration for each dialect Define the tables in both `src/server/db/schema/sqlite.ts` and `src/server/db/schema/postgres.ts`, with the same table names. Then generate one migration per dialect: ```bash pnpm db:generate:sqlite --name my-change pnpm db:generate:postgres --name my-change pnpm validate:migrations ``` The Postgres run needs a `DATABASE_URL` to be set, but does not connect to a database. Both dialects must end up with the same migration tag, such as `0018_`, in `drizzle/migrations/sqlite` and `drizzle/migrations/postgres`. ### Write the code | What | Where | | -------------------------------------------------------------------- | -------------------------------------------------------------- | | Data access | `src/server/db/repositories/.repository.ts` | | Business logic | `src/server/services/.service.ts` | | Server functions, checking permissions with `requireAdminPermission` | `src/server/functions/.ts` | | Components | `src/components//` | | Pages | `src/routes/{-$locale}/admin/` or `src/routes/{-$locale}/app/` | | Plugin: manifest and contributions such as the `admin.nav` entry | `src/plugins//manifest.ts`, `src/plugins//plugin.ts` | All database access goes through the repository. Business code does not reference a SQL dialect. The `/admin` and `/app` layouts already guard their route trees, so a new page needs no guard of its own. What a plugin can contribute is in [Plugins](https://kernlift.dev/docs/core/plugins.md). ### Wire it into the shared files A module also needs a few lines in files the foundation owns: * the plugin import and list entry in `src/plugins/installed.ts`; * copy in `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts`, with identical keys; * permission rows in `src/server/services/super-admin-bootstrap.service.ts` and the preset roles in `src/server/db/repositories/users-rbac.repository.ts`. Wrap each of those slices, and the tables from step 2, in marker lines: ```ts // @module: import { reviewsPlugin } from "./reviews/plugin"; // @end-module: ``` The comment syntax follows the file: `//`, `/* */`, ``, `--` or `#`, and `{/* @module: */}` between JSX elements. Regions cannot nest, and the foundation must compile with every region removed. In `src/plugins/installed.ts` keep the imports in sorted order, so that organising imports never moves a line out of its region. ### Write the validator Create `scripts/validate/.ts`. Assert behaviour and wiring, not that files exist. Call the repository with fixtures whose names start with `validate-`, check the results, then clean the fixtures up. Then add to `package.json`: * a script `"validate:": "tsx scripts/validate/.ts"`; * a `pnpm validate:` segment in the `validate:all` chain. ### Write the manifest Create `modules//module.json`. The directory name must equal `key`. ```json { "key": "reviews", "kind": "module", "version": "0.1.0", "requires": [], "files": [ "src/plugins/reviews/**", "src/components/reviews/**", "src/routes/{-$locale}/admin/reviews.tsx", "src/server/services/reviews.service.ts", "src/server/db/repositories/reviews.repository.ts", "src/server/functions/reviews.ts", "scripts/validate/reviews.ts" ], "fragments": [ "src/plugins/installed.ts", "src/server/db/schema/sqlite.ts", "src/server/db/schema/postgres.ts", "src/i18n/locales/en/messages.ts", "src/i18n/locales/zh/messages.ts", "src/server/services/super-admin-bootstrap.service.ts", "src/server/db/repositories/users-rbac.repository.ts" ], "migrations": ["0018_reviews"], "packages": [], "validators": ["validate:reviews"], "i18nNamespaces": ["reviewsCopy"], "admin": { "routes": ["/admin/reviews"], "configPages": [] }, "screenshots": [], "docs": [], "tables": ["reviews"], "configKeys": [], "skillPackages": [] } ``` | Field | Rule the build enforces | | ----------------------- | ------------------------------------------------------------------------------------------------------------------- | | `files` | Every glob matches at least one file; no file is claimed by two modules. A leading `!` excludes a path | | `fragments` | Every listed file has an `@module:` region; a file a module owns entirely carries no markers | | `migrations` | The tag exists as a `.sql` file and a journal entry in both dialects | | `packages` | `name@range` entries that are in `package.json` dependencies | | `validators`, `scripts` | Script names that exist in `package.json` | | `tables` | Exactly the tables the module's files and regions define, in both dialects. Required when the module has migrations | | `configKeys` | Admin config keys the module's own code writes. A trailing `.` means every key under that prefix | | `skillPackages` | The Skill package ids the module's own code publishes, one per Skill directory it ships | The remaining fields are descriptive. `key` equals the directory name and `version` is the module's own version. `kind` is `module` for a feature and `template` for an item that brings a runtime of its own, as `agent-starter` does. `requires` lists modules this one depends on. `i18nNamespaces` names the dictionary namespaces it owns, and `admin`, `screenshots` and `docs` record its console pages and material. `tables`, `configKeys` and `skillPackages` say what data the module owns, so the build checks them against the code. ### Check the manifest against the code ```bash pnpm registry:build ``` The build slices the checkout by manifest and writes `registry/dist/`: `index.json`, one `@.json` per item, and `.files..json` pages for large items. It prints a line per item with its file, fragment and migration counts. A manifest that breaks one of the rules above stops the build with a message naming the module and the problem. ### Archive the change ```bash openspec-cn archive "" -y --skip-specs ``` `registry/dist/` is build output. It is ignored by git and you do not need to keep it. ## Verify the module * `pnpm validate:registry` passes: the foundation plus every module reproduces the checkout byte for byte, and the foundation type-checks without any module. * `pnpm validate:`, `pnpm validate:plugins`, `pnpm validate:app-i18n`, `pnpm validate:route-i18n`, `pnpm validate:auth-boundary` and `pnpm validate:migrations` pass. * `pnpm typecheck`, `pnpm build` and `pnpm check` report nothing new, and `pnpm validate:all` turns no passing check red. * `pnpm validate:kernlift-lifecycle` passes: it applies and removes the built items in a scratch project, including the data purge. ## Troubleshooting ### "has migrations but declares no tables in module.json" List every table the module creates in `tables`. ### "module.json tables \[…] differ from the sqlite tables its files define \[…]" `tables` must match the `sqliteTable(...)` and `pgTable(...)` names inside the module's own files and marked regions. Either a table definition sits outside an `@module` region, or the list is out of date. ### "no file matches …" A glob in `files` matches nothing. Fix the path or remove the entry. ### `… has no @module: region` A file listed in `fragments` carries no region for the module. Add the markers, or remove the file from `fragments`. ### `pnpm validate:registry` fails to type-check the foundation A foundation file imports something the module owns. Move that import inside an `@module` region, or have the foundation reach the feature through a plugin slot. ## Next steps - [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md) - [Plugins](https://kernlift.dev/docs/core/plugins.md) - [Templates and derived products](https://kernlift.dev/docs/core/plugins/templates.md) - [Validators and the release gate](https://kernlift.dev/docs/core/validators.md) --- # Write a console plugin > Add a feature of your own as a local plugin: a workspace sidebar entry, a page and a dashboard card that an administrator can switch on and off. Source: https://kernlift.dev/docs/core/plugins/console-plugins A local plugin wires a feature you wrote into the console without editing the shells. This guide builds one called `notes`: an entry in the workspace sidebar, a page at `/app/notes` and a card on the `/app` dashboard. The same steps apply to the admin console with the `admin.nav` slot. For how the kernel works, see [Plugins](https://kernlift.dev/docs/core/plugins.md). ## Before you begin * A project that runs locally with `pnpm dev`. * An administrator account with `config.read` and `config.write`, to open **Settings → Plugins**. * A plugin id: a lower-case slug such as `notes`, unique among the plugins in `src/plugins/installed.ts`. * The pass/fail set of `pnpm validate:all` recorded before you start, so you can confirm afterwards that no passing check now fails. ## Build the plugin ### Write the manifest The manifest is pure data. `kind: "local"` marks a plugin that belongs to this project. `routes` lists the path prefixes the plugin owns, without the locale prefix. ```ts title="src/plugins/notes/manifest.ts" import { defineManifest } from "../kernel/types"; export const notesManifest = defineManifest({ id: "notes", version: "0.1.0", kind: "local", routes: ["/app/notes"], }); ``` ### Add the copy Navigation labels are dictionary keys. Add `notes` to the `appConsole` namespace in both `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts`. A key present in one locale only fails `pnpm validate:app-i18n`. ### Add the page Create the route under the locale-aware tree. `active` must be the `id` of the `app.nav` entry you contribute in the next step. ```tsx title="src/routes/{-$locale}/app/notes/index.tsx" import { createFileRoute } from "@tanstack/react-router"; import { useAuth } from "@/components/auth/auth-state"; import { AppConsoleLayout } from "@/components/layout/app-console-sidebar"; import { useI18n } from "@/i18n/use-i18n"; export const Route = createFileRoute("/{-$locale}/app/notes/")({ component: NotesPage, }); function NotesPage() { const { locale, t } = useI18n(); const { user } = useAuth(); return (

{t("appConsole.notes")}

); } ``` The page needs no guard of its own. The `/app` layout protects it, and the same layout returns not found for the route while the plugin is switched off. Load data through a server function that calls `requireCurrentUserId()`, as described in [Add a page](https://kernlift.dev/docs/customize/new-page.md). ### Write the dashboard card A dashboard card is a component that receives the current locale. ```tsx title="src/plugins/notes/notes-card.tsx" import { Surface, SurfaceContent } from "@/components/motion/surface"; import { getDictionary, type Locale, localizedPath } from "@/i18n/messages"; export function NotesCard({ locale }: { locale: Locale }) { const { t } = getDictionary(locale); return ( {t("appConsole.notes")} ); } ``` Build it from `@workspace/beui`, `src/components/motion` and Tailwind utilities. A file under `src/plugins` that imports `src/components/ui` or reads `process.env` fails `pnpm validate:plugins`. ### Contribute to the slots ```ts title="src/plugins/notes/plugin.ts" import { NotebookPen } from "lucide-react"; import { definePlugin } from "../kernel/types"; import { notesManifest } from "./manifest"; import { NotesCard } from "./notes-card"; export const notesPlugin = definePlugin({ manifest: notesManifest, contributes: { "app.nav": [ { id: "notes", icon: NotebookPen, labelKey: "appConsole.notes", path: "/app/notes", section: "product", order: 50, }, ], "app.dashboard.cards": [{ id: "notes.summary", order: 10, component: NotesCard }], }, }); ``` The foundation's own `product` entries use orders 0 to 40, so 50 places the entry after them. Each field is typed in `src/plugins/slots.ts`; see [Client slots and server slots](https://kernlift.dev/docs/core/plugins.md). ### Register it Add the plugin to the installed list. Keep it outside every `// @module:` region. Those regions belong to the shipped modules, and a local plugin inside one fails the validator. ```ts title="src/plugins/installed.ts" import { notesPlugin } from "./notes/plugin"; export const installedPlugins: readonly Plugin[] = [ foundationPlugin, // … the regions of the shipped modules … notesPlugin, ]; ``` Run `pnpm dev` once so `src/routeTree.gen.ts` picks up the new route file. ## Add server-side behaviour A plugin that serves HTTP endpoints or reacts to paid orders adds a `plugin.server.ts` with `defineServerPlugin`, contributes to `api.routes` or `billing.fulfilment`, and is listed in `src/plugins/installed.server.ts` as well. That file is also imported by the agent service, so nothing reachable from it may import React, icons or `@/` aliases. Server functions of the plugin call `requirePluginEnabled("notes")` from `src/server/plugins/state.ts` after their auth guard, so they reject calls while the plugin is off. Endpoints contributed to `api.routes` need no such call, because the host returns `404` for a switched-off plugin. See [Fulfil paid orders](https://kernlift.dev/docs/extensions/payments/fulfilment.md) for the billing slot. ## Verify 1. `pnpm typecheck` passes. A wrong slot name or a missing field in a contribution is a type error. 2. `pnpm validate:plugins` passes. It checks that the registry builds, that the nav entry reaches a route file, that the entry sits under a prefix in the plugin's `routes`, and that the page's `active` value is a contributed `app.nav` id. 3. Open `/app`: the **Notes** entry is in the sidebar and the card is above the account summary. Open `/app/notes`. 4. Open **Settings → Plugins** (`/admin/plugins`). The `notes` row lists its workspace entry and its route. Switch it off. 5. Reload `/app`: the entry and the card are gone, and `/app/notes` shows the not-found page. Switch it back on and both return. 6. `pnpm validate:all` turns no check red against the set you recorded. ## Troubleshooting ### The app fails to start with `duplicate_slot_key` Another plugin already contributes that key to the slot: an `app.nav` entry with the same `id`, or an `admin.nav` entry with the same `to`. The message names the slot, the key and both plugins. ### The app fails to start with `duplicate_plugin_route` Two manifests claim the same prefix in `routes`. A prefix has one owner; nest the new route under a prefix of its own. ### `pnpm validate:plugins` reports `module-entries-sit-in-their-own-routes` A nav entry of the plugin points outside the prefixes in its manifest. Add the prefix to `routes`; otherwise switching the plugin off would hide the entry but leave the page reachable. ## Next steps - [Client slots and server slots](https://kernlift.dev/docs/core/plugins.md) What a slot is and where each one is declared. - [Add a page](https://kernlift.dev/docs/customize/new-page.md) Copy, guards and server functions for the page itself. - [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md) Ship the feature through the registry. - [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md) Contribute an agent capability to the workbench. --- # Plugins > How the plugin kernel works: what a plugin is, the client and server slots it contributes to, how plugins are installed at build time and switched on and off at runtime. Source: https://kernlift.dev/docs/core/plugins The admin console and the workspace do not hard-code features. They read **slots** (the sidebar, the dashboard, the billing header and the agent workbench), and every installed **plugin** contributes entries to them. The foundation itself is a plugin, each module is one, and a feature you write for your own product can be one too. To write one, see [Write a console plugin](https://kernlift.dev/docs/core/plugins/console-plugins.md). ## What a plugin is A plugin is a manifest plus contributions to named slots, in one folder under `src/plugins//`. | File | Holds | Loaded by | | ------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------ | | `manifest.ts` | Pure data: `id`, `version`, `kind`, `requires`, `routes` | Anything | | `plugin.ts` | Browser-safe contributions: navigation with icons, blocks, workbench extensions | The web app | | `plugin.server.ts` | Server-only contributions: API routes, billing fulfilment, agent host extensions. Optional | The web app's server and the agent service | The manifest's `routes` lists the path prefixes the plugin owns, without the locale prefix, such as `/admin/cms` or `/app/image`. `requires` lists plugin ids that must be installed and switched on. | Kind | Meaning | Can be switched off | | --------- | ------------------------------------------------------------------------------- | ------------------- | | `builtin` | The foundation: the console every installation has | No | | `module` | A module that ships in the repository, with a marker region and a `module.json` | Yes | | `agent` | An agent capability; requires `agent-starter` | Yes | | `local` | Belongs to your project. It has no marker region and no `module.json` | Yes | ## Installed at build time, enabled at runtime Plugins are not downloaded or loaded while the app runs. The template deploys to Cloudflare Workers, which cannot load remote code, file routes are fixed at build time, and a plugin has to pass type checking and the validators together with the host. A plugin therefore has two separate states. **Installed** is a build-time fact. `src/plugins/installed.ts` is an explicit list, and what a deployment runs is readable there. A module's entry sits in its `// @module:` region of that list. You add a `local` plugin by hand, outside any region. `src/plugins/installed.server.ts` is the matching list of server halves. The agent service imports it, so nothing reachable from it may import React, icons or `@/` aliases. **Enabled** is a runtime fact, stored in the admin config table under `plugins.state.v1`. Only the ids an operator switched off are stored, so a plugin installed later is on by default. The enabled set is resolved like this: 1. `builtin` plugins are always on. 2. A plugin in the disabled list is off. 3. A plugin whose dependency is off is off too, transitively. An administrator with `config.write` changes it in **Settings → Plugins** (`/admin/plugins`). The console rejects switching off a plugin that an enabled plugin still requires and names the dependents. It rejects switching on a plugin whose dependency is off and names the dependency. ## Client slots and server slots A slot is a typed, named list that the host reads and plugins contribute to. Client slots add UI: `admin.nav` and `app.nav` take sidebar entries, and `app.dashboard.cards` takes a card on the `/app` dashboard. A plugin contributes to them through `contributes` in `plugin.ts`, and the console shells read them through `usePluginValues(slot)`. Server slots add behaviour: `api.routes` serves endpoints under `/api/plugins//…`, and `billing.fulfilment` delivers what a paid order buys. A plugin contributes to them through `contributes` in `plugin.server.ts`. Each slot declares the shape of one contribution and the field that keys it. The full list, with each contribution's type, is in `src/plugins/slots.ts` (client) and `src/plugins/server-slots.ts` (server). The agent slots exist only when the `agent-starter` template is installed; [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md) covers them. The registry merges the installed plugins once, when it is built, and rejects every conflict with one of these errors: | Error | Cause | | --------------------------- | ------------------------------------------------ | | `duplicate_plugin` | Two plugins share an id | | `duplicate_slot_key` | Two contributions to one slot share a key | | `duplicate_plugin_route` | Two plugins claim one route prefix | | `missing_plugin_dependency` | A plugin requires one that is not installed | | `plugin_dependency_cycle` | Plugins require each other in a loop | | `unknown_plugin_slot` | A contribution names a slot that is not declared | ## What switching a plugin off does | Surface | Effect | | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Navigation and blocks | The shells read contributions of enabled plugins only, so its entries and cards disappear. | | Pages under `/admin` and `/app` | The console layouts call the route guard in `beforeLoad`; a path owned by a disabled plugin resolves to not found. The owner is the plugin with the longest matching route prefix. | | `/api/plugins//…` | The catch-all route returns `404`. | | Server functions | A module's own functions call `requirePluginEnabled()` after their auth guard and reject the call. | | Billing | Only fulfillers of enabled plugins are called. | | Agent | A disabled plugin's scenes, routes and skills are skipped, and a run on its scene is rejected with `plugin_disabled`. | The route guard runs in the two console layouts. A public route prefix in a manifest, such as `/blog`, records ownership but is not blocked there. Disabling a plugin does not uninstall it. Files, tables, data and migrations stay. ## Deployment capabilities Some entries depend on what the deployment has. An `app.nav` entry may carry `requires: "agent"`, and it is hidden when the agent service is not available, even with its plugin enabled. The console layouts resolve the enabled ids and the capabilities together on the server and pass both to the shell. See [Agent runtime](https://kernlift.dev/docs/extensions/agent.md). ## How modules relate to plugins A module is a feature whose boundary is recorded in `modules//module.json`: files, shared-file regions, migrations and packages. A plugin is how that module's console presence is wired in. The two must agree in three places, which `pnpm validate:plugins` checks: * The plugin id equals the module key, and both carry the same version. * The module's `files` include `src/plugins//**`. * The module's `fragments` include `src/plugins/installed.ts`, where its marker region sits. Schema, permission seeds and dictionary entries are not plugin contributions. They stay in `// @module:` regions of the shared files. See [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md). ## Files - Kernel/ - src/plugins/kernel/types.ts - src/plugins/kernel/registry.ts - src/plugins/kernel/state.ts - Slots and installed lists/ - src/plugins/slots.ts - src/plugins/server-slots.ts - src/plugins/installed.ts - src/plugins/installed.server.ts - src/plugins/registry.ts - src/plugins/registry.server.ts - Runtime state and guards/ - src/plugins/route-guard.ts - src/plugins/context.tsx - src/server/plugins/state.ts - src/server/plugins/server-state.ts - src/server/plugins/api-dispatch.ts - src/routes/{-$locale}/admin/plugins.tsx - Examples/ - src/plugins/foundation/plugin.ts - src/plugins/cms/plugin.ts - src/plugins/image-agent/plugin.server.ts - Check/ - scripts/validate/plugins.ts ## Next steps - [Write a console plugin](https://kernlift.dev/docs/core/plugins/console-plugins.md) Add a nav entry, a page and a dashboard card of your own. - [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md) Add an agent capability to the one workbench. - [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md) Keep a feature of your own in a module with a manifest. --- # Templates and derived products > How a module differs from a template inside the repository, what the business templates are, and how a product of your own is built on the foundation by adding one plugin. Source: https://kernlift.dev/docs/core/plugins/templates Everything in this project sits on one foundation. A **module** adds a feature to it, a **template product** adds a whole product shape with a runtime of its own, and a **derived product** is what you build by putting one plugin of yours on top. The differences determine what has to be deployed and where your own code goes. ## Module or template product Both are already in the repository, each described by a manifest in `modules//module.json`. The `kind` field identifies which one it is. | | Module | Template product | | ------------------------- | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | `kind` in `module.json` | `module` | `template` | | What it adds | One feature: pages, server code, its tables, copy and a validator | A product shape: workspace packages, a second process, a runtime, and the tables and settings that runtime needs | | Example in the repository | `cms`, `newsletter`, `affiliate`, `image-agent` | `agent-starter` | | Changes how you deploy | No | Yes: a service to run next to the web app | | Others build on it | Rarely | Yes: agent capability plugins require it | `agent-starter` is the one template product. Its manifest lists what a feature module never carries: the `packages/agent-*` workspace packages and `apps/agent-service`, the scripts `dev:agent`, `build:agent-service` and `agent:publish-skills`, the migration `0016_agent_starter` with the run, thread, skill and workspace tables, and six validators. `image-agent`, by contrast, is a module with `requires: ["agent-starter"]`: a plugin folder, two routes, one settings key and no table. A template product is a base that other items build on. A module usually has nothing built on top of it. The inventory of both is in [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md). ## Business templates are derived products The business templates sold beside the base (`image-studio`, `video-studio`, `image-agent` and `video-agent`) are derived products that are already built. Each is its own private repository: the base plus the plugin, pages and plans of one product. You clone one instead of the base and keep it up to date the same way. See [Get Kernlift](https://kernlift.dev/docs/guide/get-kernlift.md). The `image-agent` plugin inside the base repository is the shipped example of an agent capability; the business template of the same name is a separate repository. The rest of this page explains how such a product is put together, which is also how you build one of your own. ## A derived product is the foundation plus one plugin A product built on the template, such as a site that generates images or video, does not fork the console. The foundation already carries sign-in, plans and checkout, the credits ledger, provider configuration, file storage, the admin console and the validators. Your product adds one plugin that contributes its pages and entries to the console's slots, plus your landing pages and plans. There are two ways to build it, depending on whether the product needs the agent. | | Without the agent | With the agent | | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | | What generates | A channel task: `POST /api//generate`, read back through `GET /api/status` | An agent run that calls `model.generate` on the same scenes and publishes artifacts | | Your plugin | A `local` console plugin: an `app.nav` entry, a page that starts tasks on `image-creation` or `video-creation`, optionally a dashboard card | An `agent` plugin on top of `agent-starter`: a scene, a Skill, composer controls, optionally its own cards and panels | | Slots used | `app.nav`, `app.dashboard.cards`, optionally `api.routes` and `billing.fulfilment` | `agent.host`, `agent.workbench`, optionally `api.routes` | | Interaction | A form and a result | A conversation: the reader describes, revises and gets results inside the messages | | Database | Any supported one, including Cloudflare D1 | Postgres, or SQLite on Node | | Deployment | The web app alone | The web app and the agent service | Both share the same provider wiring. An image or video provider is configured once in `/admin/config/ai`, tasks are priced in credits and results land in the user's files, whichever path starts them. See [Get image and video generation working](https://kernlift.dev/docs/extensions/ai/media-generation.md). ### Without the agent The foundation is a complete web app without the agent service. `/app/ai` already starts and tracks channel tasks, so a generation product is a page of your own over the same server functions and API, registered as a `local` plugin. Nothing else in the shells changes, and the plugin can be switched off in **Settings → Plugins**. See [Write a console plugin](https://kernlift.dev/docs/core/plugins/console-plugins.md). ### With the agent Run the agent service from `agent-starter`, then add one capability plugin. The image agent is the shipped example: it declares the `agent.image` scene, ships the Image Studio Skill, adds a frame picker to the composer and renders `image` artifacts. A video capability is built the same way. It needs no artifact kind of its own, because `video` is a core kind that the conversation already plays inline. The host code does not reference the plugin by name, so installing a second capability adds an entry to the installed lists and requires no change to the workbench. See [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md). Because the agent is optional at runtime too, one codebase can serve both. Where the agent service is not deployed, entries marked `requires: "agent"` are hidden and the plain channel pages keep working. ## What stays the foundation's job Whichever path you take, these are not rebuilt per product: * **Money.** Plans, checkout and the credits ledger. A plugin that delivers something for a paid order contributes a fulfiller to `billing.fulfilment` and does not modify orders. * **Configuration.** Provider credentials live in `/admin/config/*`, never in the environment. * **Access.** Protected route trees are guarded at the layout, so a plugin's new page is protected by default. * **Checks.** A plugin ships its own validator, and `pnpm validate:all` covers the rest. ## Files - Manifests/ - modules/kernlift/module.json - modules/agent-starter/module.json - modules/image-agent/module.json - Where a plugin is added/ - src/plugins/installed.ts - src/plugins/installed.server.ts - src/plugins/slots.ts - src/plugins/server-slots.ts - The shipped capability plugin/ - src/plugins/image-agent/plugin.ts - src/plugins/image-agent/plugin.server.ts - Whether the agent is there/ - src/server/agent-host/availability.ts ## Next steps - [Plugins](https://kernlift.dev/docs/core/plugins.md) The kernel a derived product plugs into. - [Write a console plugin](https://kernlift.dev/docs/core/plugins/console-plugins.md) The path without the agent. - [Agent plugins](https://kernlift.dev/docs/extensions/agent/plugins.md) The path with the agent. - [Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) The template product that brings the agent stack. - [What the base repository contains](https://kernlift.dev/docs/reference/capabilities.md) The foundation, its modules and what each one adds. --- # Project structure > Find your way around a Kernlift checkout and know where each kind of change belongs. Source: https://kernlift.dev/docs/core/project-structure A Kernlift project is one repository: the application, its migrations, validators, agent skills, the optional agent service and the tooling that packages it into modules. This page shows where each part lives. The reasons behind the layout are in [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md). ## Before you begin * A project cloned and installed with the [Quick start](https://kernlift.dev/docs/quick-start.md). ## The top level ```text title="my-saas/" src/ the web application (routes, components, plugins, server code, copy) packages/ workspace packages: beui (the design system), kernlift-skills, and the agent-* packages apps/agent-service/ the optional agent service, a separate process (agent-starter module) drizzle/migrations/ hand-maintained migrations, one directory per dialect: sqlite/ and postgres/ scripts/ db/, jobs/, validate/, registry/, assets/, skills/, plus the Node and Worker smoke tests modules/ one module.json per module, plus the foundation manifest skills/ agent skills for working on the project (quick-start, new-page, deploy, ...) agent-skills/ skills the agent itself runs (agent-starter module) tools/kernlift/ the kernlift CLI package openspec/ specs and change proposals (openspec/changes/) docs/ maintainer notes and design references public/ icons, share image and placeholder artwork deploy.config.json the platform, database and agent choice this build is made for wrangler.jsonc Cloudflare Worker entry and bindings (Cloudflare projects only) Dockerfile the Node image every other platform runs .env.example every environment variable the source reads ``` A project carries only its own platform's deployment files: `wrangler.jsonc` on Cloudflare, `fly.toml` on Fly.io, `.railway/railway.ts` on Railway, `compose.yaml` for Docker. `kernlift deploy-target ` switches between them and rewrites `deploy.config.json`. The product documentation you are reading is published from the store project and is not part of your checkout. ## Inside `src/` ```text title="src/" routes/{-$locale}/ pages; the optional locale segment serves /zh routes app.tsx, app/ signed-in workspace (/app/*), guarded once in the layout admin.tsx, admin/ admin console (/admin/*), guarded once in the layout routes/api/ API handlers such as /api/billing/*, /api/chat and /api/agent/* components/ UI grouped by capability motion/ the beUI components pages import admin/ admin page patterns (records, metrics, panels, config forms) marketing/ the public site: shell, page-shell primitives, landing, pricing layout/ AppShell and the workspace sidebar plugins/ console plugins: the foundation plugin and one per module, with the slots they fill (admin.nav, app.nav, dashboard cards, billing actions) i18n/ locales/{en,zh}/messages.ts plus per-feature copy files config/site.ts site name, canonical URL, description and social image styles/app.css the product tokens on :root, shared by every page server/ auth/ the only code that reads a session: context, guards, API boundary functions/ server functions called from routes and components services/ orchestration across capabilities db/repositories/ all database access db/schema/ sqlite.ts and postgres.ts, the same tables in two dialects jobs/ scheduled work: runScheduledJobs() and the in-process loop agent-host/ the web side of the agent: availability, transport, credits, storage plugins/ plugin state and the API routes plugins contribute platform/ runtime capabilities: cache backends, storage drivers, bindings, deployment server-entry.ts the Worker entry named in wrangler.jsonc server-entry.node.ts the server entry of the Node build (pnpm build:node) ``` Each server layer calls only the one below it, so business code never touches a SQL dialect. The web app runs without `apps/agent-service`. When the service is absent, agent entries report that it is not deployed. ## Where your changes go | You want to | Change | | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Rename the product | `src/config/site.ts` and the artwork in `public/`; see [Rebrand the project](https://kernlift.dev/docs/customize/branding.md) | | Replace the home page | `src/components/marketing/example-landing.tsx`; see [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) | | Change colours or build a screen | `src/styles/app.css` and `src/components/motion`; see [Use the design system](https://kernlift.dev/docs/customize/design-system.md) | | Change or add copy | Both `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts`; see [Add and change copy](https://kernlift.dev/docs/customize/i18n.md) | | Add an admin or workspace page | A route under `src/routes/{-$locale}/admin/` or `app/` and a navigation entry in `src/plugins/foundation/plugin.ts`; see [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) | | Connect a provider | Nothing in code: use `/admin/config/*`, see [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) | | Add a database table | Both schema files, then a migration for each dialect | | Add recurring background work | A job in `src/server/jobs/scheduled.ts`; see [Background jobs](https://kernlift.dev/docs/core/background-jobs/run.md) | | Add a feature check | A validator in `scripts/validate/`, wired into `pnpm validate:all` | | Add a module | Follow the `new-module` skill; see [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md) | **Keep provider settings out of the environment** Environment variables cover only startup and infrastructure. Feature code does not read `process.env`; provider credentials belong in the admin console. ## Verify Run the checks you will run before every change is finished, in this order: 1. `pnpm typecheck`. It needs `worker-configuration.d.ts`, which `pnpm cf-typegen` generates, and an up-to-date `src/routeTree.gen.ts`, which `pnpm dev` or `pnpm build` rewrites when routes change. 2. `pnpm check`. It reports some pre-existing stylesheet issues. Do not run `biome check --write --unsafe` across the repository to silence them. 3. `pnpm validate:all`. ## Next steps - [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md) Why the code is layered this way. - [First steps](https://kernlift.dev/docs/customize/first-steps.md) Finish the setup checklist and pick what to customise first. - [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md) Symptoms and fixes when something does not start. - [Validators and the release gate](https://kernlift.dev/docs/core/validators.md) What `pnpm validate:all` proves. --- # Validators and the release gate > Why every capability carries an executable check that asserts behaviour and wiring, and how the release gate decides which checks must pass. Source: https://kernlift.dev/docs/core/validators Every capability in Kernlift carries a validator, an executable script that checks the feature works and is reachable. A release gate determines which of those checks must pass. The full list of scripts is in [Validators](https://kernlift.dev/docs/reference/validators.md). ## One validator per capability `scripts/validate/*.ts` holds one check per capability, each exposed as a `validate:*` script in `package.json` and chained into `pnpm validate:all`. A change is not finished until its validator exists and passes. Modules ship their own validators too, named in their manifest. A validator reports each check it ran, most as a JSON report with the evidence for each, and exits non-zero when any check fails. ## Behaviour and wiring, not file existence A check that only asserts a file exists passes while the file sits unreferenced by any route. This repository has shipped that bug more than once, so validators assert behaviour and wiring. The usual shapes are: | Shape | What it proves | | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | | Run a repository or service with `validate-` prefixed fixtures against the real database, then remove them | The logic works on real tables, including failure paths | | Render pages with the real marketing snapshot in both locales | The page shows real data in English and Chinese, with no hardcoded prices | | Read routes, shells and dictionaries | The feature is reachable: routed, guarded, in the navigation and translated | Validators never fake a provider. Checks that need real credentials are part of external validation. ## The release gate Not every validator passes today. `pnpm validate:all` runs the whole chain and stops at the first failure, so it cannot serve as a gate while some checks are known to fail. CI runs `pnpm validate:gate`: | Group | How the gate treats it | | ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | | Validators not listed as known failures | Must pass; any failure is a regression | | Validators in `scripts/validate/known-failures.json` | Run too; one that starts passing must be removed from the list | | `validate:all`, `validate:gate`, `validate:storage-drivers` | Not run by the gate. The storage driver check writes real objects to a bucket, so it runs only deliberately | Each known failure carries a written reason and what fixing it takes. The list may only shrink. A validator that starts failing must be fixed and must not be added to it. When you change something, record the pass and fail set before and after, and confirm you did not turn a passing check red. ## External validation Local validators check state machines and not-configured paths. Checks against real providers need sandbox or production credentials and run separately through `pnpm validate:external`. Without credentials those checks are reported as skipped, and `EXTERNAL_VALIDATE_STRICT=true` makes a skipped check fail. See [Runtimes and database adapters](https://kernlift.dev/docs/deploy/runtimes.md). ## Notable validators | Script | Proves | | ----------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `validate:auth-boundary` | Every API route is guarded or explicitly public with a reason | | `validate:migrations` | Both migration chains replay and match the schema | | `validate:billing-fulfilment` | Billing notifies every enabled fulfilment plugin once, records failures and retries them from the scheduled round | | `validate:optional-agent` | The web app is complete without the agent service, and its scheduled jobs run under one lock | | `validate:plugins` | The plugin registry rejects conflicts, disabling cascades, and every contributed entry reaches a route file | | `validate:store-boundary` | Nothing that sells Kernlift has come back into the template | | `validate:products` | Server-side pricing, licence issue and revoke, bundle expansion | | `validate:registry` | Foundation plus modules reproduce the checkout; the foundation type-checks alone | | `validate:init-cli` | Tokens never in argv, unlicensed refusal, upgrades keep local edits | | `validate:skills` | Skills reference only real scripts, paths, routes and commands | | `validate:module-catalog` | Module pages render from the real snapshot with no price literals | | `validate:docs` | Bilingual navigation and links resolve; module, Agent API, schema and environment references match source | | `validate:landing-blocks` | Home page counts are counted from the checkout | `validate:products`, `validate:module-catalog`, `validate:docs` and `validate:landing-blocks` belong to the store project; a project created from the template does not have them. ## Files - The checks/ - scripts/validate - scripts/validate/gate.ts - scripts/validate/known-failures.json - scripts/validate/lint-budget.json - What they read/ - scripts/validate/change-path.ts - scripts/validate/render.ts - scripts/validate/fixtures.ts `change-path.ts` resolves an OpenSpec change whether it is active or archived, so no validator hardcodes a change directory. `render.ts` server-renders a page so a check can assert on the rendered markup. `fixtures.ts` creates and removes the `validate`-prefixed rows a check needs, so it does not depend on seed data. ## Next steps - [Validator reference](https://kernlift.dev/docs/reference/validators.md) Every check, what it asserts and how to run it alone. - [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md) The boundaries these checks enforce. - [Project structure](https://kernlift.dev/docs/core/project-structure.md) Where a new check goes. - [Upgrading a fork](https://kernlift.dev/docs/guide/upgrading.md) Run the gate before and after, and keep passing checks passing. --- # Rebrand the project > Replace the Kernlift name, URL, description, icons and share image with your own, and choose where people land after signing in. Source: https://kernlift.dev/docs/customize/branding A new project still shows the Kernlift name in its header, browser tab, emails and share cards. Site identity is set in one file, `src/config/site.ts`. The rest of this guide covers the places that file does not cover: the page titles in the message dictionaries, the generated artwork and the sender name. ## Before you begin * A project that runs locally with `pnpm dev`. See [Quick start](https://kernlift.dev/docs/quick-start.md). * Your product name, a one-sentence description and the production domain. * Optional: your own logo as an SVG, and a 1200×630 share image. ## Set the site identity ### Edit `src/config/site.ts` ```ts title="src/config/site.ts" export const siteConfig = { name: "Acme", shortName: "Acme", url: normalizeOrigin(process.env.SITE_URL ?? "https://acme.com"), description: "One sentence that says what Acme does.", ogImage: "/og-default.png", locale: "en", themeColor: "#3859D6", backgroundColor: "#F6F5F1", twitter: { site: "", card: "summary_large_image" }, } as const; ``` | Field | Used by | | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | `name` | The public header and footer, the auth pages, the workspace sidebar, system pages, the email shell, `og:site_name`, the feed title and the web manifest | | `shortName` | `short_name` in `/manifest.webmanifest` | | `url` | Canonical links, `og:url`, the sitemap, `robots.txt`, the feed and absolute links in email | | `description` | The fallback meta description, the feed and the manifest | | `ogImage` | The fallback `og:image` and `twitter:image`, relative to `url` | | `themeColor`, `backgroundColor` | The `theme-color` meta tag and the manifest | | `twitter.site` | `twitter:site`; leave it empty to omit the tag | A fresh clone still carries the template's own `name`, `shortName` and `url`; change all three. ### Set the production origin `SITE_URL` overrides `siteConfig.url` at runtime, so one build can serve a preview domain and the production domain. Set it wherever the app runs: ```bash title=".env" SITE_URL=https://acme.com ``` A trailing slash is not needed, because the config strips it. OAuth callbacks and auth email links use the **Base URL** at `/admin/config/auth` instead. It is seeded from the site address on first start; change it there if the domain changes. See [Environment variables](https://kernlift.dev/docs/reference/env.md). ### Replace the default titles in both dictionaries The site-wide default title and the home page title are copy, so they live in the message dictionaries, not in `site.ts`. Edit the same keys in `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts`: | Key | Where it appears | | ---------------------------------------------- | --------------------------------------------------------- | | `seo.default.title`, `seo.default.description` | The fallback title and description from the root document | | `seo.home.title`, `seo.home.description` | The home page | | `content.blogCopy` | The blog index intro, with the CMS module | How copy is organised is covered in [Add and change copy](https://kernlift.dev/docs/customize/i18n.md). ## Replace the icons and the share image ### Choose generated or hand-made artwork The project ships placeholder artwork drawn by a script. Either keep the generator and give it your name and colours, or replace the files with your own. To regenerate, edit the constants at the top of `scripts/assets/generate-site-assets.ts` (`siteName`, `tagline` and `palette`), then run: ```bash pnpm assets:generate ``` It rewrites `favicon.svg`, `favicon.ico`, `apple-touch-icon.png`, `icon-192.png`, `icon-512.png` and `og-default.png` in `public/`, plus the images under `public/placeholder/`. ### Or replace the files by hand Keep these names and sizes, because the root document, the manifest and the shells reference them by path: | File | Size | Used for | | -------------------------------------------- | ---------------- | ------------------------------------------------------------------------------ | | `public/favicon.svg` | vector | The browser tab, and the logo mark in the public header, auth and system pages | | `public/favicon.ico` | 32×32 | Browsers without SVG icon support | | `public/apple-touch-icon.png` | 180×180 | iOS home screen | | `public/icon-192.png`, `public/icon-512.png` | 192×192, 512×512 | The web manifest | | `public/og-default.png` | 1200×630 | The default share image | If you run `pnpm assets:generate` later it overwrites these files. ### Match the browser chrome to your palette Set `themeColor` and `backgroundColor` in `site.ts` to your primary colour and page background. They are plain hex strings and do not follow the CSS tokens automatically. If you change `--primary` or `--background`, change them here too. See [Use the design system](https://kernlift.dev/docs/customize/design-system.md). ## Check metadata and the sitemap Pages build their `` through `buildMeta()` in `src/lib/seo.ts`, which falls back to the site config for anything a page does not supply. You maintain two lists: 1. Open `src/server/services/static-seo.service.ts` and edit `publicSeoRoutes`: remove pages you deleted and add public pages you created. `/sitemap.xml` renders this list once per locale with `hreflang` alternates. 2. Leave `robots.txt` alone unless you add another private area. It is served from `src/routes/robots[.]txt.ts`, already disallows `/admin`, `/app` and `/api`, and points at the sitemap on your configured origin. Do not add a `public/sitemap.xml`. It would shadow the route, and `pnpm validate:site-metadata` fails. ## Set the email sender name The email shell takes the product name from `site.ts`, but the sender is a stored setting. Open **Settings → Email Config** (`/admin/config/email`) and set the from address to your own name and verified domain. See [Send transactional email](https://kernlift.dev/docs/extensions/email.md). ## Choose where signed-in users land A visitor who signs in from a protected page returns to it through the `redirectTo` parameter. Without one, they land on `signedInHome` in `src/config/site.ts`, which is `/app/profile` by default. Sign-in, sign-up, social sign-in and the button shown after a verified email all read it. ```ts signedInHome: "/app", ``` Write a site-relative path under `/app` without a locale prefix. The prefix is added for the visitor's language, and the auth pages only follow relative paths outside `/auth`. ## Verify ```bash pnpm validate:site-metadata pnpm validate:example-landing pnpm typecheck ``` Then start `pnpm dev` and check: * The header, the browser tab and `/auth/sign-in` show your name and mark. * `/manifest.webmanifest` returns your `name`, `short_name` and colours. * `/sitemap.xml` and `/robots.txt` use your origin when `SITE_URL` is set. * View source on `/`: `og:title`, `og:image` and the canonical link carry your name and domain. * Sign out and sign in again: you land on the page you chose. `pnpm validate:site-metadata` fails when an icon is missing, when a source file references an image that is not in `public/`, or when a page writes its own canonical link instead of calling `buildMeta()`. ## Next steps - [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) Rewrite the example home page with the page-shell primitives. - [Use the design system](https://kernlift.dev/docs/customize/design-system.md) Change the colour tokens every page reads. - [Add and change copy](https://kernlift.dev/docs/customize/i18n.md) Edit the message dictionaries in both locales. --- # Use the design system > Build or restyle a screen with beUI, the motion components and the product tokens, change the theme, and avoid the imports the validators reject. Source: https://kernlift.dev/docs/customize/design-system Every page in the project uses one design system: the admin console, the workspace, the auth and system pages and the public site. It has three layers: tokens on `:root`, components from `@workspace/beui` re-exported through `src/components/motion`, and a small set of page patterns. Every page uses the design system by default. You add no wrapper and set no attribute. ## Before you begin * A project that runs with `pnpm dev`. * The screen you want to build or restyle, and whether it is a console page (`/admin`, `/app`) or a public page. * For a new page, read [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) or [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) first. This guide covers the visual layer they both use. ## Know the layers | Layer | Lives in | Use it for | | ----------------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Tokens | `src/styles/app.css`, on `:root` and `:root[data-theme="dark"]` | Colours, radius and fonts. Tailwind utilities such as `bg-background`, `text-muted-foreground` and `border-border` read them | | beUI source | `packages/beui` (the `@workspace/beui` workspace package) | The components themselves: buttons, inputs, select, tabs, table, surface, modal, popover, form layout | | Motion components | `src/components/motion` | What pages import. Each file re-exports or adapts a beUI component for this app (`button`, `input`, `select`, `switch`, `checkbox`, `tabs`, `surface`, `table`, `morphing-modal`, `drawer`, `tooltip`, `toast`, `empty-state`, `status-tag`, `skeleton`, `loader`, `theme-toggle`) | | Admin patterns | `src/components/admin` | Whole regions of a console page: record lists, metric rows, panels, config forms, save state | | Public primitives | `src/components/marketing/ui/page-shell.tsx` | Bands, headers and panels for public pages | | Shells | `src/components/layout` | `AppShell` (admin, setup) and `AppConsoleLayout` (workspace): sidebar, header and the page's single `
` | ## Build a screen ### Pick the frame A console page renders inside `AppShell` (admin) or `AppConsoleLayout` (workspace). A public page renders inside `PublicMarketingShell`. The shell renders the `
` element. Use `
` and `
` inside it, and do not add a second `
`. ### Compose a pattern before writing markup For a console page, start from the patterns in `src/components/admin`: | Pattern | Import | Gives you | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- | | `AdminRecords` | `@/components/admin/admin-records` | A searchable, paginated record list from `columns`, `rows` and `rowKey`; a table on desktop and labelled records on a phone | | `AdminMetrics` | `@/components/admin/admin-metrics` | A row of figures from `items` (`label`, `value`, optional `detail`) | | `AdminPanel`, `AdminFacts` | `@/components/admin/admin-detail` | A titled panel with optional `actions`, and a label/value grid for detail pages | | `ConfigShell`, `ConfigPanel`, `ConfigPanelGrid`, `ConfigField`, `ConfigFormFields`, `ConfigSelect`, `ConfigSwitch`, `ConfigTextarea`, `ConfigMessage`, `ConfigDetailsTable` | `@/components/admin/config-layout` | The layout of every `/admin/config/*` form | | `useAdminSave`, `AdminSaveFeedback` | `@/components/admin/admin-save` | Permission-aware save state: `allowed`, `pending`, `result`, `save()` and the saved or failed message | | `AdminSectionWorkspace` | `@/components/admin/admin-section-workspace` | An `AppShell` page with a title, header `actions` and links (`tabs`) to its sub-pages | | `adminRouteFeedback` | `@/components/admin/admin-route-feedback` | The pending and error components to spread into an admin route | `useAdminSave("config.write")` reads the signed-in user's permissions from the layout snapshot. When `allowed` is false, disable the form and show the read-only message. The server function still checks the permission. ### Fill in with motion components Import controls from `src/components/motion`, and form layout from the beUI package: ```tsx import { FieldLegend, FieldSet } from "@workspace/beui/form-layout"; import { Button } from "@/components/motion/button"; import { Input } from "@/components/motion/input"; import { Surface, SurfaceContent } from "@/components/motion/surface"; ``` `Button` and `ButtonLink` take `variant="primary" | "secondary" | "ghost" | "outline" | "danger"`. `@workspace/beui` has no index export. Import the subpath you need (`@workspace/beui/form-layout`, `@workspace/beui/components/motion/*`), or the app's wrapper in `src/components/motion` when one exists. ### Style with utilities on tokens Use Tailwind utilities that resolve to tokens: `bg-background`, `bg-card`, `bg-muted`, `text-foreground`, `text-muted-foreground`, `text-primary`, `border-border`, `ring-ring`, `rounded-lg`. Do not write hex colours, `rgb()` values or inline `style` colours in a page, because a hard-coded colour does not follow the dark theme. Use the `dark:` variant only when a token cannot express the difference. The variant follows `data-theme="dark"` on the root element. ## Change the theme ### Edit the tokens in both themes Open `src/styles/app.css`. The product tokens are the block at the end of `:root`, under the comment that begins "beUI: one set of tokens for the whole product", and the same names in `:root[data-theme="dark"]`: ```css title="src/styles/app.css" :root { --background: #f6f5f1; --foreground: #20231f; --card: #ffffff; --primary: #3859d6; --primary-foreground: #ffffff; --muted: #eeede8; --muted-foreground: #62666e; --accent: #e8edf9; --border: #ddded8; --ring: #3859d6; --radius: 0.625rem; } ``` Change a value in both blocks. To change the brand colour, set `--primary`, `--ring` and `--brand-accent` together, and pick a `--primary-foreground` that stays readable on it. `--radius` scales every rounded corner. The sidebar has its own `--sidebar-*` set. ### Leave the Tailwind mapping alone The `@theme inline` block maps each token to a utility colour (`--color-primary: var(--primary)`). Edit it only when you add a new token and want a utility for it. ### Keep fonts in the stylesheet Fonts are imported at the top of `app.css` (Geist, Geist Mono and Noto Sans SC) and named in the `font-family` on `:root` and `--font-sans` in `@theme inline`. Replace the import and both names to change the typeface. ### Bring the validator and the site config along `pnpm validate:beui-console` asserts that the six core tokens are hex values in both themes and pins the page background to `#f6f5f1` (light) and `#101114` (dark). When you change `--background`, update those two values in `scripts/validate/beui-console.ts` in the same change. Then set `themeColor` and `backgroundColor` in `src/config/site.ts` to match; see [Rebrand the project](https://kernlift.dev/docs/customize/branding.md). ## Avoid what the validators reject | Rule | Enforced by | | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | | No route under `admin`, `app`, `auth` or `system` may reach a module in `src/components/ui` (shadcn), directly or through its imports | `pnpm validate:beui-console` | | Every admin and workspace page reaches `AppShell` or `AppConsoleLayout` | `pnpm validate:beui-console` | | Console pages and their components add no `
` of their own | `pnpm validate:beui-console` | | `app.css` declares no bare element rule (`a`, `button`, `h1`, `table` and so on) outside a cascade layer | `pnpm validate:beui-console` | | Tokens are not scoped to a surface attribute | `pnpm validate:beui-console` | | The landing and pricing pages hard-code no colour, use no inline style and no `ds-`/`mk-` class prefix | `pnpm validate:example-landing` | | New files carry no `!important` | `pnpm check` | `src/styles/app.css` carries historical `!important` and specificity debt, and `biome.json` exempts that one file. Do not widen the exemption, and do not run `biome check --write --unsafe` across the repository. That command strips `!important` from the stylesheet and rewrites React hook dependency arrays. A page also declares no class-name prefix of its own. If a design tool produced the screen, rebuild it with the components and utilities above. Do not paste its class names. ## Add a component beUI does not have yet 1. Check `src/components/motion` first; most controls are already there. 2. If it is missing, install it from the beUI registry into `packages/beui/src/components/`, then add a thin file in `src/components/motion` that re-exports it, as `src/components/motion/surface.tsx` does. Your coding agent can fetch components through the beUI MCP server at `https://mcp.beui.dev/mcp`. 3. Supply labels through the app's dictionaries. beUI components that render text read it from `BeuiLocaleProvider`, which the layouts already mount. ## Verify ```bash pnpm validate:beui-console pnpm validate:example-landing pnpm validate:mobile pnpm check ``` Open the screen in both themes (the toggle is in the public header and in the console's account menu) and in both locales, at phone width and desktop width. An area that keeps a light background in the dark theme is using a hard-coded colour. ## Next steps - [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) Route, server function, copy, guard and navigation entry. - [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) The public primitives in use. - [Architecture and layers](https://kernlift.dev/docs/guide/architecture.md) Where the design system sits in the repository. - [Validators](https://kernlift.dev/docs/reference/validators.md) Every check and what it asserts. --- # First steps after install > Read the setup checklist, connect email, then choose which customisation guide to open next. Source: https://kernlift.dev/docs/customize/first-steps You have a project running and you are signed in as administrator. This page takes it to the point where people can sign up: read the setup checklist, connect email, then start turning the template into your own product. ## Before you begin * A running project from the [Quick start](https://kernlift.dev/docs/quick-start.md). * You are signed in at `/auth/sign-in` with the administrator account. * Credentials for one email provider: Resend, Cloudflare Email or Aliyun DirectMail. ## Read the setup checklist ### Open `/setup` The page reads live configuration, so it shows what this deployment can do now. Each item is **Ready** or **Not ready**, and **Configure** opens the page that fixes it. ### Check the required items Four items are required. The rest are **optional**; set them up only when your product needs them. | Item | Required | Where you fix it | | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Session secret** | Yes | `BETTER_AUTH_SECRET` in `.env`; you set it in the quick start | | **Sign-in method** | Yes | **Settings → Auth Config**; email and password is on by default | | **Email delivery** | Yes | **Settings → Email Config** | | **Scheduled jobs** | Yes | Nothing locally: `pnpm dev` runs a round every minute. In production it depends on the platform; see [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md) | | **Payment provider** | optional | **Settings → Payment Config** | | **Object storage** | optional | **Settings → Storage Config** | | **AI channels** | optional | **Settings → AI Config** | | **Newsletter provider** | optional | The waitlist's **Provider settings** tab, with the newsletter module | | **Analytics provider** | optional | **Settings → Analytics Config** | On a fresh project only **Email delivery** is usually missing. **Scheduled jobs** turns **Ready** within a minute of the server starting. ## Connect email Verification and password reset emails cannot be sent until a provider is active, so do this first. ### Open Email Config On `/setup`, click **Configure** next to **Email delivery**, or go to **Settings → Email Config**. ### Fill in one provider Enter the provider's credentials: an **API key** for Resend, an **Account ID** and **API token** for Cloudflare, or an **AccessKey ID**, **AccessKey Secret** and **Sender account** for Aliyun. Set the **From address** your emails come from. ### Make it active and save Tick **Set as active email provider** and click **Save provider**. The page confirms with **Email provider configuration saved.** Provider-specific details, templates and the delivery log are in [Send transactional email](https://kernlift.dev/docs/extensions/email.md). ## Make the project yours The project works, but it still looks and reads like the template. Each of these has its own guide. Do them in this order, and skip what you do not need yet. | You want to | Open | | ------------------------------------------------------- | ---------------------------------------------------------------------- | | Put your name, domain, icons and share image on it | [Rebrand the project](https://kernlift.dev/docs/customize/branding.md) | | Replace the example home page and understand `/pricing` | [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) | | Change colours and fonts, or restyle a screen | [Use the design system](https://kernlift.dev/docs/customize/design-system.md) | | Rewrite copy in English and Chinese | [Add and change copy](https://kernlift.dev/docs/customize/i18n.md) | | Add your first product screen under `/app` or `/admin` | [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) | The quickest visible change is the first one: edit `src/config/site.ts`, which holds the site name, canonical URL, description and social image. ## Verify Go back to `/setup`. **Email delivery** now shows **Ready**, and the page shows **Nothing required is missing**. Sign up with a second email address in a private window: the verification email arrives from your **From address**. ## Troubleshooting ### `/setup` sends me to the sign-in page You are not signed in. Sign in at `/auth/sign-in` with the administrator account and open `/setup` again. ### `/setup` shows a permission denied page The account you signed in with is not an administrator. Sign in with the account created by `pnpm db:bootstrap-super-admin`. ### Email delivery stays Not ready after saving The provider was saved without being made active, or a required credential is empty. Tick **Set as active email provider**, fill in every credential for that provider and save again. ### Something else is wrong [Troubleshoot a project](https://kernlift.dev/docs/guide/troubleshooting.md) lists symptoms and fixes for the session secret, generated types, migrations, scheduled jobs and the agent. ## Next steps - [Rebrand the project](https://kernlift.dev/docs/customize/branding.md) Name, domain, icons, share image and metadata. - [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) Rewrite the example home page. - [Connect a payment provider](https://kernlift.dev/docs/extensions/payments/setup.md) Charge for your product with Stripe, Creem, PayPal, DodoPayments, WeChat Pay, Alipay or Waffo. - [Deploy your project](https://kernlift.dev/docs/deploy.md) Go live on Cloudflare, Fly.io, Railway or Docker. --- # Add and change copy > Edit copy in English and Chinese, add a locale-aware route, and understand the optional locale segment and the i18n validators. Source: https://kernlift.dev/docs/customize/i18n Every page ships in English and Simplified Chinese from one route file. English is served without a prefix (`/pricing`), Chinese under `/zh` (`/zh/pricing`). Components contain no copy. Copy comes from a dictionary, and both locales carry the same keys. ## Before you begin * A project that runs with `pnpm dev`. * The text in both languages. A key that exists in one dictionary only is a bug, even when the page looks fine in the language you are testing. * For a whole new page, follow [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) or [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md). This guide covers the copy and routing they rely on. ## Know where copy lives | Store | Files | Read with | | --------------------- | --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | | The main dictionaries | `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts` | `t("shell.nav.dashboard")` from `useI18n()` or `getDictionary(locale)`, or a whole namespace with `getMessageNamespace(locale, "publicSite")` | | Feature copy files | `src/i18n/*.ts`, for example `admin-plans.ts`, `auth-pages.ts`, `system-pages.ts` | The exported table indexed by locale: `adminEditingMessages[locale]` | Both hold the same kind of data. The main dictionaries carry shared and public copy and every navigation label. A feature file keeps the copy of one console area next to its types. Use whichever the code you are editing already uses. The helpers are all in `src/i18n/messages.ts`: | Helper | Use | | ---------------------------------- | ----------------------------------------------------------------------------------- | | `locales`, `defaultLocale` | `["en", "zh"]` and `"en"` | | `normalizeLocale(value)` | Turns a route param into a `Locale`; anything unknown becomes `en` | | `localizedPath(path, locale)` | `/pricing` for `en`, `/zh/pricing` for `zh`. Build every internal link with it | | `switchLocalePath(path, locale)` | The same page in another locale; the language switcher uses it | | `getDictionary(locale)` | `{ locale, t }` outside a route component | | `getMessageNamespace(locale, key)` | One top-level namespace as a typed object, including arrays and formatter functions | | `localeToIntlTag(locale)` | `en-US` or `zh-CN` for `Intl` number and date formatting | ## Change existing copy ### Find the key Search both `messages.ts` files and `src/i18n/` for the English text you see on the page. Public and shared copy is in the main dictionaries; console copy may be in a feature file. ### Edit the same key in both locales Change the value under the same path in the English and the Chinese entry. Values are strings, arrays, or functions for text with a number in it: ```ts title="src/i18n/locales/en/messages.ts" pricing: { title: "Plans", credits: (count: number) => `${count.toLocaleString("en-US")} credits included`, }, ``` Do not rename a key to change its text, because other files may read it. ## Add new copy ### Add the keys to both dictionaries For a few strings, add them to an existing namespace. For a new page or feature, add a namespace of its own, at the same position in both files: ```ts title="src/i18n/locales/en/messages.ts" reportsPage: { title: "Reports", empty: "No reports yet.", }, ``` ```ts title="src/i18n/locales/zh/messages.ts" reportsPage: { title: "报表", empty: "还没有报表。", }, ``` Keys inside a module's `// @module:` region belong to that module. Put your own keys outside those regions. ### Read them in the component Inside a route component under `{-$locale}`: ```tsx import { useI18n } from "@/i18n/use-i18n"; const { locale, t } = useI18n(); return

{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 ; } ``` Do not create a `src/routes/zh/` tree or a second file per language. `pnpm validate:route-i18n` fails on either. ### Let the parent route handle unknown locales `src/routes/{-$locale}.tsx` is the parent of every page. It returns not found for a first segment that is not a known locale and puts the resolved `locale` into the route context, which `useI18n()` reads. You do not repeat that check in a page. ### Link and describe the page per locale Build links with `localizedPath()`. For a public page, pass the localized path to `buildMeta()` and add `hreflang` alternates, as `buildHomeHead()` in `src/components/marketing/example-landing.tsx` does. The root document sets `` from the URL (`en` or `zh-Hans`) on its own. ### Regenerate the route tree Run `pnpm dev` once. It rewrites `src/routeTree.gen.ts` to include the new route. `pnpm typecheck` fails until it does. ## Know what the validators check | Validator | What it asserts about i18n | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `pnpm validate:route-i18n` | Every page route is under `src/routes/{-$locale}/`; no `src/routes/zh/` files exist; the parent route validates the locale; the home page is one route around one shared component | | `pnpm validate:app-i18n` | The shells, navigation labels, auth, system, setup and public pages read their copy from the dictionaries; navigation entries carry a `labelKey`; listed strings are not hard-coded | | `pnpm validate:beui-console` | Each console copy file in `src/i18n/` (names starting with `admin`, `asset`, `email`, `support`, `auth`, `system`, `billing` or `config`) has `en` and `zh` entries with identical keys, and no other locale | | `pnpm validate:system` | The system state pages and their copy | `pnpm validate:app-i18n` also compares the key sets of the main dictionaries and names any key that exists in only one locale. **Adding a third locale** The locale list is the `locales` constant in `src/i18n/messages.ts`, with a dictionary per entry and tags in `localeHrefLang` and `localeToIntlTag`. The console copy files and `pnpm validate:beui-console` accept `en` and `zh` only, so adding a third locale requires changing those files and that validator. ## Verify ```bash pnpm typecheck pnpm validate:route-i18n pnpm validate:app-i18n pnpm validate:beui-console ``` Open the page at its English path and under `/zh`. Use the language switcher on the page. It opens the same page in the other language, and every label changes. ## Next steps - [Add an admin or workspace page](https://kernlift.dev/docs/customize/new-page.md) Use a new namespace on a new console page. - [Replace the landing and pricing pages](https://kernlift.dev/docs/customize/landing-pages.md) The public copy namespaces in use. - [Rebrand the project](https://kernlift.dev/docs/customize/branding.md) The titles and descriptions that live in the dictionaries. --- # Replace the landing and pricing pages > Rewrite the example home page, add public pages from the page-shell primitives, and know what /pricing reads and what the validators enforce. Source: https://kernlift.dev/docs/customize/landing-pages The foundation ships an example landing page at `/`, and its copy says the page is meant to be rewritten. `/pricing` is a working page that lists the plans checkout charges. This guide shows how to rewrite the landing page and explains what `/pricing` reads. ## Before you begin * A project that runs with `pnpm dev`, and your name already in `src/config/site.ts`. See [Rebrand the project](https://kernlift.dev/docs/customize/branding.md). * The copy for your home page in every locale you ship. English and Chinese are both required by default; see [Add and change copy](https://kernlift.dev/docs/customize/i18n.md). * For `/pricing`: at least one active plan. See [Pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md). ## Know the pieces | Piece | File | What it is | | ----------------- | ------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | Home route | `src/routes/{-$locale}/index.tsx` | Loads the session snapshot and renders `ExampleLandingPage` for `/` and `/zh` | | Landing component | `src/components/marketing/example-landing.tsx` | `ExampleLandingPage`, `buildHomeHead` and `loadHomeRouteData` | | Landing copy | `publicSite.landing` in both `messages.ts` files | Title, intro, two calls to action, `features`, `steps` and the closing band | | Public shell | `src/components/marketing/public-shell.tsx` | `PublicMarketingShell` (header, footer, skip link) and `PublicPageHero` | | Layout primitives | `src/components/marketing/ui/page-shell.tsx` | `Section`, `SectionHeader`, `Panel`, `PanelGrid`, `Eyebrow`, `PageTitle`, `ArrowLink`, `Screenshot`, `CommandLine`, `FactList`, `PageContainer` | | Pricing page | `src/components/marketing/pricing-plans-page.tsx` | `PricingPlansPage`, rendered by `src/routes/{-$locale}/pricing.tsx` | | About and contact | `src/components/marketing/localized-pages.tsx` | Two short pages built the same way; copy them for new pages | ## Rewrite the home page ### Start with the copy Edit `publicSite.landing` in `src/i18n/locales/en/messages.ts` and in `src/i18n/locales/zh/messages.ts`. If the existing structure (a hero, a feature grid, three steps and a closing call to action) suits your product, changing these strings is the whole job. Set `seo.home.title` and `seo.home.description` in the same files for the page's `` and share card. ### Change the layout in `example-landing.tsx` Compose bands from the primitives. `Section` is one full-width band. `tone="stage"` gives it the muted background, and bands alternate between `page` and `stage`. `tone="inverted"` is for a single closing band. ```tsx title="src/components/marketing/example-landing.tsx" <PublicMarketingShell locale={locale}> <PublicPageHero actions={ <ButtonLink href={localizedPath("/auth/sign-up", locale)} variant="primary"> {copy.primaryCta} </ButtonLink> } copy={copy.copy} eyebrow={siteConfig.name} title={copy.title} /> <Section tone="stage"> <div className="grid min-w-0 gap-8"> <SectionHeader eyebrow={copy.featuresEyebrow} title={copy.featuresTitle} /> <PanelGrid columns={3}> {copy.features.map((feature) => ( <Panel key={feature.title}> <h3 className="m-0 text-base leading-6 font-semibold">{feature.title}</h3> <p className="m-0 text-sm leading-6 text-muted-foreground">{feature.body}</p> </Panel> ))} </PanelGrid> </div> </Section> </PublicMarketingShell> ``` Buttons come from `@/components/motion/button` (`Button`, `ButtonLink`). Build every internal link with `localizedPath(path, locale)` so `/zh` pages link to `/zh` pages. Style with Tailwind utilities on the product tokens (`text-muted-foreground`, `border-border`, `bg-card`); see [Use the design system](https://kernlift.dev/docs/customize/design-system.md). ### Keep the file, the exports and the two links Several validators read this page. They stay green when you: * keep the component in `src/components/marketing/example-landing.tsx`, exported as `ExampleLandingPage`, with `loadHomeRouteData` next to it, and keep the home route rendering it; * read copy with `getMessageNamespace(locale, "publicSite").landing`; * keep a link to `/auth/sign-up` and one to `/pricing`; * render the site name, `title`, `primaryCta`, `secondaryCta`, every `features[].title` and every entry of `steps`. If your design drops the feature grid or the steps, remove those keys from both dictionaries and update the expected list in `scripts/validate/example-landing.ts` in the same change. Do not leave a validator asserting copy the page no longer renders. ### Show account controls to a signed-in visitor The home route is the only public page that loads the session. `loadHomeRouteData()` returns the session user, whether they can open `/admin`, and their credit balance. `ExampleLandingPage` passes a `PublicAccountMenu` to the shell's `account` prop, which replaces the sign-in and sign-up buttons. Leave `account` unset on other public pages so they stay anonymous and cacheable. ## Add another public page 1. Add copy under a new namespace in both `messages.ts` files, the way `aboutPage` is defined. 2. Add a component next to `AboutMarketingPage` in `src/components/marketing/localized-pages.tsx` (or in its own file under `src/components/marketing/`): a `PublicMarketingShell` around a `PublicPageHero` and one or more `Section`s. 3. Add the route by copying `src/routes/{-$locale}/about.tsx` and changing the path in `createFileRoute("/{-$locale}/about")`. 4. Add the path to `publicSeoRoutes` in `src/server/services/static-seo.service.ts` so it appears in `/sitemap.xml`. 5. To put it in the header, add an entry to `publicNavigation` in `src/components/marketing/public-shell.tsx` and a matching label under `publicSite.navigation` in both dictionaries. Footer links are in the same file. 6. Run `pnpm dev` once so `src/routeTree.gen.ts` picks up the route. ## Know what `/pricing` reads `/pricing` has no plan data in code. Its loader calls `getMarketingSite()` for the current locale and keeps the plans whose status is `active`. Those rows come from the `pricing_plans` table, one per plan and locale, and you edit them at `/admin/plans`. | On the page | Comes from | | ---------------------------------------------- | ------------------------------------------------------------------------ | | Plan name, description, features, button label | The plan's row for the current locale | | Price | That row's `priceCents` and `currency`, formatted for the locale | | Interval line | `publicSite.pricing.intervals` (`month`, `year`, `lifetime`, `one_time`) | | "credits included" line | `includedCredits`, shown when it is above zero | | Heading, intro, empty state | `publicSite.pricing` in the dictionaries | A plan's button posts to `/api/billing/checkout`. The server re-prices the plan and sends the browser to the provider's checkout. A signed-out visitor is sent to sign in and returned to `/pricing`. Any other failure lands on `/system/payment-failed` with the reason. `/app/billing/upgrade` offers the same plans to signed-in users. To change what is for sale, edit plans in the console. To restyle the page, edit `PricingPlansPage` but keep `requestCheckout()` as the only way a button starts a purchase. With no active plan the page shows only the `publicSite.pricing.empty` line. ## Follow the rules the validator enforces `pnpm validate:example-landing` reads `example-landing.tsx` and `pricing-plans-page.tsx` and fails when either file: * imports from `src/components/ui` (shadcn); * hard-codes a colour (`#hex`, `rgb(` or `hsl(`); * uses a `ds-`, `mk-` or `ds-mk-` class name. The `ds-mk-*` marketing namespace is retired. Do not bring it back, and do not carry over class names from whatever tool generated a design; * uses an inline `style={{ … }}`; * does not render inside `PublicMarketingShell`. A public page declares no tokens of its own. If a colour is missing, add or change a token on `:root` in `src/styles/app.css` so every surface gets it. The same validator also follows every link the landing, the pricing page and the shell render, and every path in `publicSeoRoutes`, and fails on one that reaches no route file. ## Verify ```bash pnpm validate:example-landing pnpm validate:marketing pnpm validate:route-i18n pnpm validate:app-i18n pnpm validate:mobile ``` Then open `/` and `/zh` in the light and dark theme, at phone width and desktop width. Open `/pricing` signed out and click a plan. You are sent to sign in and then returned to `/pricing`. ## Next steps - [Pricing plans](https://kernlift.dev/docs/extensions/payments/pricing-plans.md) Create the plans `/pricing` lists. - [Use the design system](https://kernlift.dev/docs/customize/design-system.md) Tokens, motion components and what not to import. - [Add and change copy](https://kernlift.dev/docs/customize/i18n.md) Keep both dictionaries in step. - [Publish content with the CMS](https://kernlift.dev/docs/extensions/cms.md) Blog, changelog and legal pages. --- # Add an admin or workspace page > Add one screen under /admin or /app with a guarded server function, copy in both locales and a navigation entry. Source: https://kernlift.dev/docs/customize/new-page This guide adds a single screen: an operator page under `/admin` or a customer page under `/app`. The layout already protects it, so you add a route file, a server function that checks who is calling, copy in two languages and one navigation entry. For a whole feature with its own tables, build a module. See [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md). ## Before you begin * A project that runs with `pnpm dev`, and an administrator account. See [Run the admin console](https://kernlift.dev/docs/core/admin.md). * The path (`/admin/<name>` or `/app/<name>`), what the page reads and what it writes. * For an admin page: the permission key that gates it. Reuse an existing key from the catalog at `/admin/permissions` when one fits. * If you work with a coding agent, the `new-page` skill carries the same steps. See [Use agent skills](https://kernlift.dev/docs/core/agent-skills.md). ## Understand what the layout gives you | Area | Layout route | What it does before your page loads | | ---------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | | `/admin/*` | `src/routes/{-$locale}/admin.tsx` | Requires a session and the `admin.access` permission. No session redirects to `/system/session-expired`; no permission to `/system/permission-denied` | | `/app/*` | `src/routes/{-$locale}/app.tsx` | Requires a session. No session redirects to `/system/session-expired`; a banned account to `/system/permission-denied` | Both layouts also return not found for a page that belongs to a plugin which is switched off, and pass the signed-in user's permissions to the page through `AuthProvider`. A new file under either directory is protected without any code of its own. The layout protects pages. It does not protect data: a server function is an HTTP endpoint anyone can call, so each server function must check the caller. ## Add the page ### Write the server function Add it to the matching file in `src/server/functions/`, or a new file there. Validate input with zod, resolve the caller first, then delegate to a service. ```ts title="src/server/functions/reports.ts" import { createServerFn } from "@tanstack/react-start"; import { requireAdminPermission } from "./admin-permissions"; import { requireCurrentUserId } from "./session"; // Admin: gate on a permission. export const getAdminReports = createServerFn({ method: "GET" }).handler(async () => { await requireAdminPermission("reports.read"); return listReports(); }); // Workspace: bind to the signed-in user. export const getMyReports = createServerFn({ method: "GET" }).handler(async () => { const userId = await requireCurrentUserId(); return listReportsForUser(userId); }); ``` `requireAdminPermission()` throws `Permission denied: <key>` for a caller without the permission. `requireCurrentUserId()` rejects a caller with no session or a banned account. There is no fallback identity. Database access belongs in a repository under `src/server/db/repositories/`, called from a service. ### Add the copy to both locales Add a namespace with the same keys to `src/i18n/locales/en/messages.ts` and `src/i18n/locales/zh/messages.ts`, and a label for the navigation entry under `shell.nav` (admin) or `appConsole` (workspace). See [Add and change copy](https://kernlift.dev/docs/customize/i18n.md). ### Create the route file For an admin page, copy the shape of `src/routes/{-$locale}/admin/rate-limits.tsx`: ```tsx title="src/routes/{-$locale}/admin/reports.tsx" import { createFileRoute } from "@tanstack/react-router"; import { AdminRecords } from "@/components/admin/admin-records"; import { adminRouteFeedback } from "@/components/admin/admin-route-feedback"; import { AppShell } from "@/components/layout/app-shell"; import { getMessageNamespace, normalizeLocale } from "@/i18n/messages"; import { getAdminReports } from "@/server/functions/reports"; export const Route = createFileRoute("/{-$locale}/admin/reports")({ ...adminRouteFeedback, loader: () => getAdminReports(), component: AdminReportsPage, }); function AdminReportsPage() { const rows = Route.useLoaderData(); const locale = normalizeLocale(Route.useParams().locale); const copy = getMessageNamespace(locale, "adminReportsCopy"); return ( <AppShell activeNav="Reports" currentPage={copy.currentPage} locale={locale} mode="admin"> <AdminRecords columns={[{ key: "name", label: copy.name, render: (row) => row.name }]} emptyLabel={copy.empty} rowKey={(row) => row.id} rows={rows} /> </AppShell> ); } ``` `adminRouteFeedback` supplies the pending and error components. Spread it into every admin route. For a workspace page, copy `src/routes/{-$locale}/app/tickets/index.tsx`. That page renders inside `AppConsoleLayout` from `@/components/layout/app-console-sidebar`, reads copy with `useI18n()`, and passes the id of its navigation entry as `active`. A list page that has a detail child returns `<Outlet />` when the path goes deeper, as `src/routes/{-$locale}/admin/orders.tsx` does. ### Build the body from the design system Compose the admin patterns (`AdminRecords`, `AdminMetrics`, `AdminPanel`, the `Config*` layout, `useAdminSave`) and components from `src/components/motion`. Do not import `src/components/ui`, and do not add a `<main>`, because the shell renders it. See [Use the design system](https://kernlift.dev/docs/customize/design-system.md). For a page that saves, call `useAdminSave("<key>.write")`. Disable the form when `allowed` is false, and check the same permission again in the server function that writes. ### Add the navigation entry Sidebar entries are plugin contributions. For a page that is part of your product, add it to the foundation plugin in `src/plugins/foundation/plugin.ts`. An admin entry goes in the `adminNav` array: ```ts title="src/plugins/foundation/plugin.ts" { ...operations, label: "Reports", labelKey: "shell.nav.reports", to: "/admin/reports", icon: ListChecks, permission: "reports.read", order: 650, }, ``` The group constants at the top of the file (`overview`, `operations`, `commerce`, `platform`, `security`, `settings`) set the sidebar section. `order` sets the entry's position. Foundation entries step by 100, so yours fits between two of them. `permission` is required, and the sidebar hides the entry from anyone who lacks it. A workspace entry goes in the `app.nav` list of the same plugin: ```ts title="src/plugins/foundation/plugin.ts" { id: "reports", icon: ListTodo, labelKey: "appConsole.reports", path: "/app/reports", section: "product", order: 35, }, ``` `section` is `product` or `account`. The page passes the same `id` as `active` to `AppConsoleLayout`. To ship the page as something that can be switched off at `/admin/plugins`, give it its own plugin. See [Console plugins](https://kernlift.dev/docs/core/plugins/console-plugins.md). ### Grant a new permission Skip this if you reused an existing key. For a new key, add a row to `superAdminPermissionTemplates` in `src/server/services/super-admin-bootstrap.service.ts`, then run: ```bash pnpm db:bootstrap-super-admin ``` The script upserts every permission and grants them all to the Super Admin role. Grant the key to other roles at `/admin/roles`. See [Manage users, roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). ### Regenerate the route tree ```bash pnpm dev ``` Starting the dev server rewrites `src/routeTree.gen.ts` with the new route. Then run `pnpm typecheck`. ## Verify ```bash pnpm typecheck pnpm validate:auth-boundary pnpm validate:plugins pnpm validate:beui-console pnpm validate:route-i18n pnpm validate:app-i18n ``` What these catch on a new page: | Validator | Fails when | | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `pnpm validate:auth-boundary` | An exported server function neither resolves identity nor checks a permission. A deliberately public function must be listed with its reason in `publicServerFunctions` in `scripts/validate/auth-boundary.ts` | | `pnpm validate:plugins` | A navigation entry points at no route file, an admin entry has no `permission`, or a workspace page passes an `active` id that no `app.nav` entry declares | | `pnpm validate:beui-console` | The page reaches `src/components/ui`, renders outside the shells, or adds its own `<main>` | | `pnpm validate:route-i18n` | The route file is not under `src/routes/{-$locale}/` | Then check in the browser: * Open the page at its English path and under `/zh`, in the light and the dark theme. * Sign in as a user without the permission. The sidebar entry is gone, and opening the URL directly shows the route's error state because the loader's server function rejects the call. * Sign out and open the URL. You are redirected to `/system/session-expired`. ## Next steps - [Use the design system](https://kernlift.dev/docs/customize/design-system.md) The admin patterns and motion components. - [Console plugins](https://kernlift.dev/docs/core/plugins/console-plugins.md) Contribute pages and navigation from a plugin of your own. - [Authentication and authorization model](https://kernlift.dev/docs/core/auth.md) Why server functions check the caller themselves. --- # Deploy to Cloudflare Workers > Deploy the Worker on D1 or on Postgres through Hyperdrive, store the session secret, create the production administrator, and optionally add the agent container. Source: https://kernlift.dev/docs/deploy/cloudflare On Cloudflare the project is a Worker with an R2 bucket and a KV namespace. Its database is D1, or Postgres reached through Hyperdrive. The agent service is optional and runs as a Cloudflare container, on Postgres only. Use this guide for the first production deployment, or after you change a binding. ## Before you begin * A Cloudflare account, with `wrangler` signed in (`npx wrangler login`). * `deploy.config.json` says `"platform": "cloudflare"`. If it names another platform, run `pnpm kernlift deploy-target cloudflare` first; see [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md). * For Postgres: an empty Postgres database and its connection URL; see [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md). * `.env.production` in the project root. `pnpm kernlift deploy-target cloudflare` generates it with the session secret. ## Create resources in Cloudflare Sign in to Wrangler with the account where you will deploy. Replace `my-saas` with your project name. ### Choose the database connection For D1, create the database and record the printed `database_id`. ```bash npx wrangler d1 create my-saas-edge ``` For Postgres, create Hyperdrive instead. Replace the example connection string with yours and keep the configuration ID. ```bash npx wrangler hyperdrive create my-saas-db --connection-string='postgresql://USER:PASSWORD@HOST:5432/DB' ``` ### Create the object bucket Keep the bucket name for the R2 binding. ```bash npx wrangler r2 bucket create my-saas-assets ``` ### Create the cache namespace Keep the namespace ID for the KV binding. ```bash npx wrangler kv namespace create my-saas-cache ``` Copy the D1 `database_id`, the KV `id`, the R2 bucket name and the Hyperdrive id into the existing `wrangler.jsonc` entries. If Wrangler offers to add a binding automatically, decline. The template already declares `EDGE_DB`, `BUCKET`, `CACHE` and `HYPERDRIVE`, and the application looks bindings up by those names. See [creating D1](https://developers.cloudflare.com/d1/get-started/), [creating R2 buckets](https://developers.cloudflare.com/r2/buckets/create-buckets/), [creating KV namespaces](https://developers.cloudflare.com/kv/get-started/) and [Hyperdrive](https://developers.cloudflare.com/hyperdrive/get-started/). ## Bind the resources ### Fill in `wrangler.jsonc` Replace every `replace-with-...` placeholder with a real id and keep the worker `name`. A D1 project carries: ```jsonc title="wrangler.jsonc" "r2_buckets": [{ "binding": "BUCKET", "bucket_name": "my-saas-assets" }], "kv_namespaces": [{ "binding": "CACHE", "id": "<your KV namespace id>" }], "d1_databases": [ { "binding": "EDGE_DB", "database_name": "my-saas-edge", "database_id": "<your D1 database id>", "migrations_dir": "./drizzle/migrations/sqlite" } ] ``` A Postgres project has no `d1_databases` block. It sets `DATABASE_DIALECT` to `postgres` and `DATABASE_ADAPTER` to `hyperdrive` under `vars`, and carries: ```jsonc title="wrangler.jsonc" "hyperdrive": [{ "binding": "HYPERDRIVE", "id": "<your Hyperdrive id>" }] ``` ### Set the production variables Under `vars`, a D1 project ships `APP_ENV` as `development`; change it to `production`. Add `SITE_URL` with your public origin. Secrets never go in this file. ### Regenerate the binding types ```bash pnpm cf-typegen ``` **Re-rendering sets your wrangler.jsonc aside** `pnpm kernlift deploy-target cloudflare --dialect postgres` turns a D1 project into a Hyperdrive one by rendering `wrangler.jsonc` again from the template. Your current file, with its resource ids, moves to `.kernlift/previous-deploy/wrangler.jsonc`; copy the bucket name and KV id from it into the new file. ## Migrate and deploy ### Apply the migrations For D1: ```bash pnpm db:migrate:d1:remote ``` For Postgres, migrate the database directly from the checkout. Hyperdrive is a Worker binding, so the migration uses the Postgres URL itself: ```bash DATABASE_DIALECT=postgres DATABASE_URL='postgresql://USER:PASSWORD@HOST:5432/DB' pnpm db:migrate ``` ### Build and deploy ```bash pnpm build pnpm run deploy ``` The script runs `wrangler deploy` and prints the Worker URL. ### Store the session secret A secret is attached to an existing Worker, so store it after the first deploy. The value is read from `.env.production` over standard input: ```bash grep '^BETTER_AUTH_SECRET=' .env.production | cut -d= -f2- | npx wrangler secret put BETTER_AUTH_SECRET grep '^CONFIG_ENCRYPTION_KEY=' .env.production | cut -d= -f2- | npx wrangler secret put CONFIG_ENCRYPTION_KEY ``` ### Create the production administrator For D1, run the bootstrap from the checkout; `--remote` reaches the deployed database through wrangler: ```bash DATABASE_DIALECT=d1 SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='<password>' pnpm db:bootstrap-super-admin --remote ``` For Postgres, point it at the production database: ```bash DATABASE_DIALECT=postgres DATABASE_URL='postgresql://USER:PASSWORD@HOST:5432/DB' SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='<password>' pnpm db:bootstrap-super-admin ``` The script reads the email and password from the environment. It does not accept them as arguments. **Use pnpm run deploy** `pnpm deploy` without `run` is pnpm's own workspace command, not the project script. ## Add the agent container Skip this section if the project does not include the agent. The agent needs Postgres, so the project must be on Hyperdrive. `pnpm kernlift deploy-target cloudflare --agent` renders `wrangler.jsonc` with the `containers` and `durable_objects` blocks and adds the agent secrets to `.env.production`. ### Store the agent secrets ```bash grep '^AGENT_INTERNAL_SIGNING_SECRET=' .env.production | cut -d= -f2- | npx wrangler secret put AGENT_INTERNAL_SIGNING_SECRET grep '^AGENT_RESOURCE_GRANT_SECRET=' .env.production | cut -d= -f2- | npx wrangler secret put AGENT_RESOURCE_GRANT_SECRET ``` Store `AGENT_DATABASE_URL` the same way. It is the direct Postgres URL. The container cannot use the Hyperdrive binding, so it connects to the same database directly. ### Point the agent back at the Worker Set `AGENT_WEB_INTERNAL_URL` under `vars` in `wrangler.jsonc` to the Worker's public URL. The agent service calls the web app there. ### Deploy again ```bash pnpm build pnpm run deploy ``` Wrangler builds the container image from `apps/agent-service/Dockerfile`. One instance runs, because the service holds run state in memory. ## Verify * `pnpm run deploy` prints the Worker URL, and the site loads there. * `/setup`, signed in as the administrator, names Cloudflare and the database in its first line and shows **Session secret** as ready. * `/admin/config/auth` shows the **Base URL** the site answers on. Change it there if the site uses another domain. * **Scheduled jobs** turns ready within a couple of minutes. The Cron Trigger in `wrangler.jsonc` runs a round every minute. * With the agent, `/app/agent` opens the workbench. * In the repository, `pnpm smoke:worker` after `pnpm build` runs the built Worker on a throwaway D1 database, and `pnpm validate:deploy-targets` checks the rendered configuration. ## Troubleshooting ### `EDGE_DB D1 binding is required when DATABASE_ADAPTER=d1` The Worker has no D1 binding named `EDGE_DB`. Check `d1_databases` in `wrangler.jsonc` and deploy again. ### `DATABASE_ADAPTER=hyperdrive needs the HYPERDRIVE Worker binding.` The `hyperdrive` entry in `wrangler.jsonc` is missing or still carries the placeholder id. Put the real Hyperdrive id there and deploy again. ### The Worker refuses to start with a session secret error `APP_ENV` is not `development` and `BETTER_AUTH_SECRET` is missing. Store it with the command above. ### Pages fail with missing tables Migrations ran against a local database only. Run `pnpm db:migrate:d1:remote`, or `pnpm db:migrate` against the Postgres URL. ### Scheduled jobs stay not ready Check that `wrangler.jsonc` keeps `"triggers": { "crons": ["* * * * *"] }` and that the deployed Worker lists the trigger. ## Reference * [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) and [Environment variables](https://kernlift.dev/docs/reference/env.md) * [Cache](https://kernlift.dev/docs/core/admin/cache.md) and [Storage](https://kernlift.dev/docs/extensions/storage.md) * [Wrangler configuration](https://developers.cloudflare.com/workers/wrangler/configuration/) * [D1](https://developers.cloudflare.com/d1/), [R2](https://developers.cloudflare.com/r2/), [KV](https://developers.cloudflare.com/kv/), [Hyperdrive](https://developers.cloudflare.com/hyperdrive/), [Containers](https://developers.cloudflare.com/containers/) ## Next steps - [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) - [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md) - [Run the agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) --- # Deploy with Docker Compose > Run the project on your own server with compose.yaml: set the public URL, start the stack with migrations, put TLS in front, and create the production administrator. Source: https://kernlift.dev/docs/deploy/docker On a Docker host the project is a compose stack: a `migrate` service that applies the migrations and exits, the `web` service built from the root `Dockerfile`, and either a SQLite file on a volume or a bundled Postgres. The agent service is optional and runs as a compose service, on Postgres only. Nothing remote is created. Use this guide for the first deployment on a server you manage. ## Before you begin * A server with Docker and Docker Compose (`docker compose version` prints a version), and the project checked out on it. * `deploy.config.json` says `"platform": "docker"`. Run `pnpm kernlift deploy-target docker` to set it, with `--dialect sqlite`, `--dialect postgres` or `--agent` as needed. See [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md). * `compose.yaml` and `.env.production` in the project root; that command writes them. `.env.production` is not committed, so copy it to the server yourself. * A domain pointing at the server, and a reverse proxy that terminates TLS. ## Prepare the values ### Set the public URL In `.env.production`, set `SITE_URL` to the public address, for example `https://your-domain.com`. Without it the web service falls back to `http://localhost:3000`. On first start the app also seeds the auth **Base URL** from it, so OAuth callbacks and email links would point there. ### Check the generated secrets The same file must hold `BETTER_AUTH_SECRET` and `CONFIG_ENCRYPTION_KEY`, and `POSTGRES_PASSWORD` when the database is Postgres. With the agent it also holds `AGENT_INTERNAL_SIGNING_SECRET` and `AGENT_RESOURCE_GRANT_SECRET`. Compose fails to start when one of them is missing. To add missing keys without changing existing ones, run `pnpm kernlift deploy-target docker` again. ## Start the stack ### Build, migrate and start ```bash pnpm run deploy ``` The script runs: ```bash docker compose --env-file .env.production up -d --build ``` The `migrate` service runs `node scripts/db/migrate-runtime.mjs` first; `web` starts only after it succeeds. With Postgres, `migrate` waits for the `postgres` service to be healthy. ### Put TLS in front The `web` service publishes port 3000. Point your reverse proxy at it and serve the site over HTTPS on the address you put in `SITE_URL`. ### Create the production administrator ```bash docker compose --env-file .env.production exec web node .output/scripts/bootstrap-super-admin.mjs ``` The script runs inside the web container, against its own database, and prompts for the email and password. ## Where the data lives | Database | Service | Volume | | ---------- | -------------------------------------------------------------------- | -------- | | `sqlite` | None; `web` opens `/data/app.db` | `data` | | `postgres` | `postgres`, image `postgres:16-alpine`, user and database `kernlift` | `pgdata` | Back these volumes up. Removing them removes the database. Files uploaded by users are not stored on the server. Configure S3-compatible storage in `/admin/config/storage`; see [Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md). With `"agent": true`, the stack also has an `agent` service built from `apps/agent-service/Dockerfile`. The web service reaches it at `http://agent:3001` on the compose network. The agent publishes no port. Run one instance, because it holds run state in memory. ## Deploy a new version Pull the new code and run `pnpm run deploy` again. The images are rebuilt, `migrate` applies any new migrations, and `web` is replaced after it succeeds. ## Verify * `docker compose ps` shows `web` running and `migrate` exited successfully. * The site loads over HTTPS at your domain. * `/setup`, signed in as the administrator, names Docker and the database in its first line and shows **Session secret** as ready. * `/admin/config/auth` shows the **Base URL** the site answers on. Change it there if the site uses another domain. * **Scheduled jobs** turns ready within a couple of minutes. The jobs run inside the web container. * With the agent, `/app/agent` opens the workbench. * In the repository, `pnpm smoke:node` after `pnpm build:node` checks the build you ship, and `pnpm validate:deploy-targets` checks the rendered `compose.yaml`. ## Troubleshooting ### Compose stops with `set BETTER_AUTH_SECRET`, `set CONFIG_ENCRYPTION_KEY` or `set POSTGRES_PASSWORD` The value is missing from `.env.production`, or the command ran without `--env-file .env.production`. Use `pnpm run deploy`. ### OAuth sign-in or email links point at `localhost:3000` The **Base URL** at `/admin/config/auth` still holds the fallback address. Correct it there. Also set `SITE_URL` in `.env.production` and run `pnpm run deploy` again so metadata and absolute links use the public address. ### `web` never starts `migrate` failed. Read its output with `docker compose logs migrate`. ### Scheduled jobs stay not ready on `/setup` Check that the web container is up with `docker compose ps`. If `JOBS_IN_PROCESS=false` is set, an external cron has to run `pnpm jobs:run` instead. ## Next steps - [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) - [Run the Node build](https://kernlift.dev/docs/deploy/node.md) - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) - [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) --- # Deploy to Fly.io > Create the Fly app, import the generated secrets, deploy the Node image with migrations, create the production administrator, and optionally add the agent app. Source: https://kernlift.dev/docs/deploy/fly On Fly.io the project is one app built from the root `Dockerfile`. Its database is a SQLite file on a volume, for a single machine, or a Postgres you bring. The agent service is optional and runs as a second app on Fly's private network, on Postgres only. Use this guide for the first production deployment. ## Before you begin * The `fly` CLI, signed in (`fly auth login`). * `deploy.config.json` says `"platform": "fly"`. Run `pnpm kernlift deploy-target fly` to set it, with `--dialect`, `--agent` or `--region` as needed. See [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md). * `fly.toml` and `.env.production` in the project root; that command writes them. * For Postgres: a database and its connection URL; see [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md). The examples use `my-saas` as the app name and `iad` as the region. Use the `app` and `primary_region` from your `fly.toml`. ## Create the app and store the secrets `kernlift deploy-target fly` prints these steps for your project. ### Set the public URL In `.env.production`, set `SITE_URL` to the address the site will be served from. For Postgres, add a `DATABASE_URL=` line with the connection URL to the same file. ### Create the app ```bash fly apps create my-saas ``` For SQLite, also create the volume that holds the database file: ```bash fly volumes create data --app my-saas --region iad --size 1 --yes ``` ### Import the secrets The values are read from `.env.production` over standard input. For SQLite: ```bash grep -E '^(BETTER_AUTH_SECRET|CONFIG_ENCRYPTION_KEY|SITE_URL)=' .env.production | fly secrets import --app my-saas ``` For Postgres, include the database URL: ```bash grep -E '^(BETTER_AUTH_SECRET|CONFIG_ENCRYPTION_KEY|SITE_URL|DATABASE_URL)=' .env.production | fly secrets import --app my-saas ``` ## Deploy ### Deploy the web app ```bash fly deploy ``` `pnpm run deploy` runs the same command. Fly builds the root `Dockerfile` and applies the migrations before the new version takes traffic. With Postgres, `release_command` runs `node scripts/db/migrate-runtime.mjs` on a temporary machine. With SQLite, the app process migrates the file on the volume and then starts the server. ### Create the production administrator ```bash fly ssh console --app my-saas --pty -C "node .output/scripts/bootstrap-super-admin.mjs" ``` The script runs inside the app, against its own database, and prompts for the email and password. **Keep one machine running** The scheduled jobs run inside the web process, so `fly.toml` sets `min_machines_running = 1`. A stopped machine runs no fulfilment retries or AI task polling. With SQLite, do not scale the app beyond one machine, because the database file belongs to one machine. ## Add the agent app Skip this section if the project does not include the agent. With `"agent": true`, the project also carries `fly.agent.toml` for the `my-saas-agent` app, and `fly.toml` points the web app at `http://my-saas-agent.internal:3001`. The agent app has no public service and is not auto-stopped mid-run. ### Create the agent app and import its secrets ```bash fly apps create my-saas-agent grep -E '^(AGENT_INTERNAL_SIGNING_SECRET|AGENT_RESOURCE_GRANT_SECRET|DATABASE_URL)=' .env.production | fly secrets import --app my-saas-agent ``` ### Give the web app the signing secret ```bash grep -E '^AGENT_INTERNAL_SIGNING_SECRET=' .env.production | fly secrets import --app my-saas ``` ### Deploy the agent service ```bash fly deploy -c fly.agent.toml ``` Run a single machine, because the service holds run state in memory. ## Verify * `fly deploy` prints the app's address, and the site loads there. * `/setup`, signed in as the administrator, names Fly.io and the database in its first line and shows **Session secret** as ready. * `/admin/config/auth` shows the **Base URL** the site answers on. Change it there if the site uses another domain. * **Scheduled jobs** turns ready within a couple of minutes. * With the agent, `/app/agent` opens the workbench. * In the repository, `pnpm smoke:node` after `pnpm build:node` checks the build you ship, and `pnpm validate:deploy-targets` checks the rendered `fly.toml`. ## Troubleshooting ### The deploy fails in the release command The migration could not reach Postgres. Check that `DATABASE_URL` was imported into the app and that the database accepts connections from Fly. ### The app refuses to start with a session secret error `BETTER_AUTH_SECRET` was not imported. Run the import command again. ### Scheduled jobs stay not ready on `/setup` Check that `fly.toml` keeps `min_machines_running = 1`. If `JOBS_IN_PROCESS=false` is set, an external cron has to run `pnpm jobs:run` instead. ### The workbench says the agent service is not deployed The web app cannot reach `my-saas-agent.internal:3001`, or the two apps hold different values of `AGENT_INTERNAL_SIGNING_SECRET`. Import the secret into both apps from the same `.env.production`. ## Next steps - [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) - [Run the Node build](https://kernlift.dev/docs/deploy/node.md) - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) - [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) --- # Deploy your project > Pick one of the four platforms, store the generated secrets, migrate, deploy, and create the production administrator. Source: https://kernlift.dev/docs/deploy This tutorial takes the project you ran locally to a public URL. A project deploys to one platform: Cloudflare, Fly.io, Railway or a Docker host. The choice is recorded in `deploy.config.json`, and only that platform's files are in the repository. This page is the shortest path. Each platform has a full guide. ## Before you begin * A project that builds locally: `pnpm build` finishes without errors. * The CLI of the platform you deploy to, signed in: `wrangler`, `fly`, `railway`, or Docker Compose. * For Postgres on Cloudflare or Fly.io: a Postgres database and its connection URL. Railway and Docker create their own. ## Choose a platform | Platform | Databases | Agent service | Pick it when | | ---------- | ------------------------------------------- | -------------------------------------------------- | -------------------------------------------------------------------- | | Cloudflare | D1, or Postgres through Hyperdrive | Cloudflare container, Postgres only | You want a Worker with D1, R2 and KV bindings | | Fly.io | SQLite on a volume, or Postgres | A second app on the private network, Postgres only | You want a container close to your users and bring your own Postgres | | Railway | Postgres | A second service | You want the platform to create Postgres with the app | | Docker | SQLite on a volume, or the bundled Postgres | A compose service, Postgres only | You run your own server | Cloudflare gets the Worker build; the other three get the Node build that the root `Dockerfile` packages. The agent service is optional everywhere and always needs Postgres. The model behind this table is in [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md). ## Deploy ### Confirm or switch the platform The repository records its platform in `deploy.config.json`. Read it: ```bash cat deploy.config.json ``` Run `deploy-target` for the platform you want, even when it is the one already recorded: a fresh clone has no `.env.production`, and this command generates it. The command writes the platform's files, moves another platform's files to `.kernlift/previous-deploy/`, completes `.env.production` and prints the remaining steps. It creates nothing remote and moves no data. ```bash pnpm kernlift deploy-target fly --no-agent pnpm cf-typegen ``` The options are listed in the [deployment configuration reference](https://kernlift.dev/docs/reference/deploy-config.md). ### Check the production values `.env.production` holds the generated session secret and the public URL. It is ignored by git and is never committed. Set `SITE_URL` in it to the address the site will be served from. The commands below read secrets from this file over standard input, so no value appears on a command line. ### Migrate and deploy on your platform **Cloudflare** ```bash pnpm db:migrate:d1:remote pnpm build pnpm run deploy grep '^BETTER_AUTH_SECRET=' .env.production | cut -d= -f2- | npx wrangler secret put BETTER_AUTH_SECRET grep '^CONFIG_ENCRYPTION_KEY=' .env.production | cut -d= -f2- | npx wrangler secret put CONFIG_ENCRYPTION_KEY ``` `wrangler.jsonc` must carry real ids for D1, R2 and KV first. Full guide: [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md). **Fly.io** ```bash fly apps create my-saas fly volumes create data --app my-saas --region iad --size 1 --yes grep -E '^(BETTER_AUTH_SECRET|CONFIG_ENCRYPTION_KEY|SITE_URL)=' .env.production | fly secrets import --app my-saas fly deploy ``` The volume is for SQLite only. Migrations run before the new version takes traffic. Full guide: [Deploy to Fly.io](https://kernlift.dev/docs/deploy/fly.md). **Railway** ```bash railway init --name my-saas railway config apply --yes railway variables --service web --set "BETTER_AUTH_SECRET=$(grep '^BETTER_AUTH_SECRET=' .env.production | cut -d= -f2-)" railway variables --service web --set "CONFIG_ENCRYPTION_KEY=$(grep '^CONFIG_ENCRYPTION_KEY=' .env.production | cut -d= -f2-)" railway variables --service web --set "SITE_URL=$(grep '^SITE_URL=' .env.production | cut -d= -f2-)" railway up ``` `railway config apply` creates the services and Postgres; the pre-deploy step runs the migrations. Full guide: [Deploy to Railway](https://kernlift.dev/docs/deploy/railway.md). **Docker** ```bash pnpm run deploy ``` The script runs `docker compose --env-file .env.production up -d --build`; the `migrate` service finishes before `web` starts. Put a reverse proxy with TLS in front of port 3000. Full guide: [Deploy with Docker Compose](https://kernlift.dev/docs/deploy/docker.md). **Use pnpm run deploy** `pnpm deploy` without `run` is pnpm's own workspace command, not the project script. ### Create the production administrator The production database is not your local one, so it needs its own administrator. On Fly.io, Railway and Docker the image carries a script that prompts for the email and password: ```bash fly ssh console --app my-saas --pty -C "node .output/scripts/bootstrap-super-admin.mjs" docker compose --env-file .env.production exec web node .output/scripts/bootstrap-super-admin.mjs ``` On Railway, open a shell with `railway ssh --service web` and run `node .output/scripts/bootstrap-super-admin.mjs`. On Cloudflare D1, run it from the checkout with `wrangler` signed in: ```bash DATABASE_DIALECT=d1 SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='<password>' pnpm db:bootstrap-super-admin --remote ``` ## Verify Open `/setup` on the deployed URL and sign in as the administrator. Then open `/admin/config/auth` and check the **Base URL**; change it there if the site answers on another domain. * The first line names the platform, the database and whether the agent service is included. * **Session secret** is ready. * **Scheduled jobs** turns ready within a couple of minutes of the first deploy. The checklist reads the live database, so configure the providers you need from there, starting with **Email delivery**. Storage is configured in `/admin/config/storage`; on Cloudflare you can also use the bucket binding the runtime detects. ## Troubleshooting ### The app refuses to start with a session secret error `BETTER_AUTH_SECRET` did not reach the platform while `APP_ENV` is not `development`. Store it again with the command for your platform. ### OAuth sign-in or email links point at the wrong address OAuth callbacks and links in emails use the **Base URL** at `/admin/config/auth`. Correct it there; the change takes effect within about 30 seconds, without a redeploy. ### Scheduled jobs stay not ready on `/setup` Nothing is starting the rounds. The item names the switch for your platform: the Cron Trigger in `wrangler.jsonc` on Cloudflare, a running web process on the others. ## Next steps - [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md) D1, Hyperdrive for Postgres, and the agent container. - [Deploy to Fly.io](https://kernlift.dev/docs/deploy/fly.md) SQLite on a volume or Postgres, with the agent as a second app. - [Deploy to Railway](https://kernlift.dev/docs/deploy/railway.md) Services and Postgres from `.railway/railway.ts`. - [Deploy with Docker Compose](https://kernlift.dev/docs/deploy/docker.md) One server, `compose.yaml` and a reverse proxy. - [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) Allowed combinations and what each platform owns. --- # Run the Node build > Build the Node server with pnpm build:node or the root Dockerfile, give it its environment, migrate, and run it on any host. Source: https://kernlift.dev/docs/deploy/node Every platform except Cloudflare runs the same Node server. `pnpm build:node` produces it, the root `Dockerfile` packages it, and Fly.io, Railway and Docker Compose each deploy that image with a generated configuration. Use this guide to understand what the build contains, or to run it on a host that has no platform guide. For the three supported platforms, follow [Deploy to Fly.io](https://kernlift.dev/docs/deploy/fly.md), [Deploy to Railway](https://kernlift.dev/docs/deploy/railway.md) or [Deploy with Docker Compose](https://kernlift.dev/docs/deploy/docker.md) instead. ## Before you begin * A host with Node 22, or Docker. * A database: Postgres (see [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md)), or a SQLite file on a disk that survives restarts, for a single instance. * A session secret. `.env.production`, generated by `kernlift deploy-target`, already holds one. ## What the build produces | Path | Contents | | ------------------------------------------- | -------------------------------------------------------------------------------------------- | | `.output/server/index.mjs` | The server. `pnpm start` runs it; it listens on `PORT`, 3000 in the image | | `.output/scripts/bootstrap-super-admin.mjs` | Creates the administrator against the deployment's own database, without a TypeScript runner | | `scripts/db/migrate-runtime.mjs` | Applies the migration chain with plain Node | | `drizzle/migrations/` | The SQLite and Postgres chains the migrator reads | The root `Dockerfile` runs `pnpm build:node` and copies these four into a `node:22` image, together with the database drivers (`better-sqlite3`, `postgres`, `drizzle-orm`), which are loaded by name at run time and are not part of the bundle. It runs as the `node` user, exposes port 3000 and provides `/data` for a SQLite file on a mounted volume. The agent service is a separate image, `apps/agent-service/Dockerfile`. `pnpm build` produces this build when `deploy.config.json` names `fly`, `railway` or `docker`. `pnpm build:node` always produces it. ## Environment The server reads its settings from the process environment. | Variable | Value | | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `APP_ENV` | `production` | | `PORT` | The port to listen on | | `BETTER_AUTH_SECRET` | The session secret from `.env.production` | | `CONFIG_ENCRYPTION_KEY` | The credential encryption key from `.env.production`; keep it stable | | `SITE_URL` | The canonical origin for metadata and absolute links | | `DATABASE_DIALECT` | `postgres` or `sqlite` | | `DATABASE_URL` | A `postgresql://` URL, or a file path such as `/data/app.db` | | `JOBS_IN_PROCESS` | Leave unset. `false` turns off the scheduled-jobs loop; an external cron must then call `pnpm jobs:run` | | `AGENT_SERVICE_URL`, `AGENT_INTERNAL_SIGNING_SECRET` | Only with the agent service: its private address and the shared signing secret | No provider credentials go here; see [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md). All variables are described in [Environment variables](https://kernlift.dev/docs/reference/env.md). ## Build and run ### Build From a checkout: ```bash pnpm install pnpm build:node ``` Or build the image from the repository root: ```bash docker build -t kernlift-web . ``` ### Apply the migrations With `DATABASE_DIALECT` and `DATABASE_URL` set, run the migrator before the new version takes traffic: ```bash node scripts/db/migrate-runtime.mjs ``` It keeps the same bookkeeping table as `pnpm db:migrate`, so either can be used on the same database. ### Start the server ```bash node .output/server/index.mjs ``` This is also the image's default command. The scheduled jobs start with the process and run a round every minute. When several replicas run, a lock row in the config table limits each round to one replica. ### Create the administrator In the same environment as the server: ```bash node .output/scripts/bootstrap-super-admin.mjs ``` It prompts for the email and the password, and does not echo the password. Without a terminal, set `SUPER_ADMIN_EMAIL` and `SUPER_ADMIN_PASSWORD` in the environment instead. ### Configure runtime services Sign in and open `/setup`. Enter S3-compatible credentials in `/admin/config/storage`. The bucket binding driver exists only on Cloudflare. At `/admin/config/cache` the backend is process memory, one cache per process. See [Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md) and [Cache](https://kernlift.dev/docs/core/admin/cache.md). ## Verify * `/setup` shows **Session secret** and **Scheduled jobs** as ready; the second one needs a minute or two after the first start. * In the repository, `pnpm smoke:node` after `pnpm build:node` starts the build on a throwaway SQLite database and checks that pages render, the agent API returns 503 without the agent service, and a scheduled round is recorded. * `pnpm validate:deploy-targets` checks that the image runs the Node build and carries the migrations and the migrator. ## Troubleshooting ### `.output/server/index.mjs is missing` The last build was the Cloudflare one, which writes `dist/`. Run `pnpm build:node`. ### `DATABASE_URL is required when DATABASE_ADAPTER=postgres` `DATABASE_DIALECT` is `postgres` but `DATABASE_URL` is empty. Set the connection string. ### The server refuses to start with a session secret error `APP_ENV` is not `development` and `BETTER_AUTH_SECRET` is missing or the template default. Set the generated value. ### Scheduled jobs stay not ready on `/setup` The web process is stopped, or `JOBS_IN_PROCESS=false` is set and nothing calls `pnpm jobs:run`. ## Next steps - [Deploy to Fly.io](https://kernlift.dev/docs/deploy/fly.md) - [Deploy to Railway](https://kernlift.dev/docs/deploy/railway.md) - [Deploy with Docker Compose](https://kernlift.dev/docs/deploy/docker.md) - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) --- # Deploy to Railway > Create the Railway project, services and Postgres from .railway/railway.ts, set the generated secrets, deploy, and create the production administrator. Source: https://kernlift.dev/docs/deploy/railway On Railway the project is a `web` service built from the root `Dockerfile` and a Postgres database, both declared in `.railway/railway.ts`. The agent service is optional and runs as a second service named `agent`. Use this guide for the first production deployment. ## Before you begin * The `railway` CLI, signed in (`railway login`). * `deploy.config.json` says `"platform": "railway"`. Run `pnpm kernlift deploy-target railway` to set it, with `--agent` if you want the agent service. See [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md). * `.railway/railway.ts` and `.env.production` in the project root; that command writes them. Railway projects run on Postgres. You do not need to prepare a database. The configuration declares one and passes its `DATABASE_URL` to the services. ## Create the project `kernlift deploy-target railway` prints these two steps for your project. ### Create the Railway project ```bash railway init --name my-saas ``` ### Apply the configuration ```bash railway config apply --yes ``` This creates the `web` service, the Postgres database and, with the agent, the `agent` service. `railway config plan` shows the changes first without applying them. ## Store the secrets and deploy ### Set the public URL In `.env.production`, set `SITE_URL` to the public address of the `web` service: your own domain, or the one Railway assigns. ### Set the variables on the web service The commands read each value from `.env.production`, so you type no secret on the command line. ```bash railway variables --service web --set "BETTER_AUTH_SECRET=$(grep '^BETTER_AUTH_SECRET=' .env.production | cut -d= -f2-)" railway variables --service web --set "CONFIG_ENCRYPTION_KEY=$(grep '^CONFIG_ENCRYPTION_KEY=' .env.production | cut -d= -f2-)" railway variables --service web --set "SITE_URL=$(grep '^SITE_URL=' .env.production | cut -d= -f2-)" ``` Set secrets this way. Do not write them into `.railway/railway.ts`. ### Deploy ```bash railway up ``` `pnpm run deploy` runs the same command. The `web` service's pre-deploy step runs `node scripts/db/migrate-runtime.mjs`, so the migrations are applied before the new version takes traffic. ### Create the production administrator Open a shell in the web service: ```bash railway ssh --service web ``` Then run the script the image carries. It prompts for the email and password: ```bash node .output/scripts/bootstrap-super-admin.mjs ``` **Scheduled jobs need a running web service** The scheduled jobs run inside the `web` service. If the service is not running, no fulfilment retries or AI task polling happen until it is. ## Add the agent service Skip this section if the project does not include the agent. With `"agent": true`, `.railway/railway.ts` declares an `agent` service with one replica, built from `apps/agent-service/Dockerfile`, and points the web service at `http://agent.railway.internal:3001`. ### Set the agent secrets ```bash railway variables --service web --set "AGENT_INTERNAL_SIGNING_SECRET=$(grep '^AGENT_INTERNAL_SIGNING_SECRET=' .env.production | cut -d= -f2-)" railway variables --service agent --set "AGENT_INTERNAL_SIGNING_SECRET=$(grep '^AGENT_INTERNAL_SIGNING_SECRET=' .env.production | cut -d= -f2-)" railway variables --service agent --set "AGENT_RESOURCE_GRANT_SECRET=$(grep '^AGENT_RESOURCE_GRANT_SECRET=' .env.production | cut -d= -f2-)" ``` ### Deploy ```bash railway up ``` ## Verify * The site loads at the public address of the `web` service. * `/setup`, signed in as the administrator, names Railway and Postgres in its first line and shows **Session secret** as ready. * `/admin/config/auth` shows the **Base URL** the site answers on. Change it there if the site uses another domain. * **Scheduled jobs** turns ready within a couple of minutes. * With the agent, `/app/agent` opens the workbench. * In the repository, `pnpm smoke:node` after `pnpm build:node` checks the build you ship, and `pnpm validate:deploy-targets` checks the rendered `.railway/railway.ts`. ## Troubleshooting ### The web service refuses to start with a session secret error `BETTER_AUTH_SECRET` is not set on the `web` service. Run the `railway variables` command again and redeploy. ### OAuth sign-in or email links point at the wrong address The **Base URL** at `/admin/config/auth` does not match the public address. Correct it there; no redeploy is needed. ### Scheduled jobs stay not ready on `/setup` Check that the `web` service is running. If `JOBS_IN_PROCESS=false` is set, an external cron has to run `pnpm jobs:run` instead. ### TypeScript reports errors in `.railway/railway.ts` The file starts with `@ts-nocheck` because the `railway` CLI type-checks it and this project does not. Keep that line. ## Next steps - [Manage configuration](https://kernlift.dev/docs/core/configuration/project.md) - [Run the Node build](https://kernlift.dev/docs/deploy/node.md) - [Deployment model](https://kernlift.dev/docs/deploy/runtimes.md) - [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) --- # Deployment model > One platform per project, two build targets, which databases and agent setups each platform allows, where secrets live, when migrations run, and how scheduled jobs are started. Source: https://kernlift.dev/docs/deploy/runtimes A project deploys to one platform: Cloudflare, Fly.io, Railway or a Docker host. The choice is stored in a committed file, `deploy.config.json`. It determines which build runs, which platform files are in the repository, which databases are possible, and how migrations and scheduled jobs are started. Routes, guards, repositories and validators are the same on every platform. For the steps, see [Deploy your project](https://kernlift.dev/docs/deploy.md). ## One platform per project ```json title="deploy.config.json" { "platform": "cloudflare", "agent": false, "database": "d1" } ``` The file is committed in the repository you clone, and `kernlift deploy-target <platform>` rewrites it. It holds no secrets. The build reads it to pick a target, and the app bundles it, so `/setup` on a deployment reports the platform, database and agent choice that build was made for. Only the chosen platform's files are in the project root: `wrangler.jsonc`, or `fly.toml` and `fly.agent.toml`, or `.railway/railway.ts`, or `compose.yaml`. The `deploy` script in `package.json` runs that platform's deploy command. Every field and file is listed in [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md). ## Two build targets | Target | Platforms | Server entry | Output | Started by | | ------------ | ----------------------- | -------------------------- | ---------- | ------------------------------- | | `cloudflare` | Cloudflare | `src/server-entry.ts` | `dist/` | `wrangler deploy` | | `node` | Fly.io, Railway, Docker | `src/server-entry.node.ts` | `.output/` | `node .output/server/index.mjs` | `pnpm build` picks the target from `deploy.config.json`, so a build gives the same output wherever it runs, including a platform's remote builder. `pnpm build:cloudflare` and `pnpm build:node` name the target explicitly. A project without the file builds for Cloudflare. The Worker entry also carries the Cron Trigger handler and the agent container class. The Node entry has neither. It starts the scheduled-jobs loop when the process loads. The root `Dockerfile` packages the Node build for all three Node platforms. See [Run the Node build](https://kernlift.dev/docs/deploy/node.md). ## Platform, database and agent matrix | | Cloudflare | Fly.io | Railway | Docker | | -------------------------- | --------------------------------- | ------------------------------ | ------------------- | ------------------------------ | | Database without the agent | D1 or Postgres through Hyperdrive | Postgres or SQLite on a volume | Postgres | Postgres or SQLite on a volume | | Database with the agent | Postgres through Hyperdrive | Postgres | Postgres | Postgres | | Agent service | Cloudflare container | The `<name>-agent` app | The `agent` service | The `agent` compose service | | Object storage | R2 binding or S3-compatible | S3-compatible | S3-compatible | S3-compatible | | Cache | KV or process memory | Process memory | Process memory | Process memory | The agent needs a database with transactions that the web app and the agent service share, so it always runs on Postgres. SQLite is a single-machine option: one machine owns the file. D1 exists only on Cloudflare. `kernlift deploy-target` rejects a combination outside this table before it writes anything. The agent service is one instance, because it holds run state in memory, and it is reached only on the platform's private network. A deployment without it is a complete web app. See [Agent runtime](https://kernlift.dev/docs/extensions/agent.md). ## Secrets Production secrets are generated once into `.env.production`: the session secret, the agent signing secrets when the agent is included, and the password of the bundled Postgres on Docker. The file is written with mode 0600 and is ignored by git and by the Docker build context. A second run of the CLI fills in missing keys and never rotates a value that is already there. From that file the values go to the platform's secret store: `wrangler secret put`, `fly secrets import`, `railway variables`, or `docker compose --env-file .env.production`. The commands read them over standard input, so a secret is never printed, placed on a command line or written into a committed file. Provider credentials are not part of this. They stay in the database and are managed in `/admin/config/*`. ## Migrations before traffic The schema is built only by the migration chain, and each platform applies it before the new version serves requests. | Platform | What applies the migrations | | ------------------------ | -------------------------------------------------------------------------- | | Cloudflare with D1 | `pnpm db:migrate:d1:remote`, run before `pnpm run deploy` | | Cloudflare with Postgres | `pnpm db:migrate` from the checkout, against the Postgres URL | | Fly.io with Postgres | `release_command` in `fly.toml`, on a temporary machine | | Fly.io with SQLite | The app process, before the server starts; a release machine has no volume | | Railway | The `preDeploy` step of the `web` service | | Docker | The `migrate` compose service; `web` starts after it succeeds | The Node platforms run `node scripts/db/migrate-runtime.mjs`, which needs no TypeScript runner and keeps the same bookkeeping table as `pnpm db:migrate`, so the two can be used on the same database. The production administrator is a separate step, because the production database is not the local one. The Node image carries `node .output/scripts/bootstrap-super-admin.mjs`. Cloudflare runs `pnpm db:bootstrap-super-admin` from the checkout, with `--remote` for D1. ## Scheduled jobs Background work runs once a minute through `runScheduledJobs()`: fulfilment retries, credit expiry and unfinished AI tasks. What starts a round depends on the build target. * **Cloudflare:** the per-minute Cron Trigger in `wrangler.jsonc` calls the Worker's `scheduled` handler. * **Fly.io, Railway, Docker:** a loop inside the web process. Every replica runs the loop, and a lock row in the config table lets one of them run each round. No separate jobs process or platform cron is configured. A stopped web process runs nothing, which is why `fly.toml` keeps `min_machines_running = 1`. Setting `JOBS_IN_PROCESS=false` turns the loop off. An external cron then has to call `pnpm jobs:run`. Each round records when it ran. `/setup` shows **Scheduled jobs** as not ready when no round has run for five minutes or the last one had failures, and names the switch for the deployed platform. ## What switching does `kernlift deploy-target <platform>` re-renders the deployment from the templates that ship with the CLI. It rewrites `deploy.config.json`, writes the new platform's files, points the `deploy` script at the new platform, and adds any missing keys to `.env.production`. Files of the previous platform move to `.kernlift/previous-deploy/`. Nothing is deleted, and a copy already there is never overwritten. Switching changes files only. It creates no remote resource, does not touch the running deployment and moves no data. The next `pnpm build` follows the new target. Flags are in the [deployment configuration reference](https://kernlift.dev/docs/reference/deploy-config.md). ## Local development Local development is the same for every platform: `pnpm dev` on a SQLite file. A project whose production database is Postgres still develops on SQLite locally. ```bash DATABASE_DIALECT=sqlite DATABASE_URL=./local.db ``` ```bash pnpm db:migrate SUPER_ADMIN_EMAIL=you@example.com SUPER_ADMIN_PASSWORD='<password>' pnpm db:bootstrap-super-admin pnpm dev ``` The bootstrap step creates the first administrator, the permission set and the super admin role, and writes the baseline operational content. There is no demo data, and external provider success is never faked. ## Database adapters There are two schema families, SQLite and Postgres, and every repository is written against both. `DATABASE_DIALECT` picks the family. `DATABASE_ADAPTER` picks how to connect and defaults to the dialect. | Adapter | Dialect | Used by | Configuration | | ------------ | ---------- | -------------------------------------------------- | --------------------------------------------------------------- | | `sqlite` | `sqlite` | Local development, Fly.io and Docker with a volume | `DATABASE_URL` is a file path | | `d1` | `d1` | Cloudflare | The `EDGE_DB` binding | | `postgres` | `postgres` | Fly.io, Railway, Docker, any Node host | `DATABASE_URL=postgresql://...` | | `hyperdrive` | `postgres` | Cloudflare with Postgres | `DATABASE_ADAPTER=hyperdrive` and the `HYPERDRIVE` binding | | `turso` | `sqlite` | A Node host on libSQL | `DATABASE_ADAPTER=turso`, `DATABASE_URL`, `DATABASE_AUTH_TOKEN` | A Worker may not reuse a socket opened for another request, so the `hyperdrive` adapter creates its Postgres client per request and leaves pooling to Hyperdrive. A project can register its own adapter. See [Write a custom database adapter](https://kernlift.dev/docs/extensions/database/custom-adapter.md). ### Supabase-Hosted Postgres Supabase and Neon are hosted Postgres endpoints on the generic Drizzle Postgres adapter. The application does not use Supabase-specific APIs, client SDKs, auth helpers, storage APIs or RLS as a business dependency. Authorization stays in the server-side auth, RBAC and repository layers. ```bash DATABASE_DIALECT=postgres DATABASE_URL=postgresql://USER:PASSWORD@HOST:5432/postgres ``` See [Use Postgres and Supabase](https://kernlift.dev/docs/extensions/database/postgres.md) and [Use Turso](https://kernlift.dev/docs/extensions/database/turso.md). ### Cloudflare Workers and D1 `wrangler.jsonc` defines the Worker entry `src/server-entry.ts`, the D1 binding `EDGE_DB`, `DATABASE_DIALECT=d1` and the D1 migration directory `./drizzle/migrations/sqlite`. D1 shares the SQLite schema family, so it applies the same migrations as local SQLite. D1 has no interactive transactions. Code that opens one runs its statements in sequence there. ### Changing the schema A schema change needs a matching migration in both dialects: ```bash pnpm db:generate:sqlite --name=my-change pnpm db:generate:postgres --name=my-change pnpm validate:migrations ``` `pnpm db:generate:sqlite` writes to `drizzle/migrations/sqlite` and `pnpm db:generate:postgres` to `drizzle/migrations/postgres`. The two directories are never shared. `pnpm db:generate` writes a new migration for a schema difference and does not prepare a database. ## Storage over the S3-compatible protocol Uploads, deletes and signed URLs use the S3-compatible protocol through Admin-managed S3-compatible config in `/admin/config/storage`: endpoint, region, bucket, access key, secret key, an optional CDN or public access domain, and Image/video/audio/file upload MIME categories. Cloudflare R2, Aliyun OSS, MinIO, AWS S3 and similar providers share this path. Storage credentials are admin settings, not environment variables, so every platform configures storage the same way. On Cloudflare, the bucket binding is available as a second driver behind the same storage interface. The other platforms have no binding and use S3-compatible credentials. ## External provider validation Local validation checks state machines and missing-provider failure paths. Real provider checks need sandbox or production credentials: ```bash pnpm validate:external-readiness EXTERNAL_VALIDATE_STRICT=true pnpm validate:external ``` The readiness report is written to `openspec/EXTERNAL_VALIDATION_STATUS.json`. The intentionally unresolved OpenSpec `3.3` tasks are `auth-account 3.3`, `billing-payment 3.3`, `analytics-support 3.3`, `ai-workspace 3.3` and `newsletter-waitlist 3.3`. These remain unchecked until real Google OAuth, payment, analytics, AI and newsletter credentials are configured. ## Release guardrails * Use `pnpm validate:all` before release. * Use `pnpm validate:deploy-targets` after changing a deployment template or a Dockerfile. * Use `pnpm validate:migrations` after changing Drizzle schema or migration files. * Use `pnpm build` before deploy, then the smoke check for the build you ship: `pnpm smoke:worker` after `pnpm build` on Cloudflare, `pnpm smoke:node` after `pnpm build:node` elsewhere. * Keep SQLite/D1 migrations in `drizzle/migrations/sqlite` and Postgres migrations in `drizzle/migrations/postgres`. * Keep `A32-A34` and `A82-A98` out of routes and design generation inputs. * Keep `/zh` route parity intact. * Do not add mock providers or fake provider ids, checkout URLs, payout success, email ids, AI output or analytics reports. ## Files - Deployment choice/ - deploy.config.json - vite.config.ts - src/server/platform/deployment.ts - Build targets/ - src/server-entry.ts - src/server-entry.node.ts - Dockerfile - apps/agent-service/Dockerfile - Platform templates and steps/ - tools/kernlift/src/deploy/render.js - tools/kernlift/src/deploy/templates.js - tools/kernlift/src/deploy/platforms.js - tools/kernlift/src/deploy/secrets.js - Migrations and administrator/ - scripts/db/migrate-runtime.mjs - scripts/db/bootstrap-super-admin.ts - scripts/db/bootstrap-super-admin.runtime.ts - Scheduled jobs/ - src/server/jobs/scheduled.ts - src/server/jobs/in-process.ts - src/server/jobs/heartbeat.ts - Adapters and bindings/ - src/server/db/client.ts - src/server/db/adapter-registry.ts - src/server/platform/cache-backends.ts - src/server/platform/storage-drivers.ts ## Next steps - [Deploy your project](https://kernlift.dev/docs/deploy.md) - [deploy.config.json](https://kernlift.dev/docs/reference/deploy-config.md) - [Deploy to Cloudflare Workers](https://kernlift.dev/docs/deploy/cloudflare.md) - [Run the Node build](https://kernlift.dev/docs/deploy/node.md) - [Environment variables](https://kernlift.dev/docs/reference/env.md) --- # Run an affiliate program > Set the program terms, give partners referral codes, turn their orders into commissions and review payouts in the admin console. Source: https://kernlift.dev/docs/extensions/affiliate The affiliate module gives partners referral codes, turns their referred orders into commissions, and records your decision on each payout request. You review payouts by hand. The module does not move money. ## Before you begin * A project that runs locally. See [Quick start](https://kernlift.dev/docs/quick-start.md). The `affiliate` module is part of the base repository; `pnpm db:bootstrap-super-admin` writes the `affiliates.read` and `affiliates.write` permissions and the default program. * An admin account with `affiliates.read` to open the pages and `affiliates.write` to submit any form. * The partner's user ID, the last part of their `/admin/users/<id>` URL. The console has no sidebar entry. Open `/admin/affiliates` directly (`/zh/admin/affiliates` for the Chinese console). ## Grant affiliate access ### Assign the Commerce Manager role Go to **Overview → Users** (`/admin/users/dashboard`), open the user's details and click **Roles**. Tick **Commerce Manager** and click **Save roles**. That role also includes the order, subscription, product, licence and credit permissions. ### Or add the permissions to your own role Go to **Operations → Roles** (`/admin/roles`), click **Edit** on the role and tick `affiliates.read` and `affiliates.write` under **Permissions** (in the **Other** group). Click **Save role**. ## Set the program terms The default program pays 20% commission with a 30-day cookie window, a $50.00 minimum payout, in USD. ### Open Program settings Open the **Program settings** tab (`/admin/affiliates/settings`). The cards show the current terms. ### Fill in Program terms * **Commission rate (%)**: the share of the order amount paid as commission, for example `20`. It cannot exceed 100%. * **Cookie window (days)**: from 1 to 365. A conversion counts only within this many days of the referral being created. * **Minimum payout**: the smallest payout request accepted, for example `50.00`. * **Currency**: a three-letter ISO 4217 code such as `USD`. * **Status**: **Active**, or **Paused** to stop recording conversions and accepting payout requests. ### Save Click **Save program settings**. The page shows **Program settings saved and audit log recorded.** New terms apply to later conversions and payout requests. Commissions already recorded keep their amount. ## Create referral codes ### Open Create referral On **Overview** or **Referrals**, find the **Create referral** form. ### Fill it in * **Affiliate user**: the partner's user ID. * **Referral code**: the code the partner shares. It is stored in upper case with spaces replaced by hyphens, so `partner acme` becomes `PARTNER-ACME`. * **Referred email**: optional. Click **Create referral**. A code that already exists is kept as it was, without an error. ## Record a conversion Checkout does not attribute orders to referral codes on its own, so you record each partner order. ### Confirm the order is paid Check the order in **Commerce → Orders** (`/admin/orders`). ### Fill in Record conversion On **Commissions** or **Overview**, enter the **Referral code**, the **Order ID** and the **Order amount cents** (`29000` for $290.00). Click **Record conversion**. The commission is the order amount times the program rate, rounded down, and starts as pending. To attribute orders automatically instead, call the service from your settlement code after the provider webhook confirms the order: ```ts title="src/server/services/example.service.ts" import { recordConversion } from "@/server/services/affiliate-operations.service"; await recordConversion({ referralCode: "PARTNER-ACME", orderId: order.id, orderAmountCents: order.amountCents, }); ``` ## Review a payout Payout requests appear on **Withdrawals**. No page creates them. Your own server code creates them. ### Find the payout ID Copy it from the **Payout** column on **Withdrawals**. ### Decide Go to **Review**, enter the **Payout ID** and a **Review note**, then click **Approve payout** or **Reject payout**. The decision is saved with you as reviewer. ### Pay the partner Send the money through your own payment channel. The module only records the decision. ## Verify 1. Create a referral with your own user ID and the code `TEST-PARTNER`. 2. Record a conversion for `TEST-PARTNER` with **Order amount cents** `30000`. 3. With the default 20% rate, **Commissions** lists a pending $60.00 commission, the referral on **Referrals** shows as converted, and **Security → Audit** (`/admin/audit`) records both actions. In the repository, run `pnpm validate:affiliate`. ## Troubleshooting ### "Affiliate program is not configured" or the pages say "No affiliate records yet" No program exists yet. Run `pnpm db:seed-baseline` to create the default program. Running it again keeps your settings. ### "Referral code is not active" No referral has that code. Codes are compared after trimming, upper-casing and replacing spaces with hyphens, so check the code on **Referrals**. ### "Affiliate program is paused; …" **Status** on **Program settings** is **Paused**. Set it to **Active** and save. ### "Conversion is outside the N-day attribution window for this referral." The referral was created more than **Cookie window (days)** ago. Use a newer referral, or raise the cookie window. ### "Payout amount is below the program minimum of N cents." Request at least **Minimum payout**, or lower the minimum on **Program settings**. ## Reference * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md) * [Drizzle ORM](https://orm.drizzle.team) ## Next steps - [Plugins](https://kernlift.dev/docs/core/plugins.md) - [Manage orders, refunds and subscriptions](https://kernlift.dev/docs/extensions/payments/subscriptions.md) - [Payment lifecycle](https://kernlift.dev/docs/extensions/payments.md) --- # Alibaba Cloud Sandbox > Connect the agent service to Alibaba Cloud Sandbox. Source: https://kernlift.dev/docs/extensions/agent/aliyun ## 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 Alibaba Cloud Sandbox ### Provision the cloud sandbox Open [Alibaba Cloud Sandbox](https://help.aliyun.com/zh/agent-sandbox/build-and-manage-custom-templates-with-code/). Provision an E2B-compatible sandbox in your account. ### Prepare the runner image Obtain the regional API URL, key and a template ID for a runner-compatible image. ## 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. <img src="/docs/guides/agent/template.en.png" alt="Runner template settings" width="512" height="1283" loading="lazy" /> ## 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. <img src="/docs/guides/agent/crawl4ai.en.png" alt="Kernlift settings for Crawl4AI" width="512" height="944" loading="lazy" /> ## 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. <img src="/docs/guides/agent/template.en.png" alt="Runner template settings" width="512" height="1283" loading="lazy" /> ## 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. <img src="/docs/guides/agent/template.en.png" alt="Runner template settings" width="512" height="1283" loading="lazy" /> ## 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/<id>/` with two entry points: `plugin.server.ts` for the agent host and `plugin.ts` for the browser. The host code contains no plugin names. It reads what each switched-on plugin declares (a scene, a Skill, cards, panels, operations) and validates every value before it reaches the reader. It is a plugin of the console kernel described in [Plugins](https://kernlift.dev/docs/core/plugins.md), with `kind: "agent"`. The [image agent](https://kernlift.dev/docs/extensions/agent/image-agent.md) is a small plugin. `scripts/validate/fixtures/agent-plugin-fixture` is a reference plugin that uses every join point, and the validator runs it. ## Before you begin * The [agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) installed and runnable. * An OpenSpec change for the plugin: `openspec-cn new change "<id>-plugin"`. * A plugin id: a lower-case slug that is also its module key. Every key the plugin declares starts with it. ## What the reader sees There is one workbench at `/app/agent` and one composer. Beside it, a picker lists **Auto**, **General** and every switched-on agent plugin. * Picking an agent swaps in its composer controls and keeps the typed text. The choice travels inside the message, so retrying an old message runs the agent it was sent to. * On **Auto** the server routes the request. The start response and the thread snapshot name the plugin the Run went to, and the workbench uses that plugin for the rest of the thread. * A plugin's cards render in the transcript and its workspace opens as a tab beside it. Several plugins' Runs can share one thread. * Switching a plugin off in **Settings → Plugins** removes it from the picker on the next focus, rejects its new Runs and operations, and shows its old cards by their summary. Switching it back on restores them. A plugin page such as `/app/image` is a shortcut into the same workbench with that agent picked. ## Choose the join points Declare only what the plugin needs. | The plugin needs to | Declare | Where | | ----------------------------------------------------- | ------------------------------------------------------------------ | ------- | | Be picked and routed to | `scenes`, `capabilityRoutes` (words, file types or both), `skills` | server | | Show its own composer controls and landing | `agent` with a lazily loaded capability | browser | | Put structured, interactive content in the transcript | `cards` (payload schema) / `cardRenderers` | both | | Open panels beside the thread | `surfaces` / `surfaces` | both | | Let the reader act without a model turn | `operations` (input, Run state, timeout) | server | | Bind a confirmation to the content the reader saw | `validateUserAnswer` (guards, approvals) | server | | Fix a Run policy on the server | `hostPinnedContext` | server | | Store a kind of result of its own | `artifactKinds` / `artifactRenderers` (`<id>.<kind>`) | both | | Serve downloads or previews over HTTP | `api.routes` under `/api/plugins/<id>/` | server | ## Rules every plugin follows 1. **Namespaced keys.** Card, panel, operation and artifact-kind keys are `<id>.<name>`. The registry rejects another plugin's prefix, a duplicate, and `<id>.workspace`, which the host opens for the plugin's workspace. 2. **Checked on both sides.** Payload and input schemas live in the plugin's browser-safe `contracts.ts`. The server validates before writing or running. The browser validates a card's payload again before rendering it. 3. **Readable without the plugin.** Every card carries a plain-text summary. With the plugin switched off or uninstalled, cards show it and artifacts of the plugin's kind are offered for download. 4. **Isolated.** Cards and panels render inside an error boundary. An operation has a timeout, and one operation or answer runs per Run at a time. Keep `plugin.server.ts` free of React and icons, because the agent service bundles it. Load the capability, cards and panels with `import()` so the workbench bundle does not grow with every plugin. ## Build the plugin The examples use a plugin with the id `storyboard`. Copy the layout of `scripts/validate/fixtures/agent-plugin-fixture` and keep only the join points you chose above. ### Contracts and manifest `contracts.ts` holds what both halves agree on: keys and zod schemas, with no React and no server imports. ```ts title="src/plugins/storyboard/contracts.ts" import { z } from "zod"; export const STORYBOARD_PLUGIN_ID = "storyboard"; export const STORYBOARD_SCENE_KEY = "agent.storyboard"; export const STORYBOARD_SKILL_PACKAGE_ID = "platform.storyboard"; export const STORYBOARD_SKILL_DIRECTORY = "src/plugins/storyboard/skills/storyboard-studio"; export const STORYBOARD_CARD_KEY = `${STORYBOARD_PLUGIN_ID}.summary`; export const STORYBOARD_CARD_SCHEMA_VERSION = 1; export const StoryboardSummaryPayload = z .object({ shots: z.number().int().min(0).max(100) }) .strict(); ``` ```ts title="src/plugins/storyboard/manifest.ts" import { defineManifest } from "../kernel/types"; export const storyboardManifest = defineManifest({ id: "storyboard", version: "0.1.0", kind: "agent", requires: ["agent-starter"], }); ``` Add `routes` when the plugin owns pages under `/app` or `/admin`. ### Server half Declare the `AgentHostExtension` and contribute it to `agent.host`. Use relative imports, because the agent service bundles this file and cannot resolve `@/` aliases. ```ts title="src/plugins/storyboard/server/extension.ts" import type { AgentHostExtension } from "../../../server/agent-extensions/types"; import { STORYBOARD_CARD_KEY, STORYBOARD_CARD_SCHEMA_VERSION, STORYBOARD_SCENE_KEY, STORYBOARD_SKILL_DIRECTORY, STORYBOARD_SKILL_PACKAGE_ID, StoryboardSummaryPayload, } from "../contracts"; export const storyboardExtension: AgentHostExtension = { id: "storyboard", scenes: [{ sceneKey: STORYBOARD_SCENE_KEY, readinessRequired: false }], capabilityRoutes: [{ scene: STORYBOARD_SCENE_KEY, pattern: /\bstoryboard\b/iu }], skills: [{ packageId: STORYBOARD_SKILL_PACKAGE_ID, directory: STORYBOARD_SKILL_DIRECTORY }], cards: { [STORYBOARD_CARD_KEY]: { payload: StoryboardSummaryPayload, schemaVersion: STORYBOARD_CARD_SCHEMA_VERSION, }, }, }; ``` ```ts title="src/plugins/storyboard/plugin.server.ts" import { defineServerPlugin } from "../kernel/types"; import { storyboardManifest } from "./manifest"; import { storyboardExtension } from "./server/extension"; export const storyboardServerPlugin = defineServerPlugin({ manifest: storyboardManifest, contributes: { "agent.host": [storyboardExtension] }, }); ``` `readinessRequired: false` keeps a plugin without a configured model from holding up the whole agent service. Add `api.routes` to the same `contributes` when the plugin serves HTTP under `/api/plugins/storyboard/`. Do not check the plugin's own on/off state anywhere. The host rejects its scenes, Skills, operations and API routes while it is switched off. ### Browser half `plugin.ts` holds only metadata and loaders. The capability, card renderers and panels are imported the first time the workbench needs them. ```ts title="src/plugins/storyboard/plugin.ts" import { Clapperboard } from "lucide-react"; import { definePlugin } from "../kernel/types"; import { STORYBOARD_CARD_KEY, STORYBOARD_CARD_SCHEMA_VERSION, STORYBOARD_SCENE_KEY, STORYBOARD_SKILL_PACKAGE_ID, } from "./contracts"; import { storyboardManifest } from "./manifest"; export const storyboardPlugin = definePlugin({ manifest: storyboardManifest, contributes: { "agent.workbench": [ { id: "storyboard", agent: { id: "storyboard", labelKey: "appConsole.storyboard", icon: Clapperboard, order: 30, scenes: [STORYBOARD_SCENE_KEY], skillPackageId: STORYBOARD_SKILL_PACKAGE_ID, load: () => import("./workbench/capability").then(({ storyboardCapability }) => storyboardCapability), }, cardRenderers: { [STORYBOARD_CARD_KEY]: { schemaVersion: STORYBOARD_CARD_SCHEMA_VERSION, load: () => import("./workbench/summary-card").then(({ summaryCard }) => summaryCard), }, }, }, ], }, }); ``` A card or panel acts only through the `actions` it receives (answer the pending question, open an artifact or panel, quote into the composer, `runOperation`) or through `useWorkbenchOperation` from `src/components/agent/extension-card.tsx`. Add the label key to both dictionaries. ### Skill Put the Skill in the plugin folder, here `src/plugins/storyboard/skills/storyboard-studio`, with a `skill.json` and a `SKILL.md`. In `skill.json`, list the plugin's scene under `scenes` and only tools that exist under `allowedTools`. `src/plugins/image-agent/skills/image-studio` is a working example. Publish it: ```bash pnpm agent:publish-skills ``` Because the extension declares the directory in `skills`, the command publishes it next to the platform Skills, and the Skill is removed when the plugin is removed. ### Register Add the two halves to the installed lists, each inside a `// @module:storyboard` … `// @end-module:storyboard` region, with the import in its own region too: | File | Entry | | --------------------------------- | ------------------------ | | `src/plugins/installed.ts` | `storyboardPlugin` | | `src/plugins/installed.server.ts` | `storyboardServerPlugin` | Dictionary entries go in both `messages.ts` files inside regions with the same marker. ### Ship and validate Write `modules/storyboard/module.json`: `files` with `src/plugins/storyboard/**`, `fragments` with the two installed lists and both dictionaries, `requires: ["agent-starter"]`, the same `version` as the manifest, and `docs` holding the full address of the plugin's guide. Then add `scripts/validate/storyboard.ts`, which asserts the plugin's behaviour through the real registries, a `validate:storyboard` script and a segment in `validate:all`, and run `pnpm registry:build`. See [Build a module](https://kernlift.dev/docs/core/plugins/build-a-module.md). ## Verify 1. `pnpm validate:agent-plugin-contract` passes. It also builds the reference plugin and drives every join point through the host. 2. Your plugin's own validator asserts its behaviour, and `pnpm validate:all` turns no check red. 3. In `/app/agent`, the plugin is listed in the picker; a request that matches its route shows **Auto ·** followed by the plugin's name and opens its workspace tab. 4. Switch the plugin off in **Settings → Plugins**: it leaves the picker when the page regains focus, and its cards show their summaries. ## Troubleshooting ### The registry refuses to start with `invalid_extension_key` A key does not start with the plugin id, or names `<id>.workspace`. Rename it in `contracts.ts`. Both halves read the same constant. ### A card shows only its summary The plugin is switched off, its renderer's `schemaVersion` is older than the card's, or the payload fails the renderer's schema. Bump both versions together when the payload changes shape. ### A message is refused with `plugin_disabled` The picked agent was switched off. The composer keeps the text and returns to **Auto**. The next message is routed without it. ## Next steps - [Plugins](https://kernlift.dev/docs/core/plugins.md) How installed and enabled plugins are resolved. - [Image agent](https://kernlift.dev/docs/extensions/agent/image-agent.md) A small plugin to read next to this guide. --- # SearXNG > Connect the agent service to SearXNG. Source: https://kernlift.dev/docs/extensions/agent/searxng ## 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 SearXNG ### Deploy the search service Open [SearXNG](https://docs.searxng.org/admin/installation-docker). Deploy a SearXNG instance reachable from the agent. ### Enable JSON responses Enable json under search.formats in settings.yml and restart. ### Check a search request Confirm that a search request with format=json returns JSON. Provider documentation · [official container guide](https://docs.searxng.org/admin/installation-docker) · [Search API](https://docs.searxng.org/dev/search_api) ## Configure the application Open `/admin/config/search` in the Kernlift admin console. | Value from provider | Admin field | | ------------------- | ----------- | | Instance URL | Base URL | Enable the service, enter the connection details and save. <img src="/docs/guides/agent/searxng.en.png" alt="Kernlift settings for SearXNG" width="512" height="944" loading="lazy" /> ## 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 <Base URL>/api/ai/channels/webhook/<provider code>?taskId={{externalTaskId}} ``` The callback must name the task with a `taskId` query parameter, an `x-ai-task-id` header or a `taskId` body field. In a request parameter, `{{externalTaskId}}` is replaced with the task ID, so you can pass this URL to the provider on each request. ### Sign every callback Each request needs an `x-ai-signature` header: the hex HMAC-SHA256 of the exact raw body, keyed with the webhook secret, optionally prefixed `sha256=`. Most providers do not sign this way, so put a small relay in front that checks the provider's own signature and re-signs: ```ts title="relay.ts" import { createHmac } from "node:crypto"; const body = JSON.stringify({ taskId, status: "succeeded", output: "https://..." }); const signature = createHmac("sha256", webhookSecret).update(body).digest("hex"); // POST with headers: { "content-type": "application/json", "x-ai-signature": signature } ``` A provider or provider scene cannot be saved in webhook mode without a stored secret. The form shows `Webhook push requires a webhook signing secret.` **Two things query the status URL** A client that reads the task through `GET /api/status?taskId=...` triggers a query once the interval has passed. Tasks nobody is reading are advanced by the `ai-channel-tasks` scheduled job, once a minute, so they still finish and settle credits. That job only runs where [background jobs](https://kernlift.dev/docs/core/background-jobs/run.md) run. ## Read the task status Start a task and follow the `statusUrl` it returns. Reading status needs a session or an API key with **Read AI task status**, and only returns tasks the caller owns. ```bash curl -X POST https://your-domain.example/api/video-creation/generate \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"A drone shot over a coastline","mediaType":"video"}' # => { "taskId": "ai_task_...", "status": "running", "statusUrl": "/api/status?taskId=...", # "estimatedPriceCredits": 12, "resultMode": "polling" } curl "https://your-domain.example/api/status?taskId=ai_task_..." \ -H "Authorization: Bearer $API_KEY" ``` When the task succeeds, URLs in its output are copied into the user's `/generated` storage folder. Without [file storage](https://kernlift.dev/docs/extensions/storage.md) the task still succeeds, and its events note that the storage import was skipped. ## Verify * The task moves from `running` to `succeeded` or `failed` on the user's `/app/ai/<taskId>` page, which also shows the credits charged or returned. * **Platform → AI Tasks** (`/admin/ai/tasks`) shows the final status. Failures are listed at `/admin/ai/failed`. * `pnpm validate:ai-channel` checks webhook signatures, polling and refunds. ## Troubleshooting ### An asynchronous task stays running Check that polling has a **Status URL template**, and that either a client reads `GET /api/status?taskId=...` or [background jobs](https://kernlift.dev/docs/core/background-jobs/run.md) are running so the `ai-channel-tasks` job can advance the task. For webhook mode, check that the provider calls the webhook URL with the task ID. ### The webhook returns 401 `Webhook secret is not configured.` means neither the provider nor the provider scene has a **Webhook signing secret**. Save one. `Webhook signature verification failed.` means `x-ai-signature` is missing or is not the HMAC of the exact raw body. The task does not change. ### The webhook returns 400 The callback does not name a task (`taskId is required.`), the callback URL names another provider (`Webhook channel does not match task.`), or the body is not JSON. The task does not change. ### The task status or output looks wrong The parser reads the wrong fields of the provider's response. Paste a real response on the provider form, click **Test parser**, and fix **Output path** or **Status mapping**. ## Reference * [Credits ledger](https://kernlift.dev/docs/extensions/credits.md) * [HMAC signatures](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/sign) ## Next steps - [AI channels, scenes and task lifecycle](https://kernlift.dev/docs/extensions/ai.md) - [Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md) --- # Chat conversations > Read the conversations your users had with an agent: who, which agent, in which language, and every message part. Source: https://kernlift.dev/docs/extensions/ai/chats Every chat a user has is stored as a conversation with its messages. `/admin/chats` is the read-only view of them, paginated, and `/admin/chats/$conversationId` is one thread with each message's role and parts. Operators use these pages to check what an agent said to a customer. ## Before you begin * `ai.read`, the same key that opens the AI operations pages. Conversations are AI output, so the operators who watch AI tasks also review conversations. See [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md). * At least one conversation. Chat needs a model channel: see [AI providers](https://kernlift.dev/docs/extensions/ai/providers.md) if `/app/ai` reports nothing configured. ## Set it up ### Give the reviewer `ai.read` It is a read key. `/admin/chats` has no write path. You cannot edit a conversation, delete it or reply as the assistant. ### Read the list `/admin/chats` pages through conversations, newest first, showing the account, the agent key, the language and when it was last updated. Page size is a search parameter, so a shared link opens the same page for someone else. ### Open one thread `/admin/chats/$conversationId` renders the messages in order with their roles: `system`, `user`, `assistant`, `tool`. Tool messages are shown, so you can see which tool call produced an answer. ## What a conversation holds <TypeTable type="{ agentKey: { type: "string", description: "Which agent answered. A deployment with several agents keeps them apart here.", }, locale: { type: '"en" | "zh"', description: "The language the conversation ran in, stored with the conversation.", }, status: { type: '"active" | "archived"', default: '"active"', description: "Archived conversations stay readable; nothing is deleted by archiving.", }, "message.role": { type: '"system" | "user" | "assistant" | "tool"', description: "Including the system prompt and every tool result, in order.", }, "message.status": { type: '"ready" | "submitted" | "streaming" | "error"', description: "A message that failed mid-stream stays in the thread with its error state.", }, }" /> Messages are persisted as they stream. An interrupted response remains in the conversation with its received content and message status. ## Verify 1. Hold a short chat from `/app/ai`, then open `/admin/chats`. The conversation is at the top with your account and agent key. 2. Open it. The system prompt, your messages and the assistant's replies are in order. 3. Change `pageSize` in the URL. The list uses that page size, and the link works in another browser. 4. Sign in with a role that lacks `ai.read`. The page denies access. ## Reference * [AI channels](https://kernlift.dev/docs/extensions/ai.md): how a chat reaches a model * [AI scenes](https://kernlift.dev/docs/extensions/ai/scenes.md): which channel a scene routes to * [Roles and permissions](https://kernlift.dev/docs/core/auth/roles.md) * [The UIMessage shape](https://ai-sdk.dev/docs/reference/ai-sdk-ui/ui-message): what a message's parts are ## Next steps - [AI providers](https://kernlift.dev/docs/extensions/ai/providers.md) Configure the channel a chat runs on. - [AI scenes](https://kernlift.dev/docs/extensions/ai/scenes.md) Route each scene to the model that should answer it. - [Credits](https://kernlift.dev/docs/extensions/credits/usage.md) What a conversation costs and where that is recorded. - [Agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) The template that turns a chat into an agent with tools. --- # Google Gemini > Route text generation to Google Gemini. Source: https://kernlift.dev/docs/extensions/ai/gemini ## 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 Google Gemini ### Create an AI Studio key Open [Google Gemini](https://aistudio.google.com/apikey). Select or import the Cloud project and create an API key. ### Confirm model access Confirm quota and copy a Gemini model ID available in the project. Provider documentation · [Google AI Studio API Keys](https://ai.google.dev/gemini-api/docs/api-key) ## Configure the application Open `/admin/config/ai` in the Kernlift admin console. | Value from provider | Admin field | | ------------------- | -------------- | | API key | API key secret | | Service endpoint | Base URL | | Model ID | Model ID | Add a provider scene for text, select **Gemini protocol**, enter the model ID, configure its price, and save. Assign the ready model to the chat scene. <img src="/docs/guides/ai/provider.en.png" alt="Kernlift settings for Google Gemini" width="1040" height="1045" loading="lazy" /> ## 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/<scene>/generate`. A scene can only route to an active, ready provider scene with the same output type: `text`, `image`, `video` or `audio`. A provider scene is not ready while it lacks an endpoint, pricing, a protocol and model ID, a polling URL or a webhook secret, whichever its settings need. ## How a price is resolved Each provider scene has a pricing mode: | Mode | Charges by | Typical use | | -------- | -------------------------------------------------------------- | -------------------------- | | `fixed` | A cost per call | One image at a fixed size | | `rules` | Request parameters, as combinations or numeric steps | Image size, video duration | | `tokens` | Token usage, one total rate or separate input and output rates | Text models and chat | Costs are entered in your currency and converted to credits with the credit unit price. The price a user pays is the cost in credits raised by the markup, rounded up, and never less than the cost. The markup comes from the provider scene, otherwise the provider, otherwise the default rules. Conversion happens when a provider scene is saved, and the result is stored. Changing the credit unit price later does not reprice existing provider scenes until each one is saved again. ## How a task runs 1. A task starts from a server function or `POST /api/<scene>/generate`, subject to the `ai.tasks.create` rate limit. Without a scene, the task type picks one. 2. The scene, its routed channel and the active provider scene for the media type are resolved, and the price in credits is computed. 3. The request URL, headers and body are rendered from the templates. 4. The price is reserved in the credits ledger, and the task is stored as `queued` with a snapshot of the channel, the price and the masked request. 5. The provider is called and the response is read with the channel's parser and status mapping. 6. The outcome settles the reservation: | Provider status | Task | Credits | Also | | ----------------- | ----------- | -------------- | ----------------------------------------------------------------------------------------------------- | | Succeeded | `succeeded` | Captured | Output URLs are copied into the user's `/generated` storage folder; a `pass` safety report is written | | Failed | `failed` | Refunded | A `warn` safety report is written | | Queued or running | `running` | Still reserved | Waits for a webhook or a poll | Every state change appends an event to the task's timeline. A user can read only their own tasks. The admin console shows all of them. ## Result modes Image, video and audio providers often finish later, so each channel chooses how results arrive. | Mode | How the result arrives | | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `sync` | In the response to the call. Text is always `sync` | | `polling` | The status URL is queried when a client reads the task through `GET /api/status` and the polling interval has passed. There is no background timer | | `webhook` | The provider, or a relay in front of it, posts to `/api/ai/channels/webhook/<provider code>` | The schema also accepts `webhook_or_polling`, but the admin form offers only direct response, status polling and webhook push. A webhook must name the task and carry an `x-ai-signature` header: the hex HMAC-SHA256 of the raw body, keyed with the channel's webhook secret. Most providers do not sign this way, so a small relay that checks the provider's own signature and re-signs is the usual setup. A callback for a channel or scene that does not match the task is rejected. Setup is in [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md). ## How chat runs 1. `POST /api/chat` accepts AI SDK UI messages and streams a reply with text and reasoning parts. 2. The conversation and the user message are stored. 3. The price is resolved, an estimate is reserved, and the model runs through the provider scene's protocol. 4. When the stream ends, credits are re-priced from reported token usage and captured. On error the reservation is refunded and the assistant message is saved with status `error`. | Protocol | Notes | | ------------------ | ----------------------------------------------------------------------------------------------------- | | `openai` | OpenAI-compatible chat completions. The API key is the bearer token in the provider's request headers | | `gemini` | Google Generative AI. The key comes from `x-goog-api-key`, `x-api-key` or a bearer token | | `edge_inference` | Cloudflare Workers AI through the `AI` binding; unavailable without the binding | | `image_generation` | Tasks only; rejected on the chat path | Tasks call the rendered request URL directly, so protocol and model ID only drive chat. ## Why it is built this way * **No code per provider.** Any HTTP API that returns JSON can be described with templates, JSON paths and a status mapping. Only a new chat protocol needs code. * **No environment keys.** Keys such as `OPENAI_API_KEY` in the environment are ignored. Only the key saved on the provider is used. * **Nothing runs unconfigured.** The template ships with no providers or scenes. Until a scene routes to a ready provider scene, tasks fail with a not-available error, no credits are taken and `/setup` shows **AI channels** as not ready. ## Files - Runtime/ - src/server/services/ai-workspace.service.ts - src/server/db/repositories/ai-workspace.repository.ts - Console/ - src/routes/{-$locale}/admin/config/ai.tsx - src/components/ai/admin-ai-operations-workspace.tsx ## Next steps - [Credits ledger](https://kernlift.dev/docs/extensions/credits.md) - [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md) --- # Get image and video generation working > Wire an image or video provider so a generation completes end to end: request variables, array parser paths, status polling, storage of the result, and the picture or clip shown in the agent conversation. Source: https://kernlift.dev/docs/extensions/ai/media-generation An image or video generation has four stages before a user sees the result: the provider request, the provider's response (often a task ID), the status query that completes the task, and file storage. This guide configures each one for the `image-creation` and `video-creation` scenes, then shows the same result published by the agent. For the model behind it, see [AI channels, scenes and task lifecycle](https://kernlift.dev/docs/extensions/ai.md). ## Before you begin * An account with an image or video provider, its API key, and a real example of its submit response and its status response. * File storage configured in **Settings → Storage Config**. Without it a task still succeeds, but nothing is copied into the user's files and the agent has no file to publish. See [Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md). * An admin account with `ai.read` and `ai.write`. * For the agent part only: the [agent starter](https://kernlift.dev/docs/extensions/agent/starter.md) running, with a model for `agent.general`. ## Wire the provider ### Create the provider and its request On **Settings → AI Config** (`/admin/config/ai`), create the provider with its base URL and API key as described in [Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md). In **Request parameters**, build the body the provider expects from these variables: | Variable | Value | | ------------------------------------------------- | ---------------------------------------------------------------------------- | | `{{prompt}}` | The prompt of the request | | `{{input}}` | The request's input; the prompt when none is given | | `{{metadata.<name>}}` | Any other field of the request, such as `size`, `aspect_ratio` or `duration` | | `{{externalTaskId}}` | The provider's task ID, once it is known. Used in the status URL | | `{{sceneKey}}`, `{{channelKey}}`, `{{mediaType}}` | The scene, the provider and the output type of the call | | `{{secret.<key>}}` | An admin config setting classified as secret | A text value is inserted as it is and any other value as JSON, so a number such as a duration arrives as a number. Any other variable is rejected with `Unsupported template variable`. A template that contains a pasted key is also rejected, so reference a secret instead. Fields sent to `POST /api/<scene>/generate` other than reserved names such as `prompt` and `mediaType`, and the fields of `input` in an agent's `model.generate` call, are the request's metadata. For example, a frame chosen in the image agent reaches the provider as `{{metadata.aspect_ratio}}`. ### Add one provider scene per model Add a provider scene with output type **Image** for the image model and one with **Video** for the video model. In **Provider scene endpoint**, enter either a path starting with `/`, which is appended to the provider's base URL, or a full `https://` URL. Set its pricing as in [Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md). ### Point the parser at the provider's fields Fill in **Upstream task ID path**, **Status path**, **Output path** and **Error path** from the real responses. Paths start at `$` and may index arrays: ```json title="Submit response" { "code": 200, "data": [{ "status": "submitted", "task_id": "task_1" }] } ``` | Field | Path | | --------------------- | ------------------- | | Upstream task ID path | `$.data[0].task_id` | | Status path | `$.data[0].status` | ```json title="Status response when finished" { "data": { "status": "completed", "result": { "images": [{ "url": ["https://cdn.example.com/a.png"] }] } } } ``` | Field | Path | | ----------- | -------------------------------- | | Status path | `$.data.status` | | Output path | `$.data.result.images[0].url[0]` | An index past the end of an array, or an index applied to an object, is treated as a missing value. Submit and status responses usually differ in shape, so set the paths for the status query separately under **Status response fields**. ### Map every status the provider returns In **Status mapping**, list which provider strings mean **Queued**, **Running**, **Succeeded**, **Failed** and **Canceled**, comma-separated. Matching ignores case. Include the status of the submit response too (`submitted` above belongs under **Queued**). A status that is in no list fails the task with `Unmapped AI channel status`, even when the provider accepted the work. Paste a real response and click **Test parser** before saving. ### Set how the result arrives Most image and video APIs return a task ID. Under **Result handling**, choose **Status polling** and fill in **Status URL template** with `{{externalTaskId}}` in it, plus **Interval sec**. On a provider scene, the status URL may be a path starting with `/`. It is then resolved against the provider's base URL, the same way as the endpoint: ```text Provider base URL https://api.example.com Status URL template /v1/tasks/{{externalTaskId}} Queried https://api.example.com/v1/tasks/task_1 ``` A full `https://` URL is used as it is. For providers that call back instead, see [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md). ### Route the scenes Route `image-creation` to the image provider scene and `video-creation` to the video provider scene. A scene only routes to an active, ready provider scene of the same output type. ## How a running task finishes A task that the provider accepted stays `running` until its status is queried. Three triggers query it, and each one settles the credits when the provider reports that the task ended: | Trigger | When | | ------------------------------------------- | ------------------------------------------------------------------------------------------------- | | A client reading `GET /api/status?taskId=…` | Whenever the polling interval has passed. The `/app/ai/<taskId>` page does this while it is open. | | The scheduled job `ai-channel-tasks` | Once a minute, for tasks nobody is watching. See [Background jobs](https://kernlift.dev/docs/core/background-jobs.md). | | The agent's `model.collect` | When a run picks up a generation it started with `async: true`. | When the task succeeds, every URL in its output is downloaded and stored as a private file in the user's `/generated` folder, marked as coming from that task. The task's output then lists those stored files. ## Check the storage endpoint Generated files are written through the storage provider you configured. For an S3-compatible provider, the address of an object follows the **S3 endpoint**: | Endpoint | Object address | | -------------------------------------------- | ------------------------------------------------------------------------- | | `https://s3.example.com` | `https://s3.example.com/<bucket>/<key>` (path style) | | The host already starts with the bucket name | `https://<bucket>.storage.example.com/<key>` | | A host ending in `.aliyuncs.com` | `https://<bucket>.oss-<region>.aliyuncs.com/<key>` (virtual-hosted style) | Requests and presigned URLs are signed for the same address, so enter the endpoint exactly as the provider documents it. For Alibaba Cloud OSS, enter the region endpoint without the bucket. ## Publish from the agent The agent generates through the same scenes and needs no further configuration. In a run: 1. A skill calls `model.generate` with `sceneKey: "image-creation"` or `"video-creation"` and a `saveTo` path. With `async: true` it gets a task handle and later calls `model.collect` with the same `saveTo`. 2. The file written at `saveTo` is a small manifest that names the stored file. The picture or clip itself is already in storage. 3. The skill calls `artifact.publish` with `kind: "image"` or `"video"` and that path. The artifact's revision then points at the stored file, and nothing is downloaded or uploaded again. This applies when the manifest names exactly one file, the file belongs to the user, came from an AI task, and its content type matches the kind. 4. The conversation shows the artifact in the message: a picture as a preview, a clip as a player with controls. The side panel can still open it. Preview grants last one minute. A clip is read in ranges while it plays, so when a load fails on an expired grant the player fetches a new grant once and resumes at the same position. When a load fails while the grant is still valid, the card shows its open and download actions instead of the player. For pictures with a frame picker and a per-run limit, install the [image agent](https://kernlift.dev/docs/extensions/agent/image-agent.md). ## Verify 1. Start an image task from `/app/ai`, or with the API: ```bash curl -X POST https://<your-domain>/api/image-creation/generate \ -H "Authorization: Bearer $API_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt":"A lighthouse at dusk","mediaType":"image"}' ``` 2. The task moves from `running` to `succeeded` on `/app/ai/<taskId>`, and its events include `Generated output imported to storage.` 3. The picture is listed among the user's generated files on `/app/assets`. 4. Repeat with `video-creation` and `"mediaType":"video"`. 5. With the agent installed, ask `/app/agent` for a picture or a clip. The result appears inside the message, and a clip still plays after the page has been open for more than a minute. 6. In the repository, `pnpm validate:generation-pipeline` checks parser paths, the relative status URL and object addressing. `pnpm validate:agent-generation`, which ships with the agent starter, checks publishing and the players. Neither calls a provider. ## Troubleshooting ### The task fails although the provider accepted it The submit response's status is in no **Status mapping** list, or **Status path** points at the wrong field. The task's error names the unmapped status. Add it under **Queued** or **Running**. ### The task stays running Check that **Upstream task ID path** reads the ID from the submit response (use an index when the provider returns an array), that polling is enabled with a **Status URL template**, and that background jobs run. `/setup` warns when five minutes pass without a round. ### The task succeeds but no file is stored The task's events show `Generated output storage import skipped.` with the reason for each URL. A `403` from an S3-compatible provider usually means the endpoint style does not match the table above. ### The agent's artifact says it could not be loaded The published path was not the `saveTo` manifest of a generation in this run, or the kind does not match the file. Publish a clip as `video` and a picture as `image`. ## Next steps - [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md) Webhook callbacks instead of polling. - [Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md) Price a generation by size or duration. - [Image agent](https://kernlift.dev/docs/extensions/agent/image-agent.md) An image page on the agent workbench. - [Set up file storage and uploads](https://kernlift.dev/docs/extensions/storage.md) Where generated files are kept. --- # OpenAI > Route text generation to OpenAI. Source: https://kernlift.dev/docs/extensions/ai/openai ## 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 OpenAI ### Create a project key Open [OpenAI](https://platform.openai.com/api-keys). Create a project key and store it securely. ### Choose a model Open the model list for that project and copy a model ID it can call. Provider documentation · [API platform](https://platform.openai.com/api-keys) ## Configure the application Open `/admin/config/ai` in the Kernlift admin console. | Value from provider | Admin field | | ------------------- | -------------- | | Project API key | API key secret | | API endpoint | Base URL | | Model ID | Model ID | Add a provider scene for text, select **OpenAI protocol**, enter the model ID, configure its price, and save. Assign the ready model to the chat scene. <img src="/docs/guides/ai/provider.en.png" alt="Kernlift settings for OpenAI" width="1040" height="1045" loading="lazy" /> ## 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.<name>}}`. Never paste a key into a header value. ### Choose result handling and parsing Text is always **Direct response**. For image, video and audio providers that finish later, choose **Status polling** or **Webhook push**. See [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md). For those providers, fill in **Upstream task ID path**, **Status path**, **Output path**, **Error path** and **Event ID path** (defaults `$.id`, `$.status`, `$.output`, `$.error`), and in **Status mapping** list which provider status strings mean **Queued**, **Running**, **Succeeded**, **Failed** and **Canceled**, comma-separated. Paste a real response and click **Test parser**. ### Save Leave **Use system default pricing** ticked, or untick it to set **Base cost credits** and **Markup** for this provider. Click **Save**. The provider appears in the list. ## Add a model ### Describe the model In the provider's row, click **Provider scenes**, then **Add provider scene**. Under **Provider scene**, fill in **Provider scene code**, **Provider scene name**, **Output type** and **Status**. ### Set the request Under **Provider scene request**: * **Text**: choose **Protocol** (**OpenAI protocol**, **Gemini protocol** or **Edge inference**) and enter the **Model ID** exactly as the provider names it, for example `gpt-4o-mini` or `gemini-2.5-flash`. The request goes to the provider's **Base URL**. * **Image, video, audio**: enter the full **Provider scene endpoint**, or leave it empty to use the provider's **Base URL**. Add headers or parameters only this model needs. Empty sections inherit the provider. Click **Preview** under **Request preview** to see the rendered request. Under **Provider scene result delivery**, leave **Inherit** unless this model returns results differently from the rest of the provider. ### Price it and save Choose a **Pricing mode** under **Provider scene pricing**, as described in [Price a provider scene](https://kernlift.dev/docs/extensions/ai/scenes.md), and click **Save**. **Keys in the environment are ignored** Only the key saved on the provider is used. Environment variables such as `OPENAI_API_KEY` are not read. ## Verify In the provider scenes list, **Routing readiness** shows **Ready**, or what is missing: **Missing endpoint**, **Missing pricing**, **Missing protocol or model ID**, **Missing polling URL** or **Missing webhook secret**. A ready provider scene can now be picked on **Scene routing**. `pnpm validate:ai-channel` checks the channel schema, parsing and pricing. ## Troubleshooting ### Chat fails with "AI channel ... is not configured" The provider has no API key in its request headers. Save **API key secret** on the provider, or add an `x-goog-api-key` header for a Gemini provider. Chat reads the bearer token for OpenAI, and `x-goog-api-key`, `x-api-key` or a bearer token for Gemini. ### 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. ### 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). ### The provider scene is not offered on Scene routing Only active, ready provider scenes with the same output type as the scene are listed. Check **Routing readiness**, **Status** and **Output type**. ## Reference * [AI channels](https://kernlift.dev/docs/extensions/ai.md) * [Cache](https://kernlift.dev/docs/core/admin/cache.md) * [OpenAI API reference](https://platform.openai.com/docs/api-reference) ## Next steps - [Route scenes and set pricing](https://kernlift.dev/docs/extensions/ai/scenes.md) - [Receive async results](https://kernlift.dev/docs/extensions/ai/async.md) - [AI channels, scenes and task lifecycle](https://kernlift.dev/docs/extensions/ai.md) --- # Route scenes and set pricing > Your product exposes named AI scenes such as chat or image-creation, each routed to a model and priced in credits. Source: https://kernlift.dev/docs/extensions/ai/scenes Callers request a scene by its code. Each scene routes to one provider scene, so you can swap the model behind it without changing callers. Every call is priced in credits. The credits are held before the provider is called, then charged on success or returned on failure. ## Before you begin * At least one provider with a provider scene. See [Connect an AI provider](https://kernlift.dev/docs/extensions/ai/providers.md). * An admin account with `ai.read` and `ai.write`. * A test user with credits. See [Charge usage with credits](https://kernlift.dev/docs/extensions/credits/usage.md). ## Confirm the provider's billing unit Check the exact model ID, currency and billing unit in the provider console or current price list before pricing the scene. Text models often separate input and output tokens. Image and video models may charge per request, size or duration. Consult [OpenAI pricing](https://platform.openai.com/docs/pricing), [Gemini pricing](https://ai.google.dev/gemini-api/docs/pricing) or [Workers AI pricing](https://developers.cloudflare.com/workers-ai/platform/pricing/). For a compatible HTTP service, use its own contract or price list. This application does not sync provider prices. Convert the current price to the **Provider scene cost** or token rates below, add your markup, then compare one real test request with the provider bill and the credits charged here. The example numbers below are not current provider prices. ## Set the credit price ### Open Default rules Go to **Settings → AI Config** (`/admin/config/ai`) and open **Default rules**. ### Fill in the global defaults Under **Global defaults**, fill in **1 credit price** (what one credit is worth, for example `0.01`), **Markup** in percent (for example `50`) and **Currency** (for example `USD`), then click **Save**. ## Price a provider scene ### Open the provider scene Open **Providers**, click **Provider scenes** on the provider's row, and open the model with **Configure provider scene**. ### Choose a pricing mode Under **Provider scene pricing**, choose a **Pricing mode**: * **Fixed credits**: enter **Provider scene cost** (in your currency) for one call, and optionally **Provider scene markup (optional)**. The preview shows **Cost credits** and **Final charge**. * **Parameter rules**: charge by request parameters such as `size` or `duration`. With **Parameter combinations**, add each parameter's **Parameter name**, **Default value** and **Allowed values**. One price row is generated per combination, prefilled from **Default cost** and **Default markup**. With **Numeric step**, set **Step parameter**, **Step size**, **Cost per step** and **Minimum steps**. * **Token conversion**: for text models. Choose **Use one total-token rate** and enter **Total tokens per currency unit**, or **Input / output rates** and enter both. Chat holds an estimate while the reply streams, then charges for the tokens the model reports. ### Save Click **Save**. `/admin/ai/pricing` lists the resulting price of every provider scene. The charge is the cost in credits raised by the markup, rounded up, and never less than the cost. The markup comes from the provider scene, otherwise the provider, otherwise **Default rules**. With **1 credit price** `0.01`: * A fixed cost of `0.04` is 4 cost credits. With a 50% markup the user pays 6 credits. * A rate of `1000000` total tokens per currency unit makes 10,000 tokens one cost credit. A 25,000-token reply is 3 cost credits, or 5 credits with a 50% markup. **Changing the credit price** Costs are converted to credits with the credit price at the moment you save a provider scene, and the result is stored. If you later change **1 credit price**, open each provider scene and save it again, or users keep paying the old amount. ## Create a scene and route it ### Add the scene Open **Scene routing** and click **Add scene**. Fill in **Display name**, **Code** (for example `chat` or `image-creation`), **Output type**, **Sort** and **Status**, then click **Save**. ### Pick the model In the scene's row, pick a model from the **Provider scene** dropdown. Only active, ready provider scenes with the same output type are listed. If none is ready, click **Create a provider scene first**. The scene is routed when you save that form. The badge changes to **Active route**. Chat uses the scene with code `chat` unless the request names another. Tasks call `POST /api/<code>/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. <img src="/docs/guides/ai/provider.en.png" alt="Kernlift settings for Cloudflare Workers AI" width="1040" height="1045" loading="lazy" /> ## 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. <img src="/docs/guides/analytics/clarity-crisp.en.png" alt="Kernlift settings for Microsoft Clarity" width="512" height="466" loading="lazy" /> ## 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. <img src="/docs/guides/analytics/clarity-crisp.en.png" alt="Kernlift settings for Crisp" width="512" height="466" loading="lazy" /> ## 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. <img src="/docs/guides/analytics/google.en.png" alt="Kernlift settings for Google Ads" width="512" height="562" loading="lazy" /> ## 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. <img src="/docs/guides/analytics/google.en.png" alt="Kernlift settings for Google Analytics" width="512" height="562" loading="lazy" /> ## 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. <img src="/docs/guides/analytics/plausible.en.png" alt="Kernlift settings for Plausible" width="512" height="466" loading="lazy" /> ## 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. <img src="/docs/guides/analytics/umami.en.png" alt="Kernlift settings for Umami" width="512" height="562" loading="lazy" /> ## 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://<your-domain>`, 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. <img src="/docs/guides/auth/github.en.png" alt="Kernlift settings for GitHub" width="512" height="464" loading="lazy" /> ## 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. <img src="/docs/guides/auth/google.en.png" alt="Kernlift settings for Google" width="512" height="464" loading="lazy" /> ## 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://<your-domain>`, 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 <TypeTable type="{ google: { type: "clientId + clientSecret", default: "not configured", description: "Callback: /api/auth/callback/google on each origin you sign in from, localhost included.", }, github: { type: "clientId + clientSecret", default: "not configured", description: "Callback: /api/auth/callback/github.", }, }" /> 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/<slug>`, 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_<locale>_<slug>`. ### 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/<slug>` | | **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/<slug>`, 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_<userId>`), 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.<orderId>`. 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='<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 <name>` and `turso db tokens create <name>`. * `@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 <database-name>`. Copy the `libsql://` URL from `turso db show --url <database-name>` and create an application token with `turso db tokens create <database-name>`. 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='<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 <name>` and set it. ### `DATABASE_URL is required when DATABASE_ADAPTER=turso` Set `DATABASE_URL` to the `libsql://` URL from `turso db show --url <name>`. ### 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**. <img src="/docs/guides/email/aliyun.en.png" alt="Kernlift settings for Aliyun DirectMail" width="512" height="1209" loading="lazy" /> ## 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**. <img src="/docs/guides/email/cloudflare.en.png" alt="Kernlift settings for Cloudflare Email" width="512" height="786" loading="lazy" /> ## 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 <noreply@mail.example.com>`, 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**. <img src="/docs/guides/email/resend.en.png" alt="Kernlift settings for Resend" width="512" height="697" loading="lazy" /> ## 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. <img src="/docs/guides/newsletter/beehiiv.en.png" alt="Kernlift settings for Beehiiv" width="512" height="369" loading="lazy" /> ## 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. <img src="/docs/guides/newsletter/providers.en.png" alt="Kernlift settings for Resend" width="512" height="369" loading="lazy" /> ## 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. <img src="/docs/guides/notifications/channels.en.png" alt="Kernlift settings for Discord" width="512" height="697" loading="lazy" /> ## 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. <img src="/docs/guides/notifications/channels.en.png" alt="Kernlift settings for Feishu" width="512" height="697" loading="lazy" /> ## 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 <TypeTable type="{ transactional: { type: "category", description: "Receipts, verification, password reset. A customer cannot switch these off because they are part of the transaction.", }, system: { type: "category", description: "Operational notices about the account itself.", }, marketing: { type: "category", description: "Opt-in only. Customers opt out on the preference page.", }, }" /> 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. <img src="/docs/guides/notifications/channels.en.png" alt="Kernlift settings for Slack" width="512" height="697" loading="lazy" /> ## 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. <img src="/docs/guides/payments/alipay.en.png" alt="Kernlift settings for Alipay" width="512" height="751" loading="lazy" /> ## 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**. <img src="/docs/guides/payments/creem.en.png" alt="Kernlift settings for Creem" width="512" height="465" loading="lazy" /> ## 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**. <img src="/docs/guides/payments/dodopayments.en.png" alt="Kernlift settings for DodoPayments" width="512" height="562" loading="lazy" /> ## 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:<refundId>`. ## 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/<orderId>` 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_<orderId>` is written. 3. For a subscription, `subscription_<orderId>` 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.<orderId>`. 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. <img src="/docs/guides/payments/paypal.en.png" alt="Kernlift settings for PayPal" width="512" height="465" loading="lazy" /> ## 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: `<key>-lifetime` is the list price anyone can pay, and `<key>-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 (`<key>-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://<your-domain>/app/billing`. * **Cancel URL**: where the buyer lands otherwise, for example `https://<your-domain>/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/<order>`, 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://<your-domain>/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://<your-domain>/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://<your-domain>/app/billing`, and **Cancel URL** to where a buyer lands otherwise, for example `https://<your-domain>/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**. <img src="/docs/guides/payments/stripe.en.png" alt="Credential fields in the Stripe payment settings" width="512" height="465" loading="lazy" /> ## 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://<your-domain>/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. <img src="/docs/guides/payments/waffo.en.png" alt="Kernlift settings for Waffo" width="512" height="1001" loading="lazy" /> ## 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/<order>` 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. <img src="/docs/guides/payments/wechat-pay.en.png" alt="Kernlift settings for WeChat Pay" width="512" height="1017" loading="lazy" /> ## 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. <img src="/docs/guides/storage/connection.en.png" alt="Kernlift settings for Amazon S3" width="512" height="1052" loading="lazy" /> ## 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. <img src="/docs/guides/storage/connection.en.png" alt="Kernlift settings for Cloudflare R2" width="512" height="1052" loading="lazy" /> ## 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. <img src="/docs/guides/storage/connection.en.png" alt="Kernlift settings for MinIO" width="512" height="1052" loading="lazy" /> ## 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/<dialect>`, 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/<name>/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/<key>/module.json`, and shared files carry `@module:<key>` 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/<username>` 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 `<you>/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/<template-key>`) 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 <commit>` 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/<username>` 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/<template-key>.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 "<id>".` 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 <address>` | 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/<template-key>`) 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 <commit>` 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/<template-key>` 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='<at least 8 characters>' 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/<key>/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 <cloudflare|fly|railway|docker> [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 <platform>`. 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 <db>` | Production database (default: the current one if the new platform allows it, otherwise the platform's first choice) | | `--region <code>` | Fly.io primary region (default `iad`) | | `--cwd <dir>` | 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 `<name>-agent`, `fly.agent.toml` | Service `agent`, one replica | Service `agent` | | Web reaches the agent at | The container binding | `http://<name>-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://<name>.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 <name>` 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 <dir>` 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/<key>/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/<name>/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/<name>` 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/<x>` or `/app/<x>` 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:<name>`. `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.