Skip to content

Execution and authority

Every plugin script runs in the sandbox with an authority the kernel decides, never the script. This page explains plugin scope and execution subjects, user bootstrap and memberships, how capabilities are derived, how folds compute derived values, deployment-wide HTTP rate limits, and how long-running work is split into checkpointed workflow steps.

Ingestion assigns plugin scope (system or user); manifests do not.

  • The execution subject identifies whose data an invocation uses. It does not widen plugin privilege.
  • Kernel dispatch selects the subject, never script input.
  • Private plugins may initialize their own user entities through userBootstrap. They cannot write global domain data or declare deployment-owned httpRateLimits or oauthProviders.

The subject follows the dispatch path:

Dispatch Subject
Cron System
User bootstrap The user being initialized
User operations, imports and user-triggered provider calls The caller
Integration operations The caller, plus validated integration context
Automations A trusted automation-run subject
Durable descendants Inherited from their parent

The compiler derives local host capabilities from each entry’s reachable code, including helpers, closures and forwarding methods.

  • Executable dependencies do not merge authority: children use their own metadata, and workflow replay has no local host capabilities.
  • Ordinary scripts receive ScriptHost; policies receive PolicyHost. Narrowing a helper’s host type does not grant authority.
  • Runtime checks combine pinned metadata, script kind, subject and plugin scope. Domain services still enforce ownership.
  • Filesystem use derives capability requirements, but trusted paths are supplied separately by the kernel.
  • RyotQL reads current state, not omitted trigger-time evidence.
  • Host functions only read. An operation writes by returning a change set, which the kernel commits atomically after the run.
  • Relationship changes must choose merge or replace; membership upserts use merge to preserve annotations.

See Script writes.

  • Prefer bounded batch host calls. Do not hide N+1 bridge traffic behind concurrency: each execution has a host-call budget and at most four calls may be in flight.
  • Provider-associated scripts share a cache namespace by logical provider ID. Standalone scripts use their immutable script ID. Both are isolated by executing user, not plugin owner.

Exact host-function, filesystem and cache limits (key, TTL and restart semantics) are in the sandbox runtime reference.

A userBootstrap entry has a slug and description, and either names a direct scriptSlug or lists entities.

  • Each listed entity has a name, one of the plugin’s own entity schemas and properties valid for it. The kernel ensures declared entities itself, one per schema and user, without running a script.
  • Use a script only when setup needs logic. It must be a script-kind script. It receives { userId }, the ID of the user being bootstrapped, and returns { changes? } (changesOutputSchema from @ryot-app/plugin-backend-sdk/core).
  • A bootstrap script writes ensures as changes.entities.ensures. The kernel commits them once per bootstrap execution and script content.
manifest/plugin.ts
userBootstrap: [
{
slug: "default-collection",
description: "Create the user's default list",
entities: [{ name: "Inbox", entitySchemaSlug: "list", properties: {} }],
},
],

A memberships rule links the plugin’s member entities to a bootstrap-declared target through one of its relationship schemas, without a hook.

Field Meaning
slug Local slug
relationshipSchemaSlug The relationship written from member to target
targetEntitySchemaSlug The bootstrap-declared target schema
memberEntitySchemaSlugs At least one member schema
join What adds a member (see below)
silentEventProperty Optional. An event whose property of this name is true does not join.
recordEventSchemaSlug Optional. An event, belonging to every member schema, written for every new relationship of that schema from a member, whoever creates it

join chooses what adds a member:

join field Adds a member when
entityCreate One of the listed schemas is created
providerImport A provider import completes
events Any of its events is written
kernelCollectionAdd It is added to a kernel collection

The kernel writes the relationship in the same transaction as the source write. Hooks still see those writes.

Set fold: { scriptSlug, eventSchemaSlugs, entityProperties } on an entity schema to derive values from its subjects’ events after each write that changes them.

  • An event of a listed slug belongs to its session when the session’s schema folds that slug, and otherwise to its own entity.
  • entityProperties lists every property of the plugin’s entities the fold reads, as { entitySchemaSlug, properties }: of its subjects, and of the entities and sessions its events are on. A change to one replays the subjects that read it; other content changes fold nothing.
  • Set projection: { propertiesSchema } on an event or relationship schema to receive a value per record.

The fold is a read-only script of the same plugin. One run folds up to FOLD_LIMITS.runSubjects subjects. It receives { subjects }, each { subjectEntityId, value, absorbed, changes }, and returns exactly one result per subject.

backend/exercise-records.sandbox.ts
import { defineManifest, defineScript } from "@ryot-app/plugin-backend-sdk/driver";
import { FoldInput, FoldOutput, foldSubjects } from "@ryot-app/plugin-backend-sdk/folds";
export const manifest = defineManifest({
kind: "script",
name: "Fold exercise records",
slug: "fold.exercise-records",
});
export default defineScript({
manifest,
input: FoldInput,
output: FoldOutput,
run: foldSubjects({
value: ExerciseRecordsValue,
replay: ({ subjectEntityId }, host) => replay(subjectEntityId, host),
update: ({ value, changes, subjectEntityId }, host) =>
update(value, changes, subjectEntityId, host),
}),
});

foldSubjects({ value, replay, update }) from @ryot-app/plugin-backend-sdk/folds decodes each stored and absorbed value with value, failing the run on one that does not decode. It calls replay when there is no value or changes is null, and update otherwise. absorbed holds the values of subjects merged or restored into this one, with ids mapping their old entity and event IDs to new ones.

changes Meaning
null A full replay. Read the subject’s history and return every projected event and link output; the kernel replaces all of the subject’s outputs. New subjects, rebuilds, merges and declared property changes replay.
A list { before, after } per changed event, null outside the subject. Return only outputs that changed, reading only the history the change can affect; the kernel deletes the outputs of events without an after and keeps the rest.
Empty list Only links, a fold request or a refresh changed

foldChangeImages splits a change list into retracted and added images.

  • Incremental results must equal a full replay of the same history, so keep in value what an update needs to resume.
  • Read history with foldSubjectEventPredicate(event, { subject, eventSchemaSlugs, folds }) and foldEventImageSelection(event, entity) from @ryot-app/plugin-kit/ryotql. They route and shape events as the kernel does (ISO UTC timestamps). Use them in a static recipe with bounds as parameters.

A result whose outputs depend on the current time sets refresh: { date } (YYYY-MM-DD, from the start of that day in the user’s reporting time zone) or { instant }. When it passes, the kernel folds the subject again with an empty change list.

  • A result’s changes are applied before the fold runs once more for the subjects they changed; asking again fails the subject.
  • Fold-owned events skip before-policies and after-hooks.
  • A fold runs right after an interactive write, outside its transaction, or later as a job, so it must give the same result however late it runs.
  • A failing fold never undoes the write; its subject reads as pending or failed until a fold succeeds.
  • Changing the fold script or a folded event schema replays every subject.

See folds for the kernel side.

Every manifest includes httpRateLimits, using [] when empty.

Field Rule
key Lowercase slug
requests Positive safe integer
intervalMs Positive safe integer
origins Non-empty list of HTTP(S) origins with no path, query, fragment, credentials or wildcard
manifest/plugin.ts
httpRateLimits: [
{ key: "example-api", requests: 4, intervalMs: 1000, origins: ["https://api.example.com"] },
],
  • Origins are normalized before the unique key and origin checks.
  • Limits are deployment-global, not per plugin, script, user or credential.
  • Identical declarations can coexist. Conflicting declarations sharing a key or origin reject the prospective active snapshot.
  • Matched traffic uses an evenly spaced global schedule with no burst reservation.
  • A generic HTTP 429 retries durably after a valid Retry-After, otherwise after the declaration interval.
  • Unmatched origins are not constrained by this limiter.
  • Private plugins cannot declare httpRateLimits.

Workflow modules call declared activities and child workflows within a bounded step, then save the next checkpoint or return their final output.

Long-running workflows declare a checkpoint schema. The kernel calls run(input, step, checkpoint, execution) with null on the first step and the last saved value on later steps.

  • Return { output, changes? } to finish, or yield* step.save(nextState, changes?) to commit the next checkpoint and end this step.
  • A step’s changes commit once at its boundary, before its checkpoint or output is recorded.
  • Keep each step bounded. Use cursors and artifact references rather than accumulating source records.
  • A saved checkpoint survives process restarts without rerunning completed steps.
  • Code, configuration, input and start time stay pinned for the whole execution.
  • A bounded workflow that finishes in one step can omit checkpoint.
backend/workflows/import.sandbox.ts
export default defineWorkflow({
manifest,
input: importInput,
output: importSummary,
checkpoint: Schema.Struct({ nextPage: Schema.Int }),
run: (input, step, checkpoint) =>
Effect.gen(function* () {
const nextPage = checkpoint?.nextPage ?? 0;
const batch = yield* step.activity("read-page", readPage, { ...input, page: nextPage });
yield* step.child("apply-page", applyPage, batch);
if (batch.done) return { output: yield* step.child("summary", summary, input) };
return yield* step.save({ nextPage: nextPage + 1 });
}),
});

step.activity and step.child invoke declared script and workflow references. Their call names are local to the current checkpoint.

  • An activity script declares activity: true in its kind: "script" manifest and is defined with defineActivity. Its run returns { output, changes? }, as an operation’s does: output is what the reference’s output schema describes, and the kernel commits changes once when the activity completes and hands the workflow only output.
  • The backend compiler rejects an activity manifest defined with another helper, defineActivity without the flag, and a step.activity target that is not an activity. Manifest validation also rejects the last one.
  • The kernel keeps call outcomes only for an unfinished step, so it can complete interrupted calls without guessing whether an external write succeeded.
  • Keep call order, names and inputs deterministic within an unfinished step.
  • Move ambient time, randomness, network, filesystem and ordinary host functions into activity scripts.
  • Use Effect.fail for expected failures.
  • There is no public replay journal or durable sleep API.

Runtime pinning, checkpoint persistence and private call recovery are described in the sandbox runtime reference.

Create executable references with defineScriptReference and defineWorkflowReference from @ryot-app/plugin-backend-sdk/workflow.

  • defineExecutableAlternatives({ id, stage, references }) and selectExecutable(alternatives, key) constrain selection to registered targets.
  • Use stage: "settings" for setup choices and stage: "record" for choices refined from collected records.
  • Configuration and executable SDK methods must be called directly; method aliases are unsupported.