← back to Designer Wallcoverings

DW-Agents/dw-agents/HOOKS-API-QUICK-REFERENCE.md

265 lines

# Hooks API - Quick Reference

## One-Line Import

```typescript
import { setupHooksAPI, executeHook, hooks, HooksClient } from '../shared-hooks-api';
```

## Setup (Add to Agent Server)

```typescript
const app = express();
app.use(express.json());

// Add hooks API
setupHooksAPI(app);  // Creates REST endpoints at /api/hooks/*

app.listen(3000);
```

## 5 Ways to Use Hooks

### 1. REST API (Auto-generated)

```bash
# List all hooks
GET /api/hooks

# Execute hook
POST /api/hooks/slack
Body: { "params": { "channel": "general", "message": "Hello" } }

# Or with action string
POST /api/hooks/gmail
Body: { "action": "send test@example.com \"Subject\" \"Body\"" }
```

### 2. Convenience Wrappers (Easiest)

```typescript
// Gmail
await hooks.gmail.send('to@example.com', 'Subject', 'Body');
await hooks.gmail.read(10);
await hooks.gmail.search('from:boss@company.com');

// Slack
await hooks.slack.send('general', 'Hello team!');
await hooks.slack.listChannels();

// Twilio
await hooks.twilio.sms('+12125551234', 'Your order shipped');
await hooks.twilio.call('+12125551234');

// Health checks
await hooks.health.check('web');
await hooks.health.agents();

// Orders
await hooks.orders.process('12345678');

// Errors
await hooks.errors.notify('critical', 'Database down');
await hooks.errors.notify('high', 'API timeout');
```

### 3. Direct Execution

```typescript
const result = await executeHook('slack', 'send general "Hello"');

if (result.success) {
  console.log('Output:', result.output);
  console.log('Took:', result.executionTime, 'ms');
} else {
  console.error('Error:', result.error);
}
```

### 4. Type-Safe Client

```typescript
const hooksClient = new HooksClient(60000); // 60s timeout

await hooksClient.gmail('send', 'to@example.com', 'Subject', 'Body');
await hooksClient.slack('send', 'general', 'Hello');
await hooksClient.healthCheck('web');
await hooksClient.processOrder('12345678');
await hooksClient.notifyError('critical', 'Service down');
```

### 5. Programmatic in Routes

```typescript
app.post('/api/orders/new', async (req, res) => {
  const { orderId, email, total } = req.body;

  // Process order
  await executeHook('order-processing', orderId);

  // Notify team
  await hooks.slack.send('orders', `New order: #${orderId} - $${total}`);

  // Email customer
  await hooks.gmail.send(email, 'Order Confirmed', `Order #${orderId}`);

  res.json({ success: true });
});
```

## Available Hooks (Quick List)

| Hook | Purpose | Example |
|------|---------|---------|
| `gmail` | Email operations | `send`, `read`, `search` |
| `slack` | Slack messaging | `send`, `list-channels` |
| `twilio` | SMS/Voice | `sms`, `call` |
| `calendar` | Google Calendar | `list`, `create` |
| `shopify` | Store operations | `list-orders`, `get-product` |
| `weather` | Weather data | `current`, `forecast` |
| `service-health-check` | Service health | Service name |
| `agent-health-monitor` | Agent health | `check`, `restart` |
| `order-processing` | Process orders | Order ID |
| `error-notification` | Error alerts | Severity level |
| `inter-agent-chat` | Agent comms | `send`, `broadcast` |

## Error Handling

```typescript
const result = await executeHook('gmail', 'send test@test.com "Test" "Body"');

if (result.success) {
  console.log('Success!');
} else {
  console.error('Failed:', result.error);

  // Notify about the failure
  await hooks.errors.notify('high', `Gmail failed: ${result.error}`);
}
```

## Custom Timeout

```typescript
// One-off custom timeout (5 minutes)
await executeHook('product-import', 'large-file', 300000);

// Client with custom default timeout (2 minutes)
const client = new HooksClient(120000);
await client.processOrder('12345');
```

## Real-World Patterns

### Pattern 1: Order Processing

```typescript
app.post('/webhooks/order', async (req, res) => {
  const order = req.body;

  await executeHook('order-processing', order.id);
  await hooks.slack.send('orders', `New: $${order.total}`);
  await hooks.gmail.send(order.email, 'Confirmed', `Order #${order.id}`);

  res.json({ success: true });
});
```

### Pattern 2: Health Monitoring

```typescript
setInterval(async () => {
  for (const service of ['web', 'gmail', 'slack']) {
    const result = await hooks.health.check(service);
    if (!result.success) {
      await hooks.errors.notify('critical', `${service} is down`);
      await hooks.slack.send('alerts', `ALERT: ${service} down`);
    }
  }
}, 5 * 60 * 1000); // Every 5 minutes
```

### Pattern 3: Marketing Campaign

```typescript
app.post('/api/campaigns/launch', async (req, res) => {
  const { name, budget } = req.body;

  await hooks.slack.send('marketing', `Campaign: ${name} ($${budget})`);
  await executeHook('inter-agent-chat', `broadcast "Campaign: ${name}"`);
  await hooks.gmail.send('team@co.com', 'Campaign', `${name} launched`);

  res.json({ success: true });
});
```

### Pattern 4: Error Recovery

```typescript
try {
  await riskyOperation();
} catch (error) {
  // Notify via multiple channels
  await hooks.errors.notify('critical', error.message);
  await hooks.slack.send('critical-alerts', `ERROR: ${error.message}`);
  await hooks.twilio.sms('+12125551234', `ALERT: System error`);

  // Attempt recovery
  await executeHook('agent-health-monitor', 'restart my-service');
}
```

## Testing Your Integration

```bash
# Start your agent
npm start

# Test REST API
curl http://localhost:PORT/api/hooks

# Execute a hook
curl -X POST http://localhost:PORT/api/hooks/slack \
  -H "Content-Type: application/json" \
  -d '{"params": {"channel": "general", "message": "Test"}}'

# Check status
curl http://localhost:PORT/api/status
```

## Common Issues

| Issue | Solution |
|-------|----------|
| Hook not found | Check spelling, use `GET /api/hooks` to list |
| Timeout | Increase timeout parameter |
| Permission denied | `chmod +x /root/DW-MCP/DW-Hooks/*.js` |
| Module not found | `cd /root/DW-MCP && npm install` |

## Integration Checklist

- [ ] Import module: `import { setupHooksAPI } from '../shared-hooks-api';`
- [ ] Add Express middleware: `app.use(express.json());`
- [ ] Setup API: `setupHooksAPI(app);`
- [ ] Test: `curl http://localhost:PORT/api/hooks`
- [ ] Add to routes: Use `hooks.*` or `executeHook()`
- [ ] Add error handling: Use `hooks.errors.notify()`

## Files

- **Module**: `/root/DW-Agents/shared-hooks-api.ts`
- **Full Guide**: `/root/DW-Agents/HOOKS-API-INTEGRATION-GUIDE.md`
- **Example Agent**: `/root/DW-Agents/example-agent-with-hooks.ts`
- **Hooks Docs**: `/root/DW-MCP/DW-Hooks/README.md`

## Support

1. Read the full integration guide
2. Check the example agent
3. Test hooks directly: `node /root/DW-MCP/DW-Hooks/[hook]-hook.js`
4. Review DW-Hooks README for hook-specific docs

---

**Version:** 1.0.0 | **Updated:** 2025-11-12