Write backend code
Backend code runs on the Ryot server, inside the plugin sandbox. It is how a plugin records history, reacts to changes, imports files, talks to other services and searches online sources. This page adds an action to the Houseplants plugin from the quick start that records when you water a plant, then tours the other kinds of backend code.
Add an action
Section titled “Add an action”An operation is a named action that your screens, Ryo and connected AI tools
can run. You will add water-plant, which records a watered event on a plant.
-
Add
"@ryot-app/plugin-backend-sdk": "workspace:*"to thedependenciesin yourpackage.json, then runbun installfrom the repository root. -
Describe the input and output in
shared/, so the manifest, the backend and your screens all use the same schemas:shared/water-plant.ts import { Schema } from "@ryot-app/plugin-kit/effect";import { IsoTimestamp } from "@ryot-app/plugin-kit/schema";export const WaterPlantInput = Schema.Struct({plantId: Schema.NonEmptyString,wateredAt: IsoTimestamp,});export const WaterPlantOutput = Schema.Struct({ plantId: Schema.String }); -
Write the script. Any file under
backend/whose name ends in.sandbox.tsbecomes a sandbox script; itsslugis how the manifest refers to it:backend/operations/water-plant.sandbox.ts import { createEventChange, existingEntity } from "@ryot-app/plugin-backend-sdk/core";import { defineManifest } from "@ryot-app/plugin-backend-sdk/driver";import { Effect } from "@ryot-app/plugin-backend-sdk/effect";import { defineOperation } from "@ryot-app/plugin-backend-sdk/operation";import { EntityId } from "@ryot-app/plugin-kit/schema";import { WaterPlantInput, WaterPlantOutput } from "../../shared/water-plant";export const manifest = defineManifest({kind: "operation",name: "Water a plant",slug: "operation.water-plant",});export default defineOperation({manifest,input: WaterPlantInput,output: WaterPlantOutput,run: ({ plantId, wateredAt }) =>Effect.succeed({output: { plantId },changes: {events: {changes: [createEventChange("watered", {properties: {},occurredAt: wateredAt,eventSchemaSlug: "watered",entity: existingEntity(EntityId.make(plantId)),}),],},},}),}); -
Declare the event type and the operation in
manifest/plugin.ts:manifest/plugin.ts import { CLIENT_API_VERSION, definePlugin } from "@ryot-app/contract/modules/plugins/manifest";import { operationJsonSchema } from "@ryot-app/plugin-kit/operations";import { catalogMessage } from "../shared/messages.generated";import { PLUGIN_PACKAGE_ID } from "../shared/plugin-identity";import { WaterPlantInput, WaterPlantOutput } from "../shared/water-plant";export default definePlugin({// ...operations: [{auth: "user",slug: "water-plant",title: "Water plant",demoAccess: "protected",scriptSlug: "operation.water-plant",input: operationJsonSchema(WaterPlantInput),output: operationJsonSchema(WaterPlantOutput),hints: { readOnly: false, idempotent: false, destructive: false },description: "Record that one of your plants was watered at the given time.",},],entitySchemas: [{slug: "plant",icon: "sun",eventSchemas: [{slug: "watered",propertiesSchema: { fields: {} },name: catalogMessage("event-schema.watered.name"),},],// ...},],// ...}); -
Add the new text to
shared/messages/en.json:"event-schema.watered.name": "Watered","home.water": "Water now", -
Add a button that calls the operation, as shown in Run an action, and put
<WaterButton plantId={plant.id} />next to each plant on the home screen. -
Raise the manifest
version, runbun run build, and use Update package in Settings → Plugins. The review screen now lists Water plant marked Changes data.
How an operation works
Section titled “How an operation works”- The script never writes to the database.
runreturns anoutputfor the caller and a set ofchanges. When the run ends, Ryot checks the changes and commits them in one transaction, or none at all. The same applies to every kind of backend script that writes. - Reading goes through the host.
runreceives a second argument,host, for reading data (host.executeRyotql, usually throughexecuteRyotqlRecipe), calling URLs (host.httpCall), reading the plugin’s configuration (host.getPluginConfig) and more. The compiler sees which ones you use; you never declare permissions. - Refuse bad requests with a message. Fail with
reject(catalogMessage("..."))from@ryot-app/plugin-backend-sdk/operationwhen a request cannot succeed as sent. The caller gets your message, translated. - The manifest entry is public.
titleis what Ryo shows when it asks someone to approve the action.descriptionexplains it to people and AI tools.hintsdrives the Read-only, Changes data and Can delete data labels on the install screen, so keep it honest.auth: "user"means a signed-in person runs it.demoAccess(allowedorprotected) decides whether a server’s demo account may run it.
Changes can create, update and delete entities, events and relationships, write the user’s plugin preferences and more. See Data contracts for every part of a change set and its limits.
Kinds of backend code
Section titled “Kinds of backend code”Each .sandbox.ts file default-exports one definition. Group them in folders by purpose:
operations/, automations/, workflows/, imports/, integrations/, providers/ and
bootstrap/, with shared helpers in backend/lib/.
| Definition | Use it for | Learn more |
|---|---|---|
defineOperation |
Actions that screens, Ryo and other clients call | Data contracts |
defineAutomation |
Reacting after something changes, listed in the manifest’s hooks |
Lifecycle hooks |
defineAutomationPolicy |
Checking a change before it is saved, and allowing or rejecting it | Lifecycle hooks |
defineWorkflow |
Long jobs split into saved steps, such as imports | Execution |
defineScript |
Scheduled jobs (crons), per-user setup (userBootstrap) and other internal tasks |
Execution |
defineProvider |
Searching an online source and fetching item details | Package layout |
Imports and integrations are built from these pieces: an importSources entry in the manifest
starts a workflow with the uploaded file, and integrationProviders connect services such as media
servers. See Imports and ingestion.
Workflows use a smaller toolkit from @ryot-app/plugin-backend-sdk/workflow, because they must
replay the same way if the server restarts mid-job.
Limits
Section titled “Limits”Every run has limits, including 30 seconds of CPU time, 64 MiB of memory and 1,000 host calls, with
at most four in flight at once. Prefer one batched query over many small ones. The full table of
limits is in kernel/sandbox/README.md in the repository, and the
execution reference explains the host-call budget.
Expected errors
Section titled “Expected errors”run returns an Effect, and its failure type is inferred from your code. Use tagged errors for
failures you expect, and reject for requests a person needs to fix. Anything else reaches the
caller as a generic failure.
See Test your plugin to run scripts without a server.