---
title: Common Patterns
description: Common resource patterns for Elevasis SDK developers -- sequential steps, conditional branching, platform tools, error handling, and resource status management
---

This page collects the patterns you will reach for most often when writing resources. Each pattern is self-contained and can be adapted directly into your project.

---

## Sequential Workflow Steps

The simplest pattern: a chain of steps where each step feeds its output into the next.

Each `WorkflowStep` requires `id`, `name`, `description`, `handler`, `inputSchema`, `outputSchema`, and `next`. There is no `type` field on a step -- `StepType` (`LINEAR` / `CONDITIONAL`) is a label for `next.type` only, not a step property.

```typescript
import { z } from 'zod';
import type { WorkflowDefinition, WorkflowStep } from '@elevasis/sdk';

const inputSchema = z.object({ orderId: z.string() });
const outputSchema = z.object({ shipped: z.boolean(), trackingNumber: z.string() });

type Input = z.infer<typeof inputSchema>;

const validateStep: WorkflowStep = {
  id: 'validate',
  name: 'Validate Order',
  description: 'Checks the order exists before shipping',
  inputSchema: z.object({ orderId: z.string() }),
  outputSchema: z.object({ order: z.unknown() }),
  handler: async (input: Input) => {
    const order = await getOrder(input.orderId);
    if (!order) throw new Error(`Order ${input.orderId} not found`);
    return { order };
  },
  next: { type: 'linear', target: 'ship' },
};

const shipStep: WorkflowStep = {
  id: 'ship',
  name: 'Ship Order',
  description: 'Creates a shipment and returns the tracking number',
  inputSchema: z.object({ order: z.unknown() }),
  outputSchema: z.object({ shipped: z.boolean(), trackingNumber: z.string() }),
  handler: async (input) => {
    const tracking = await createShipment(input.order);
    return { shipped: true, trackingNumber: tracking.number };
  },
  next: null, // terminal -- no further steps
};

const fulfillOrder: WorkflowDefinition = {
  config: { resourceId: 'fulfill-order', name: 'Fulfill Order', type: 'workflow', description: 'Validates and ships an order', version: '1.0.0', status: 'dev' },
  contract: { inputSchema, outputSchema },
  steps: { validate: validateStep, ship: shipStep },
  entryPoint: 'validate',
};
```

**Key points:**

- Steps require `id`, `name`, `description`, `inputSchema`, `outputSchema`, `handler`, and `next`
- `next.type` is `'linear'` or `'conditional'` -- this is where `StepType` values apply; the step itself has no `type` field
- `next: { type: 'linear', target: 'stepName' }` routes to the next step
- `next: null` marks the terminal step
- Each step receives the full return value of the previous step as its `input`
- The terminal step's return value must satisfy `contract.outputSchema`

---

## Conditional Branching

Use a `next.type` of `'conditional'` when the next step depends on the output of the current step. The step itself still has no `type` field -- the routing decision lives entirely in `next`.

```typescript
import { z } from 'zod';
import type { WorkflowStep } from '@elevasis/sdk';

const scoreStep: WorkflowStep = {
  id: 'score',
  name: 'Score Application',
  description: 'Calculates a risk score and routes on the result',
  inputSchema: z.object({ applicationId: z.string() }),
  outputSchema: z.object({ score: z.number(), applicationId: z.string() }),
  handler: async (input) => {
    const score = await calculateRiskScore(input.applicationId);
    return { score, applicationId: input.applicationId };
  },
  next: {
    type: 'conditional',
    routes: [
      {
        condition: (output) => output.score \>= 80,
        target: 'autoApprove',
      },
      {
        condition: (output) => output.score \>= 40,
        target: 'manualReview',
      },
    ],
    default: 'autoReject', // used when no condition matches
  },
};
```

**Key points:**

- Routes are evaluated in order -- the first matching condition wins
- `default` is required and acts as the `else` branch
- The condition function receives the full handler output
- All route targets and `default` must be keys in your `steps` record

---

## Using Platform Tools in Steps

Platform tools let your steps call integrations managed by Elevasis (email, CRM, databases, etc.). Import `platform` from `@elevasis/sdk/worker` and call it with the tool name, method, parameters, and an optional credential reference when the tool requires one.

```typescript
import { z } from 'zod';
import { platform, PlatformToolError } from '@elevasis/sdk/worker';
import type { WorkflowStep } from '@elevasis/sdk';

const sendEmailStep: WorkflowStep = {
  id: 'sendEmail',
  name: 'Send Email',
  description: 'Sends a transactional email via the platform email tool',
  inputSchema: z.object({ recipientEmail: z.string(), subject: z.string(), body: z.string() }),
  outputSchema: z.object({ sent: z.boolean(), messageId: z.string() }),
  handler: async (input, context) => {
    const result = await platform.call({
      tool: 'email',
      method: 'send',
      params: {
        to: input.recipientEmail,
        subject: input.subject,
        body: input.body,
      },
      credential: 'sendgrid',          // name of the stored credential
    });

    context.logger.info('Email sent', { messageId: result.messageId });
    return { sent: true, messageId: result.messageId };
  },
  next: null,
};
```

**Key points:**

- `platform.call()` is async and times out after 30 minutes (a worker-side safety net; real enforcement is server-side)
- `credential` is the name of a platform environment variable set via `elevasis-sdk env set` when the tool needs one
- On failure, `platform.call()` throws `PlatformToolError` (not `ToolingError`)
- Always log success so executions are easy to debug in the dashboard

---

## Error Handling

### Catching Tool Errors

Use `PlatformToolError` (from `@elevasis/sdk/worker`) to handle tool-specific failures without catching everything:

```typescript
import { platform, PlatformToolError } from '@elevasis/sdk/worker';

const step = async (input) => {
  try {
    const deals = await platform.call({
      tool: 'crm',
      method: 'listDeals',
      params: { stage: 'proposal', limit: 10 },
    });

    const deal = deals[0]
      ? await platform.call({
          tool: 'crm',
          method: 'getDeal',
          params: { dealId: deals[0].id },
        })
      : null;

    if (deal) {
      await platform.call({
        tool: 'crm',
        method: 'updateDealStage',
        params: { dealId: deal.id, stage: 'closing' },
      });

      await platform.call({
        tool: 'crm',
        method: 'createDealNote',
        params: {
          dealId: deal.id,
          body: 'Reviewed proposal and moved the deal forward.',
        },
      });

      await platform.call({
        tool: 'crm',
        method: 'createDealTask',
        params: {
          dealId: deal.id,
          title: 'Send updated proposal',
          dueAt: input.followUpAt ?? null,
        },
      });

      await platform.call({
        tool: 'crm',
        method: 'recordActivity',
        params: {
          dealId: deal.id,
          type: 'stage_changed',
          title: 'Deal moved to closing',
          description: 'Reviewed the proposal and moved the deal forward.',
        },
      });
    }

    return { dealId: deal?.id ?? null, dealCount: deals.length };
  } catch (err) {
    if (err instanceof PlatformToolError) {
      // Tool failed -- log it and return a degraded result
      console.error('CRM tool failed:', err.message);
      return { dealId: null, error: err.message };
    }
    throw err; // re-throw unexpected errors
  }
};
```

### Failing an Execution Explicitly

Use `ExecutionError` when your step detects a condition that should mark the entire execution as failed:

```typescript
import { ExecutionError } from '@elevasis/sdk';

const validateStep = async (input) => {
  if (!input.userId) {
    throw new ExecutionError('userId is required', { code: 'MISSING_INPUT' });
  }
  if (input.amount \<= 0) {
    throw new ExecutionError('amount must be positive', { code: 'INVALID_AMOUNT' });
  }
  return { valid: true };
};
```

`ExecutionError` messages and metadata appear in the Elevasis dashboard under the failed execution's detail view.

### Using ToolingError

`ToolingError` is thrown by lower-level platform operations (not `platform.call()` directly). You may encounter it in advanced scenarios:

```typescript
import { ToolingError } from '@elevasis/sdk';

const step = async (input) => {
  try {
    return await doSomething(input);
  } catch (err) {
    if (err instanceof ToolingError) {
      // check err.type for the error category
      console.error('Tooling error:', err.type, err.message);
    }
    throw err;
  }
};
```

---

## Logging in Steps

The `context.logger` writes structured logs attached to the execution. Use it instead of `console.log` so logs appear in the dashboard alongside the execution record.

```typescript
import type { StepHandler } from '@elevasis/sdk';

const processStep: StepHandler = async (input, context) => {
  context.logger.info('Starting process', { userId: input.userId });

  const result = await doWork(input);

  context.logger.info('Process complete', { resultId: result.id });
  return result;
};
```

Avoid logging sensitive values (API keys, passwords, PII) since logs are stored and visible in the dashboard.

---

## Using the Execution Store

`context.store` is a simple key-value store scoped to the current execution. Use it to pass data between steps without coupling step interfaces, or to checkpoint long-running work.

```typescript
const firstStep: StepHandler = async (input, context) => {
  const data = await fetchExpensiveData(input.id);

  // Save for use by later steps
  await context.store.set('fetchedData', JSON.stringify(data));

  return { fetched: true };
};

const secondStep: StepHandler = async (input, context) => {
  const raw = await context.store.get('fetchedData');
  const data = JSON.parse(raw ?? '{}');

  return { processed: transform(data) };
};
```

Store values are strings. Serialize objects with `JSON.stringify` and parse with `JSON.parse`.

---

## Resource Status

### Dev vs Production

While building a resource, set `config.status` to `'dev'`:

```typescript
const myWorkflow: WorkflowDefinition = {
  config: {
    name: 'my-workflow',
    description: 'Does something useful',
    status: 'dev', // only manually triggerable
  },
  // ...
};
```

Dev resources:

- Appear in `elevasis-sdk resources` output
- Can be triggered with `elevasis-sdk exec my-workflow --input '{...}'`
- Will NOT receive scheduled or webhook-triggered executions
- Will NOT appear as available to external callers

When you are ready to go live, change to `'prod'` and redeploy:

```typescript
config: {
  name: 'my-workflow',
  description: 'Does something useful',
  status: 'prod', // receives all execution sources
},
```

### Global Default Status

Set a project-wide default in `elevasis.config.ts` to keep all resources in `'dev'` mode during development without touching each resource file:

```typescript
import type { ElevasConfig } from '@elevasis/sdk';

const config: ElevasConfig = {
  defaultStatus: 'dev',
};

export default config;
```

Individual resources that set their own `config.status` override this default.

---

## Organizing Multiple Resources

As your project grows, organize resources by business domain. Each domain gets its own directory with an `index.ts` barrel that exports `workflows` and `agents` arrays:

```typescript
// src/orders/fulfill-order.ts
export const fulfillOrder: WorkflowDefinition = { ... };

// src/billing/send-invoice.ts
export const sendInvoice: WorkflowDefinition = { ... };

// src/orders/index.ts
import { fulfillOrder } from './fulfill-order.js';
export const workflows = [fulfillOrder];
export const agents = [];

// src/billing/index.ts
import { sendInvoice } from './send-invoice.js';
export const workflows = [sendInvoice];
export const agents = [];

// src/index.ts
import type { DeploymentSpec } from '@elevasis/sdk';
import * as orders from './orders/index.js';
import * as billing from './billing/index.js';

const org: DeploymentSpec = {
  workflows: [
    ...orders.workflows,
    ...billing.workflows,
  ],
  agents: [
    ...orders.agents,
    ...billing.agents,
  ],
};

export default org;
```

The keys in `workflows` and `agents` are the resource identifiers used in CLI commands and the dashboard. Choose names that are descriptive and use kebab-case for consistency.

---

## Human-in-the-Loop UI Integration

The platform's HITL mechanism works in two parts: your workflow code creates an approval task, and a UI surfaces that task to a reviewer.

### Creating approval tasks

Call `approval.create()` from any workflow step to pause execution and emit a task to the Command Queue:

```typescript
import { approval } from '@elevasis/sdk/worker'

const task = await approval.create({
  actions: [
    { id: 'approve', label: 'Approve', type: 'primary' },
    { id: 'reject', label: 'Reject', type: 'danger' },
  ],
  context: { dealId, proposalUrl },
  description: 'Review proposal before sending',
})

if (task.actionId === 'approve') {
  // continue with approved path
}
```

The workflow step suspends at `approval.create()` and resumes only after a reviewer submits an action. See [Platform Adapters](../platform-tools/adapters-platform.mdx) for the full `approval.create()` reference.

### Built-in Command Center handling

The Command Queue page in the Command Center surfaces all pending approval tasks automatically. Reviewers can filter by resource, approve or reject with an optional comment, and view decision history. No custom UI code is required -- deploy your workflow and the queue populates as tasks arrive.

### Custom UI handling

`@elevasis/ui` exposes the following hooks for approval task operations, exported from `@elevasis/ui/hooks`:

- `useCommandQueue` -- fetches the list of pending tasks for the organization
- `useSubmitAction` -- POSTs an action decision to `/command-queue/{taskId}/action`
- `usePatchTask` -- updates task metadata
- `useDeleteTask` -- removes a task

Use these hooks to build a custom approval queue surface in your template UI. `useSubmitAction` accepts `taskId`, `actionId`, and optional `notes`, and optimistically marks the task as `processing` while the request is in flight.

For triggering executions from custom pages (the other side of the workflow interaction), see [UI Execution](../deployment/execution-reference.mdx#ui-execution).

---

**Last Updated:** 2026-02-25
