Before you start
Workflow
- 1Choose an existing published action you may invoke. Set PERMUTE_ACTION_ID and JSON input that matches its published contract.
- 2Create and retain a valid PERMUTE_REQUEST_ID for one user operation before sending. The example reads that saved ID; reruns for the same operation must use identical input.
- 3Inspect the receipt or failure. Resolve an uncertain result before creating a replacement request. The browser recovery example defines a function that accepts your retained original request.
Example
import { PermuteClient } from '@permute/sdk';
function required(name: string): string {
const value = process.env[name]?.trim();
if (!value) throw new Error('Set ' + name);
return value;
}
const client = new PermuteClient({
apiKey: required('PERMUTE_API_KEY'),
}).withWorkspace(required('PERMUTE_WORKSPACE_ID'));
const actionId = required('PERMUTE_ACTION_ID');
// Persist this ID and input before the original send; keep them identical on retry.
const request = {
requestId: required('PERMUTE_REQUEST_ID'),
input: JSON.parse(required('PERMUTE_ACTION_INPUT')),
};
const receipt = await client.actions.invoke(actionId, request);
console.log(receipt.revisionId, receipt.output);Reject a business operation
Handlers receive reject(code, message, details?). Use it for expected business failures: validation_failed (400), record_conflict or invalid_transition (409), permission_denied (403), or not_found (404). Any other code, including execution_failed, ends the invocation as the generic execution_failed (500). Rejection stops the handler and discards staged database writes; connector or SDK effects already sent cannot be undone.
Messages and details are returned to the caller, so keep diagnostics and secrets out. Messages permit 1–1,000 characters. Optional details accepts up to 20 string fields, with keys of 1–100 characters and values up to 500. Invalid rejections and unexpected exceptions return execution_failed (500), with private exception text in server logs.
Both the API-key and browser SDKs expose PermuteApiError.code, status, and details. Recover using codes rather than matching messages. Reload a stale record on record_conflict; correct input on validation_failed. For request_in_progress (409), wait and retry the same request. request_conflict (409) means the ID was already used for different input or a different action revision than the app’s pin. outcome_unknown (409) requires retaining the original request and checking external state before another write. Transport and authentication failures can still use general API error codes.
// Handler source, published with its input and output contracts.
exports.handler = ({ input, db, reject }) => {
if (!input.name.trim()) reject('validation_failed', 'Enter a name.', { field: 'name' });
db.insert('customers', input);
return input;
};Writes, retries, and limits
Handlers run sandboxed JavaScript. db.insert, db.update, and db.delete stage local writes until the handler completes and its output validates. An action can write to one managed database, with up to 100 mutations; the mutations and receipt commit atomically. Reads are outside that write transaction.
Each invocation is limited to 15 seconds, 100 reads, 100 KB of input, and 1 MB of result data. The 100-mutation limit applies to managed database changes. To record application-specific audit history atomically with those changes, stage an audit-table insert in the same database and include that table in the declared write capability. The invocation receipt is not a complete application change log or an audit-retention commitment.
A new user operation needs a new requestId. Reuse both requestId and input when retrying an uncertain response (changing the payload is not a retry). Do not generate a new ID merely because a network request failed.
Optional connectors maps names to connector IDs. Handlers call connectors.<name>.request with provider-relative HTTP paths, query for supported SQL providers, or putObject for S3. Each external call needs a stable stepId; credentials remain on the server, and the connected account’s grants apply.
External effects happen when awaited and cannot be rolled back with local database writes. Successful steps replay their saved responses; uncertain outcomes block automatic resend and require checking provider state. There is no reconciliation API or long-running workflow runner. Changing a published database write target requires a new action.
Set llm: true in the definition to allow llm() calls; without it, calls fail. Anyone who can save and publish the action can set it; no separate grant exists. An action which only calls the AI model can declare sources: []. llm() returns a promise of a string, or of the parsed JSON value which matches outputSchema; outputSchema accepts type, properties, required, additionalProperties, items, enum, const, oneOf, numeric, length and item-count bounds, plus title, description, default and examples; patterns, formats and $ref are rejected. Calls use Claude Haiku 4.5; when the organization’s AI credits run out, calls fail with "AI usage limit reached for this billing period." Each action also has an AI credit limit of 2,000 credits per UTC month. Anyone who can view the action and holds the Change AI limits permission on its workspace (part of admin access, or granted on its own) can set it up to 5,000 credits on the action’s page or with client.aiCredits.setLimit(actionId, { monthlyCredits }); only organization admins can set more, in the web app; past it, calls fail with "This Business Action reached its monthly limit of N AI credits." (N is the current limit). No rejection code is specific to AI call failures: reject with validation_failed when the input caused the failure, for example a request over 200 KB, and otherwise let the error end the invocation as execution_failed. Each invocation can make at most 10 llm() calls; each request is limited to 200 KB and each answer to 2,000 output tokens. AI calls use the workspace organization’s AI credits. AI calls count toward the invocation’s 15 seconds; the first call after a quiet period can take about 10 seconds, so keep answers short, make few sequential calls, and start independent calls together with Promise.all. An uncaught llm() error ends the invocation as execution_failed without its message; catch it and reject with a fitting code when callers need the reason. AI calls are not steps: a completed request returns its saved receipt without calling the model, but a retry of an unfinished request calls the model again, even with the same requestId, and can receive a different answer. A model answer passed into a connector or SDK step must match on retry: if the retry gets a different answer, that step is rejected and the invocation returns outcome_unknown (409). Retrying with the same requestId fails the same way until the model repeats its earlier answer, and retrying with a new requestId repeats completed external calls.
Recover a write after sign-in or an app update
Before sending a write, retain its original document.baseURI, actionId, requestId, and input in storage appropriate to the input’s sensitivity. Never store credentials or session cookies. The SDK does not persist or automatically retry requests.
After sign-in or a newer app release, resume as the same user with the original base URL and request (not the new page’s defaults). This preserves the action and app revision selected for the original attempt. Old revisions still enforce current permissions.
A later 401, 403, or 409 does not establish that an earlier attempt failed to commit. Keep an uncertain request until its outcome is reconciled; do not clear it, alter its input, or create a replacement ID just because a retry failed. Resolve an earlier uncertain write before submitting edited input as a new operation.
import { PermuteAppClient } from '@permute/sdk/app';
// Load this data from your app's retained original request, without credentials.
async function resumeWrite(pending: {
baseUrl: string;
actionId: string;
request: { requestId: string; input: Record<string, unknown> };
}) {
const originalApp = new PermuteAppClient({ baseUrl: pending.baseUrl });
return originalApp.actions.invoke(pending.actionId, pending.request);
}