Mirra

Scripts

Scripts are serverless functions that run in isolated execution environments within the Mirra platform. Scripts execute in response to manual triggers, scheduled events, or real-time events from integrated services like Telegram, Gmail, and voice calls.


Syntax

Creating a Script

POST /api/sdk/v1/scripts

Node.js Handler

export async function handler(event, context) {
  // Process event data
  return { success: true, data: result };
}

Python Handler

async def handler(event, context):
    # Process event data
    return {"success": True, "data": result}

Description

Scripts provide serverless compute capabilities for automation, data processing, and integrations. Each script runs in an isolated execution environment with configurable memory, timeout, and cost controls. Scripts can be triggered manually via the SDK API, automatically by subscribing to events from integrated services, or on a schedule using assignments.

The Mirra platform supports two runtime environments: Node.js 18 with TypeScript support and Python 3.11 with modern async/await syntax. Both runtimes provide access to the Mirra SDK, which enables scripts to interact with user data, send messages, create calendar events, and call external APIs through Resources.

Scripts support version control, allowing developers to maintain multiple versions and deploy specific versions safely. Each deployment creates a new function deployment, enabling rollback and testing workflows.

Event-Driven Execution

Scripts automatically execute when subscribed events occur. The event subscription system supports complex filtering with field-level conditions, enabling precise control over when scripts run. For example, a script can execute only for Telegram messages containing ticker symbols, or only for calendar events with specific attendees.

// Script automatically executes for matching events
export async function handler(event, context) {
  // event contains normalized fields across all trigger types
  const message = event.messageText;
  const sender = event.senderName;
  const timestamp = event.timestamp;
  
  // Process the event
  await mirra.memory.create({
    type: 'event_log',
    content: `${sender}: ${message}`,
    metadata: { timestamp }
  });
  
  return { success: true };
}

Event subscriptions are created via the SDK API:

POST /api/sdk/v1/scripts/{scriptId}/subscriptions

See Event-Driven Scripts for complete documentation on available events, filtering conditions, and subscription management.

Runtime Environments

Node.js 18

The Node.js runtime provides TypeScript support, ES modules, and access to popular NPM packages. Scripts can import standard Node.js built-ins and common libraries like lodash, axios, and date-fns.

import { format } from 'date-fns';
 
export async function handler(event, context) {
  const timestamp = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
  console.log('Executed at:', timestamp);
  
  return {
    success: true,
    timestamp,
    data: event
  };
}

Python 3.11

The Python runtime provides modern Python syntax with type hints, async/await support, and access to popular pip packages including requests, pandas, and numpy.

from datetime import datetime
 
async def handler(event, context):
    timestamp = datetime.now().isoformat()
    print(f"Executed at: {timestamp}")
    
    return {
        "success": True,
        "timestamp": timestamp,
        "data": event
    }

Configuration Options

Scripts accept configuration parameters that control execution behavior, resource access, and cost limits:

runtime

Execution environment. Must be "nodejs18" or "python3.11". Default: "nodejs18".

timeout

Maximum execution time in seconds. Range: 1-300. Default: 30. Scripts exceeding this limit are terminated.

memory

Memory allocation in MB. Range: 128-3008. Default: 128. Higher memory allocation provides proportionally more CPU.

maxCostPerExecution

Maximum cost per execution in USD. Default: 1.0. Executions exceeding this limit fail with a cost limit error.

maxExecutionsPerDay

Maximum executions per 24-hour period. Default: 100. Scripts stop executing when this limit is reached until the next day.

allowedResources

Array of resource IDs the script can access. Empty array (default) denies all resource access. See Resources for details.

Version Control

Scripts maintain multiple versions, enabling safe deployments and rollbacks. Each version is immutable once created. Deployments reference a specific version number, creating a new function deployment with that version's code.

# Create a new version
POST /api/sdk/v1/scripts/{scriptId}/versions
 
# Deploy specific version
POST /api/sdk/v1/scripts/{scriptId}/deploy

Marketplace Publishing

Scripts can be published to the Mirra marketplace with free, pay-per-execution, or subscription pricing models. Published scripts appear in marketplace listings and can be installed by other users. The marketplace supports staff picks, trending sections, and user reviews.


Examples

Tracking Ticker Mentions

This example demonstrates event-driven execution with entity extraction. The script subscribes to Telegram messages and voice transcripts containing ticker symbols, then logs each mention to memory.

export async function handler(event, context) {
  // Check if event contains ticker entities
  if (!event.entities?.tickers) {
    return { success: true, message: 'No tickers found' };
  }
  
  // Log each ticker mention
  for (const ticker of event.entities.tickers) {
    await mirra.memory.create({
      type: 'ticker_mention',
      content: `${ticker.symbol} mentioned: ${event.messageText}`,
      metadata: {
        ticker: ticker.symbol,
        confidence: ticker.confidence,
        source: event.source,
        timestamp: event.timestamp
      }
    });
  }
  
  return {
    success: true,
    tickersTracked: event.entities.tickers.length
  };
}

Subscription configuration:

{
  "conditions": [
    {
      "field": "entities.tickers",
      "operator": "exists"
    }
  ]
}

Telegram Auto-Responder

This example shows basic message handling and response. The script receives Telegram messages and sends an acknowledgment reply.

export async function handler(event, context) {
  // Verify event type
  if (event.type !== 'telegram.message') {
    return { success: false, error: 'Not a Telegram message' };
  }
  
  // Send response
  await mirra.telegram.sendMessage({
    chatId: event.telegramChatId,
    text: `Received: ${event.messageText}`
  });
  
  return { success: true };
}

Calendar Event Logger

This example demonstrates calendar integration. The script logs new calendar events to memory with structured metadata.

export async function handler(event, context) {
  // Verify event type
  if (event.type !== 'calendar.event_created') {
    return { success: false, error: 'Not a calendar event' };
  }
  
  // Create memory entry
  await mirra.memory.create({
    type: 'calendar_event',
    content: event.calendarSummary,
    metadata: {
      eventId: event.calendarEventId,
      startTime: event.calendarStartTime,
      endTime: event.calendarEndTime,
      location: event.calendarLocation,
      attendees: event.calendarAttendees
    }
  });
  
  return { success: true };
}

Data Processing Pipeline

This example shows manual script execution for data transformation. The script processes an array of items, adding timestamps and processing flags.

export async function handler(event, context) {
  // Validate input
  if (!event.data || !Array.isArray(event.data)) {
    return { success: false, error: 'Invalid input: expected data array' };
  }
  
  // Process each item
  const result = event.data.map(item => ({
    ...item,
    processed: true,
    processedAt: new Date().toISOString(),
    processedBy: context.scriptId
  }));
  
  return {
    success: true,
    itemsProcessed: result.length,
    result
  };
}

Use Cases

Scripts enable automation across multiple domains:

Automation

  • Auto-respond to Telegram messages based on content or sender
  • Create calendar reminders before events
  • Log call summaries and transcripts to external systems
  • Track ticker mentions across all communication channels

Data Processing

  • Transform and validate incoming data
  • Aggregate information from multiple sources
  • Generate periodic reports
  • Sync data between Mirra and external systems

Integrations

  • Connect external APIs through Resources
  • Process webhooks from third-party services
  • Trigger workflows based on events
  • Send notifications to multiple channels

See Also

On this page