Skip to Content
FeaturesOperations

Operations

An operation is where your own logic lives. You write a function, host it anywhere that serves HTTP, and register the URL — and from then on Foir is the only thing that can call it.

This is the main path for building on Foir, not a side feature. Anything your app needs that isn’t reading and writing records is an operation: sending an email through your provider, syncing a CRM, summarising text with a model, validating something against a system only you can reach. You do not need an API tier in front of Foir to do any of it — see You Don’t Need a Backend for why, and Writing an Operation Endpoint for how.

Overview

You supply the logic. Foir supplies everything around it: the signed dispatch your endpoint verifies, authentication of whoever triggered it, per-key and per-visitor rate limits, the operation’s own quotas and preconditions, retries and dead letters, a log of every run, and the organization each run belongs to. Secrets stay in Foir’s vault and arrive already filled in, so your function holds no credentials at all.

Who may trigger an operation is configuration rather than code you write: a signed-in user whose role grants it, or, for a public “request a quote”, anyone at all, named on your publishable key. A hook or a schedule runs one on its own. See App architecture for how operations fit around your app.

How It Works

Trigger fires → Foir POSTs an OperationPayload to your endpoint → Your endpoint returns the result (sync) or 202 + later callback (async) → Foir records the execution
  1. A trigger fires (user clicks a button, a lifecycle event occurs, a schedule runs, or an API call is made)
  2. Foir signs a short-lived token with the operation’s declared grants and POSTs the OperationPayload to your endpoint with X-Foir-Token and X-Foir-Context headers
  3. Your endpoint verifies the token, processes the request, and either returns a synchronous result or returns 202 Accepted and reports back later via the callback API
  4. Foir records the execution result for audit and tracking

Touch Points

Operations can be triggered from different places in the platform:

Touch PointWhen It FiresWhat It Receives
UIUser clicks a button on a record in the consoleThe full record context
FieldUser triggers it on a specific field in the editorThe field value + full record context
LifecycleAutomatically on create, update, publish, etc.The full record context
ScheduleCron expression matches the current timeA schedule payload (no record context)
APIExternal call via the public APIUser-provided input

Execution Modes

Declaring async makes an operation accept async runs. A call through the API or CLI runs sync unless it passes mode: ASYNC; runs from hooks and schedules use async when the operation declares it.

ModeBehaviourUse For
syncThe caller is waiting, so Foir calls your endpoint directly and returns what it answers, bounded by the operation’s timeoutMs. Nothing calls back: the response body is the result.Short, deterministic work a caller waits on: AI summaries, validation, lookups, checkout steps.
asyncFoir POSTs the dispatch and gets back 202 Accepted. Your endpoint queues the work, then calls back to report progress, complete, fail, or cancelled. The execution tracks state until terminal.Long-running work — large data syncs, AI jobs that exceed the sync wall clock, anything you want progress reporting on.

Async mode uses a callback handshake: every async dispatch carries a scoped callback token your endpoint uses to report back. The platform tracks the execution to a terminal state and dispatches OPERATION_COMPLETED, OPERATION_FAILED, OPERATION_CANCELLED, or OPERATION_TIMED_OUT lifecycle events when it gets there.

The HTTP Contract

Every operation endpoint speaks the same language.

Request headers

HeaderDescription
X-Foir-TokenSigned token scoped to this dispatch — verify it with the SDK’s verifyScopedToken against https://api.foir.dev/.well-known/jwks.json. Carries the declared grants.
X-Foir-ContextSemicolon-separated key=value pairs: project, org_id, app, operation, execution_id, triggered_by (api / ui / lifecycle / schedule / webhook, the same value as the body’s trigger.type) and causation_chain. org_id names the organization the run was started at, and is absent for a run at the project itself, so two organizations of one project, dispatching the same operation to the same endpoint, are told apart here.
Content-Typeapplication/json
User-Agentfoir-operations/1.0

Request body (OperationPayload)

{ "executionId": "exe_456", "operationKey": "ai-summarize", "trigger": { "type": "api" }, "input": { "text": "The full text to summarize...", "maxLength": 200 }, "context": { "projectId": "project_...", "tenantId": "tenant_...", "actorId": "usr_...", "userId": "usr_...", "timestamp": "2026-04-28T10:30:00Z" }, "callback": { "token": "eyJhbGciOiJFZERTQS...", "endpoint": "https://api.foir.dev/v1/steps/exe_456/reply", "expiresAt": "2026-04-29T10:30:00Z", "causationChain": ["ai-summarize"], "signingKey": "..." } }

readDispatch(request) from @foir/sdk/server parses this body into a typed OperationPayload. trigger.type is api, ui, lifecycle (a hook) or schedule. input is always an object. userId is present when the run acts for a user: the person who ran it, or the owner of the record whose event fired the hook. actorId is who started the run, and is empty when nobody did, as for a hook’s run. record, content and triggerContext appear only when the caller that started the run attached them.

The callback field is present only on async dispatches: where your endpoint replies, the bearer token it replies with, and the key it signs each reply with. A blocking (sync) dispatch carries no callback at all, because your response body is the result.

Response — sync mode

Your endpoint returns the result body directly:

Success:

{ "success": true, "result": "A concise summary of the widget...", "metadata": { "model": "gpt-4", "tokens": 85 } }

Error:

{ "success": false, "error": { "code": "UPSTREAM_ERROR", "message": "AI service returned 429: rate limited" } }

Response — async mode

Your endpoint returns 202 Accepted immediately and queues the work. When work finishes, it replies at the run’s own reply route, callback.endpoint, with the token and key from the callback field of the payload.

The Editor SDK ships a typed createCallbackClient helper that handles this for you. Call cb.progress({ pct, message }) while work is running, then cb.complete(result) or cb.fail(code, message) when you’re done. See Server API Reference.

To reply without the SDK, POST a JSON body to callback.endpoint: { "result": ... } when the work is done, { "failure": { "code": "...", "message": "..." } } when it failed, { "progress": { "percent": 40, "message": "..." } } while it runs, or { "cancel": {} } to stop the run. Send Authorization: Bearer and callback.token, and X-Foir-Signature: sha256= and the hex HMAC-SHA256 of the request body under callback.signingKey. The answer says where the run now stands: { "status": "completed", "cancelled": false, "applied": true }.

Response: a run cut into slices

An async run that takes longer than one call can be cut into slices, so no endpoint has to hold work between calls. Each dispatch does a bounded amount of work, then answers one of two ways:

  • 202 Accepted, replying with the outcome as above. The slice that finishes the run answers this way.
  • A continuation: 200 with the content type application/vnd.foir.continuation+json and a body naming where the next slice resumes. Foir queues the next call, hands it the cursor as continuation on the dispatch body, and gives it a fresh callback block.
{ "cursor": "page-7", "delayMs": 30000, "progressPct": 40, "progressMessage": "40 of 100 products" }
FieldMeaning
cursorRequired. Where the next slice resumes, as you write it. At most 16 KiB.
delayMsHow long to wait before the next slice, up to 900000 (15 minutes). Use it to poll a third party that finishes later, such as a bulk export.
progressPct, progressMessageProgress shown on the execution while it runs.

The next slice reads continuation: { "cursor": "page-7", "slice": 1 }. The content type is what marks a continuation, so a result that happens to have a cursor field is still a result. The Editor SDK builds the answer with continueRun.

  • Only an async run continues. A sync call’s caller is waiting, and a query or field operation’s answer is read inline, so either fails with UNEXPECTED_CONTINUATION when its endpoint answers one.
  • A continuation is not a retry. It does not spend the retry budget. A run takes at most 1000 slices. One that asks for more fails with SLICES_EXHAUSTED and is dead-lettered holding its last cursor, and retrying the dead letter resumes the run from there. A dead letter written by any failing slice keeps that slice’s cursor in the same way.
  • Cancelling stops it. A run cancelled while a slice is running takes no next slice.
  • Each slice is its own call, so the queue’s concurrency, the per-host bound and the circuit breaker govern the work itself. The execution shows how many slices the run has taken.
  • Local development works the same way. foir operations dev reports a continuation your local server answers, and the next slice arrives down the same session.

Authentication and Grants

Every dispatch carries a scoped token in X-Foir-Token. Your endpoint verifies it against the platform’s JWKS endpoint at https://api.foir.dev/.well-known/jwks.json — the SDK’s verifyScopedToken handles this for you. The verified claims tell you which tenant, project, and app the dispatch belongs to, and which grants it carries.

The grants are what your endpoint can do when it calls back to the public API. They are written in the permission catalogue’s names, <resource>:<verb>[.<reach>][:<model>], for example records:read:product, records:write:order, records:create:order, appsecrets:read, status:write, files:write. records:read or records:write with no model is refused: operations always declare which specific models they touch. Operation permissions lists every grant an operation may declare.

Each grant stands for itself. records:write:<model> changes a record that is there and records:create:<model> makes one, so an operation that does both declares both.

Only making a record takes no read. An operation that updates, deletes or publishes a record of a model declares records:read:<model> beside records:write:<model>, records:delete:<model> or records:publish:<model>: each finds the record first, and Foir refuses one from an operation that cannot read the model. An operation that declares only the create can make records, is answered with the new record’s _id alone, and must ask for no other field of it. See Changing a record takes reading it.

An operation is written by grants. One that still declares capabilities is refused, and the refusal names Operation permissions, which says what each of those names is written as now.

The token is the credential for those calls. requireScopedToken returns it as dispatch, and a data client built with createFoirClient({ apiUrl, dispatch, generated }) calls Foir as the operation, sending the token and never an api key. generated comes from foir types --operation <key>, which types the surface the operation’s token is served. See Writing an Operation Endpoint.

The legacy HMAC X-Foir-Signature header is no longer used for operation dispatches. The SDK’s verifyOperationSignature / verifyAndParseOperation helpers were removed in @foir/sdk@0.8.0. Use verifyScopedToken.

In the console

Creating an Operation

  1. Go to Automation > Operations
  2. Click New Operation
  3. Configure:
    • Key — unique identifier (e.g., ai-summarize)
    • Name — display name
    • Endpoint URL — where Foir will POST the payload
    • Supports async callback: on for an operation that calls back when the work finishes
    • Description — what this operation does
  4. Save

What the operation may do when its endpoint calls back, its grants, is not set on this form. Declare it in foir.config.ts and push. An operation created here carries none until you do.

Execution Tracking

Every operation execution is recorded with:

  • Status: PENDING, DISPATCHED, RUNNING, COMPLETED, FAILED, CANCELLED, or TIMED_OUT
  • Duration — how long the execution took
  • Result or error — the response from your endpoint (or callback)
  • Trigger context — how and where it was invoked
  • Retry count — how many attempts were made
  • Progress — for async operations that report progress

View execution history in Automation > Operations > Executions.

Dead Letters

Failed executions that have exhausted all retries appear in the dead-letter queue. From there you can inspect the error, retry the execution, or dismiss it.

Via the CLI

# List all operations foir operations list # Get an operation by ID or key foir operations get <idOrKey> # Execute an operation by key (input passed with -d/--data or -f/--file) foir operations execute ai-summarize --data '{ "maxLength": 200 }' # Execute asynchronously foir operations execute long-export --data '{ "since": "2026-01-01" }' --async # List dead-letter operations foir operations dead-letters # Retry a dead letter foir operations retry-dead-letter <id> # Dismiss a dead letter foir operations dismiss-dead-letter <id>

For app-owned operations, use foir apps trigger <appName> <operationKey> instead — see CLI Commands.

Via the API

The public API is per-operation typed. Each operation gets its own execute<OpName> mutation generated from its declared input/output schema; there is no generic executeOperation field. For an operation keyed ai-summarize the generated mutation is executeAiSummarize. Every execute mutation requires the operations:execute scope, or operations:execute:<operation-key> for that one operation: a key, a role and a key’s anonymous list can each grant operations one at a time (per-operation scopes).

Execute an Operation

The mutation returns an Execute<OpName>Payload envelope: execution is always present (so you can read execution.id and execution.status), and result carries the typed output — populated on SYNC completion, null on ASYNC dispatch.

mutation ExecuteSummary { executeAiSummarize( input: { maxLength: 200 tone: "professional" } mode: SYNC # default; pass ASYNC for operations that support async-callback ) { execution { id status } result { summary } } }

The same dispatch through the data client:

const dispatched = (await foir.ns.operations['execute.ai-summarize']({ input: { maxLength: 200, tone: 'professional' }, mode: 'SYNC', })) as { execution: { id: string; status: string }; result: { summary: string } | null };

Note the name. GraphQL addresses the operation by its generated field, executeAiSummarize; the data client addresses it by execute. plus the operation key, execute.ai-summarize. operations is the only namespace where the two differ, and passing the field name to the data client fails — the manifest lists keys under namespaces.operations.execute, and nothing derives a field name from what you send.

The input argument is the only payload — there is no separate content argument. Pass everything your endpoint needs through the typed input object.

Read an Execution

With a publishable or a server key, run reads, history, cancellation and subscriptions require a signed-in user and are limited to that user’s own runs. A visitor through such a key has only what the key gives, so executing an operation with one also needs a signed-in user whose role grants operations:execute (or that operation by name), or what the key gives naming the operation.

For ASYNC dispatches, use the returned execution.id to read terminal state. operationExecution requires the operations:read scope.

query GetExecution($id: String!) { operationExecution(id: $id) { id operationKey status result error startedAt completedAt createdAt } }

The same read through the data client:

const execution = (await foir.ns.operations.operationExecution({ id: executionId })) as { id: string; status: string; result: unknown; error: string | null; };

You can also page execution history with operationExecutions(operationKey:, status:, first:, after:) (Relay connection, operations:read). A refused list is an error, not an empty page.

Execution statuses: PENDING, DISPATCHED, RUNNING, COMPLETED, FAILED, CANCELLED, TIMED_OUT.

Subscribe for Real-Time Updates

Instead of polling, subscribe to the per-operation execution subscription (operation<OpName>Execution) for progress and terminal events over WebSocket — see Real-time and Subscriptions.

Cancel an Execution

cancelOperationExecution returns a Boolean and requires the operations:execute scope.

mutation CancelExecution($id: String!) { cancelOperationExecution(id: $id) }

The same cancel through the data client:

await foir.ns.operations.cancelOperationExecution({ id: executionId });

Config System

Operations can be defined in foir.config.ts using defineOperation. See Operation Configuration for the full reference, including mode, callbackTtlSeconds, callbackTimeoutRetryPolicy, precondition, and quotas.

Quotas meter operations and nothing else — record reads, media and search carry no per-user counter. For charging for content rather than for actions, see What a quota can meter and Charging for content.

Examples

AI Summarization (sync)

Register a sync operation that calls an AI service to summarize content. Attach it as a field-level touch point on content or text fields. Users click “Summarize” in the editor and the result is written back to the field.

Long-Running Export (async)

Register an async operation for jobs that take minutes. Your endpoint returns 202 immediately, queues the work in your own background runner, and replies with progress as it goes. When done, it replies with the final artifact URL as the result. The console shows live progress, and lifecycle hooks fire OPERATION_COMPLETED so downstream automations can chain.

Contact Form Handler (sync, API-triggered)

Expose an API-triggered operation that accepts form submissions and forwards them to your CRM:

mutation SubmitContactForm { executeContactFormHandler( input: { name: "Jane Doe" email: "jane@example.com" message: "Question about your enterprise plan..." } ) { execution { id status } } }

The same dispatch through the data client:

const submitted = (await foir.ns.operations['execute.contact-form-handler']({ input: { name: 'Jane Doe', email: 'jane@example.com', message: 'Question about your enterprise plan...', }, })) as { execution: { id: string; status: string } };

Note: as above — the key, contact-form-handler, not the field name executeContactFormHandler.

External Data Sync (async, lifecycle-triggered)

Use a lifecycle-triggered operation to push content changes to an external system whenever records are published. Declare async mode so a slow upstream doesn’t block publishing. The hook fires, your endpoint accepts the dispatch with 202, queues the work, and the eventual completion fires an OPERATION_COMPLETED event you can hook in turn.

Best Practices

  • Verify the scoped token — always validate X-Foir-Token against the platform JWKS before processing the request.
  • Pick the right mode — sync for sub-minute deterministic work, async for anything that can run long, anything you want progress on, or anything that depends on a slow upstream.
  • Return quickly in async mode — your endpoint should ack with 202 in milliseconds. Do the actual work in your own background queue and call back when done.
  • Handle retries idempotently — your endpoint may receive the same payload more than once if a network blip caused Foir to retry.
  • Call Foir as the operation instead of holding a long-lived Foir key in your service: build the data client from the dispatch token (createFoirClient({ apiUrl, dispatch, generated }), with dispatch from requireScopedToken) for any reads and writes the operation needs.
  • Monitor dead letters — check the dead-letter queue regularly for failed executions.
  • Use appropriate touch points — only enable the triggers your operation actually needs.
Last updated on