@offsida/sdk
Authoring helpers for Offsida integration packages and typed workflows: definePackage, defineAction, defineConnection, defineTrigger (Zod-inferring) and, from @offsida/sdk/workflow, defineWorkflow with its step and trigger builders. The contract types are re-exported from @offsida/types, so one import covers an action.
When an action fails: retries and PermanentError
An action that throws fails its attempt. The platform retries a failed attempt: by default 2 more times, the first 5 seconds later and the second 10 seconds after that (3 attempts and about 15 seconds of waiting in all). That is right for a failure that may pass, such as a 429, a 5xx or a network error. The run page shows the step's progress while it retries ("attempt 2 of 3") and the last attempt's error. Your action can read the same count as ctx.attempt: { number, of } (below).
Each attempt also lists the outbound calls it made that failed: an HTTP status of 400 or above, or a network error (fetch and ctx.connections[name].fetch alike, and a call your code caught too). The run page shows each one as method, host and path with its status, for example GET api.example.com/jobs/109776/ → 404. Repeats of one call are grouped with a count, at most 10 entries are kept per attempt (then "and N more"), and the retry line names the last failed call. The query string, headers and bodies are never recorded. A fetch your module captured at load (const f = fetch at the top level) is not seen.
Fail at once: PermanentError
When a retry cannot help (rejected credentials, a record that does not exist, a 4xx the remote will repeat), throw PermanentError. The step fails on its first attempt with your message, and the run fails with it:
import { defineAction, PermanentError } from '@offsida/sdk';
export const jobSummary = defineAction({
// …
async run({ jobId }, ctx) {
const res = await ctx.connections.simpro.fetch(`/jobs/${jobId}`);
if (res.status === 404) throw new PermanentError(`simPRO job ${jobId} not found`, { code: 'job_not_found' });
if (!res.ok) throw new Error(`simPRO answered ${res.status}`); // retried
return res.json();
},
});
code is yours, not a platform error code: a short identifier (a letter or digit, then letters, digits, _ . : -, up to 64 characters). The run records it as the step's error.code, and the step's error is marked permanent. A code that is not such an identifier is dropped; the failure is still permanent.
cause (optional) is kept on the error, as on any Error.
- The platform recognises a
PermanentError by a brand it carries, not by its class or name, so an action bundled with two copies of the SDK works, and an error from another library that happens to be named PermanentError is still retried. isPermanentError(e) tests for the brand.
- A permanent failure counts like any other failed step for metering.
offsida run runs an action once, with no retries; a PermanentError there fails the step the same way, with its code.
Retry later: RetryableError
When the failure will pass and you know roughly when (a record another process holds locked, a 429 or 503 that says Retry-After), throw RetryableError with afterMs. The step is run again after that long, through a durable wait: nothing runs while it waits, the wait survives a deploy, and it holds no isolate and no step timeout.
import { defineAction, RetryableError } from '@offsida/sdk';
export const updateJob = defineAction({
// …
async run({ jobId }, ctx) {
const res = await ctx.connections.simpro.fetch(`/jobs/${jobId}`, { method: 'PATCH' /* … */ });
if (res.status === 423) throw new RetryableError(`simPRO job ${jobId} is being edited`, { afterMs: 10 * 60_000, code: 'job_locked' });
if (!res.ok) throw new Error(`simPRO answered ${res.status}`); // retried on the step's policy
return res.json();
},
});
- The message is shown on the run page to everyone in the org who can see the run, as "Retrying at 14:32 (deferral 3 of 10): simPRO job 109776 is being edited". Don't put secrets or payload data in it. (Secret values the step resolved are redacted, as in any step error.)
- A step may defer at most 10 times, and wait at most 24 hours in all.
afterMs is clamped to at least 1 second and at most what is left of the 24 hours; a missing or non-numeric afterMs is 1 second. The 11th deferral, or one with less than a second of the 24 hours left, fails the step for good with code retry_budget_exhausted and your message.
- A deferral does not use up the step's
retries: the attempt after it gets the step's whole retry policy again. ctx.attempt.number keeps counting across deferrals.
code is as PermanentError's: it is recorded on the deferred attempt's error. isRetryableError(e) tests for the brand.
- It takes effect for an artifact pushed after the platform added it; an artifact pushed before treats it as a plain error (retried on the step's policy) until it is pushed again.
custom.code.inline steps get it at once. offsida run runs an action once, so a RetryableError there fails the step with its message.
Tune the retries: retries
A custom.code step (browser steps included) may set its own retry policy. In a typed workflow, pass retries to step.action():
step.action('login', bsafeLogin, {
input: { username: 'dispatch' },
browser: { domains: ['portal.bsafe.example'] },
retries: { limit: 0 }, // never retry a login against a real account
});
In a JSON definition it is "retries": { "limit": 0 } in the step's params.
| Field |
Meaning |
Allowed |
Default |
limit |
How many times a failed attempt is retried (0: never). |
integer 0–10 |
required |
delayMs |
The wait before the first retry, in milliseconds. |
integer 1 000–600 000 |
10 000 |
backoff |
How the wait grows from one retry to the next. |
'constant', 'linear' or 'exponential' |
exponential |
A value out of range is refused when the workflow is saved. A step without retries gets the default policy: 2 retries, 5 s then 10 s apart, so a failure that never clears fails the step after 3 attempts and about 15 seconds. A PermanentError is never retried, whatever the step's retries says. Built-in steps (http.request and the rest) get the same default policy and do not take retries yet.
Which attempt is this: ctx.attempt
ctx.attempt says which attempt of the step is running: { number, of }, where number counts from 1 and of is how many attempts the step's retry policy allows (the run page's "attempt N of M"). Under the default policy a failure that never clears runs attempts 1, 2 and 3 of 3. Use it to say why a step is still waiting, or to do something different on the last try:
import { defineAction } from '@offsida/sdk';
export const updateJob = defineAction({
// …
async run({ jobId, note }, ctx) {
const res = await ctx.connections.simpro.fetch(`/jobs/${jobId}`, { method: 'PATCH', body: JSON.stringify({ note }) });
if (res.status === 423) {
console.log(`job ${jobId} is locked in simPRO (attempt ${ctx.attempt.number} of ${ctx.attempt.of})`);
if (ctx.attempt.number === ctx.attempt.of) await alertOffice(jobId); // the last try: no retry follows
throw new Error('waiting on simPRO lock'); // retried
}
return res.json();
},
});
- A
PermanentError ends the step on the attempt that throws it, whatever of says.
- Each attempt's
ctx.attempt is fresh: nothing an earlier attempt did is carried in it.
offsida run and local workflow runs never retry, so a step there is always attempt 1 (of is still the policy's).
- A
sandbox.run or container.run step gets the same numbers as the environment variables OFFSIDA_ATTEMPT and OFFSIDA_ATTEMPTS.
- An action revision pushed before the platform added
ctx.attempt does not have it: push the action again.
Which run: ctx.run
An action can tell which run it is in (offsida.web#582), to put a reference to it in a note or message it writes somewhere else:
export const addJobNote = defineAction({
// …
async run({ jobId, text }, ctx) {
const ref = ctx.run ? ` (ref ${ctx.run.id})` : '';
await ctx.connections.simpro.fetch(`/jobs/${jobId}/notes`, {
method: 'POST',
body: JSON.stringify({ note: `[Offsida] ${text}${ref}` }),
});
},
});
ctx.run.id is the run's id, ctx.run.workflowId its workflow's, and ctx.run.url its run page in Offsida (opening it needs a sign-in to the org). They are identifiers, never the run's data.
ctx.run is the same for every step and attempt of one run.
offsida run and local workflow runs give a placeholder id starting local_ and no url. So does localCtx, unless you pass run.
- A
sandbox.run or container.run step gets the same as the environment variables OFFSIDA_RUN_ID and OFFSIDA_RUN_URL.
ctx.run may be absent: an action revision pushed before the platform added it does not have it. Push the action again.
- A workflow definition can't reference the run (there is no
run root for $ref); only action code sees it.
Step settings: switches an environment can flip
An action can declare settings apart from its input: switches such as a test mode, a rate, or a short list of ids, each with a default (offsida.web#555). The action reads them as ctx.settings, typed from the schema:
export default defineAction({
inputSchema: z.object({ jobId: z.number() }),
settings: z.object({
testMode: z.boolean().default(true).meta({ title: 'Test mode', confirm: true }),
scheduleRate: z.enum(['Callout', 'Standard']).default('Callout'),
}),
run: async (input, ctx) => (ctx.settings.testMode ? dryRun(input) : apply(input)),
});
A workflow file sets a step's baseline, which lives in git:
step.action('apply', jobAttachmentChanges, { input: { jobId }, settings: { testMode: false } });
- A setting is a boolean, a number, a string enum, or a string with a
.max() of at most 256, and needs a .default(). At most 32 per action. Settings are never secret: a secret goes in the vault (secrets) or the package's config.
- An owner or builder can override a step's setting for one environment in Offsida (the editor, or
PUT /v1/workflows/{id}/settings). A push leaves the overrides alone, and drops only those whose step or setting the push removed.
ctx.settings holds every setting: the environment's override, else the workflow file's value, else the default. An override goes live at the next publish.
- If an action changes so that an override no longer fits (a narrower range, a removed enum value), publish is refused naming the step and setting, and
offsida push --publish exits 3 until an admin fixes it.
.meta({ confirm: true }) marks a setting whose change must be confirmed at publish, as new access is: offsida push --publish then exits 2 (needs confirming in Offsida).
- A pulled action's settings are typed the same way:
offsida types pull writes each action's declared settings (another repo's package, or a marketplace subscription's), so a name it doesn't declare or a value of the wrong type fails the push type-check. A file pulled before CLI support for this leaves them untyped: re-pull.
- A composite action can't declare settings.
- An action revision pushed before the platform added settings has none: push the action again.
Dynamic options: pick values from the connected account
A field can offer a dropdown filled from the user's own account, through the connection bound to the step, instead of
asking them to paste an id. The package lists options providers; a field names one with withOptions:
import { defineAction, defineOptionsProvider, definePackage, withOptions } from '@offsida/sdk';
import { z } from 'zod';
const listTeams = defineOptionsProvider({
requires: ['microsoft-365'],
async run(ctx) {
const res = await ctx.connections['microsoft-365'].fetch('https://graph.microsoft.com/v1.0/me/joinedTeams');
const body = (await res.json()) as { value: Array<{ id: string; displayName: string }> };
return { items: body.value.map((t) => ({ value: t.id, label: t.displayName })) };
},
});
const listChannels = defineOptionsProvider({
requires: ['microsoft-365'],
async run(ctx, { values }) {
const res = await ctx.connections['microsoft-365'].fetch(`https://graph.microsoft.com/v1.0/teams/${values.teamId}/channels`);
const body = (await res.json()) as { value: Array<{ id: string; displayName: string; description?: string }> };
return { items: body.value.map((c) => ({ value: c.id, label: c.displayName, description: c.description ?? undefined })) };
},
});
const sendTeamsMessage = defineAction({
requires: ['microsoft-365'],
inputSchema: z.object({
teamId: withOptions(z.string(), 'listTeams'),
channelId: withOptions(z.string(), 'listChannels', { dependsOn: ['teamId'] }),
text: z.string(),
}),
run: async (input, ctx) => {
/* … */
},
});
export default definePackage({
connections,
actions: { 'send-teams-message': sendTeamsMessage },
optionsProviders: { listTeams, listChannels },
});
dependsOn names sibling fields. The provider gets exactly their values (values.teamId), never the rest of the
input. The editor clears the channel when the team changes, and lists nothing while the team is empty or a reference.
- A provider answers
{ items: [{ value, label, description? }], nextCursor? }: at most 100 items a page, label up to
200 characters. Return nextCursor and the editor offers "Load more", calling again with cursor. An answer outside
the limits is refused, not trimmed.
requires names exactly one connection, one the action requires too. A provider's ctx holds only that connection,
and it can reach only that connection's declared origins: it can't send what it reads anywhere else.
- A provider must only read. The platform calls it whenever the editor asks, outside any run. It has 5 seconds; a
thrown error's message is shown under the field (with credentials removed).
- The list only helps the user pick. A typed or pasted id and a
$ref still work, and nothing checks a value against
the list at publish or run time.
withOptions(schema, provider, { search: true }) marks a type-ahead field (people, repositories): the provider gets the
user's text as query.
Step titles: tell repeated steps apart
A step shows under its id unless you give it a title. withTitle takes plain text or a template over the trigger and the steps before it:
const update = step
.action('update', updateJob, { input: { jobId: trigger.jobId } })
.withTitle(template`Update simPRO job ${trigger.jobId}`);
- The title renders when the step starts. The run page shows it, and the editor shows it with a placeholder for each value (
Update simPRO job ‹jobId›).
- A value the run doesn't have renders as a placeholder, and the step still runs.
- The rendered title is one line, cut to 300 characters with
…. The full values stay in the step's input and output.
- A title can't reference a secret: push refuses one that reads a credential header such as
trigger.headers.authorization.
An action can carry a title template of its own, from its input and output, so every step that runs it is named well — in your workflows, a marketplace subscriber's, or inside a composite:
export default defineAction({
title: 'Update a simPRO job',
inputSchema: z.object({ jobId: z.number() }),
outputSchema: z.object({ status: z.string() }),
titleTemplate: ({ input, output }) => template`Update simPRO job ${input.jobId} → ${output.status}`,
run: async (input, ctx) => { … },
});