Pikku workflow

From pikkujs/pikku · View interactive version

Pikku workflow is an AI agent skill from the GitHub repository pikkujs/pikku. Durable workflows: pikkuWorkflowFunc, workflow.do/sleep/suspend/approval, compensate. For multi-step work and anything a trigger starts (schedule, event, webhook, form submit), even with one step.

How to use this skill

Skill file

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?

Rules

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.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.