siloworker-sdk
v1.0.0
Published
Official JavaScript/TypeScript SDK for SiloWorker workflow automation platform
Downloads
9
Maintainers
Readme
SiloWorker JavaScript/TypeScript SDK
Official JavaScript/TypeScript SDK for the SiloWorker workflow automation platform.
Installation
npm install siloworker-sdkQuick Start
import { SiloWorker } from 'siloworker-sdk';
const client = new SiloWorker('your-api-key');
// Create a simple workflow
const { agent_id } = await client.agents.create({
project_id: 'your-project-id',
name: 'Welcome Email',
nodes: [{
id: 'email',
type: 'sendgrid',
config: {
to: '{{input.email}}',
subject: 'Welcome!',
text: 'Thanks for signing up!'
}
}],
connections: []
});
// Execute the workflow
const result = await client.executeWorkflow(agent_id, {
email: '[email protected]'
});
console.log('Workflow started:', result.run_id);Features
- ✅ Full TypeScript support with auto-completion
- ✅ Automatic retries with exponential backoff
- ✅ Webhook handling with signature verification
- ✅ Progress tracking and streaming
- ✅ Batch operations for bulk management
- ✅ Error handling with detailed error types
- ✅ Framework integrations (Express, Next.js)
Configuration
const client = new SiloWorker({
apiKey: 'your-api-key',
baseURL: 'https://api.siloworker.dev', // optional
timeout: 30000, // 30 seconds
retries: 3,
debug: false
});Core Resources
Agents (Workflows)
// Create workflow
const { agent_id } = await client.agents.create({
project_id: 'prj_xxx',
name: 'My Workflow',
nodes: [/* workflow nodes */],
connections: [/* node connections */]
});
// List workflows
const agents = await client.agents.list();
// Get workflow details
const agent = await client.agents.get(agent_id);
// Update workflow
await client.agents.update(agent_id, { name: 'Updated Name' });
// Delete workflow
await client.agents.delete(agent_id);Runs (Executions)
// Start a run
const { run_id } = await client.runs.start(agent_id, {
email: '[email protected]',
name: 'John Doe'
});
// Get run status
const run = await client.runs.get(run_id);
// Wait for completion
const completedRun = await client.runs.waitForCompletion(run_id, {
timeout: 300000, // 5 minutes
onProgress: (run) => console.log('Status:', run.status)
});
// Resume failed run
await client.runs.resume(run_id);
// Resume from specific step
await client.runs.resume(run_id, 'step_id');
// Stream progress
for await (const run of client.runs.streamProgress(run_id)) {
console.log('Progress:', run.status);
}Projects
// Create project
const project = await client.projects.create({
name: 'My Project',
description: 'Project description'
});
// List projects
const projects = await client.projects.list();Schedules
// Create cron schedule
const schedule = await client.schedules.create({
agent_id: 'agent_xxx',
cron: '0 9 * * *', // Daily at 9 AM
input: { type: 'daily_report' }
});
// Create interval schedule
const schedule = await client.schedules.create({
agent_id: 'agent_xxx',
interval_seconds: 3600, // Every hour
input: { type: 'hourly_check' }
});
// List schedules
const schedules = await client.schedules.list();
// Enable/disable schedule
await client.schedules.enable(schedule_id);
await client.schedules.disable(schedule_id);Workspace Management
// Get workspace info
const workspace = await client.workspace.get();
// Update API keys for external services
await client.workspace.updateSettings({
api_keys: {
sendgrid: 'your-sendgrid-key',
twilio: {
account_sid: 'your-account-sid',
auth_token: 'your-auth-token'
}
}
});
// Regenerate API key
const { api_key } = await client.workspace.regenerateApiKey();Advanced Features
Batch Operations
const batch = await client.batch();
// Resume all failed runs
const result = await batch.resumeAllFailed();
console.log(`Resumed ${result.resumed_count} runs`);
// Resume failed runs for specific agent
await batch.resumeAllFailed('agent_xxx');
// Cancel all running runs
await batch.cancelAllRunning();
// Get runs by status
const failedRuns = await batch.getRunsByStatus('failed');Webhook Handling
Express.js
import express from 'express';
import { WebhookUtils } from 'siloworker-sdk';
const app = express();
app.use('/webhooks/siloworker', express.raw({ type: 'application/json' }));
app.post('/webhooks/siloworker', WebhookUtils.createExpressMiddleware(
'your-webhook-secret',
{
onEvent: async (event) => {
console.log('Webhook:', event.type, event.data);
if (event.type === 'run.completed') {
// Handle completion
}
}
}
));Next.js API Route
// pages/api/webhooks/siloworker.js
import { WebhookUtils } from 'siloworker-sdk';
export default WebhookUtils.createNextjsHandler('your-webhook-secret', {
onEvent: async (event) => {
console.log('Webhook received:', event.type);
}
});
export const config = {
api: {
bodyParser: {
sizeLimit: '1mb',
},
},
}Manual Verification
import { WebhookUtils } from 'siloworker-sdk';
// Verify signature
const isValid = WebhookUtils.verifySignature(
payload,
signature,
'your-webhook-secret'
);
// Parse webhook
const event = WebhookUtils.parseWebhook(payload);
// Verify and parse in one step
const event = WebhookUtils.verifyAndParse(
payload,
signature,
'your-webhook-secret'
);Error Handling
import {
SiloWorkerError,
AuthenticationError,
ValidationError,
RateLimitError
} from 'siloworker-sdk';
try {
await client.runs.start('invalid-agent-id', {});
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof ValidationError) {
console.log('Validation error:', error.details);
} else if (error instanceof RateLimitError) {
console.log('Rate limit exceeded');
} else if (error instanceof SiloWorkerError) {
console.log('API error:', error.statusCode, error.message);
}
}Workflow Validation
const validation = client.agents.validateWorkflow(nodes, connections);
if (!validation.valid) {
console.log('Errors:', validation.errors);
}
if (validation.warnings.length > 0) {
console.log('Warnings:', validation.warnings);
}Templates
// List available templates
const templates = await client.templates.list();
// Get template details
const template = await client.templates.get('lead-notification');
// Create agent from template
const { agent_id } = await client.agents.createFromTemplate('lead-notification', {
project_id: 'prj_xxx',
name: 'My Lead Notifications',
parameters: {
slack_channel: '#sales',
email_template: 'welcome'
}
});Framework Integrations
React Hook
import { useState, useEffect } from 'react';
import { SiloWorker } from 'siloworker-sdk';
function useWorkflowRun(agentId, input) {
const [run, setRun] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const execute = async () => {
setLoading(true);
setError(null);
try {
const client = new SiloWorker(process.env.REACT_APP_SILOWORKER_API_KEY);
const result = await client.executeWorkflow(agentId, input, { wait: true });
setRun(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
return { run, loading, error, execute };
}Express Middleware
import { SiloWorker } from 'siloworker-sdk';
function createSiloWorkerMiddleware(apiKey) {
const client = new SiloWorker(apiKey);
return (req, res, next) => {
req.siloworker = client;
next();
};
}
app.use(createSiloWorkerMiddleware(process.env.SILOWORKER_API_KEY));
app.post('/api/workflows', async (req, res) => {
const result = await req.siloworker.executeWorkflow(
req.body.agent_id,
req.body.input
);
res.json(result);
});Environment Variables
# Required
SILOWORKER_API_KEY=your-api-key
# Optional
SILOWORKER_BASE_URL=https://api.siloworker.dev
SILOWORKER_TIMEOUT=30000
SILOWORKER_DEBUG=falseTypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import { SiloWorker, Agent, Run, WorkflowNode } from 'siloworker-sdk';
const client = new SiloWorker('api-key');
// Fully typed responses
const agents: Agent[] = await client.agents.list();
const run: Run = await client.runs.get('run_id');
// Type-safe workflow creation
const nodes: WorkflowNode[] = [
{
id: 'email',
type: 'sendgrid',
config: {
to: '[email protected]',
subject: 'Hello'
}
}
];Examples
See the examples directory for complete working examples:
API Reference
For complete API documentation, visit: https://docs.siloworker.dev
Support
License
MIT License - see LICENSE file for details.
