@elevasis/sdk 0.4.5 → 0.4.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,288 @@
1
+ ---
2
+ title: Writing Resources
3
+ description: Guide to creating workflows and agents using WorkflowDefinition, AgentDefinition, and OrganizationResources with the Elevasis SDK
4
+ ---
5
+
6
+ Resources are the building blocks of your Elevasis project. A resource is a workflow or agent definition that the platform can execute on your behalf. You define them in TypeScript, export them from a single entry point, and the platform handles scheduling, retries, logging, and execution.
7
+
8
+ This page covers how to structure your resources, write step handlers, and export everything through `OrganizationResources`.
9
+
10
+ ## WorkflowDefinition
11
+
12
+ A workflow is a series of named steps executed in sequence or branching paths. You define it with a `WorkflowDefinition` object.
13
+
14
+ A complete workflow definition has four required properties:
15
+
16
+ - `config` - metadata about the workflow (name, description, status)
17
+ - `contract` - Zod schemas for input and output validation
18
+ - `steps` - a record of named step handlers
19
+ - `entryPoint` - the name of the first step to execute
20
+
21
+ ### Minimal Example
22
+
23
+ ```typescript
24
+ import { z } from 'zod';
25
+ import type { WorkflowDefinition, OrganizationResources } from '@elevasis/sdk';
26
+
27
+ const echoInput = z.object({
28
+ message: z.string(),
29
+ });
30
+
31
+ const echoOutput = z.object({
32
+ result: z.string(),
33
+ });
34
+
35
+ type EchoInput = z.infer<typeof echoInput>;
36
+ type EchoOutput = z.infer<typeof echoOutput>;
37
+
38
+ const echoWorkflow: WorkflowDefinition = {
39
+ config: {
40
+ name: 'echo',
41
+ description: 'Returns the input message unchanged',
42
+ status: 'dev',
43
+ },
44
+ contract: {
45
+ input: echoInput,
46
+ output: echoOutput,
47
+ },
48
+ steps: {
49
+ run: async (input: EchoInput): Promise<EchoOutput> => {
50
+ return { result: input.message };
51
+ },
52
+ },
53
+ entryPoint: 'run',
54
+ };
55
+ ```
56
+
57
+ ### config
58
+
59
+ The `config` block identifies the workflow on the platform:
60
+
61
+ | Field | Type | Description |
62
+ | ----- | ---- | ----------- |
63
+ | `name` | `string` | Unique name within your organization. Used by the CLI and platform UI. |
64
+ | `description` | `string` | Human-readable summary shown in the dashboard. |
65
+ | `status` | `'dev' | 'production'` | Controls availability. Use `'dev'` while building. See [Resource Status](#resource-status). |
66
+
67
+ ### contract
68
+
69
+ The `contract` block defines the Zod schemas for input and output. The platform validates input against `contract.input` before passing it to your step handler, and validates the step's return value against `contract.output`.
70
+
71
+ Always use `z.object()` for both schemas. Use `z.infer` to derive TypeScript types from the schemas -- this keeps types and runtime validation in sync automatically.
72
+
73
+ ```typescript
74
+ const contract = {
75
+ input: z.object({
76
+ userId: z.string().uuid(),
77
+ action: z.string(),
78
+ }),
79
+ output: z.object({
80
+ success: z.boolean(),
81
+ message: z.string(),
82
+ }),
83
+ };
84
+ ```
85
+
86
+ ### steps
87
+
88
+ The `steps` record maps step names to handler functions. Each handler receives the validated input and an optional `StepContext` (execution metadata). Single-step workflows have one entry; multi-step workflows have one entry per step.
89
+
90
+ ```typescript
91
+ const steps = {
92
+ validate: async (input: MyInput) => {
93
+ // first step -- returns output to pass to next step
94
+ return { validated: true, data: input };
95
+ },
96
+ process: async (input: ValidatedData) => {
97
+ // second step
98
+ return { result: 'done' };
99
+ },
100
+ };
101
+ ```
102
+
103
+ ### entryPoint
104
+
105
+ `entryPoint` is the name of the first step. For single-step workflows it is always the only step name. For multi-step workflows it is the name of the first step in the chain.
106
+
107
+ ```typescript
108
+ const workflow: WorkflowDefinition = {
109
+ // ...
110
+ entryPoint: 'validate', // execution starts here
111
+ };
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Multi-Step Workflows
117
+
118
+ For workflows with more than one step, import `StepType` from `@elevasis/sdk` to configure step routing.
119
+
120
+ ### Linear Steps
121
+
122
+ Use `StepType.LINEAR` to connect steps in a fixed sequence. Each step declares a `next` property pointing to the next step name.
123
+
124
+ ```typescript
125
+ import { z } from 'zod';
126
+ import { StepType } from '@elevasis/sdk';
127
+ import type { WorkflowDefinition, WorkflowStep } from '@elevasis/sdk';
128
+
129
+ const fetchStep: WorkflowStep = {
130
+ type: StepType.LINEAR,
131
+ handler: async (input) => {
132
+ const data = await fetchSomething(input.id);
133
+ return { data };
134
+ },
135
+ next: { target: 'process' },
136
+ };
137
+
138
+ const processStep: WorkflowStep = {
139
+ type: StepType.LINEAR,
140
+ handler: async (input) => {
141
+ return { result: transform(input.data) };
142
+ },
143
+ next: null, // terminal step
144
+ };
145
+
146
+ const pipeline: WorkflowDefinition = {
147
+ config: { name: 'pipeline', description: 'Fetch then process', status: 'dev' },
148
+ contract: { input: pipelineInput, output: pipelineOutput },
149
+ steps: { fetch: fetchStep, process: processStep },
150
+ entryPoint: 'fetch',
151
+ };
152
+ ```
153
+
154
+ ### Conditional Branching
155
+
156
+ Use `StepType.CONDITIONAL` to route to different steps based on output values. Each route has a `condition` function and a `target` step name. The first condition that returns `true` wins. A `defaultTarget` is required as a fallback.
157
+
158
+ ```typescript
159
+ import { StepType } from '@elevasis/sdk';
160
+ import type { WorkflowStep } from '@elevasis/sdk';
161
+
162
+ const routerStep: WorkflowStep = {
163
+ type: StepType.CONDITIONAL,
164
+ handler: async (input) => {
165
+ const score = await evaluate(input);
166
+ return { score };
167
+ },
168
+ next: {
169
+ routes: [
170
+ {
171
+ condition: (output) => output.score \>= 80,
172
+ target: 'highScorePath',
173
+ },
174
+ {
175
+ condition: (output) => output.score \>= 50,
176
+ target: 'mediumScorePath',
177
+ },
178
+ ],
179
+ defaultTarget: 'lowScorePath',
180
+ },
181
+ };
182
+ ```
183
+
184
+ ---
185
+
186
+ ## StepContext
187
+
188
+ Every step handler can optionally accept a second `context` parameter. TypeScript allows you to omit it if you do not need it -- you can write `handler: async (input) => { ... }` without declaring `context`.
189
+
190
+ When you do need it, the context provides runtime metadata:
191
+
192
+ ```typescript
193
+ import type { StepHandler } from '@elevasis/sdk';
194
+
195
+ const myStep: StepHandler = async (input, context) => {
196
+ const { executionId, organizationId, resourceId, logger, store } = context;
197
+
198
+ logger.info('Starting step', { executionId });
199
+
200
+ // store is a simple key-value store scoped to this execution
201
+ await store.set('progress', '50%');
202
+
203
+ return { done: true };
204
+ };
205
+ ```
206
+
207
+ | Field | Type | Description |
208
+ | ----- | ---- | ----------- |
209
+ | `executionId` | `string` | Unique ID for this execution run |
210
+ | `organizationId` | `string` | Your organization ID |
211
+ | `resourceId` | `string` | ID of the workflow or agent being executed |
212
+ | `logger` | `Logger` | Structured logger -- messages appear in the Elevasis dashboard |
213
+ | `store` | `Store` | Key-value store scoped to the current execution |
214
+
215
+ ---
216
+
217
+ ## AgentDefinition
218
+
219
+ Agents are autonomous resources that use an LLM and tools to complete a goal. You define them with `AgentDefinition`.
220
+
221
+ **Note:** Agent execution in the worker runtime is not yet fully supported. Defining agents is supported for forward compatibility, but executions will return a failure response until agent execution ships.
222
+
223
+ ```typescript
224
+ import type { AgentDefinition } from '@elevasis/sdk';
225
+
226
+ const myAgent: AgentDefinition = {
227
+ config: {
228
+ name: 'my-agent',
229
+ description: 'Answers questions using platform tools',
230
+ status: 'dev',
231
+ },
232
+ agentConfig: {
233
+ model: { provider: 'openai', model: 'gpt-4o' },
234
+ systemPrompt: 'You are a helpful assistant.',
235
+ maxIterations: 10,
236
+ },
237
+ tools: [],
238
+ };
239
+ ```
240
+
241
+ ---
242
+
243
+ ## OrganizationResources
244
+
245
+ All resources must be exported through an `OrganizationResources` default export from `src/index.ts`. This is the entry point the platform reads when you deploy.
246
+
247
+ ```typescript
248
+ import type { OrganizationResources } from '@elevasis/sdk';
249
+
250
+ const org: OrganizationResources = {
251
+ workflows: {
252
+ echo: echoWorkflow,
253
+ pipeline: pipeline,
254
+ },
255
+ agents: {
256
+ // myAgent: myAgent,
257
+ },
258
+ };
259
+
260
+ export default org;
261
+ ```
262
+
263
+ The keys under `workflows` and `agents` are used as resource identifiers on the platform. They appear in CLI output (`elevasis resources`), execution commands (`elevasis exec`), and the dashboard.
264
+
265
+ ### Resource Status
266
+
267
+ Set `config.status` to control whether the platform accepts execution requests:
268
+
269
+ - `'dev'` - Resource is visible in the dashboard but the platform will not route scheduled or webhook-triggered executions to it. You can still trigger it manually via `elevasis exec`.
270
+ - `'production'` - Resource is live and accepts all execution sources.
271
+
272
+ Use `'dev'` while you are building and testing. Switch to `'production'` when you are ready to go live.
273
+
274
+ You can also set a global default status in `elevasis.config.ts`:
275
+
276
+ ```typescript
277
+ import type { ElevasConfig } from '@elevasis/sdk';
278
+
279
+ const config: ElevasConfig = {
280
+ defaultStatus: 'dev',
281
+ };
282
+
283
+ export default config;
284
+ ```
285
+
286
+ ---
287
+
288
+ **Last Updated:** 2026-02-25
@@ -0,0 +1,340 @@
1
+ ---
2
+ title: Common Patterns
3
+ description: Common resource patterns for Elevasis SDK developers -- sequential steps, conditional branching, platform tools, error handling, and resource status management
4
+ ---
5
+
6
+ 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.
7
+
8
+ ---
9
+
10
+ ## Sequential Workflow Steps
11
+
12
+ The simplest pattern: a chain of steps where each step feeds its output into the next.
13
+
14
+ ```typescript
15
+ import { z } from 'zod';
16
+ import { StepType } from '@elevasis/sdk';
17
+ import type { WorkflowDefinition, WorkflowStep } from '@elevasis/sdk';
18
+
19
+ const inputSchema = z.object({ orderId: z.string() });
20
+ const outputSchema = z.object({ shipped: z.boolean(), trackingNumber: z.string() });
21
+
22
+ type Input = z.infer<typeof inputSchema>;
23
+ type Output = z.infer<typeof outputSchema>;
24
+
25
+ const validateStep: WorkflowStep = {
26
+ type: StepType.LINEAR,
27
+ handler: async (input: Input) => {
28
+ const order = await getOrder(input.orderId);
29
+ if (!order) throw new Error(`Order ${input.orderId} not found`);
30
+ return { order };
31
+ },
32
+ next: { target: 'ship' },
33
+ };
34
+
35
+ const shipStep: WorkflowStep = {
36
+ type: StepType.LINEAR,
37
+ handler: async (input) => {
38
+ const tracking = await createShipment(input.order);
39
+ return { shipped: true, trackingNumber: tracking.number };
40
+ },
41
+ next: null, // terminal -- no further steps
42
+ };
43
+
44
+ const fulfillOrder: WorkflowDefinition = {
45
+ config: { name: 'fulfill-order', description: 'Validates and ships an order', status: 'dev' },
46
+ contract: { input: inputSchema, output: outputSchema },
47
+ steps: { validate: validateStep, ship: shipStep },
48
+ entryPoint: 'validate',
49
+ };
50
+ ```
51
+
52
+ **Key points:**
53
+
54
+ - `next: { target: 'stepName' }` routes to the next step
55
+ - `next: null` marks the terminal step
56
+ - Each step receives the full return value of the previous step as its `input`
57
+ - The terminal step's return value must satisfy `contract.output`
58
+
59
+ ---
60
+
61
+ ## Conditional Branching
62
+
63
+ Use `StepType.CONDITIONAL` when the next step depends on the output of the current step.
64
+
65
+ ```typescript
66
+ import { StepType } from '@elevasis/sdk';
67
+ import type { WorkflowStep } from '@elevasis/sdk';
68
+
69
+ const scoreStep: WorkflowStep = {
70
+ type: StepType.CONDITIONAL,
71
+ handler: async (input) => {
72
+ const score = await calculateRiskScore(input.applicationId);
73
+ return { score, applicationId: input.applicationId };
74
+ },
75
+ next: {
76
+ routes: [
77
+ {
78
+ condition: (output) => output.score \>= 80,
79
+ target: 'autoApprove',
80
+ },
81
+ {
82
+ condition: (output) => output.score \>= 40,
83
+ target: 'manualReview',
84
+ },
85
+ ],
86
+ defaultTarget: 'autoReject', // used when no condition matches
87
+ },
88
+ };
89
+ ```
90
+
91
+ **Key points:**
92
+
93
+ - Routes are evaluated in order -- the first matching condition wins
94
+ - `defaultTarget` is required and acts as the `else` branch
95
+ - The condition function receives the full handler output
96
+ - All route targets and `defaultTarget` must be keys in your `steps` record
97
+
98
+ ---
99
+
100
+ ## Using Platform Tools in Steps
101
+
102
+ 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 a credential reference.
103
+
104
+ ```typescript
105
+ import { platform, PlatformToolError } from '@elevasis/sdk/worker';
106
+ import type { WorkflowStep } from '@elevasis/sdk';
107
+ import { StepType } from '@elevasis/sdk';
108
+
109
+ const sendEmailStep: WorkflowStep = {
110
+ type: StepType.LINEAR,
111
+ handler: async (input, context) => {
112
+ const result = await platform.call({
113
+ tool: 'email',
114
+ method: 'send',
115
+ params: {
116
+ to: input.recipientEmail,
117
+ subject: input.subject,
118
+ body: input.body,
119
+ },
120
+ credential: 'SENDGRID_API_KEY', // references a platform env var
121
+ });
122
+
123
+ context.logger.info('Email sent', { messageId: result.messageId });
124
+ return { sent: true, messageId: result.messageId };
125
+ },
126
+ next: null,
127
+ };
128
+ ```
129
+
130
+ **Key points:**
131
+
132
+ - `platform.call()` is async and times out after 60 seconds
133
+ - `credential` is the name of a platform environment variable set via `elevasis env set`
134
+ - On failure, `platform.call()` throws `PlatformToolError` (not `ToolingError`)
135
+ - Always log success so executions are easy to debug in the dashboard
136
+
137
+ ---
138
+
139
+ ## Error Handling
140
+
141
+ ### Catching Tool Errors
142
+
143
+ Use `PlatformToolError` (from `@elevasis/sdk/worker`) to handle tool-specific failures without catching everything:
144
+
145
+ ```typescript
146
+ import { platform, PlatformToolError } from '@elevasis/sdk/worker';
147
+
148
+ const step = async (input) => {
149
+ try {
150
+ const result = await platform.call({
151
+ tool: 'crm',
152
+ method: 'createContact',
153
+ params: { email: input.email, name: input.name },
154
+ credential: 'CRM_API_KEY',
155
+ });
156
+ return { contactId: result.id };
157
+ } catch (err) {
158
+ if (err instanceof PlatformToolError) {
159
+ // Tool failed -- log it and return a degraded result
160
+ console.error('CRM tool failed:', err.message);
161
+ return { contactId: null, error: err.message };
162
+ }
163
+ throw err; // re-throw unexpected errors
164
+ }
165
+ };
166
+ ```
167
+
168
+ ### Failing an Execution Explicitly
169
+
170
+ Use `ExecutionError` when your step detects a condition that should mark the entire execution as failed:
171
+
172
+ ```typescript
173
+ import { ExecutionError } from '@elevasis/sdk';
174
+
175
+ const validateStep = async (input) => {
176
+ if (!input.userId) {
177
+ throw new ExecutionError('userId is required', { code: 'MISSING_INPUT' });
178
+ }
179
+ if (input.amount \<= 0) {
180
+ throw new ExecutionError('amount must be positive', { code: 'INVALID_AMOUNT' });
181
+ }
182
+ return { valid: true };
183
+ };
184
+ ```
185
+
186
+ `ExecutionError` messages and metadata appear in the Elevasis dashboard under the failed execution's detail view.
187
+
188
+ ### Using ToolingError
189
+
190
+ `ToolingError` is thrown by lower-level platform operations (not `platform.call()` directly). You may encounter it in advanced scenarios:
191
+
192
+ ```typescript
193
+ import { ToolingError } from '@elevasis/sdk';
194
+
195
+ const step = async (input) => {
196
+ try {
197
+ return await doSomething(input);
198
+ } catch (err) {
199
+ if (err instanceof ToolingError) {
200
+ // check err.type for the error category
201
+ console.error('Tooling error:', err.type, err.message);
202
+ }
203
+ throw err;
204
+ }
205
+ };
206
+ ```
207
+
208
+ ---
209
+
210
+ ## Logging in Steps
211
+
212
+ 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.
213
+
214
+ ```typescript
215
+ import type { StepHandler } from '@elevasis/sdk';
216
+
217
+ const processStep: StepHandler = async (input, context) => {
218
+ context.logger.info('Starting process', { userId: input.userId });
219
+
220
+ const result = await doWork(input);
221
+
222
+ context.logger.info('Process complete', { resultId: result.id });
223
+ return result;
224
+ };
225
+ ```
226
+
227
+ Avoid logging sensitive values (API keys, passwords, PII) since logs are stored and visible in the dashboard.
228
+
229
+ ---
230
+
231
+ ## Using the Execution Store
232
+
233
+ `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.
234
+
235
+ ```typescript
236
+ const firstStep: StepHandler = async (input, context) => {
237
+ const data = await fetchExpensiveData(input.id);
238
+
239
+ // Save for use by later steps
240
+ await context.store.set('fetchedData', JSON.stringify(data));
241
+
242
+ return { fetched: true };
243
+ };
244
+
245
+ const secondStep: StepHandler = async (input, context) => {
246
+ const raw = await context.store.get('fetchedData');
247
+ const data = JSON.parse(raw ?? '{}');
248
+
249
+ return { processed: transform(data) };
250
+ };
251
+ ```
252
+
253
+ Store values are strings. Serialize objects with `JSON.stringify` and parse with `JSON.parse`.
254
+
255
+ ---
256
+
257
+ ## Resource Status
258
+
259
+ ### Dev vs Production
260
+
261
+ While building a resource, set `config.status` to `'dev'`:
262
+
263
+ ```typescript
264
+ const myWorkflow: WorkflowDefinition = {
265
+ config: {
266
+ name: 'my-workflow',
267
+ description: 'Does something useful',
268
+ status: 'dev', // only manually triggerable
269
+ },
270
+ // ...
271
+ };
272
+ ```
273
+
274
+ Dev resources:
275
+
276
+ - Appear in `elevasis resources` output
277
+ - Can be triggered with `elevasis exec my-workflow --input '{...}'`
278
+ - Will NOT receive scheduled or webhook-triggered executions
279
+ - Will NOT appear as available to external callers
280
+
281
+ When you are ready to go live, change to `'production'` and redeploy:
282
+
283
+ ```typescript
284
+ config: {
285
+ name: 'my-workflow',
286
+ description: 'Does something useful',
287
+ status: 'production', // receives all execution sources
288
+ },
289
+ ```
290
+
291
+ ### Global Default Status
292
+
293
+ Set a project-wide default in `elevasis.config.ts` to keep all resources in `'dev'` mode during development without touching each resource file:
294
+
295
+ ```typescript
296
+ import type { ElevasConfig } from '@elevasis/sdk';
297
+
298
+ const config: ElevasConfig = {
299
+ defaultStatus: 'dev',
300
+ };
301
+
302
+ export default config;
303
+ ```
304
+
305
+ Individual resources that set their own `config.status` override this default.
306
+
307
+ ---
308
+
309
+ ## Organizing Multiple Resources
310
+
311
+ As your project grows, split resources into separate files and import them into `src/index.ts`:
312
+
313
+ ```typescript
314
+ // src/workflows/fulfill-order.ts
315
+ export const fulfillOrder: WorkflowDefinition = { ... };
316
+
317
+ // src/workflows/send-invoice.ts
318
+ export const sendInvoice: WorkflowDefinition = { ... };
319
+
320
+ // src/index.ts
321
+ import { fulfillOrder } from './workflows/fulfill-order';
322
+ import { sendInvoice } from './workflows/send-invoice';
323
+ import type { OrganizationResources } from '@elevasis/sdk';
324
+
325
+ const org: OrganizationResources = {
326
+ workflows: {
327
+ 'fulfill-order': fulfillOrder,
328
+ 'send-invoice': sendInvoice,
329
+ },
330
+ agents: {},
331
+ };
332
+
333
+ export default org;
334
+ ```
335
+
336
+ 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.
337
+
338
+ ---
339
+
340
+ **Last Updated:** 2026-02-25