Automations in the SDK
The brainerce SDK methods for automations in admin mode. Read the guide, validate, test on a real record, save drafts, pause and archive, plus what an API key can never do.
The brainerce package wraps the Automations REST API in admin mode (apiKey, server only). Every method takes the storeId first. For the model behind it (events, triggers, steps, runs, plans, safety) read Automations; for complete definitions, see the automation recipes.
import { BrainerceClient } from 'brainerce';
const admin = new BrainerceClient({ apiKey: process.env.BRAINERCE_API_KEY! });The key needs automations:read for the reads and automations:write for everything that drafts, tests, pauses or archives. A test also needs the read scope of what it shows (products:read, orders:read, customers:read). On a plan without automations the methods that create, change, test, activate or retry reject with PLAN_FEATURE_REQUIRED; the reads (list, get, version, runs, run, guide), pauseAutomation, pauseAndCancelAutomation and archiveAutomation keep working, so a store that dropped to a lower plan can still stop its automations and read their history.
The flow
// 1. Get the guide (once). No topic: the index plus the basics.
const index = await admin.getAutomationGuide(storeId);
const triggers = await admin.getAutomationGuide(storeId, 'triggers'); // or 'all'
// 2. Validate. Writes nothing.
const check = await admin.validateAutomationDefinition(storeId, { definition });
if (!check.ok) throw new Error(JSON.stringify(check.errors)); // [{ code, path }]
// 3. Test on a real record. Writes and sends nothing.
const trial = await admin.testAutomation(storeId, {
definition,
entity: { type: 'Order', id: orderId },
});
// 4. Save a DRAFT. Nothing runs.
const draft = await admin.createAutomation(storeId, {
name: 'Hold risky first orders',
definition,
});
// 5. The merchant approves it in the dashboard.Approving is not on this list on purpose. See What a key can never do.
Methods
All return a promise. Types are exported from brainerce.
| Method | Scope | Returns |
|---|---|---|
listAutomations(storeId, params?) | automations:read | PaginatedResponse<AutomationListItem>. params: page, limit (default 20, at most 100), status, search. |
getAutomationGuide(storeId, topic?) | automations:read | AutomationGuide (topic, text, topics). topic is an id from the index, or 'all'. An unknown topic answers with basics. |
getAutomation(storeId, automationId) | automations:read | AutomationDetail: the automation and its versions (newest first, at most 100), without definitions. |
getAutomationVersion(storeId, automationId, versionId) | automations:read | AutomationVersionDetail: the full definition, definitionHash, approval fields, the grant. |
listAutomationRuns(storeId, automationId, params?) | automations:read | PaginatedResponse<AutomationRunListItem>. params: page, limit, status. |
getAutomationRun(storeId, automationId, runId) | automations:read | AutomationRunDetail: the steps with status and error code, and loopChildren for a loop. Codes and counts only. |
validateAutomationDefinition(storeId, { definition }) | automations:write | AutomationValidationResult: ok, errors, definitionHash, referencedDefinitions, grant. |
testAutomation(storeId, input) | automations:write | AutomationTestResult. input is one of three shapes, below. |
createAutomation(storeId, { name, definition }) | automations:write | AutomationDraftResult: automationId, versionId, version, definitionHash. |
createAutomationVersion(storeId, automationId, { definition }) | automations:write | AutomationDraftResult. A new draft version. The trigger type cannot change. |
pauseAutomation(storeId, automationId) | automations:write | AutomationLifecycleResult. Stops new runs; started runs finish. |
pauseAndCancelAutomation(storeId, automationId) | automations:write | AutomationLifecycleResult. Also cancels runs still queued or waiting. |
archiveAutomation(storeId, automationId) | automations:write | AutomationLifecycleResult. Terminal. |
Renaming (renameAutomation), duplicating (duplicateAutomation) and running a failed run again (retryAutomationRun) have SDK methods too: see the SDK README table. Approving, activating and switching a version stay dashboard-only.
testAutomation input
// A product test (product.updated, inventory.stock_changed@1, review.created@1).
await admin.testAutomation(storeId, {
definition,
entity: { type: 'Product', id: productId },
change: { field: 'price', before: 120, after: 90 }, // product.updated only
variantId, // inventory.stock_changed@1: required when the product has variants
});
// An order, customer or cart test, or the clock (the Store; entity.id is the store id).
await admin.testAutomation(storeId, {
definition,
entity: { type: 'Store', id: storeId },
});Send exactly one of productId and entity (TEST_ENTITY_INVALID otherwise). The entity.type for each trigger family:
| Trigger | entity.type |
|---|---|
order.*, return.*, order.refunded@1, order.edited@1, order.field_set@1 | Order |
customer.* | Customer |
checkout.abandoned@1 | Cart |
product.updated@2, inventory.stock_changed@1, review.created@1 | Product |
schedule.fired@1 | Store |
product.created@1 and product.metafield_changed@1 cannot be tested. The result ends with wroteNothing: true. A wait is shown as would_wait, a for_each loop as one would_loop step with counts, and a condition on a current.* value is judged on today's data. Narrow the result with 'entity' in result (an entity test) or 'product' in result (a product test).
Errors
Errors are BrainerceErrors. The stable code is error.code; extra fields are under error.details.details. A rejected definition is 400 DEFINITION_INVALID and the validator findings are an array of { code, path } at error.details.details.errors.
import { BrainerceError } from 'brainerce';
try {
await admin.createAutomation(storeId, { name, definition });
} catch (e) {
if (e instanceof BrainerceError && e.code === 'DEFINITION_INVALID') {
console.error((e.details as any)?.details?.errors); // [{ code: 'ACTION_NEEDS_GUARD', path: 'steps[0].contract' }]
} else if (e instanceof BrainerceError && e.code === 'QUOTA_EXCEEDED') {
// 50 drafts per store per rolling 24 hours from API keys, MCP and the assistant
} else {
throw e;
}
}Codes you will meet: DEFINITION_INVALID, NAME_INVALID, NAME_TOO_LONG, DEFINITION_TOO_LARGE, QUOTA_EXCEEDED, TRIGGER_TYPE_CHANGE, AUTOMATION_ARCHIVED, AUTOMATION_NOT_FOUND, TEST_ENTITY_INVALID, TEST_REQUIRES_ORDER_ACCESS (and the product, customer and cart variants), PLAN_FEATURE_REQUIRED. The full table is on the REST page.
What a key can never do
approveAutomationVersion, activateAutomation and switchAutomationVersion exist in the client so a dashboard session can use the same class, but an API key always gets 403 APPROVAL_REQUIRES_DASHBOARD_USER (approve) or 403 ACTIVATION_REQUIRES_DASHBOARD_USER (activateAutomation, switchAutomationVersion), whatever its scopes. The merchant opens the automation in Settings, then Automations, and uses Review and approve or Approve and turn on. The person who approves becomes the identity the runs act as. HTTP connections for send_http_request@1 are created in the dashboard only, and have no SDK method.
Never tell a merchant a draft is live. Tell them it is saved and waiting for their approval.
App SDK Reference (@brainerce/app-sdk)
Manifest builder, connector / payment / shipping contracts, scopes, events and webhook verification for marketplace apps built on @brainerce/app-sdk.
Storefront Bot (AI chat widget)
Add Brainerce's AI shopping assistant to any storefront with one line of code. The bot answers product questions, shows recommendation cards, handles cart adds, and escalates to the merchant team when needed.