Transform data
Build and publish a workflow
Use @permute/sdk@^0.20.0 or newer for the workflows namespace. Create a reusable revenue calculation from two sample orders. Run the draft, verify the total is 350, then publish the tested flow.
Workflow
- 1Install @permute/sdk with bun add @permute/sdk. Set PERMUTE_API_KEY and PERMUTE_WORKSPACE_ID for a workspace where the key can read and write data and operations. Save the example as workflow.ts and run bun workflow.ts.
- 2Write two sample orders and inspect the materialized source for its exact table name.
- 3Create a flow, add one transform, then read its source state before saving the complete handler.
- 4Run the draft and wait for that workflow to complete. Check the exact run output equals 350 before publishing.
- 5For later edits, repeat read → save → run → inspect → publish. On a 409 conflict, read again and reconcile your changes before retrying. Each new run has its own output; published operations are available through sources and queries.
- 6Transform handlers can also call await event.llm({ prompt, system?, outputSchema? }) for steps which need language understanding, such as classifying or extracting values from text. Allow it first: pass llm: true in the addTransform input, or call operations.update(operationId, { llm: true }) before saving the source. This is the step’s "Allow AI calls" setting in the app, and changing it needs the same access as saving the step’s source, so it cannot change while the step or its downstream path is locked. Changing it marks existing code stale, like changing inputs; save the source again before running. 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 operation also has an AI credit limit of 2,000 credits per UTC month. Anyone who can view the operation 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 in the app or with client.aiCredits.setLimit(operationId, { monthlyCredits }); only organization admins can set more, in the web app; past it, calls fail with "This operation reached its monthly limit of N AI credits." (N is the current limit), and the run fails. Test runs count only toward the organization. It returns a string, or the parsed JSON value which matches outputSchema. Each run allows at most 10 calls, each request up to 200 KB and each answer up to 2,000 output tokens, and the calls use the workspace organization’s AI credits; batch rows into one prompt and start independent calls together with Promise.all.
- 7To start the published flow from another system, call operations.update(flow.operation.id, { webhook: true }) and give the returned webhookUrl to the sender; calling it again returns the same URL, API reads never show it, and people who can edit the flow can show it on its trigger page in the web app. Each POST starts a normal run of the published flow without passing the request. The URL replies 200 {"data":{"status":"queued"}} even while a run is active, but then starts no second run, and the operation shows pending while its run is queued or running. A paused flow (isEnabled: false) replies 200 {"data":{"status":"ignored"}}. A flow runs on a schedule or by webhook, not both: adding one while the other exists returns 400 invalid_request, but one request can switch, for example { webhook: false, schedule: { type: 'hourly', minute: 0 } }. Workflow steps run with their parent and cannot have their own webhook (400 invalid_request).
- 8Managed databases can also be inputs: include the dbas_ ID in dataSourceIds and transform inputIds, inspect its live schema with sources.get, then read it with event.remoteQuery(databaseId, sql). The key needs current database read access. Queries exceeding 1,000 rows fail; narrow or paginate reads with stable ordering.
Example
import { PermuteClient } from '@permute/sdk';
const client = new PermuteClient({
apiKey: process.env.PERMUTE_API_KEY!,
}).withWorkspace(process.env.PERMUTE_WORKSPACE_ID!);
// 1. Create sample input and wait for materialization.
const dataset = await client.datasets.create({
type: 'custom', key: 'workflow-guide', name: 'Sample orders', context: [],
});
await dataset.replace({ orders: [{ amount: 100 }, { amount: 250 }] });
const input = await client.sources.get(dataset.id);
const table = input.tables[0];
if (!table) throw new Error('Sample table is missing');
const sql = 'SELECT SUM(amount) AS total FROM "' + table.name.replaceAll('"', '""') + '"';
// 2. Add a transform to a new flow.
let flow = await client.workflows.create({
name: 'Revenue total', description: 'Sum sample orders', dataSourceIds: [dataset.id],
});
await client.workflows.command(flow.operation.id, {
command: {
type: 'addTransform', expectedRevision: flow.revision,
input: { name: 'Total', instruction: 'Sum order amounts', inputIds: [dataset.id] },
},
});
flow = await client.workflows.get(flow.operation.id);
const operationId = flow.operationIds[0];
if (!operationId) throw new Error('Transform is missing');
// 3. Save code using the state we just read.
const current = await client.operations.getSource(operationId);
await client.operations.updateSource(operationId, {
source: 'module.exports = { handler: async (event) => ({ revenue: await event.query(' +
JSON.stringify(sql) + ') }) };',
expectedRevision: current.revision,
expectedDataFlowRevision: current.dataFlowRevision,
expectedUpdatedAt: current.updatedAt,
});
// 4. Run the whole draft and wait for this workflow, not an older run.
const started = await client.operations.run(flow.operation.id, { version: 'draft' });
async function waitForWorkflow() {
const deadline = Date.now() + 5 * 60_000;
while (Date.now() < deadline) {
const workflow = await client.operations.listRuns({ workflowId: started.workflowId });
if (workflow.status === 'failed') throw new Error(workflow.items.find((run) => run.error)?.error ?? 'Workflow failed');
if (workflow.status === 'completed') return workflow;
await new Promise((resolve) => setTimeout(resolve, 1500));
}
throw new Error('Timed out waiting for workflow');
}
const workflow = await waitForWorkflow();
const run = workflow.items.find((run) => run.operationId === operationId);
if (!run?.outputDocId) throw new Error('Run output is missing');
const preview = await client.operations.getRunOutput(operationId, run.id);
const revenueBlockId = Object.entries(preview.names).find(([, name]) => name.toLowerCase() === 'revenue')?.[0];
const rows = revenueBlockId ? preview.tables[revenueBlockId] as Array<{ total: unknown }> : undefined;
console.table(rows);
if (rows?.length !== 1 || Number(rows[0].total) !== 350) {
throw new Error('Unexpected total; inspect the source and fix the handler before publishing');
}
// 5. Publish only after validating the output, using its current version token.
const ready = await client.revisions.list(flow.operation.id);
await client.revisions.publish(flow.operation.id, { expectedVersion: ready.version });
console.log('Published flow:', flow.operation.id, 'Output source:', operationId);