Skip to content

Instantly share code, notes, and snippets.

@abhiaiyer91
Created February 25, 2025 18:09
Show Gist options
  • Save abhiaiyer91/47810a5bf51c1859588250a0bd200092 to your computer and use it in GitHub Desktop.
Save abhiaiyer91/47810a5bf51c1859588250a0bd200092 to your computer and use it in GitHub Desktop.
import { Workflow, Step } from '@mastra/core';
import { z } from 'zod';
async function main() {
// Step A: Increment the counter
const incrementStep = new Step({
id: 'increment',
description: 'Increments the current value by 1',
outputSchema: z.object({
newValue: z.number(),
}),
execute: async ({ context }) => {
// Get the current value (either from trigger or previous increment)
const currentValue = context.getStepResult<{ newValue: number }>('increment')?.newValue ||
context.getStepResult<{ startValue: number }>('trigger')?.startValue || 0;
// Increment the value
const newValue = currentValue + 1;
console.log(`Step A: ${newValue}`);
return { newValue };
},
});
// Step B: Check if we've reached the target
const checkTargetStep = new Step({
id: 'checkTarget',
description: 'Checks if the current value has reached the target',
outputSchema: z.object({
reachedTarget: z.boolean(),
}),
execute: async ({ context }) => {
const currentValue = context.getStepResult<{ newValue: number }>('increment')?.newValue || 0;
const target = context.getStepResult<{ target: number }>('trigger')?.target || 0;
// Check if we've reached the target
const reachedTarget = currentValue >= target;
console.log(`Step B: ${reachedTarget}`);
return { reachedTarget };
},
});
// Create the workflow
const counterWorkflow = new Workflow({
name: 'counter-workflow',
triggerSchema: z.object({
target: z.number(),
startValue: z.number(),
}),
});
// Define the workflow steps with cyclical dependency
counterWorkflow
.step(incrementStep)
.then(checkTargetStep)
.after(checkTargetStep)
.step(incrementStep, {
when: {
ref: { step: checkTargetStep, path: 'reachedTarget' },
query: { $eq: false },
},
})
.then(checkTargetStep)
.commit();
// Run the workflow
const { runId, start } = counterWorkflow.createRun();
console.log('Starting workflow run:', runId);
// Example with target: 3, startValue: 0
const result = await start({
triggerData: {
target: 10,
startValue: 0
}
});
console.log('Exit');
console.log('Results:', result.results);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment