Pikku Workflow
What to reach for and why. For how to call it, run this once: pikku doc workflow pikkuWorkflowFunc TypedWorkflow wireScheduler. Depth: references/workflow-reference.md.
Is it a workflow?
- A trigger starts it → workflow, even with one step. A schedule, event, webhook or form submit that kicks off background work. Owners see "trigger, then steps", and Studio shows which step failed; a queue job hides that. Do not move a workflow to a queue worker on your own.
- It crosses a boundary that can fail and must not be lost or run twice (payment, third-party call, email, a wait for a person) → workflow.
- Someone must approve →
workflow.approval, never a status column of your own. - On-screen request/response, or one local algorithm → plain function. Do not wrap it.
- All-or-nothing writes → one
kysely.transaction, in one step or a plain function, never split across steps. A step is a unit of retry, not atomicity: nothing opens a transaction around it.
Rules
- A retried step re-runs its side effects, and a run recovered after a crash re-runs the step caught in flight. Durability is at-least-once, so a charge or email can fire twice. Pass a stable idempotency key built from the workflow's own data (
order-${orderId}-charge), neverrandomUUID()orDate.now(), as anidempotencyKeyfield of the step's input:await workflow.do('Charge the card', 'chargeCard', { orderId: data.orderId, idempotencyKey:order-${data.orderId}-charge}). The function (yours, or an addon function that takes one) uses it as the unique key of the effect. - Every step is a pikku function. Input and output are Zod schemas, not generics.
pikkuWorkflowFuncis the default.pikkuWorkflowGraphandpikkuWorkflowComplexFunconly with the owner's approval, never to dodge an error.- No try/catch around steps. Declare
compensateon the function itself; the engine runs it. Use a milestone to bound the unwind. An expected failure (a quote provider with no price) is not that: return a structured outcome from the step and let the workflow branch to a fallback. Compensation is for failures that should unwind the run. - A sub-workflow is for a real orchestration you also start on its own. A child that would be one step is a function.
- A schedule or other trigger has no signed-in user, so the run has no session: its steps are
pikkuSessionlessFunc. ApikkuFuncstep fails at run time, andpikku validatewon't say so. - A trigger never calls
rpc.invoke, and never adds scheduler or workflow services:pikku dev,pikku serveand stages bring them. A custom host providesworkflowServicein its singleton services before a trigger callsrpc.startWorkflow, and a scheduled trigger also needs a scheduler or platform cron. - Workflows go in
packages/functions/src/wirings/*.workflow.ts, exported. Start, run, status and approve routes come fromscaffold.workflow, and reach only workflows markedexpose: true(anything else answers 404). - Loops in a workflow body:
for...ofwithawait workflow.do(...)is the durable sequential fanout and stays (strict-modeno-await-in-loopis off for*.workflow.ts); for parallel steps usePromise.all(items.map(...))overworkflow.do. NevermapConcurrentfrom@pikku/core/utilsinside apikkuWorkflowFuncbody: it runs plain async work that is not recorded as steps. Bounded concurrency in a workflow fanout is a separate future change. - On a schedule, the
wireSchedulerfunc is apikkuVoidFuncthat only starts the workflow, in the workflow's file:func: async (_services, _input, { rpc }) => { await rpc.startWorkflow('weeklyReport', {}) }, andrpc.startWorkflowis called the same way from a function. A cron has no session. - An approval takes a real
schema, and the workflow branches on the result. A no is an answer (approveStepwith{ approve: false }), neverupdateRunStatus('cancelled'), which skips compensation. Waiting approvals come fromWorkflowRunService, not theworkflowRunstable. - A
pikkuWorkflowFuncbody is analysed statically into a graph, but the body itself runs again on every replay, so anything the graph cannot show is an error (PKU641), never silently dropped. Declare everyconst/letat the top level, and take the input as a plaindataand readdata.xrather than destructuring it. - Allowed:
const/let,if/else(a branch step),switch,for (const x of data.items)(sequential fanout),await Promise.all(data.items.map((x) => workflow.do(...)))(parallel fanout),await Promise.all([workflow.do(...), ...]),return,throw, and awaitedworkflow.do/sleep/suspend/approval. - Rejected:
while,do/while,for,for..in,try/catch, aconst/letinside a block, an inlineworkflow.dofunction, an un-awaitedworkflow.do, destructured step results, andforEach,reduceand a baremapthat wraps workflow calls or stands as a statement (use for-of orPromise.all(map)). A ternary (a ? b : c) is rejected too: useif/else. APromise.all(x.map(...))that is not a flat list ofworkflow.dosteps over a data array (data.items, notdata.items.filter(...)) is rejected with the reason it did not match. Anything else (nestedPromise.all, aswitchper item) belongs inpikkuWorkflowComplexFunc, with the owner's approval. - Replay: the body runs again on every replay, so
Date.now(),new Date()(no arguments),Math.random(),crypto.randomUUID()andawaitof anything that is not a workflow call (await rpc.invoke(...),await helper()) are rejected too. Do them inside a step function (workflow.do) and pass the result on. approversis required: leaving it out is compile error PKU645.anyis not an authorization boundary, so chooseownerornot-initiatorwhen it matters who decides.not-initiatoronly excludes the starter: any other signed-in user passes, whatever their role. To limit the decision to a group, addapproverScopeor equivalent route permissions. The approve route needs a session, even on anauth: falseworkflow; a function callingapproveStepwith no session is the application answering and is not judged against the policy.
A scheduled report, whole
The whole shape, so write it rather than look for one to copy. Steps go in packages/functions/src/functions/<area>/*.function.ts, one file each, with the columns from pikku meta db <table> and the email from the pikku-emails skill.
// packages/functions/src/wirings/weekly-report.workflow.ts
export const weeklyReport = pikkuWorkflowFunc({
input: z.object({ teamId: z.string() }),
output: z.object({ sent: z.number() }),
func: async (_services, data, { workflow }) => {
const report = await workflow.do('Count the week', 'countWeek', data)
return await workflow.do('Email the figures', 'sendWeeklyReport', report)
},
})
export const startWeeklyReports = pikkuVoidFunc({
func: async ({ kysely }, _input, { rpc }) => {
const teams = await kysely.selectFrom('team').select('teamId').execute()
for (const { teamId } of teams) await rpc.startWorkflow('weeklyReport', { teamId })
},
})
wireScheduler({ name: 'weeklyReport', schedule: '0 6 * * 1', func: startWeeklyReports })
// A step: counts or sends, and takes everything it needs as input.
export const sendWeeklyReport = pikkuSessionlessFunc({
input: WeekReport,
output: z.object({ sent: z.number() }),
func: async ({ emailService }, report) => {
await emailService.send({
to: report.email,
template: { name: 'weekly-report', locale: report.locale, data: { count: report.count } },
})
return { sent: 1 }
},
})
Step calls, all in one place
When the CLI cannot tell you, report it; do not dig for it. pikku doc, pikku meta and pikku addons search are the source of truth for how Pikku is called and what this project has. If one fails, or lacks a fact you need, run pikku report "<the exact command and what was missing>" once, then carry on from what you do know. Do not read node_modules, dist or .pikku to work around it: the report is how the gap gets fixed.
Every call is made on workflow (third argument of func), each step has a unique name, and none needs a read of node_modules or .pikku to learn its shape:
await workflow.do('Load the order', 'loadOrder', data) // a function, or 'addon:function'
await workflow.do('Charge', 'chargeCard', input, { retries: 3, retryDelay: '30s' }) // options: description, retries, retryDelay, compensate: false
await workflow.do('Latest item', 'addon:listLatest', null) // a function that takes no input is given `null` ({} and leaving it out do not type-check)
await workflow.sleep('Wait two days', '2d') // a duration: '30s', '5min', '2h', '2d' (whole numbers, no spaces) or milliseconds
const answer = await workflow.approval('A manager approves', { schema, approvers: 'not-initiator', expiry: '48h' })
await Promise.all(items.map((x) => workflow.do(`Notify ${x.id}`, 'notify', x))) // parallel fanout; a for...of with await is the sequential one
A branch is a plain if/else on an earlier step's result. A child workflow is a workflow.do whose function is another pikkuWorkflowFunc's name. pikku meta workflows get <name> prints the steps the compiler found, which is the check that each call above was read as a step.
An approval, whole
Four pieces: the workflow with its gate, a function that starts it, one that lists what waits, and one that answers. The gate's reason is one exported constant, because the answer must name the same gate or it lands on nothing.
// packages/functions/src/wirings/expense-approval.workflow.ts
export const EXPENSE_APPROVAL = 'A manager approves the expense'
export const ExpenseDecision = z.object({ approve: z.boolean() })
export const expenseApproval = pikkuWorkflowFunc({
input: z.object({ expenseId: z.string(), teamId: z.string() }),
output: z.object({ approved: z.boolean() }),
func: async (_services, data, { workflow }) => {
const decision = await workflow.approval(EXPENSE_APPROVAL, {
schema: ExpenseDecision,
approvers: 'not-initiator',
expiry: '7d',
})
if (decision.status === 'expired' || !decision.data.approve) return { approved: false }
await workflow.do('Mark the expense approved', 'markExpenseApproved', data)
return { approved: true }
},
})
// Start: a pikkuFunc the screen calls. `rpc.startWorkflow` returns { runId }.
const { runId } = await rpc.startWorkflow('expenseApproval', { expenseId, teamId })
// List: a run at a gate is `suspended`. `limit` applies before your team filter, so page through
// every suspended run (or use a team-filtered query) rather than reading only the first 50.
const runs = await workflowRunService.listRuns({ workflowName: 'expenseApproval', status: 'suspended', limit: 50 })
const waiting = runs.filter((run) => (run.input as { teamId?: string }).teamId === teamId)
// Answer: your own pikkuFunc with the project's permission, so the rule of who decides is yours.
// Check the run belongs to the caller first, then:
await workflowService.approveStep(runId, EXPENSE_APPROVAL, { approve }, session)
workflowRunService and workflowService are optional services: check them and throw MissingServiceError when absent. The generated /workflow/<name>/approve/:runId route only knows approvers and approverScope; a rule the project already writes as a permission belongs in the answering function. The scaffolded route does not run that function's permission or ownership check, so any signed-in user can approve through it: protect or disable the scaffolded approve route, and use approverScope only when it enforces the same policy, including any run-ownership check.