ObjectStackObjectStack

Hook schema — Data Protocol property reference

Hook schemas of the ObjectStack Data Protocol: Hook, HookContext, HookEvent and 2 more — each property with its type, default and a TypeScript example.

Source: packages/spec/src/data/hook.zod.ts

TypeScript Usage

import { HookSchema, HookContextSchema, HookEvent, HookRefusalSchema, HookTextSchema } from '@objectstack/spec/data';
import type { Hook, HookContext, HookRefusal, HookText } from '@objectstack/spec/data';

// Validate data
const result = HookSchema.parse(data);

Hook

Properties

PropertyTypeRequiredDescription
namestring✅Hook unique name (snake_case)
labelstringoptionalDescription of what this hook does
objectstring | string[]✅Target object(s)
eventsEnum<'beforeFind' | 'afterFind' | 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeDelete' | 'afterDelete'>[]✅Lifecycle events
handlerstringoptionalHandler function name (string, post-build) or inline function (pre-build) — DEPRECATED, prefer body
body{ language: 'expression'; source: string } | { language: 'js'; source: string; capabilities?: Enum<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | …>[]; timeoutMs?: integer; … }optionalHook body — expression (L1) or sandboxed JS (L2). A hook body cannot send mail: a js body granted email.send is refused, because a message cannot be taken back if the write that runs the hook rolls back; send mail on a record change from an action, a job or a flow. A hook body may add a timeline entry (activity.append), which commits or rolls back with the write.
prioritynumberoptional (default: 100)Execution priority
asyncbooleanoptional (default: false)Run specifically as fire-and-forget
conditionstring | { dialect: Enum<'cel' | 'cron' | 'template'>; source: string; ast?: any; meta?: object }optionalPredicate (CEL); hook runs only when TRUE. e.g. Precord.status == "closed" && record.amount != null && record.amount > 1000
descriptionstringoptionalHuman-readable description of what this hook does
retryPolicy{ maxRetries?: number; backoffMs?: number }optionalRetry policy for failed hook executions
timeoutMsnumberoptionalMaximum execution time in milliseconds before the hook is aborted
timeoutneveroptional[REMOVED] hook.timeout was removed in @objectstack/spec 17 — its unit (milliseconds) lived only in the description, beside a body-level timeoutMs and a retryPolicy.backoffMs that spell theirs, so the same number read as two conventions on one surface. Rename the key to timeoutMs; the value (milliseconds) is unchanged. Run os migrate meta --from 17 to list the mechanical edits for existing sources; --write applies the ones it can prove, and you apply the rest by hand.
onErrorEnum<'abort' | 'log'>optional (default: "abort")Error handling strategy. abort: refuse the operation; a blocking hook's abort rolls the write back inside a unit of work, which the write door opens for an after* hook on an object on the default datasource whose driver declares transactions (elsewhere the caller is refused and the row stays stored). log: log the error and continue
refusalsRecord<string, { message: string; status?: integer; reasons?: Record<string, object>; params?: string[] }>optionalRefusal catalogue keyed by the SCREAMING_SNAKE code the hook throws: { message, status?, reasons?, params? }. The hook (a js body or a handler) refuses by code only, optionally with a declared reason and params; the runtime answers with the declared message (translated through hooks.<hook>.refusals.<CODE>.message, or ….<CODE>.reasons.<REASON>.message, in the caller's locale, holes filled from params) and status. A code not declared here, or a reason a code with reasons does not declare, is refused loudly — at save when the hook throws it literally, otherwise at run time; under a code with no reasons a thrown reason is not read
textsRecord<string, { message: string; params?: string[] }>optionalTexts the hook writes into records, keyed by the snake_case key its code asks for with ctx.text(KEY, params): { message, params? }. ctx.text answers the sentence in the organization's language (the Localization setting when somebody set it, else the app's i18n.defaultLocale), translated through hooks.<hook>.texts.<key>.message with the declared message as the fallback, its holes filled from params. A key not declared here is refused — at save when the hook asks for it literally, otherwise at run time
runAsEnum<'system' | 'user' | 'inherit'>optional (default: "inherit")Execution identity for the hook's ctx.api data operations: system = elevated (bypasses RLS), user = the triggering user (RLS-respecting), inherit = the context of the write that fired the hook (the pre-runAs behaviour; the default). A hook with no trigger user has no identity to scope to, so under user its ctx.api data operations are REFUSED — declare system to make the elevation explicit. This covers any hook fired by a write that carried no user (an isSystem plugin/service write; a system-elevated flow node). Elevation does not reach identity assignment: a system hook's governed writes (insert, update, delete, transfer, restore, purge) to sys_user_position, sys_user_permission_set, sys_invitation and sys_member are refused with PERMISSION_DENIED, and a system hook whose body names such a write is refused at save; declare user for position holdings and permission-set grants (the ADR-0090 D12 delegated-administration gate then judges the user the hook acts for), and change invitations and memberships through the organization endpoints. Nor does it reach a ledger: a system hook body's update, transfer, delete, purge or restore of an object declared managedBy: 'append-only' is refused with PERMISSION_DENIED; an insert is not judged by this rule. Nor does it lift the organization wall: a system hook has its reads and writes judged by the organization wall of the user whose write fired it. A write whose own data names an organization outside it, or empties a record's organization, is refused with PERMISSION_DENIED. Where the wall denies the user (no active organization under isolated, no membership under group), its reads of an organization's records return none, its deletes remove none, and its other writes are refused with PERMISSION_DENIED. A hook under a write of a flow run that began for no caller is not judged by it. Scope: ctx.api only — condition evaluation, the readonly strip on ctx.input, ctx.session and async are unchanged.
_lockEnum<'none' | 'no-overlay' | 'no-delete' | 'full'>optionalItem-level lock — controls overlay & delete (ADR-0010).
_lockReasonstringoptionalHuman-readable reason shown when a write is refused by _lock.
_lockSourceEnum<'artifact' | 'package' | 'env-forced'>optionalLayer that set _lock (artifact | package | env-forced).
_provenanceEnum<'package' | 'org' | 'env-forced' | 'platform'>optionalOrigin of the item (package | org | env-forced | platform).
_packageIdstringoptionalOwning package machine id.
_packageVersionstringoptionalOwning package version.
_lockDocsUrlstringoptionalOptional documentation link surfaced next to _lockReason.

Nested Shape: Hook.body[language='expression']

L1 expression body — pure formula, no IO

PropertyTypeRequiredDescription
language'expression'✅
sourcestring✅Formula expression source

Nested Shape: Hook.body[language='js']

L2 sandboxed JS body — runs inside an isolated VM with declared capabilities

PropertyTypeRequiredDescription
language'js'✅
sourcestring✅Function body source
capabilitiesEnum<'api.read' | 'api.write' | 'api.transaction' | 'crypto.uuid' | 'log' | …>[]optional (default: [])Granted capability tokens
timeoutMsintegeroptionalPer-invocation timeout (ms)
memoryMbintegeroptionalPer-invocation memory cap (MB)

Nested Shape: Hook.retryPolicy

PropertyTypeRequiredDescription
maxRetriesnumberoptional (default: 3)Maximum retry attempts on failure
backoffMsnumberoptional (default: 1000)Backoff delay between retries in milliseconds

Nested Shape: Hook.refusals[string]

PropertyTypeRequiredDescription
messagestring✅The sentence the user reads when the hook throws this code — in the source locale, translated whole through hooks.<hook>.refusals.<CODE>.message in the caller's locale. With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter, and a hole over another name, a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused
statusintegeroptionalHTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the body itself sets on the throw is not read — the catalogue decides
reasonsRecord<string, { message: string }>optionalFurther sentences under this same code, keyed by the snake_case reason the hook throws beside the code ({ code, reason }): { message }. The wire code and status stay this entry's. A reason not declared here is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read
paramsstring[]optionalThe names this entry's sentences may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook throws in params ({ code, params: { NAME: value } }). A hole over any other name, logic, an unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences are plain text and a {{ }} hole is refused

Nested Shape: Hook.texts[string]

PropertyTypeRequiredDescription
messagestring✅The sentence the hook writes into a record — in the source locale, translated whole through hooks.<hook>.texts.<key>.message in the organization's language when the hook asks for it (ctx.text). With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter
paramsstring[]optionalThe names this text may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook passes in ctx.text(KEY, { NAME: value }). A hole over any other name is refused at parse; a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is refused

HookContext

Properties

PropertyTypeRequiredDescription
idstringoptionalUnique execution ID for tracing
objectstring✅
eventEnum<'beforeFind' | 'afterFind' | 'beforeInsert' | 'afterInsert' | 'beforeUpdate' | 'afterUpdate' | 'beforeDelete' | 'afterDelete'>✅
inputRecord<string, any>✅Mutable input parameters
resultanyoptionalOperation result (After hooks only)
previousRecord<string, any>optionalRecord state before operation
submittedRecord<string, any>optionalWhat the caller submitted, as sent (update only) — diagnostics only, never the persist image
dispatch{ mode: Enum<'record' | 'per-row'>; index: integer; scope: Record<string, any> }optionalHow this hook call relates to the caller's write (engine-produced)
session{ userId?: string; actor?: string; organizationId?: string; accessToken?: string; … }optionalCurrent session context
provenance{ flowRunId?: string; attributedUserId?: string; performedByClientId?: string; performedByAgentId?: string; … }optionalServer-stamped write provenance (never client-supplied, never an authorization input)
referentialFieldClearbooleanoptionalEngine-produced marker: true exactly when this write is the engine's own referential cleanup (the set_null cascade UPDATE clearing — or, for multiple: true, removing the deleted member from — a lookup, tree or user field that references a record being deleted, where a user field takes part only when it declares its deleteBehavior). Absent on every other write, including a user hand-clearing the same field; read as ctx.referentialFieldClear === true. The declared projection of the operation-private __referentialFieldClear, carried across the sandbox boundary by contract; server-derived and never client-supplied.
referentialCascadeDeletebooleanoptionalEngine-produced marker: true exactly when this delete is one the engine's cascade issued (the child delete removing a row that references a record being deleted through a relation whose deleteBehavior resolves to cascade, at any depth), in both phases of that delete. Absent on every other delete, including a user hand-deleting the same child and a delete a hook issues through ctx.api; read as ctx.referentialCascadeDelete === true. The delete twin of referentialFieldClear, carried across the sandbox boundary by contract; server-derived, never client-supplied, and with no operation-private spelling to read instead.
transactionanyoptionalDatabase transaction handle
qlany✅ObjectQL Engine Reference
apianyoptionalCross-object data access (IScopedContext — object(name) + transaction(cb))
noticeanyoptionalTell the person who made THIS insert/update what the save set in motion: ctx.notice(message) hands one non-empty string to the write's own onNotice listener, answered as the create/update notice. Bound by the engine on every insert/update dispatch (a no-op when nothing listens); absent on find/delete
textanyoptionalAnswer one of the hook's declared texts: await ctx.text(KEY, params?) returns the sentence in the organization's language (translated through hooks.<hook>.texts.<key>.message, the declared message as the fallback, holes filled from params). Bound by the runtime on every path a hook runs on; a key the hook does not declare rejects the call
user{ id?: string; name?: string; email?: string; organizationId?: string }optionalCurrent user info shortcut

Nested Shape: HookContext.dispatch

PropertyTypeRequiredDescription
modeEnum<'record' | 'per-row'>✅'record' = this call is the caller's whole write; 'per-row' = one of N dispatches for one write
indexinteger✅0-based position in the per-row fan-out; always 0 when mode is "record"
scopeRecord<string, any>✅Scratch shared by every dispatch of one caller write, across both phases (same object identity)

Nested Shape: HookContext.session

PropertyTypeRequiredDescription
userIdstringoptional
actorstringoptionalService-principal label for audit attribution when the caller is not a real user (e.g. svc:flow:<flowName>)
organizationIdstringoptionalActive organization ID (blessed developer-facing name)
accessTokenstringoptional
isSystembooleanoptionalTrue when the call was made with an elevated system context (engine self-writes)
skipTriggersbooleanoptionalTrue when record-change automation (flow triggers) must be suppressed for this write — e.g. package seed replay. Lifecycle hooks still run.
skipAutomationsbooleanoptionalTrue when metadata-bound automation hooks must be suppressed for this write — e.g. a data import the system principal runs with "run automations" unchecked, or the system principal's import undo. Implies skipTriggers; code-registered system hooks (audit, security) still run. Only the system principal may take an app's declared controls off a write, and the import undo door is not an exception: an undo by any other caller runs under the object's hooks, record-change triggers and state machine.
positionsstring[]optionalPosition names held by the caller (ADR-0090 D3; formerly roles), copied from ExecutionContext.positions. For hook READS only — e.g. tailoring a message, or branching a business rule the hook runs through its own ctx.api channel. Authorization is decided by the security service on the ExecutionContext (permissions / positions / derived posture); this is NOT an authorization input and a hook must not gate a write by testing it. A hook context carries no services key, so the sharing service cannot be called from one either — the sharing gates already ran inside the engine before the hook chain.
preserveAuditbooleanoptionalTrue when this write is a historical import that must KEEP its caller-supplied updated_at/updated_by (and the readonly audit family) instead of being stamped with the import instant. Server-set, opt-in, absent on normal writes; read by the built-in audit hook. A stamping policy, not an authorization input.
localestringoptionalThe caller's locale (BCP-47), copied from ExecutionContext.locale: the request's Accept-Language, else the localization setting; absent on a write no person asked for. The body runner answers a declared refusal (HookSchema.refusals) in it. Descriptive only — not an authorization input.
principalKindEnum<'human' | 'agent' | 'service' | 'guest' | 'system'>optionalWhat kind of principal is calling (ADR-0090 D10, ADR-0151 D5), copied verbatim from ExecutionContext.principalKind. A person reads human through every door; an agent reads agent — an OAuth client acting for the person in userId (with provenance.performedByClientId set) and an AI service account acting as itself (userId is the account, no performedByClientId) alike. Absent when the envelope carries no kind, which the envelope reads as human. Descriptive only — not an authorization input.
rolesneveroptional[REMOVED] HookContext.session.roles was removed in @objectstack/spec 17.0.0 (ADR-0049 D2) — it was declared, read by two dead exemption branches, and never produced: ObjectQL's buildSession() builds the session field by field and has never written roles, so every read resolved undefined and a guard keyed on it was dead code that merely LOOKED like an authorization decision. Delete the key. To gate a hook on the caller, read ctx.session.userId / ctx.session.isSystem; to judge PRIVILEGE, ask the security service, which evaluates the ADR-0095 vocabulary on the execution context — capability grants (permissions), placements (positions) and the derived posture — never a role-name string comparison (ADR-0090 D3 bans the role spelling outright). Nothing to migrate: a HookContext is built per operation by the engine and never stored, so no metadata source carries this key. NOTE an ACTION body's ctx.session is a different object and still carries its own roles array today; that surface is tracked separately and is not what this key was.

Nested Shape: HookContext.provenance

PropertyTypeRequiredDescription
flowRunIdstringoptionalId of the automation flow run performing this write, when it originates from a flow data node. Lets a hook recognize the run that OWNS state that run itself opened — the approvals record lock exempts the run holding the pending request.
attributedUserIdstringoptionalThe real human credited for a write whose authorization subject was the SYSTEM — e.g. the admin whose better-auth update-member-role call the identity adapter executes as isSystem. ATTRIBUTION ONLY: the audit writer records it as sys_audit_log.user_id; no security middleware reads it, and it never becomes the subject the write is authorized as.
performedByClientIdstringoptional[ADR-0090 D10 rule 4] The AGENT that performed this write — the OAuth client (azp, the client_id of a registered sys_oauth_application) the access token was issued to, when an AI client acted on behalf of the human in session.userId. Copied from ExecutionContext.performedBy.clientId, which only the /mcp OAuth door sets. ATTRIBUTION ONLY, exactly like attributedUserId: the audit writer records it in sys_audit_log.metadata as performed_by beside on_behalf_of; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every non-delegated write, so a hook tells the two apart by the key being there rather than by guesswork.
performedByAgentIdstringoptionalThe in-product AI agent that performed this write for the signed-in person in session.userId, whose write it runs as: the agent the chat runs as. Copied from ExecutionContext.performedBy.agentId, which only the server-constructed in-product AI path sets, after resolving it as the agent it actually ran. ATTRIBUTION ONLY, exactly like performedByClientId: the record-write audit writer records it in sys_audit_log.metadata as performed_by beside on_behalf_of, the key an OAuth client id is also recorded in (when performedByClientId is also present the row records the client instead). A value matching the client_id of an existing sys_oauth_application row is an OAuth client, and a row carrying conversation_id or confirmation_id names an in-product agent; a row meeting neither may name an agent or the client of a since-deleted application, which the row alone cannot tell apart, and the contract does not keep an agent name and a client_id from being the same string (where both tells apply the mark decides, and a matching value with no mark is the client unless an agent shares that string); no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the person made themselves.
performedByConversationIdstringoptionalThe AI conversation an in-product AI write was performed in. Copied from ExecutionContext.performedBy.conversationId, set beside performedByAgentId. ATTRIBUTION ONLY: the record-write audit writer records it as sys_audit_log.metadata.conversation_id, only when performed_by names the in-product agent; no security middleware reads it.
performedByConfirmationIdstringoptionalThe confirmation the person gave before an AI-performed write ran: the id of the pending item their approval decided. Copied from ExecutionContext.performedBy.confirmationId; absent when the write needed no confirmation. ATTRIBUTION ONLY: the record-write audit writer records it as sys_audit_log.metadata.confirmation_id, only when performed_by names the in-product agent; no security middleware reads it, and it is never the authorization for the write, which runs as the person with every gate re-checked.
impersonatedBystringoptionalThe ADMINISTRATOR (a sys_user id) who made this write from an impersonation session, while session.userId is the impersonated user the write is authorized as. Copied from ExecutionContext.impersonatedBy, which the shared request-identity resolution sets from the session read. ATTRIBUTION ONLY, exactly like performedByClientId: the audit writer records it as sys_audit_log.metadata.impersonated_by and on the sys_activity row; no security middleware reads it and it never becomes the subject the write is authorized as. Absent on every write the user made themselves.

Nested Shape: HookContext.user

PropertyTypeRequiredDescription
idstringoptional
namestringoptional
emailstringoptional
organizationIdstringoptionalActive organization ID of the acting user (equals session.organizationId)

HookEvent

Allowed Values

  • beforeFind
  • afterFind
  • beforeInsert
  • afterInsert
  • beforeUpdate
  • afterUpdate
  • beforeDelete
  • afterDelete

HookRefusal

Properties

PropertyTypeRequiredDescription
messagestring✅The sentence the user reads when the hook throws this code — in the source locale, translated whole through hooks.<hook>.refusals.<CODE>.message in the caller's locale. With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter, and a hole over another name, a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused
statusintegeroptionalHTTP status the refusal is answered with (4xx; a refusal is never a fault). Absent: 400. A status the body itself sets on the throw is not read — the catalogue decides
reasonsRecord<string, { message: string }>optionalFurther sentences under this same code, keyed by the snake_case reason the hook throws beside the code ({ code, reason }): { message }. The wire code and status stay this entry's. A reason not declared here is refused loudly. Absent: the code has the one sentence, and a thrown reason is not read
paramsstring[]optionalThe names this entry's sentences may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook throws in params ({ code, params: { NAME: value } }). A hole over any other name, logic, an unknown formatter, an empty hole and a currency formatter with no code are refused. Absent: the sentences are plain text and a {{ }} hole is refused

Nested Shape: HookRefusal.reasons[string]

PropertyTypeRequiredDescription
messagestring✅The sentence the user reads when the hook throws this reason under its code — in the source locale, translated through hooks.<hook>.refusals.<CODE>.reasons.<REASON>.message in the caller's locale; its {{ }} holes follow the entry's message rule

HookText

Properties

PropertyTypeRequiredDescription
messagestring✅The sentence the hook writes into a record — in the source locale, translated whole through hooks.<hook>.texts.<key>.message in the organization's language when the hook asks for it (ctx.text). With no params every {{ }} hole is refused; with params a hole is a path over one of them with an optional known formatter
paramsstring[]optionalThe names this text may fill: a {{ NAME }} or {{ NAME | formatter }} hole renders the value the hook passes in ctx.text(KEY, { NAME: value }). A hole over any other name is refused at parse; a hole holding logic, an unknown formatter, an empty hole and a currency formatter with no code are refused where the text is compiled (os validate, compile, the publish gate). Absent: the sentence is plain text and a {{ }} hole is refused

On this page