ObjectStackObjectStack

Actions — permission-checked UI buttons

Declare buttons as metadata with server-side behavior — bind them to lists, records and navigation, permission-check both sides, and expose them to AI.

An action is a button declared as metadata: where it appears (locations), when it's visible (visible), who may run it (requiredPermissions), and what it executes — an inline sandboxed script, a registered server handler, a flow, or a URL. The same declaration renders in the Console, executes over REST, and (with an explicit opt-in) becomes an AI tool over MCP.

The types you'll actually use:

typeWhat it doesServer behavior
script (default)Run server-side logicInline body or a handler registered via target
flowLaunch a flow (e.g. a screen-flow wizard)target names the flow
urlNavigate / open a linktarget is the URL (${ctx.record.id} interpolation supported)
modalOpen a modal page — client-side only, no server dispatchtarget names the modal page (to collect input and run logic, use script + params)
apiCall an HTTP endpointtarget is the endpoint; method / bodyShape / bodyExtra shape the request. A same-origin target is dispatched through the action doors (REST and MCP), which forward it in-process after their gates; an off-origin one is called by the browser directly
formOpen a form view, prefilled with the current record — in-shell, and the submit lands on the created record (contract)target names the FormView; routed to /forms/:target?recordId=…

Prefer confirmText/params over the two action properties that are not wired: shortcut (nothing dispatches keydown events to actions) and bulkEnabled (the multi-select toolbar reads the list view's bulkActions, not this flag). The liveness ledger carries the per-property status of everything the action schema accepts.

Define your first action

From the bundled Todo example — a "Mark Complete" button on the task list and record header:

src/actions/task.actions.ts
import { defineAction } from '@objectstack/spec/ui';

export const CompleteTaskAction = defineAction({
  name: 'complete_task',
  label: 'Mark Complete',
  objectName: 'todo_task',          // which object this action belongs to
  icon: 'check-circle',
  type: 'script',
  target: 'completeTask',           // resolved to the handler registered below
  locations: ['record'],
  successMessage: 'Task marked as complete!',
  refreshAfter: true,
  ai: {
    exposed: true,
    description: 'Mark a todo task as complete. Use when the user says a task is done or finished.',
  },
});

Register it in your stack — top-level actions carrying an objectName are merged into that object automatically (and ordered by order):

objectstack.config.ts
export default defineStack({
  // ...
  actions: Object.values(actions),
});

Give it server behavior — two paths

Path A: inline body (sandboxed)

Self-contained logic ships inside the metadata and runs in the server sandbox — signature (input, ctx), with ctx.api.object(name) for data access, a 5-second default timeout, and declared capabilities. input and ctx are the wrapper's parameters, so a body must not declare them again: const input = … does not compile, and os validate / os build / the publish door refuse it (action-body-does-not-compile):

export const MarkDoneAction = defineAction({
  name: 'showcase_mark_done',
  label: 'Mark Done',
  objectName: 'showcase_task',
  type: 'script',
  body: {
    language: 'js',
    source:
      "var id = ctx.recordId || (ctx.record && ctx.record.id);" +
      "if (!id) throw new Error('No record to mark done');" +
      "await ctx.api.object('showcase_task').update({ id: id, done: true, progress: 100 });" +
      "return { ok: true, id: id };",
    capabilities: ['api.write'],
  },
  successMessage: 'Task marked done.',
  visible: 'has(record.done) && record.done != true',
  locations: ['record', 'record_section'],
  refreshAfter: true,
});

Body-carrying actions are registered automatically at boot.

ctx.record is read-only — persist through ctx.api.

ctx.record is the record the dispatcher pre-fetched before the action ran: a snapshot the runtime never writes back. Assigning to it changes a copy that dies with the sandbox, and the action still returns success:

ctx.record.done = true;      // ❌ discarded — even though `done` is a declared field
return { ok: true };         //    the action reports success, the record is unchanged

await ctx.api.object('showcase_task').update({ id: ctx.recordId, done: true });  // ✅ persists

This holds for declared fields too — it is not a spelling problem, so no did-you-mean will appear. Do not reason from ctx.input, which is written back in a hook body; an action's output is its return value and its write channel is ctx.api (declare capabilities: ['api.write']).

You will be told rather than left guessing. os validate / os lint / os compile raise action-record-write-discarded, and the sandbox logs the discarded fields at invocation time — the latter also catching computed keys, aliases and bodies authored in Studio, which no lint ever inspects.

Both report only writes that reach nothing. Building a payload on the snapshot and then persisting it is a normal, live pattern and stays quiet:

ctx.record.done = true;
await ctx.api.object('showcase_task').update(ctx.record);   // ✅ lands — not reported

Refuse in the user's language — refusals

A body that refuses with throw new Error('…') answers every caller in the language the author wrote. To refuse in the caller's language, declare the refusals the body may throw, keyed by code, and throw the code instead of the sentence — the same catalogue a hook declares:

export const SubmitSignoff = defineAction({
  name: 'submit_signoff',
  label: 'Submit for sign-off',
  objectName: 'crm_invoice',
  type: 'script',
  refusals: {
    NOT_DRAFT: { message: 'Only a draft invoice can be signed off.', status: 409 },
    STAGE_LOCKED: {
      message: 'This stage change is not allowed.',
      params: ['stage'],
      reasons: { closed: { message: 'A {{ stage }} invoice can no longer change.' } },
    },
  },
  body: {
    language: 'js',
    source:
      "if (ctx.record.status !== 'draft') throw { code: 'NOT_DRAFT' };" +
      "if (ctx.record.closed) throw { code: 'STAGE_LOCKED', reason: 'closed', params: { stage: ctx.record.stage } };" +
      "return { ok: true };",
    capabilities: [],
  },
});

The server answers a declared code with its entry: the message (or the declared reason's), translated in the caller's locale with the declared sentence as the fallback, its {{ }} holes filled from the throw's params, and the entry's status (400 when it names none). The sentence rides on the refusal's userMessage, which the console's failure toast shows. Translate it beside the action's other copy — objects.<object>._actions.<action>.refusals.<CODE>.message (and ….reasons.<REASON>.message), or globalActions.<action>.refusals.… for an action with no objectName; os i18n extract scaffolds the keys.

A code the catalogue does not declare, a reason a code with reasons does not declare, or a throw with no code is refused loudly: at save when the body names it literally, otherwise when it runs, as a fault naming the action and the code. An error a ctx.api call raised and the body let through unchanged passes through as before, and so does a crash. refusals is read only for a type: 'script' action with a js body (an inline target function is lowered to one by os build); on any other action it is refused.

Write in the organization's language — texts

A body that writes a sentence into a record — the subject of the email activity it logs — writes it in the language the author typed, whoever reads the record. To write it in the organization's language, declare the sentence under texts, keyed by a snake_case key, and ask for it with ctx.text instead of building the string — the same texts a hook declares:

export const SendEmail = defineAction({
  name: 'send_email',
  label: 'Send email',
  objectName: 'crm_contact',
  type: 'script',
  texts: {
    email_subject: { message: 'Email: {{ subject }}', params: ['subject'] },
  },
  body: {
    language: 'js',
    source:
      "const subject = await ctx.text('email_subject', { subject: input.subject });" +
      "await ctx.api.object('crm_activity').insert({ subject, contact: ctx.recordId });" +
      "return { ok: true };",
    capabilities: ['api.write'],
  },
});

ctx.text(key, params) answers the sentence in the organization's language — the Localization setting when somebody set it, else the app's i18n.defaultLocale — never the language of the person who pressed the button: the record is read by the whole organization. It picks the translation first, then fills its {{ }} holes from params. With no translation the declared sentence is written and the action goes on; a Localization setting that cannot be read rejects the call. Translate it beside the action's other copy — objects.<object>._actions.<action>.texts.<key>.message, or globalActions.<action>.texts.<key>.message for an action with no objectName; os i18n extract scaffolds the keys.

A key the action does not declare is refused: at save when the body asks for it literally, otherwise when it runs, as a fault naming the action and the key. A string the body builds itself is written as it is. texts is read only for a type: 'script' action with a js body; on any other action it is refused.

Path B: a registered handler (full TypeScript)

For logic that belongs in real source files, point target at a handler name and register it in your config's onEnable lifecycle hook:

src/actions/task.handlers.ts
import type { ActionHandlerContext } from '@objectstack/spec/ui';

export async function completeTask(ctx: ActionHandlerContext): Promise<void> {
  const { record, engine } = ctx;   // ctx = { record, params, user, session, engine }
  await engine.update('todo_task', record.id as string, {
    status: 'completed',
  });
}

Annotate ctx with the published ActionHandlerContext, never a local copy of it: a hand-rolled context interface drifts from the contract the moment either side moves, and the drift is silent because the copy is what your handler is checked against. (The contract's own docblock asks for ActionHandler; that is a function type, so it fits an arrow-function handler assigned to a const, while a function declaration like the one above annotates its parameter instead.)

Write only the fields the action owns — and read that literally, because a handler's ctx.engine runs elevated (isSystem). The read-only strip that protects a server-owned column from an ordinary caller is gated on not being a system write, so it does not run on a handler's write at all. What a handler names, lands. A server-owned field is therefore more dangerous here than in a form PUT, not less.

completed_date is the example. It is readonly on todo_task — the server owns it, and the object's beforeUpdate hook stamps it on the completion transition. Adding completed_date: new Date().toISOString() to the write above looks harmless, and on that transition it is: the hook overwrites it. But a completion write that is not a transition — re-completing a task that is already completed — is not stamped, so nothing overwrites the handler's value and nothing strips it either, and the action silently replaces the real completion timestamp with "now". That is why the snippet sends status alone.

ctx.engine.find(object, query) takes the engine's query envelope. The second argument is the same options bag engine.find takes everywhere else — the filter goes under where, and fields, orderBy, limit, offset and expand mean what they mean on the engine. One platform, one query shape.

await ctx.engine.find('todo_task', { where: { status: 'completed' } });
await ctx.engine.find('todo_task', { where: { amount: { $gt: 100 } }, fields: ['id', 'subject'], limit: 50 });
await ctx.engine.find('todo_task', {});   // the unfiltered read

The parameter is typed EngineQueryOptions (ActionEngineFacade in @objectstack/spec/ui), so if you annotate ctx with the published ActionHandlerContext a bare filter is a compile error at the call site — { status: 'completed' } has nowhere to land, and neither does a filter held in a FilterCondition variable. A hand-written test double must honour the envelope too.

One envelope key is not on this parameter: context. A handler's ctx.engine is trusted and mints its own elevated ExecutionContext, so a context you write here would be overridden, never honoured — and writing one reads as narrowing a query to an identity or a tenant when it does nothing of the kind. It is subtracted from the type, so ctx.engine.find('todo_task', { where: { … }, context: { tenantId: 'org_acme' } }) is a compile error rather than a silent no-op. To scope a read, put the scope in where. (An untyped handler still passes the key and still has it overridden, with no error — one more reason to annotate ctx.)

If you do not annotate it — a handler in an objectstack.config.js / .mjs, your own copy of the context type, or (ctx: any) — the facade refuses the bare filter at runtime instead, naming the stray key and prescribing the same fix. That runtime refusal is what stops { deleted_at: null } from being dropped unexecuted and quietly widening the read to every row.

Upgrading? This parameter used to be the where half on its own, and the runtime wrapped it. find(o, f) becomes find(o, { where: f }); an unfiltered find(o, {}) is unchanged. The old shape had the trap the other way round: writing the engine's own envelope produced { where: { where: … } }, which matched no row and returned [] with no error at all.

ctx.engine.delete(object, id) takes one id — or an array of them. Both spellings are contract: ActionEngineFacade in @objectstack/spec/ui declares the parameter string | string[], so a handler that already holds a list does not have to unroll it into a loop to stay on the contract.

await ctx.engine.delete('todo_task', record.id as string);        // one row
await ctx.engine.delete('todo_task', ['tsk_0001', 'tsk_0002']);   // a set

The array form is a convenience over the same per-row path — not a bulk and not an atomic delete. The runtime issues one delete per id, in order, with no transaction around the set: a failure part-way through leaves the ids before it deleted and the ids after it untouched, and the rejection you see is the one that stopped it. An empty array deletes nothing and resolves.

objectstack.config.ts
export const onEnable = async (ctx: { ql: { registerAction: (...args: unknown[]) => void } }) => {
  ctx.ql.registerAction('todo_task', 'completeTask', completeTask);
};

The "dead button" trap: only actions with an inline body register themselves. A script action whose target names a handler that was never registerAction-ed compiles fine but throws Action 'x' on object 'y' not found at click time. (An action with neither body nor target is rejected at authoring time.) Also note that both data surfaces a body reaches — ctx.api.object(name) and the handler's ctx.engine facade — are trusted: they run under the caller's identity elevated to system, so they bypass row- and field-level security (writes stay attributed to the caller and scoped to their organization). Enforce any caller-specific rules yourself — and read Authorization inside an action before you write that guard, because ctx.record.id is present even when the caller cannot read the row.

body belongs to script only. Every other type dispatches on target — the page to open, the URL, the flow, the endpoint — so a body on a modal/url/flow/api/form action would never be invoked. Writing one (typically type: 'modal' with params and a body, expecting the body to run when the modal is submitted) is rejected at authoring time rather than shipping a button that opens a modal and silently writes nothing. To collect input and run logic, use type: 'script' with params — the same dialog is collected, then the body runs with those values as its input.

Bind it to the UI

locations is the primary binding. Each word says what the action acts on, and the action appears on every surface that word covers:

LocationActs onWhere the button renders
listNo recordList view toolbar
recordOne recordRecord page header and the per-row menu in list views
record_pageOne record, openedRecord page header
record_rowOne record, in a listPer-row menu in list views
record_relatedOne record, in its parentEach row of a related list inside a parent record — there only, never on the object's own list views (unlike record_row). Declared, not yet placed: the console does not draw it on those rows yet
record_sectionOne recordNamed action bars on record pages

record_related takes the "One record" cell too. To keep a record page action out of the header's buttons and put it straight into the header's 「More」 (⋯) menu, set component: 'action:menu' on it.

Protocol 19 replaced the page-part words: list_toolbar is list, list_item is record_row, record_header and record_more are record_page (record when the action was on list rows as well), and an action that was only in the ⋯ menu keeps that place with component: 'action:menu'. Run os migrate meta --from 18 to list the mechanical edits for existing sources; --write applies the ones it can prove, and you apply the rest by hand.

Choose the header's buttons

A page header draws at most three of its actions as buttons and puts the rest in its 「More」 menu. By default it picks the first three by each action's order. An object arranges them itself with actionLayout, one arm per action scope. Each arm has two parts: pinned, the buttons in the order drawn, and more, the order of 「More」:

ObjectSchema.create({
  name: 'crm_opportunity',
  // ...
  actionLayout: {
    // the list scope: actions placed at list, drawn on the list page toolbar
    list: { pinned: ['mass_assign', '$export'], more: ['send_digest'] },
    // the record scope: actions placed at record or record_page
    record: { pinned: ['mark_won', 'mark_lost'], more: ['clone', 'share'] },
  },
});
  • pinned is required in an arm and names at most three; pinned: [] pins none. more is optional. A name appears once, in one part.
  • An action the scope places that neither part names goes to the end of 「More」, in its default order. A pinned action hidden by its visible predicate or its permissions leaves its button out; no other action takes its place.
  • The record arm is a scope, not a page: it orders the record header wherever it is drawn, on the record page, in the side preview and in a phone's bottom action bar. It also orders the actions a list row already offers, adding none: the row's ⋮ menu, its right-click menu and, on a list page, the selection bar's actions for one selected record list the ones it names first, pinned then more, then the rest as before. The selection bar's buttons, at most three, are the first of that order; the row's own inline button does not change. A record page whose page:header authors its own actions list keeps that list.
  • The list scope can also pin its built-in Import and Export as $import and $export. A built-in is only ever pinned: not pinned, the list page draws it in its own Import / Export menu, as without the key (also with pinned: []), so more names actions only. The record scope has no built-ins: New, Edit and Delete keep their places.
  • Leave an arm out (or actionLayout out) and that scope draws as before.
  • The schema refuses more than three pinned, a name given twice, a malformed name, a built-in the scope does not have and a built-in in more. os validate, os build and os lint also refuse a name that is no action of the object, or one the scope does not place.
  • An administrator sets the same arms in the running app: the app name at the top of the sidebar, then 「Design layout」 in its menu, then 「Header buttons」 at the end of the page header. Only the arm changed is saved. For an installed object it is saved as this environment's customization, the object_extension of the base's paired .custom package, whose arm replaces the object's arm for that scope whole. Only that package writes actionLayout on an extension: any other package's extension is refused it at publish, os validate, os build and install, and places the actions it brings by their own locations and order.

Surfaces can also reference actions by name:

// List views — row and bulk menus. These are LIST-VIEW keys, so they nest
// under `list` (or a `listViews` entry) — never at the container top level:
// `ViewSchema` is a strict object and rejects them there.
defineView({
  // ...
  list: {
    // ...
    rowActions: ['complete_task'],
    bulkActions: ['showcase_bulk_reassign'],
  },
});

// Record pages — a quick-actions bar
{ type: 'record:quick_actions',
  properties: { location: 'record_section', actionNames: ['showcase_mark_done'] } }

// App navigation — an action as a nav item
{ type: 'action', actionDef: { actionName: 'crm_convert_lead' } }

// App navigation — deep-link auto-run on an object entry: land on the
// object's list surface, then run the declared action once
{ type: 'object', objectName: 'sys_environment', runAction: 'create_environment' }

Naming an action in a widget does not bypass location filtering — the engine still requires the action to declare the matching location (that's why MarkDoneAction above includes record_section).

The selection bar is the exception, and the only one: an action named in a list view's bulkActions or bulkActionDefs is placed by that declaration, not by locations. That is what the retired action.bulkEnabled tombstone prescribes ("the multi-select toolbar is driven by the LIST VIEW's bulkActions / bulkActionDefs"), and it is what lets an aggregate bulk action — one that acts on a whole selection and has no single-record home by construction — exist at all.

Declare the bulk dispatch contract

A list view can wire the same action two ways, and the two hand your body opposite input:

wiringdispatchesthe body receives
bulkActions: ['<name>']once per selected rowthat row's recordId, no _selectedIds
bulkActionDefs: [{ name: '<name>', operation: 'custom', execution: 'aggregate' }]once for the whole selectionparams._selectedIds: string[], no recordId

Say which one you wrote the body for, with the same key and the same two values the def uses:

defineAction({
  name: 'export_zip',
  type: 'api',
  target: '/api/v1/export/zip',
  execution: 'aggregate',   // this body reads params._selectedIds
});

os validate / os lint / os build then refuse a list view that wires it the other way (action-dispatch-contract-mismatch), naming the action, the view and both contracts. Without the declaration both mismatches fail silently, in opposite directions: an aggregate body wired bare-string reads _selectedIds as undefined, takes its single-record branch and reports success for one row out of ten; a per-record body wired aggregate finds no recordId and throws its own "nothing selected", which reads like a selection bug. Nothing else can catch it — recordId and _selectedIds are both built-in action params, so the strict params gate admits either bag without a word.

Both contracts name rows the caller must be able to read, and the platform reads them in the caller's own scope before anything runs: the per-record dispatch loads its recordId, and an aggregate dispatch reads every id in params._selectedIds — see Authorization inside an action. A body that writes each selected row is best declared execution: 'perRecord': each dispatch then hands it that row as ctx.record.

There is no default. An action that omits execution is checked against neither wiring — which is also the honest declaration for a body written to serve both contracts (it reads recordId and _selectedIds). There is no third value for "both": one call and N calls have different side effects, so if the two wirings want different behaviour they are two actions. Upgrading an existing app? os migrate meta emits the action-bulk-dispatch-contract-undeclared TODO, which derives the declaration from the wirings you already have.

Collect input and shape the UX

  • params — prompt the user for input before execution. Prefer field-backed params ({ field: 'due_date' }) which inherit the object field's label, type, validation, and widget config; inline params ({ name, label, type, required, options }) cover the rest. defaultFromRow prefills from the current record. The console renders each param through the same field widgets as the record form (objectui ADR-0059), so any FieldType works — a file param shows a real upload control (multiple / accept / maxSize honored), lookup a record picker, date a date picker, richtext the rich-text editor, and so on. A field-backed param resolves the same way when the action is launched from a list's selection bar. Values reach the action as the widget emits them (number a number, date YYYY-MM-DD, a lookup the record id(s), a file the uploaded sys_file id(s), arrays when multiple), and the dialog's Confirm stays disabled while an upload is in flight. A param's visible is a CEL predicate over features, current_user and data that omits the param when false.
  • confirmText — confirmation dialog before running.
  • successMessage / errorMessage / refreshAfter — post-run feedback and an automatic data refresh. successMessage is a template whose holes are {{ }} over result (the handler's answer) and record (the record the action ran on): 'Invitation sent to {{ result.email }}'; a ${…} token in it is refused. A type: 'api' or 'script' action whose handler can succeed in more than one way adds outcomeMessages, one entry per snake_case outcome the handler returns, each a template like successMessage ({{ result.* }}, {{ record.* }}; a ${…} token is refused); the toast shows the entry the answer names, else successMessage, else a generic "Action completed successfully". A message in the server's answer is shown only when the copy asks for it ({{ result.message }}). Post-success navigation is onSuccess: { navigate, openIn }. A failure toast shows errorMessage when the action declares one, else the refusal's userMessage when the handler threw one (the text it wrote for the user, in the request's locale), else the error's own message.
  • undoable — on a single-record update, the success toast offers an Undo that restores the record's prior field values (Ctrl+Z works too). The runtime only captures the prior values when this flag is set, so an action that omits it gets no Undo.
  • resultDialog — a one-time reveal dialog for output the user must copy (generated tokens, export links).
  • variant / icon / order — presentation and sort position.

params is an array of parameter definitions, never a map of values. Writing params: { … } is rejected at authoring time, and what to write instead depends on the action's type:

You wantedWrite this instead
A static request body for type: 'api'bodyExtra: { name: '{{page.inquiryName}}' } — merged last, {{page.<var>}} tokens resolved by the runtime
A value to interpolate into a type: 'url' targetPut it in the target string itself. ${param.X} interpolates a value the params dialog collected; ${ctx.X} one from the action context
A new tab for type: 'url'openIn: 'new-tab' (for an async handler that redirects, use opensInNewTab instead)

There is no object form of params on a url action to migrate to: the two things it used to mean in the renderer — a statically authored ${param.X} scope, and a params.newTab flag — were retired, not renamed (#6828). Both are already expressible with the keys above, so a third meaning of params earns nothing; if you have a case the target string genuinely cannot express, that is a spec proposal for a properly named key, not a values map under this one.

Permissions and visibility

  • requiredPermissions: ['can_close_tickets'] is a dual-surface gate (one declaration, two enforcement points): the server rejects unauthorized calls with 403, and the UI hides or disables the button for the same users. Unset means no gate beyond object CRUD permissions — except at a flow action, whose target flow is admitted by its own rules either way (the flow row below): an elevated self-triggered target is refused to every caller but the system principal, and a target that declares its own requiredPermissions is refused to a caller who does not hold them. The action inherits the flow's list; when both declare one, the caller needs both. Referenced capabilities must exist — os lint checks that.

  • A script action that dispatches to a handler another declared action owns is gated by that action too. When the handler a call reaches is the one a different declaration's own dispatch reaches — its target names that declaration's handler key, or the handler that declaration's body registered — the server applies that action's requiredPermissions (403 PERMISSION_DENIED) and its packaged-action switch (409 ACTION_DISABLED) as well as the invoked action's own, on the REST /actions endpoint and the MCP run_action tool alike. The two sets add up, so the caller needs both, and the handler does not run on a refusal. Give each action its own handler key unless the two should share one gate.

  • visible is a CEL predicate evaluated fail-closed: an expression that throws hides the action silently. Two rules save real debugging time:

    1. Always prefix record fields — record.status != "closed", never a bare status, which faults as an undeclared identifier.
    2. Guard with has() — a record-scoped predicate on record_row binds a LIST ROW, which carries only the columns that view projects. Reading a field the list does not show aborts the expression with No such key, and fail-closed means the button simply is not offered — indistinguishable from the gate having said no. has(record.x) && … answers false instead.

    Add && record.x != null only when the value is then traversed (record.x.k), called (record.x.size()), ordered (< <= > >=), negated (!record.x) or used with in — those fault on a projected NULL. A plain == / != against a literal never does, so has() alone is the whole guard there. Prefer the minimal form: an over-guarded predicate is the pattern the next author copies.

    Compound && / || predicates are fully supported — see the formulas guide for CEL syntax.

  • requiresFeature ties visibility to a feature flag (compiled into a visible predicate).

  • Relation fields bind as their id. A lookup, master_detail, user or tree field reads in a predicate as the id the server stores, never as the record it points at, on every surface (a record page that expanded the relation for display collapses it again before evaluating). So "only the record's manager sees this" is current_user.id == record.manager; record.manager.id faults, because record.manager is a string. An empty relation is null, a clean false.

  • current_user.can(object, verb) asks whether the signed-in user holds an object permission, from the effective permissions the Console already holds for its built-in Edit and Delete, so a custom action that replaces one of them can be gated the same way: visible: "current_user.can('account', 'delete')". The verb comes from the closed OBJECT_PERMISSION_VERBS table in @objectstack/spec/security; a verb outside it is a fault, not false. current_user.hasCapability('<name>') asks the capability question from the same payload. Until that payload has loaded both fault, so a visible gate stays closed and a disabled gate renders the button disabled until the answer arrives. In a UI gate they decide only what is shown: the server still enforces the request the action sends, as requiredPermissions does.

Authorization inside an action

An action body and a registered handler both run elevated: ctx.api and ctx.engine carry isSystem, so they bypass row- and field-level security by design (that is what lets an action do work the caller cannot do directly). Elevation stops at identity assignment: an insert, update, delete, transfer, restore or purge of sys_user_position, sys_user_permission_set, sys_invitation or sys_member from either is refused with PERMISSION_DENIED, and a type: 'script' action whose body writes one of them by name through ctx.api.object('…') is refused when it is saved — make a position or permission-set grant from a flow whose runAs is 'user', which an action of type: 'flow' runs as the invoking user so the delegated-administration gate judges that user, and change invitations and memberships through the organization endpoints the refusal names (row 1b). The other consequence is that any caller-specific rule has to be re-established inside your handler — and the predicate most people reach for first does not work:

if (!ctx.record?.id) return refuse();   // ❌ always false — never refuses anything

Before dispatch, the platform loads the subject row in your caller's own scope. If that read comes back empty — the row is invisible to them under row-level security, or the id names nothing — the dispatcher still puts the recordId from the request onto ctx.record.id, because a new-record / record-less action legitimately needs it there. So ctx.record.id is present either way, and the guard above passes for a caller who cannot see the row.

The signal that does distinguish them is ctx.recordLoadDenied:

// ✅ the caller-scope load did not deliver the row — do not act on it
if (ctx.recordLoadDenied) {
  throw Object.assign(new Error('Record not available'), { code: 'RECORD_NOT_FOUND' });
}
ctx.record.idctx.recordLoadDenied
Caller can read the rowthe idabsent
Caller cannot read the rowthe id (stamped)true
New-record / record-less actionthe id, if one was passedabsent

Read it as ctx.recordLoadDenied === true. The key is absent, never false, when nothing was refused — so an action that never loads a row (no recordId, or an object-less action) never trips the guard.

It reports "the row did not resolve for this caller", not "the platform saw an authorization error". A row hidden by row-level security and an id that names nothing both arrive as RECORD_NOT_FOUND, deliberately — the platform does not disclose whether a record you cannot see exists — and the flag does not pretend to separate what that read fuses. For an authorization decision they are the same answer: this caller has not demonstrated read access to that row.

Both invocation doors set it — POST /api/v1/actions/... and the MCP run_action tool — and it reaches inline body sandboxes and registered handlers alike.

Set ctx.recordLoadDenied aside only when your action is meant to run without a readable subject row (an "import this id from elsewhere" action, say). The default for a row-scoped action on a private object is to refuse.

A selection is read the same way. A record-less call that carries params._selectedIds (an aggregate bulk dispatch) has every id in it read in the caller's own scope before the action runs, as a row of the object the call names, with the same read the per-record door makes for its recordId. If any id does not come back, the whole call is refused with 404 RECORD_NOT_FOUND, the per-record door's own answer; no id is dropped, the body or flow never starts, and nothing is written. The selection must be a list of non-empty record ids (strings or numbers), at most 5000 of them, on an action declared on an object; anything else is refused 400 VALIDATION_FAILED. So ctx.params._selectedIds only ever holds ids of rows of the object the call names (ctx.params.objectName) that this caller can read — your body still decides what it may do to them.

Three kinds of call are not read, because none of them builds an elevated context on the ids: a declarative operation: 'update' action (it writes as the caller), a type: 'api' action (its target authorizes the caller itself), and a call made as the system principal.

A param-less action keeps passing its custom keys through to the handler, except a near-miss spelling of a built-in — selectedIds, __selectedIds, _recordId, _objectName — which is refused 400 naming the built-in it meant, so a selection only ever arrives under the key the platform reads.

Flow actions. A type: 'flow' action hands its target flow the same record — record.id stamped the same way — and the flow run's context (AutomationContext, the @objectstack/spec contract) declares the same key in the same spelling, recordLoadDenied?: true, so a runAs: 'system' flow has something to guard on before it acts on a row its invoker could not read. On the flow face the key is populated since #15168: dispatchFlowAction takes the producer's load outcome and spreads the signal into the context it hands automation.execute, on both doors — the REST /actions endpoint and the MCP run_action bridge — so a flow run receives this key exactly when a handler would. A runAs: 'user' flow needs no guard — it re-derives the caller's scope on its own reads, and the stub resolves to nothing.

Call it over REST

Every action is also an endpoint — the Console button and the API call run the same gate and handler:

curl -b cookies.txt -X POST \
  https://your-app.example.com/api/v1/actions/todo_task/complete_task \
  -H "Content-Type: application/json" \
  -d '{ "recordId": "rec_123", "params": {} }'
# → 200 { "success": true, "data": <your handler's return value> }

The URL names the action by its name, never by target. target binds the action to whatever runs it — a handler key here, a flow id for type: 'flow', a URL for type: 'url' — so it is an implementation detail: the server resolves your declaration by name and derives the handler key from it. Rename the underlying function freely; as long as the declaration's target follows, the public URL is unchanged.

A body recordId names one record by its id, a string or a number. Any other value is refused 400 VALIDATION_FAILED naming recordId, before the declared param contract, the record load and dispatch, for every action type. An absent, null or empty recordId is the record-less call — except on an action declared execution: 'perRecord', which runs on one record: an api or flow action declared so is refused 400 VALIDATION_ERROR naming recordId before anything is forwarded or started, and one whose record does not resolve for you answers 404 RECORD_NOT_FOUND.

Failures speak HTTP — the status code is the signal (#3962):

  • 400 — the action ran and rejected (a business rule said no, or validation failed — then with error.details.fields[] to anchor the input).
  • 404 / 403 / 503 — it never dispatched: no such action, denied, service unavailable. A url/modal/form type, or an api type whose target is on another origin, has no server dispatch and is also a 400.
  • 500 — it crashed (a TypeError in your handler, a driver error) or timed out; a timeout's message names the action and its limit, while a crash answers only Internal server error. A deliberate throw new Error('…') is a 400 rejection, not a crash.

Full table in the error catalog. The client SDK folds all of it into one { success, data?, error? } result.

Global (object-less) actions post to /api/v1/actions/global/:action, or to /api/v1/actions//:action with the object segment left empty. For credentials, see API Authentication.

An action not bound to an object accepts no record. A call to an action declared on no object that carries a recordId or a params._selectedIds is refused 400 VALIDATION_FAILED, the key named in error.details.fields[], before any record is read and before the action runs — whatever object the path names, for every caller, and at every door (REST, MCP run_action and a host's dispatchAction). To act on records, declare the action on their object.

The endpoint dispatches on the declared type, exactly like the MCP run_action tool — so the same URL invokes a script handler or a flow:

typeOver REST
scriptRuns the registered handler / inline body.
flowRuns target on the automation engine, with your identity forwarded (a runAs: 'user' flow enforces RLS as you). Dispatches the same flow as POST /api/v1/automation/:target/trigger, without having to know the flow name — and answers the same way: a run that ran and was rejected is 400 FLOW_FAILED, while a dispatch that never happened is separated out (404 unknown flow, a stored flow with no start node included, as it is never armed / 409 FLOW_DISABLED / 422 FLOW_INPUT_SCHEMA_INVALID). A target declared runAs: 'system' whose type is self-triggered (autolaunched, record_change, schedule) is refused 403 PERMISSION_DENIED to every caller but the system principal, exactly as at the trigger door, and nothing runs; holding the action's requiredPermissions does not open it. A target that declares its own requiredPermissions is refused 403 PERMISSION_DENIED to a caller who does not hold every capability it names, even when the action declares none. An AI service account is refused a target declared runAs: 'system' 403 PERMISSION_DENIED unless the action declares ai.exposed: true: an action with the opt-in is the one way an account starts a flow that runs as the system, here and over MCP run_action. See Run a flow via API for the full table — it is one table, read by both doors.
apiSame-origin target (a path starting with /): the door runs its gates — the sign-in floor, requiredPermissions, the packaged-action switch, the param contract, the subject-row load — and then forwards the request in-process to target with your own credentials, assembling the body exactly as the Console does (recordIdParam / recordIdField from the subject row, bodyShape, bodyExtra merged last, organizationId for an /api/v1/auth/ target, method). The target endpoint still authorizes you itself; its status and body come back as the answer (its data unwrapped), and a credential rotation it emits (Set-Cookie, set-auth-token) is relayed. A ${ctx.selection.*} or {{page.<var>}} token exists only in the browser and is refused 400 by name. Off-origin target (another host): 400 — the browser calls it directly, and such an action cannot be switched off in the activation ledger (the write door refuses, 409, with the reason).
url / modal / form400 — client-side navigation; there is nothing for the server to run.

Headless actions: declare it, then hide it

An action that should be callable but not appear in the UI is still a declared action. Hiding is a property you set; it is not the absence of a declaration:

defineAction({
  name: 'recalculate_commissions',
  type: 'script',
  target: 'recalcCommissions',
  locations: [],                            // no UI surface
  requiredPermissions: ['finance.admin'],   // still gated
  // `ai.exposed` is false by default — no MCP tool either
})

You keep the capability gate, the param contract, the audit trail, and Setup visibility for admins. A declaration that no surface renders costs you nothing.

Registering a handler without a declaration is not a way to hide an action — it is refused. An undeclared handler has no requiredPermissions to enforce and no param contract to check, yet it would execute with system privileges, so the server declines it:

Action 'recalc' on 'crm_account' has no declaration — add
`defineAction({ name: 'recalc', … })`, or register the handler under a declared
action's `target`.

If server-side logic should never be reachable over HTTP at all, do not register it as an action — export a plain function and call it from your own code. engine.registerAction means "publish this on the HTTP and MCP surfaces".

Migrating an app that has undeclared handlers? Startup lists every one of them under [action-governance], with the object and key to declare. There is no flag that runs them meanwhile — one would be the same ungoverned execution this rule exists to prevent — so declare each one, or drop the registration if nothing should invoke it over HTTP.

Expose it to AI (MCP)

Actions are not AI-visible by default. Opting in takes two fields — and makes the action a governed MCP tool alongside the data tools:

ai: {
  exposed: true,
  description: 'At least 40 characters explaining when an agent should use this action.',
}

Only headless-callable types appear (script with body or handler, flow); url/modal never do. The caller's identity and requiredPermissions are enforced per invocation. Details: Actions as Tools and Connect an MCP Client.

Call it from your own host code

A host that runs actions from its own door, outside REST and MCP (an in-product AI tool, a job runner), calls dispatchAction from @objectstack/runtime instead of re-implementing the door's checks. It runs the same admission and dispatch as POST /api/v1/actions/... and answers what that door answers for the same call: the sign-in floor, requiredPermissions, the packaged-action switch, the type check, the param contract, the subject-row load, then the handler, flow or forward.

import { dispatchAction } from '@objectstack/runtime';

const answer = await dispatchAction(kernel, {
  executionContext,            // the caller, as your door authenticated it
  environmentId,               // optional; the kernel's default environment when absent
  objectName: 'crm_lead',      // omit for a global (object-less) action
  actionName: 'convert',
  recordId,
  params: { owner: 'u_42' },
  posture: 'ai',               // your AI tool's door: see below
  confirm: humanApproved,      // only read under `posture: 'ai'`, never for an AI service account
  credentialHeaders,           // optional: the caller's own credentials (e.g. `authorization`, `cookie`)
});
if (answer.status !== 200) throw answer.body.error; // the REST envelope's error

Pick the posture by who drives your door:

postureRulesUse it for
'rest' (default)Exactly the REST door's. It reads ai.exposed once: an AI service account starting a runAs: 'system' flow needs the action's opt-in (the flow row under Call it over REST). It asks for a confirmation once: under an AI service account's own key (an agent acting for itself, for no person) an action declaring ai.requiresConfirmation: true is refused 428 ACTION_CONFIRMATION_REQUIRED whatever the call sends and nothing runs: hand the action to a person, or its author declares ai.requiresConfirmation: false when it is safe unattended. The same holds under 'ai'.A door a person drives, or your own server code.
'ai'The REST door's, plus the three the MCP run_action tool adds: a sys_* action needs its own ai.exposed, every action needs ai.exposed: true, and an action with ai.requiresConfirmation is refused 428 ACTION_CONFIRMATION_REQUIRED until the call carries confirm: true (an AI service account's call, whatever it carries: see 'rest'). A script action with no handler binding is also refused. A client-side or off-origin api action is refused 400 as under 'rest', with run_action's sentence (cannot be invoked via MCP) instead of the REST prescription, so the agent is not handed the action's target.A host's in-product AI tool — an agent picks the action, so it takes the AI door's rules.

posture is 'rest', 'ai' or absent ('rest'); any other value is refused 400 VALIDATION_FAILED before anything runs, so a misspelt posture cannot quietly drop the AI rules.

credentialHeaders are the caller's own credential headers, read the way the REST door reads its request's: a same-origin type: 'api' action forwards with them, and its target authorizes the caller itself. Omit them and such an action forwards with none.

Pass the kernel your HTTP door is served from. On a multi-kernel host that is the kernel that registers the kernel-resolver service. environmentId reaches that resolver the way the environment of POST /api/v1/environments/:id/actions/... does, and the resolver places the call: it runs on the environment's own kernel, and on the host kernel only where the resolver places it there. A resolver that fails refuses the call with its own status; the call never runs on the host kernel in its place. Without environmentId the resolver gets no environment to read and places the call from what else it reads (your credentialHeaders; a host door has no hostname), or not at all. A call the resolver places in no environment runs in the kernel's default environment, as the REST door's does. On a host with no kernel-resolver, nothing places the call: it runs in the environment environmentId names (or the default environment when you omit it), exactly as before.

Placement is all dispatchAction shares with the REST door's request handling. Three steps that door runs after placement are not run here, so they stay your door's job:

  • The caller's identity in that environment. The REST door resolves its caller against the kernel the request was placed on. executionContext is used as you pass it, so pass the caller as the named environment knows them (their permission sets and positions there).
  • The authentication-policy gate (ADR-0069): a session with an expired password or a pending MFA step is blocked at the REST door.
  • Environment membership: the REST door refuses a signed-in user who is not a member of the environment, 403 PROJECT_MEMBERSHIP_REQUIRED.

namespace addresses an installed package's action the way the /api/v1/actions/:namespace/:object/:action path does (_env names the environment's own). A host call writes the usual invocation audit row, without a surface.

The MCP run_action tool runs this same sequence under 'ai', so its refusals carry the REST door's status and code: a name nothing declares is 404 RESOURCE_NOT_FOUND, a flow action with no automation service is 503, a caller without the action's capability is 403, and an object whose package is disabled is 404 OBJECT_PACKAGE_DISABLED.

Resume a handed-off run as the person who approved it

When the MCP resume_run tool hands a resume to the person (an action that declares ai.requiresConfirmation: true, on a host with a pending-confirmation service), the hand-off carries the paused run: run: { runId, values, screenNodeId }, where screenNodeId names the screen the values were given for. Your approve door resumes that run with dispatchActionResume, as the person who approved it, instead of re-implementing the resume_run checks:

import { dispatchActionResume } from '@objectstack/runtime';

const answer = await dispatchActionResume(kernel, {
  executionContext: approver,  // the person who approved, signed in to the app
  environmentId,               // optional, placed as for dispatchAction
  runId: handOff.run.runId,
  values: handOff.run.values,
  screenNodeId: handOff.run.screenNodeId,  // binds the approval to that screen
  confirm: true,               // the person's confirmation
});
if (answer.status !== 200) throw answer.body.error;

It asks every resume_run check again, as that person: the run must still be paused and must have been started by them (otherwise 404 RESOURCE_NOT_FOUND, the same answer for an unknown run), the flow action that admits the run must pass every run_action check, the record is read again as them, and the run must be paused on a screen (otherwise 409). The run then resumes; it never starts a new run and is never handed off again. A wizard stays paused under the same run id as it moves from screen to screen, so pass screenNodeId back: when the run is no longer on that screen (an earlier approval of the same item moved it on, or the person advanced it in the app) the call is refused 409 RESOURCE_CONFLICT, nothing resumes, and the run stays where it is. Without screenNodeId, the run's current screen is resumed with the values given. A screenNodeId that is null, empty or not a string is refused 400, so omit the key for an item stored without one. A wizard that loops back to the same screen is not told apart by its screen id. Decide each pending item once in your approve door. Without confirm: true, an action that declares ai.requiresConfirmation: true is refused 428 ACTION_CONFIRMATION_REQUIRED, and an AI service account is refused whatever it sends. The answer is the REST envelope, with resume_run's { ok, action, objectName, recordId, result } as data. Placement, and the three steps your door keeps, are dispatchAction's.

Troubleshooting

SymptomCause → fix
Button doesn't appearlocations doesn't include the surface (empty locations is right for a selection-only action that a list view's bulkActions places); or the visible CEL throws (e.g. a bare, unprefixed field name) and fail-closed hides it; or the user fails requiredPermissions, which hides the button at every location with no greyed-out control and no message
Click → Action 'x' … not foundtarget-style script with no registered handler — add the registerAction call in onEnable (Path B above)
REST → 400 naming the action's typeThe type has no server dispatch (url/modal/form/api) — open its target in the client, or call that endpoint directly
Appears in UI, missing from list_actions (MCP)ai.exposed not true, ai.description under 40 characters, or the type isn't headless-callable
Runs but the list looks staleAdd refreshAfter: true (an operation: 'update' action re-reads its record and the object's lists on its own)

On this page