agentleFS
wittyreferencewittyreference/twilio-claude-plugin/skills/sync-reference/SKILL.md

sync-reference

Skill2 starsChanged 8 months agoMITView on GitHub

Twilio development skill: sync-reference

The file

We split this skill into the rules it gives an agent

3 rules. About 0 are common, 3 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈3

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    All Sync objects support automatic expiration:

    line 127
  2. Distinctive:

    Use Streams for ephemeral events:

    line 292
  3. Distinctive:

    Create a Sync Service in the Twilio Console or via CLI:

    line 391

≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md
<!-- ABOUTME: Complete reference for Twilio Sync API patterns, code samples, and error handling. --><!-- ABOUTME: Companion to CLAUDE.md — contains detailed examples, common patterns, and testing guidance. -->

Sync Reference

For essential patterns and quick reference, see CLAUDE.md.

API Examples

Documents

Single JSON objects (up to 16KB). Ideal for configuration, settings, or simple state.

// Create document
const doc = await syncService.documents.create({
  uniqueName: 'app-config',
  data: { theme: 'dark', version: '1.0' },
  ttl: 86400  // Optional: auto-delete after 24 hours
});

// Fetch document
const doc = await syncService.documents('app-config').fetch();
console.log(doc.data);  // { theme: 'dark', version: '1.0' }

// Update document (full replace)
await syncService.documents('app-config').update({
  data: { theme: 'light', version: '1.1' }
});

// Delete document
await syncService.documents('app-config').remove();

Lists

Ordered collections with automatic indexing. Ideal for message history, activity feeds.

// Create list
const list = await syncService.syncLists.create({
  uniqueName: 'chat-messages'
});

// Add item to list
const item = await syncService.syncLists('chat-messages')
  .syncListItems.create({
    data: { sender: 'user123', text: 'Hello!' }
  });
console.log(item.index);  // Auto-assigned index

// Fetch items (paginated)
const items = await syncService.syncLists('chat-messages')
  .syncListItems.list({ limit: 20, order: 'desc' });

// Update item by index
await syncService.syncLists('chat-messages')
  .syncListItems(0).update({
    data: { sender: 'user123', text: 'Hello! (edited)' }
  });

// Delete item
await syncService.syncLists('chat-messages')
  .syncListItems(0).remove();

Maps

Key-value stores for flexible lookups. Ideal for user sessions, device states.

// Create map
const map = await syncService.syncMaps.create({
  uniqueName: 'user-sessions'
});

// Set item by key
await syncService.syncMaps('user-sessions')
  .syncMapItems.create({
    key: 'user-123',
    data: { lastSeen: new Date().toISOString(), status: 'online' }
  });

// Get item by key
const item = await syncService.syncMaps('user-sessions')
  .syncMapItems('user-123').fetch();

// Update item
await syncService.syncMaps('user-sessions')
  .syncMapItems('user-123').update({
    data: { lastSeen: new Date().toISOString(), status: 'away' }
  });

// Delete item
await syncService.syncMaps('user-sessions')
  .syncMapItems('user-123').remove();

// List all items
const items = await syncService.syncMaps('user-sessions')
  .syncMapItems.list({ limit: 100 });

Streams

Pub/sub messaging for ephemeral events. Messages are not persisted.

// Create stream
const stream = await syncService.syncStreams.create({
  uniqueName: 'typing-indicators'
});

// Publish message to stream
await syncService.syncStreams('typing-indicators')
  .streamMessages.create({
    data: { userId: 'user-123', typing: true }
  });

TTL (Time-To-Live)

All Sync objects support automatic expiration:

// Document with 1-hour TTL
await syncService.documents.create({
  uniqueName: 'temp-session',
  data: { token: 'abc123' },
  ttl: 3600  // Seconds until auto-delete
});

// List item with TTL
await syncService.syncLists('my-list')
  .syncListItems.create({
    data: { message: 'Temporary' },
    ttl: 300  // Item expires in 5 minutes
  });

Webhook Events

Configure webhooks on your Sync Service to receive notifications:

Event TypeDescription
document_createdNew document created
document_updatedDocument data changed
document_removedDocument deleted
list_item_createdItem added to list
list_item_updatedList item changed
list_item_removedItem removed from list
map_item_createdMap item created
map_item_updatedMap item changed
map_item_removedMap item removed
stream_message_publishedMessage published to stream

Webhook Parameters

ParameterDescription
AccountSidYour Twilio Account SID
ServiceSidSync Service SID
EventTypeEvent type (see above)
ResourceSidSID of affected resource
UniqueNameUnique name if set
DateCreatedISO timestamp
DataJSON data (for create/update events)

Common Patterns

Call State Management

Track multi-step call state across webhooks:

// Store call state
exports.storeCallState = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  await syncService.documents.create({
    uniqueName: `call-${event.CallSid}`,
    data: {
      stage: 'greeting',
      selections: [],
      startTime: new Date().toISOString()
    },
    ttl: 3600  // Clean up after 1 hour
  });

  return callback(null, { success: true });
};

// Retrieve and update call state
exports.getCallState = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  const doc = await syncService.documents(`call-${event.CallSid}`).fetch();
  const callState = doc.data;

  // Update state
  await syncService.documents(`call-${event.CallSid}`).update({
    data: {
      ...callState,
      stage: 'menu',
      selections: [...callState.selections, event.Digits]
    }
  });

  return callback(null, callState);
};

User Presence

Track online/offline status across devices:

// presence.protected.js
exports.handler = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  const { userId, status } = event;

  await syncService.syncMaps('user-presence')
    .syncMapItems.create({
      key: userId,
      data: {
        status: status,  // 'online', 'away', 'offline'
        lastSeen: new Date().toISOString(),
        device: event.device || 'unknown'
      },
      ttl: 300  // Auto-offline after 5 minutes if no heartbeat
    });

  return callback(null, { success: true });
};

Activity Feed

Maintain an ordered list of events:

// Add activity
exports.addActivity = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  const { userId, action, details } = event;

  await syncService.syncLists('activity-feed')
    .syncListItems.create({
      data: {
        userId,
        action,
        details,
        timestamp: new Date().toISOString()
      },
      ttl: 604800  // Keep for 7 days
    });

  return callback(null, { success: true });
};

// Get recent activity
exports.getActivity = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  const items = await syncService.syncLists('activity-feed')
    .syncListItems.list({
      limit: event.limit || 20,
      order: 'desc'
    });

  return callback(null, {
    activities: items.map(item => item.data)
  });
};

Real-time Notifications

Use Streams for ephemeral events:

// Publish typing indicator
exports.publishTyping = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  await syncService.syncStreams('room-events')
    .streamMessages.create({
      data: {
        type: 'typing',
        userId: event.userId,
        roomId: event.roomId,
        isTyping: event.isTyping
      }
    });

  return callback(null, { success: true });
};

Error Handling

Common Error Codes

<!-- verified: live-tested 2026-03-25. See skills/sync/references/error-codes.md for full evidence. -->
CodeHTTPDescription
20404404Resource not found (documents, lists, maps, items — all use this generic code)
54006413Request entity too large (data >16KB, or Stream message >4KB)
54008400Invalid request body / invalid JSON in Data parameter
54103412Revision mismatch on conditional update (If-Match header)
54208409Map item key already exists (add is not upsert)
54301409Unique name already exists

Error Handling Pattern

exports.handler = async (context, event, callback) => {
  const client = context.getTwilioClient();
  const syncService = client.sync.v1.services(context.TWILIO_SYNC_SERVICE_SID);

  try {
    const doc = await syncService.documents(event.docName).fetch();
    return callback(null, { success: true, data: doc.data });
  } catch (error) {
    if (error.status === 404) {
      // All not-found errors return HTTP 404 (code 20404)
      const newDoc = await syncService.documents.create({
        uniqueName: event.docName,
        data: { initialized: true }
      });
      return callback(null, { success: true, data: newDoc.data, created: true });
    }
    if (error.code === 54301) {
      // Already exists (race condition) - fetch it
      const doc = await syncService.documents(event.docName).fetch();
      return callback(null, { success: true, data: doc.data });
    }
    throw error;
  }
};

Testing Sync Functions

Integration Test Pattern

describe('Sync Operations', () => {
  const testDocName = `test-doc-${Date.now()}`;

  afterAll(async () => {
    // Cleanup
    try {
      await syncService.documents(testDocName).remove();
    } catch (e) { /* ignore */ }
  });

  it('should create and fetch document', async () => {
    const context = createTestContext();
    const event = {
      docName: testDocName,
      data: { test: true }
    };

    await createDocHandler(context, event, callback);

    const [, response] = callback.mock.calls[0];
    expect(response.success).toBe(true);
    expect(response.data.test).toBe(true);
  });
});

Service Setup

Create a Sync Service in the Twilio Console or via CLI:

twilio api:sync:v1:services:create --friendly-name "My Sync Service"

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.