objectstack-automation
Design ObjectStack automation — Flows (visual logic), Triggers, Approvals, state machines, and the `jobs` (`defineJob`) / `webhooks` (`defineWebhook`) stack collections. Use when the user is adding `*.flow.ts`, wiring an event-driven rule, modelling an approval chain, or building an interactive screen flow / wizard (objectstack-ui routes those here). Do not use for data lifecycle hooks at the object layer (see objectstack-data) or for kernel / plugin events (see objectstack-platform). CEL expressions in flow conditions / edge guards: load objectstack-formula alongside.
How do I install this agent skill?
npx skills add https://github.com/objectstack-ai/objectstack --skill objectstack-automationIs this agent skill safe to install?
- Gen Agent Trust Hubpass
The skill provides a protocol for designing automation flows, including event-driven triggers, human sign-offs, and external service integrations. It incorporates security best practices such as delegated secret management and HMAC-SHA256 signature verification. However, it handles untrusted data that influences logic execution and high-privilege operations, which is a standard risk for automation frameworks.
- Socketpass
No alerts
- Snykwarn
Risk: MEDIUM · 1 issue
What does this agent skill do?
Automation Design — ObjectStack Automation Protocol
When to Use This Skill
Also vendor-integration callbacks and assignment rules.
Predicates and conditions are CEL — every
condition/guard/entryCondition/ filtervalueis an Expression envelope: a plain CEL string, or theP\...`/cel`...`` tag (author-time validation); pick one per file.
Flows — Visual Logic Orchestration
Flow Types
| Type | When to Use |
|---|---|
autolaunched | Runs without user interaction — triggered by events, APIs, or other flows |
screen | Interactive — presents UI screens to the user |
schedule | Runs on a cron/interval cadence declared on the start node's config.schedule — or a per-record date sweep via config.timeRelative |
record_change | Fires automatically on record create/update/delete. autolaunched + the same record-* binding behaves identically; record_change also opts into the trigger-readiness lint |
api | Inbound webhook (Inbound webhook triggers); a flow only ever started explicitly is autolaunched |
A flow an installed package ships is read-only. To change what it does, save
a same-named flow in the base's paired .custom package declaring
overrides: { package: '<base>', basedOn: '<base version>' }
(objectstack-platform § Customizing an installed package): it is armed in the
base's place, keeps the base's name and its one activation switch
(POST /api/v1/automation/:name/toggle, { enabled: false } = off for this
deployment), and a run suspended on the old body finishes on that body. An
undeclared same-named flow in the pair or in a dependent is refused at publish.
A flow beside it is "new similar": POST /api/v1/automation/:name/clone
{ name, label, package? } lands the copy switched off in the pair, never
package-less; a flow holding a secret / signingSecret is refused (409): author
it anew.
A package ships a flow switched off with defaultActive: false (beside
status: 'active'): unarmed (_status enabled: false) until an administrator
turns that switch on, which then outlives restart, upgrade and reinstall.
status: 'obsolete' disarms past the switch; a flow authored in the deployment
is refused the key (its switch is status).
Flow Node Types
Built-in (plugins register more):
Control Flow
| Node | Purpose |
|---|---|
start | Entry point — every flow has exactly one |
end | Exit point — can have multiple (early exit, error exit) |
decision | Conditional branching — routed by edge condition predicates, not node config |
loop | Iterate a nested config.body region once per item of config.collection — a CEL value envelope or an inline list, never a string; iteratorVariable (default item) and optional indexVariable bind inside it, maxIterations caps it |
parallel | Fan out into config.branches[] (≥ 2 regions) run concurrently, joined implicitly at block end |
try_catch | Run config.try; on failure run config.catch with the error in errorVariable (default $error); config.retry re-runs try with backoff first; in a record-after-* flow it (or errorHandling.strategy: 'retry') may not reach an inline http / connector_action: the save would wait out every attempt. Inside a subflow / map child, retried by either flow, that is silent: the flow saves but never arms (GET /api/v1/automation/_status: bound: false, unboundCause: retried_callout_in_subflow) until the child's http is durable: true or nothing retries the call. No finally — the container's ordinary out-edges are the continuation |
map | Sequential multi-instance — invoke the config.flowName flow (named as subflow's) per item of config.collection (shaped as loop's); each may pause (batch approvals); a refused name fails it at the first item |
wait | Pause execution until a timer elapses or a named signal arrives |
subflow | Invoke the flow bare config.flowName names: a package's flow gets its own, else the one holder in its dependencies closure plus sys; a package-less flow, the environment's, else the one package holder. Else os validate passes and the node fails at run time (subflow 'X' failed: … naming every candidate; no code): outside-closure — held only by an undeclared package (declare it) or the environment; ambiguous-in-closure / ambiguous-in-environment — two packages hold it (package / package-less caller) |
parallel_gateway / join_gateway / boundary_event | BPMN-interop forms a parallel / try_catch container lowers into; author the container |
Data Operations
| Node | Purpose |
|---|---|
assignment | Set variable values |
create_record | Insert a new record |
update_record | Modify existing records |
delete_record | Remove records |
get_record | Fetch records with filters — there is no query_record node |
save_notice | Tell the saver what this create/update started — record create/update trigger only, not after a pause: objectstack-data rules/lifecycle.md § Save Notice |
External Integration
| Node | Purpose |
|---|---|
http | Call an external HTTP API — always set timeoutMs (unset = no timeout). url and headers are served as written with the definition to every member who can read flows — only signingSecret and a start node's secret are withheld — so never a credential there: a credential means a declared connector called via connector_action. Retried after a record change: durable: true (outbox-queued, else sent once in the background, unretried; no response) |
notify | Send a notification (below) |
connector_action | Dispatch an action of a declared connector (§ Integrations are declared, not coded) or a plugin's. connectorConfig.input is a value-slot map like subflow input. Once evaluated, it is judged against the action's inputSchema (required, type, properties, items) before dispatch: a breach fails the step VALIDATION_ERROR (fault-routable); os validate does not judge the inputSchema fit yet. Retried after a record change: drop the retry, or run the flow on demand / on a schedule |
script | Call a registered function (Valid-but-silently-wrong #3) |
screen | Display a UI form to the user (screen flows only). config.fields[]: { name, label, type, required, options, defaultValue }, type an open widget hint; 'file' renders the upload widget and resumes with the sys_file id bound to name — a later create_record / update_record writes it into a file field, which claims the file: collect first, write after the last screen. 'record_link' (never 'record', an object field type) takes no input — it shows the reference record whose id defaultValue evaluates to, by display name, as a link to its record page: the result screen of a flow that created records, { name: 'account_link', type: 'record_link', reference: 'crm_account', defaultValue: { dialect: 'cel', source: 'account.id' } } over a create_record outputVariable: 'account'. Both keys required; required / options / placeholder / min / max refused; a resume value under its name refused (400 INVALID_SCREEN_INPUT). A completed end message is refused and a markdown link in a screen description renders literally. Next / Submit and "Step N of M" are not authored: the engine reads the graph when the screen pauses and serves progress, which alone labels the button and draws the counter. A decision, fault edge, loop back, non-screen pause (approval, wait) or subflow after a screen means "Next", no count. progress in a node config is refused |
Human Decision
| Node | Purpose |
|---|---|
approval | Route a record for human sign-off |
notify
An undeclared key is a named parse error. RAW keys are read as written:
a {token} in one is refused. The node as JSON (TypeScript: the same
literal, a FlowNode):
{ "id": "tell_owner", "type": "notify", "label": "Notify Owner", "config": {
"recipients": { "dialect": "cel", "source": "record.owner_id" },
"title": "Done: {{ record.title }}",
"message": "Closed {{ record.closed_at | date:long }}",
"topic": "task",
"severity": "warning",
"channels": ["inbox"],
"sourceObject": "task",
"sourceId": { "dialect": "cel", "source": "record.id" },
"actionUrl": "/tasks/{{ record.id }}"
} }
recipients— REQUIRED: id, list, or envelope; a CSV is ONE id. 4th form{ "emailField": "applicant_email" }: anemailfield of the trigger record, for a non-user — thenchannels: 'email'alone. An envelope must yield USER ids: an address no user holds fails the node.title— inline; XORtemplate(RAW, localizable).message— body; only with inlinetitle.- RAW:
topic(default'notify'),severity(CLOSED enuminfo|warning|critical),channels(default inbox). sourceObject+sourceId— the link: a PAIR, else dropped; none of the 3 ⇒ the trigger record (not on delete/before-create), if any.actionUrloverrides the pair.
A recipient string, written or evaluated, may be an audience selector:
team:ID— that team's members.owner_of:OBJECT:ID— that record's owner; a computed id:source: "'owner_of:crm_case:' + record.case_id".org:members— every member of the run's organization, else that of the record the notification is about, else nobody (singleposture: ascheduleflow declaring noorganization, no record). Any otherorg:value reaches nobody too. Each warns in the server log only; the node succeeds.
An option label in a notice: {{ stage | option:opportunity.stage }} in the mail
template (each recipient's language; mail-only, refused in inline title /
message) — never label() in templateData, evaluated once per run, before
fan-out.
Flow Variables
variables is an array; a variable has no label: variables: [{ name: 'case_id', type: 'text', isInput: true }, { name: 'approval_result', type: 'boolean', isOutput: true }].
→ references/examples-flows.md § Flow Example — Auto-Escalate Overdue Cases.
Failure routing & runAs
Handling a failed node: a
faultedge.{ source, target, type: 'fault' }routes a failed node to a handler instead of ending the run. Alabel: 'error'alone does nothing: an ordinary edge traverses on SUCCESS (objectstack validatereportsflow-error-label-not-fault). A handled failure does not consume the flow-level retry (errorHandling.strategy: 'retry'), which replays from the start — prefer a fault edge for a local failure. The handler reads{{ <nodeId>.error }}(run-wide{{ $error.message }}; in CEL,vars["$error"]); the run then reports success and the failed step stays in the trace.
| ROUTES (runtime failure) | Does NOT route (fatal either way) |
|---|---|
| 404, rate-limit, rejected write, failed subflow | missing required config key (objectName, url, flowName, connectorId/actionId); filter operand that evaluated to null or a non-value; graph past the nesting ceiling; unscoped run |
Writing a
readonlyfield? SetrunAs: 'system'(approval stamps, SLA markers, rollups). Under the defaultrunAs: 'user'the engine strips it fromcreate_record/update_record— the step succeeds, the drop is named in the step's warnings;os validate/os buildfail arunAs:'user'update_recordwriting one (readonlyWhen: a warning). A button, an action, an endpoint or the trigger route does not let a user start anautolaunched,record_changeorscheduleflow declaredrunAs: 'system'(403PERMISSION_DENIED), so for a flow a user starts from a button the elevated routes are ascreenorapiflow declaredrunAs: 'system', or a user-run flow whosesubflownode calls the elevated flow.
Elevate the write, not the flow. Prefer the
subflowroute — raising a wholescreenflow silently elevates every other write in it, and anapiflow adds a webhook secret and an inbound endpoint a button never uses.Elevation stops at identity assignment. A
runAs: 'system'write (insert through purge) ofsys_user_position,sys_user_permission_set,sys_invitationorsys_memberis refusedPERMISSION_DENIED, a system subflow included. Grant positions and permission sets from arunAs: 'user'flow — the delegated-administration gate judges that user and records them asgranted_by; invitations and memberships change through the organization endpoints (row 1b, https://objectstack.ai/docs/permissions/system-context#1-authorization-and-scoping).A
runAs: 'system'sweep must pin its organization. System context has no trigger user, so a scan or rollup with no organization predicate reads and writes across every tenant; filter on the platform-injected tenant column, never re-declare it per object.
Who may START a flow:
requiredPermissions: ['…']on the flow — the four entrances above refuse a non-system caller missing any named capability with403 PERMISSION_DENIED; an action starting it inherits the list, asubflownode is not an entrance. Gate an elevatedscreen/apiflow here, never oncurrent_user.positionsinside it.
A hook elevates itself with
runAs, never withsudo. An object hook (objectstack-data) declares its ownrunAs: 'system' | 'user' | 'inherit'— default'inherit', the context of the write that fired it — scoping that hook'sctx.apidata operations only, on the in-processhandlerand the sandboxedbodyalike. A'user'hook whose trigger resolved no user has nothing to scope to: itsctx.apidata operations are refused (HOOK_UNSCOPED_DATA_ACCESS, 403) rather than run unscoped.
Filter operands (config.filter)
- Each operand is a value slot, evaluated
before the query.
A whole-string query placeholder (
{current_user_id},{today},{current_year_start}) passes through verbatim for the query engine; a flow variable never shadows it, and onlyfiltergets this hand-off. - An operand that evaluates to
nullrefuses the node: a dropped condition does not narrow a query, it widens it, so a routeddelete_recordwould empty the object while the run reports success. Where the value may be absent, route around the node with adecision; to match an empty field, write the literalnull. A relation hop (record.owner.email) needs the start node'sconfig.expandto list the field — else the fault names the missing hop, not the remedy. - A computed operand is a value, never a query operator: a string, number,
bigint, boolean or date, or at an
$in/$nin/$betweencomparand a list of them with no empty entry. Anything else fails the node as a guard. Make the expression evaluate to the compared value (for a record, itsid), and write conditions in the filter itself.
Valid-but-silently-wrong (passes build, fails at runtime)
Most are caught by objectstack build:
-
A value slot takes a literal or a CEL envelope — never a
{…}token. Inassignments.*,fields.*,subflow/mapinput.*,scriptinputs.*,loop/mapcollection, notifyrecipients/templateData.*/sourceId,httpbodyand every CRUDfilteroperand, a string is the literal text it spells, and a{…}token is refused — atobjectstack validate(expression-invalid),registerFlowand the executor — naming its CEL spelling. Compute with{ dialect: 'cel', source: '…' }:'{record.owner}'→source: 'has(record.owner) ? record.owner : null'— CEL refuses an absent key where the template wrote nothing, so nothing /null/ a default is now YOUR call;'{record.tags.0}'→'record.tags[0]'; a deep path guards each step:has(vars.source) && has(vars.source.id) ? vars.source.id : null- run user:
{$User.Id}→current_user.id; a flow that can run without a user guards it,current_user != null ? current_user.id : null.current_userholdsid,positions,organizationId,isPlatformAdminonly — an email or a name is asys_userread by that id
Text slots (notify
title/message/actionUrl, screentitle/description, endmessage,httpurl/headers) render{{ }}holes — a variable path, optional formatter (adefault:argument is literal text, never a path), no logic; a{…}token there is refused with its{{ }}spelling. A date or the run user has no hole: assign it first (assignments: { v: { dialect: 'cel', source: 'current_user.id' } }), then write{{ v }}.create_record/update_recordfieldsalso take a text slot, marked{ dialect: 'template', source }, for a sentence people read. It is written in the organization's language (Localization setting if set, elsei18n.defaultLocale; key: objectstack-i18n), never the run starter's; untranslated, the authored text; an unreadable setting fails the node. A bare string stays a literal, never translated. -
create_record'soutputVariableholds the created RECORD, not its id. ❌fields: { ref: { dialect: 'cel', source: 'newRec' } }✅source: 'newRec.id' -
scriptnodes call a registered function — nothing else.config.function(required: an empty node refuses at execute, an unregistered name fails loudly) names one registered indefineStack({ functions }).The name resolves from the flow's package, as
subflow'sflowNamedoes, the platform's ownerless function in every flow's reach; a.customoverride reads as a package-less flow. Packages of twonamespaces each run their ownnormalize_phone. One namespace (or none): both held at boot warnBare-name conflict at boot; a later one installs but binds NONE of its functions or hooks (errorFailed to bind declarative hooks): rename, or another namespace. If the flow's package holds none, two holders in reach or one only outside itsdependenciesclosure fail the step as a guard (nofaultedge;$error.code: 'RESOURCE_CONFLICT'in atry_catch); a flow door'sinnerRefusalnames each holder. Fix: declare the dependency, or rename.A flow
functionis a PURE compute step — it does NOT read/write the database. It receivesctx.inputand returns a value; a later declarative node persists itsoutputVariable:[ { "id": "ai", "type": "script", "label": "AI Triage", "config": { "function": "helpdesk.aiTriageStub", "inputs": { "ticketId": { "dialect": "cel", "source": "record.id" } }, "outputVariable": "ai" } }, { "id": "apply", "type": "update_record", "label": "Apply Category", "config": { "objectName": "helpdesk_ticket", "filter": { "id": { "dialect": "cel", "source": "record.id" } }, "fields": { "ai_category": { "dialect": "cel", "source": "ai.ai_category" } } } } ]A function that writes where the platform cannot see declares it, so the run reports "cannot say" rather than
acted: 0(project code — a function has no JSON form):defineStack({ functions: { 'billing.sync': { handler: syncBilling, effect: 'writes' }, } }); -
A
selectis compared and written by its optionvalue, never its label. The request speaks the label ("Lost"); the row stores thevalue(lost).condition: "record.status == 'Lost'"parses, matches no row: the flow stages clean and never fires;fields: { status: 'Lost' }/ afilterfails the run (invalid_option). Read the field'soptions.
→ State Machines & Approvals: references/state-machines-and-approvals.md — its state-introspection route is GET /api/v1/meta/object/:name/state/:field?from=:state.
Assignment rules — route a new record to a queue or a person
assignmentRules on the stack routes each inserted
row of an ownership: 'user' object whose owner_id and queue are both still
empty — once, after every beforeInsert hook, never on update, never refusing the
insert. Entries are ordered; the first whose criteria (CEL over
record.*) match decides:
import { defineAssignmentRule } from '@objectstack/spec/automation';
export const caseIntake = defineAssignmentRule({
name: 'crm_case_intake',
object: 'crm_case',
entries: [
{ name: 'urgent', criteria: 'record.priority == "urgent"',
assignTo: { type: 'queue', value: 'crm_escalations' } }, // no strategy: parked for a claim
{ name: 'rest', assignTo: { type: 'queue', value: 'crm_support_intake' },
strategy: 'least_loaded', load: 'record.status != "closed"' }, // or 'round_robin'; `load` only with least_loaded
],
});
strategy is for a queue target only; assignTo: { type: 'user', value: '<id>' }
names one owner, who holds the row only while an active member of its organization
(else ownerless). Queues are declared in queues (objectstack-data); an approval
for the same people is a queue approver (Approver Types).
⛔ Never a beforeInsert hook that picks an owner, nor a round-robin counter field.
A packaged rule's queue is its package's own, else the one holder
in its dependencies closure plus sys: acme.helpdesk naming acme.crm's queue
declares dependencies: { 'acme.crm': '^1.0.0' }. Else refused — outside-closure
(an undeclared package's or environment-only queue), ambiguous-in-closure (two
in it) — the row is written ownerless, in no queue, and the server log warns once
(… does not resolve … from the rule's package). An organization's
sys_assignment_rule row and a rule no package ships read environment-wide (two
package holders: ambiguous-in-environment). A name no queues entry declares
reads the organization's sys_queue row.
Triggers — Event-Driven Automation
There is no standalone trigger
object and no top-level trigger / event key.
Prerequisite — declare the capabilities your nodes need
Metadata registers without its defineStack({ requires }) token. Two pairs are
instead refused at os validate / build / dev / serve (422); neither
token implies the other:
requires token | Turns on | Absent ⇒ |
|---|---|---|
automation | the flow engine + node executors | flows never execute |
triggers + automation | record-* / schedule / api start bindings | auto-launched flow refused: STACK_TRIGGER_CAPABILITY_REQUIRED |
job° | cron cadence + the timeRelative sweep | scheduled flows never launch |
queue° | the inbound-webhook consumer | inbound POST answers 503 |
approvals | approval / approval_revise (plugin-approvals) | no executor for the node type |
messaging° | notify delivery to inbox (sys_inbox_message) | silent: success with skipped: true |
webhooks + realtime | defineStack({ webhooks }) outbound dispatch | declared webhook refused: STACK_WEBHOOK_CAPABILITY_REQUIRED |
° Always-on, so list it only under --preset minimal (objectstack-platform § requires:).
Inbound webhook (api) triggers (ADR-0041 Tier 1)
Endpoint: POST /api/v1/automation/hooks/:flowName/:hookId. Configure it on
the start node config:
config key | Purpose |
|---|---|
hookId | URL path token (default 'default'). Rotate it to revoke a leaked endpoint |
secretRef / secret | HMAC-SHA256 secret, one required (else refused at registration and os validate). Ship secretRef: 'NAME': an env var the deployment fills, not OS_*; unfilled ⇒ 503. Never a literal |
- Signature:
x-objectstack-signature: t=<unix seconds>,v1=<hex>— HMAC-SHA256 of<t>.<raw body>;twithin 300 s. Vendor-signed:config.signaturereplaces it (recipe 4). - Idempotency:
x-idempotency-keydedupes retries — author the flow to be idempotent (delivery is at-least-once). - Queue-backed: the endpoint ACKs
202and enqueues; the flow runs on the consumer. - The JSON body surfaces to the flow as the trigger record (
record.*/ bare fields) plusparams. - A flow name two packages hold: the bare hook above answers
401 INVALID_SIGNATUREwhatever the signature (cause: server log only). Each package's flow is reached only atPOST /api/v1/automation/hooks/:namespace/:flowName/:hookId, by itsmanifest.namespace(_envthere: a flow no package ships).
Trigger Types (start-node config.triggerType)
triggerType | ObjectQL hook |
|---|---|
record-before-create (can modify/reject) | beforeInsert |
record-after-create | afterInsert |
record-before-update | beforeUpdate |
record-after-update | afterUpdate |
record-before-delete | beforeDelete |
record-after-delete | afterDelete |
record-before-write / record-after-write — one flow, both events | insert + update hooks |
Trigger Configuration — on the start node
{
id: 'start',
type: 'start',
label: 'On Case Escalated',
config: {
objectName: 'support_case',
triggerType: 'record-after-update',
condition: "previous.status != 'escalated' && record.status == 'escalated'",
},
}
Prefer
record-after-*; guard one that writes its own object, or it re-triggers itself. Arecord-before-*flow that throws silently blocks the write — give it a user-facing message.
→ references/examples-flows.md § Time-relative triggers.
Integrations are declared, not coded
A vendor system reachable over HTTP is a
connectors: entry inside the app — provider: 'openapi' | 'mcp' | 'rest', a
packaged spec, auth.credentialRef (the customer's administrator supplies the
value) — dispatched by connector_action. Never a plugin. Recipes,
credential hand-off, loader limits: references/integration-recipes.md.
Platform code only when one holds — and then it is the platform's, filed as a
card, the app still writing none: the protocol is not HTTP; the work writes
identity objects (users, units, positions); it processes files locally; one fixed
action contract spans several vendors; the callback is signed in no form
config.signature declares. A document the loader cannot take yet (YAML, Swagger 2.0,
$ref) is a gap named against its platform card.
Verify your work
os validate (os build also emits dist/); CEL checks: objectstack-formula
§ Verify your work.
References
See references/_index.md for pointers to the Zod
schemas in node_modules/@objectstack/spec/src/.
How can the creator link this skill?
Add the canonical catalog link to the repository README so users can inspect current installs and available audits. The publishing guide covers the complete discovery path.
<a href="https://skillzs.dev/skills/objectstack-ai/objectstack/objectstack-automation">View objectstack-automation on skillZs</a>