src — automation

Module: src-automation Cohesion: 0.80 Members: 0

src — automation

The src/automation module provides foundational capabilities for an intelligent agent to interact with its environment through scheduled tasks, event-driven triggers, and continuous monitoring. It encapsulates three core automation patterns:

  1. Authentication Monitoring (AuthMonitor): Ensures the agent's access to external services remains valid and alerts to impending expirations or issues.
  2. Gmail Trigger (GmailTrigger): Enables the agent to react in real-time to new emails, acting as an event source for agent workflows.
  3. Polling (PollManager): Allows the agent to periodically fetch and detect changes in data from various external sources (URLs, files, commands).

This module is critical for maintaining the agent's operational readiness, responsiveness, and awareness of external state changes.


1. Authentication Monitoring (AuthMonitor)

The AuthMonitor class is responsible for tracking the authentication status of various external services and channels the agent interacts with. It helps prevent operational disruptions by proactively identifying expired or invalid credentials.

Purpose

To provide a centralized, continuous monitoring system for authentication tokens and API keys, emitting events when their status changes (e.g., expiring, expired, invalid).

Key Concepts

How it Works

The AuthMonitor operates as a singleton, ensuring a single point of truth for authentication status.

  1. Initialization:

  1. Target Management:

  1. Monitoring Lifecycle:

  1. Reporting:

Events

The AuthMonitor extends EventEmitter and emits the following event:

Example Usage

import { AuthMonitor } from './auth-monitoring.js';

const monitor = AuthMonitor.getInstance({
  checkIntervalMs: 60_000, class="hl-cmt">// Check every minute
  expiryWarningMs: 2 * 24 * 60 * 60 * 1000, class="hl-cmt">// Warn 2 days before expiry
});

monitor.addTarget({
  id: 'my-custom-api',
  name: 'My Custom API',
  type: 'provider',
  envVar: 'MY_CUSTOM_API_KEY',
  expiresAt: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), class="hl-cmt">// Expires in 3 days
  state: 'unknown',
});

monitor.on('auth:changed', (event) => {
  console.log(`Auth Event: [${event.target.name}] changed from ${event.previousState} to ${event.newState}. Message: ${event.message}`);
  if (event.newState === 'expired' || event.newState === 'invalid') {
    console.error(`Action required: ${event.message}`);
    class="hl-cmt">// Trigger an alert or automated refresh
  }
});

monitor.start();

2. Gmail Trigger (GmailTrigger)

The GmailTrigger class provides an event-driven mechanism for the agent to react to new emails in a Gmail inbox. It leverages Google Cloud Pub/Sub and the GmailWebhookAdapter to receive real-time notifications.

Purpose

To act as a trigger source, waking or notifying the agent when new emails arrive that match configured filters, and generating a relevant prompt for the agent.

Key Concepts

How it Works

The GmailTrigger wraps the GmailWebhookAdapter (from src/channels/niche-channels.js) to manage the underlying Gmail API interactions and Pub/Sub subscription.

  1. Initialization:

  1. Starting the Trigger:

  1. Webhook Handling:

  1. Message Processing:

  1. Stopping the Trigger:

  1. Status:

Events

The GmailTrigger extends EventEmitter and emits the following event:

Architecture Diagram

graph TD
    A[External Webhook Endpoint] --> B{handleWebhook(body)}
    B --> C{GmailWebhookAdapter.handlePubSubNotification(data)}
    C -- New Message --> D{GmailWebhookAdapter.onNewMessage(msg)}
    D --> E{handleNewMessage(msg)}
    E -- Deduplicate & Prompt --> F[Emit 'trigger' event]
    F --> G[Agent Workflow]
    H[GmailTrigger.start()] --> I{GmailWebhookAdapter.start()}
    H --> J{GmailWebhookAdapter.setupWatch()}
    J -- Periodically --> J

Integration Points


3. Polling (PollManager)

The PollManager class provides a flexible and robust system for periodically fetching data from various external sources and detecting changes.

Purpose

To enable the agent to monitor external data sources (URLs, files, command outputs) at configurable intervals, triggering events when data changes or is retrieved.

Key Concepts

How it Works

The PollManager operates as a singleton, managing multiple independent polls.

  1. Initialization:

  1. Poll Management:

  1. Polling Lifecycle:

  1. Results:

Events

The PollManager extends EventEmitter and emits the following events:

Example Usage

import { PollManager } from './polls.js';

const pollManager = PollManager.getInstance();

pollManager.addPoll({
  id: 'github-status',
  name: 'GitHub Status API',
  type: 'url',
  target: 'https:class="hl-cmt">//www.githubstatus.com/api/v2/status.json',
  intervalMs: 30_000, class="hl-cmt">// Every 30 seconds
  enabled: true,
  onChangeOnly: true,
});

pollManager.addPoll({
  id: 'local-log-file',
  name: 'Local Log File',
  type: 'file',
  target: '/var/log/agent.log',
  intervalMs: 5_000, class="hl-cmt">// Every 5 seconds
  enabled: true,
  onChangeOnly: true,
});

pollManager.on('poll:changed', (result) => {
  console.log(`Poll [${result.pollId}] changed! New data:`, result.data);
  class="hl-cmt">// Agent can analyze the change and take action
});

pollManager.on('poll:failed', ({ pollId, error, retries }) => {
  console.error(`Poll [${pollId}] failed after ${retries} attempts: ${error}. Stopping poll.`);
});

class="hl-cmt">// To stop a specific poll:
class="hl-cmt">// pollManager.stopPoll('github-status');

class="hl-cmt">// To stop all polls:
class="hl-cmt">// pollManager.stopAll();

Integration Points


Conclusion

The src/automation module provides essential infrastructure for building reactive and robust agent systems. By offering capabilities for authentication monitoring, event-driven email processing, and flexible data polling, it empowers the agent to maintain operational integrity, respond to critical external events, and stay informed about its environment. Developers contributing to the agent's core functionality or extending its interaction capabilities will frequently interact with these components.