agentleFS
wittyreferencewittyreference/twilio-claude-plugin/skills/callbacks/SKILL.md

callbacks

Skill2 starsChanged 8 months agoMITView on GitHub

Twilio development skill: callbacks

The file

We split this skill into the rules it gives an agent

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

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    All callbacks are logged to Sync Documents with the naming convention:

    line 38
  2. Distinctive:

    All Sync documents have a 24-hour TTL.

    line 136
  3. Very specific:

    Pattern: Use console.log for all logging in Twilio Functions, including error conditions and catch blocks.

    line 148
  4. Very specific:

    Response bodies: Always pass a string to Twilio.Response.setBody(), not a plain object.

    line 150
  5. Very specific:

    All functions use .protected.js suffix, requiring valid Twilio request signatures.

    line 173
  6. Distinctive:

    Deduplication pattern: Use the resource SID + status as a composite idempotency key:

    line 183
  7. Distinctive:

    Check for the key's existence before processing.

    line 188

≈ “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

Callbacks Functions

Service: prototype-core (CORE_BASE_URL). Deploy: ./scripts/deploy-services.sh dev

This directory contains Twilio Functions that handle status callbacks from various Twilio services. All callbacks are logged to Twilio Sync for deep validation during testing.

Purpose

These functions enable deep validation of Twilio API operations. Instead of just checking for a 200 OK from the API, we can verify:

  1. The actual status callbacks Twilio sends
  2. Whether errors occurred during processing
  3. The progression of status changes over time

Functions

FunctionTriggerPurpose
message-status.protected.jsMessage StatusCallbackLogs SMS/MMS delivery status
call-status.protected.jsCall StatusCallbackLogs voice call status changes
task-status.protected.jsTaskRouter EventCallbackLogs task and worker events
verification-status.protected.jsVerify webhookLogs verification status
fallback.protected.jsAny FallbackUrlCatches primary webhook failures
pizza-order-status.protected.jsRecordingStatusCallbackTriggers transcription, stores pizza order in Sync, sends SMS confirmation
conference-health-monitor.protected.jsConference StatusCallbackMonitors conference participant events to detect orphaned participants (SUV-003)
event-stream.jsEvent Streams webhookReceives CloudEvents from Twilio Event Streams; stores in Sync List for inspection
recording-test-status.protected.jsRecordingStatusCallbackCaptures full recording callback payloads to Sync for cross-method validation
transcript-validation-status.protected.jsVoice Intelligence webhookCaptures transcript completion and operator results to Sync for validation
transcription-status.protected.jsTranscriptionStatusCallbackLogs real-time transcription events (started, content, stopped, error) to Sync

Sync Schema

All callbacks are logged to Sync Documents with the naming convention:

callbacks-{resourceType}-{resourceSid}

Example: callbacks-message-SMxxxxxxxxxxxxxx

Document structure:

{
  "resourceSid": "SMxxxxxxxxxxxxxx",
  "resourceType": "message",
  "callbacks": [
    {
      "timestamp": "2026-01-22T10:30:00.000Z",
      "status": "queued",
      "errorCode": null,
      "errorMessage": null,
      "rawPayload": { ... }
    },
    {
      "timestamp": "2026-01-22T10:30:01.000Z",
      "status": "sent",
      "errorCode": null,
      "errorMessage": null,
      "rawPayload": { ... }
    },
    {
      "timestamp": "2026-01-22T10:30:05.000Z",
      "status": "delivered",
      "errorCode": null,
      "errorMessage": null,
      "rawPayload": { ... }
    }
  ],
  "latestStatus": "delivered",
  "latestTimestamp": "2026-01-22T10:30:05.000Z",
  "errorCount": 0,
  "callbackCount": 3
}

Configuration

These functions require the following environment variables:

VariableRequiredDescription
TWILIO_SYNC_SERVICE_SIDYesSync Service for storing callback data

Deployment

These functions are auto-deployed during setup via:

npx twilio-feature-factory setup

Or manually:

./scripts/deploy-services.sh dev

Deep Validation Usage

The deep validator fetches callback data from Sync to verify:

// In deep-validator.ts
async function checkSyncCallbacks(resourceSid: string): Promise<CheckResult> {
  const doc = await getCallbackData(context, 'message', resourceSid);

  if (!doc) {
    return { passed: false, message: 'No callback data received' };
  }

  if (doc.errorCount > 0) {
    return { passed: false, message: `${doc.errorCount} errors in callbacks` };
  }

  return { passed: true, message: `Received ${doc.callbackCount} callbacks` };
}

Fallback Handler

The fallback handler is special:

  1. It catches failures from ANY primary webhook
  2. Returns safe TwiML for voice calls (prevents hang-ups)
  3. Logs prominently so failures are visible
  4. Any fallback invocation is a test failure (primary should work)

TTL

All Sync documents have a 24-hour TTL. Callback data is ephemeral and only needed during test validation. Old data automatically expires.

Logging Rules (Twilio Functions Alert Behavior)

Twilio Functions generate debugger alerts based on log level:

Log LevelAlert CodeEffect
console.logNoneSilent — use for all operational logging
console.warn82004Generates warning alert — avoid in callbacks
console.error82005Generates error alert — never use in Twilio Functions

Pattern: Use console.log for all logging in Twilio Functions, including error conditions and catch blocks. console.error() and console.warn() generate debugger alerts (82005/82004) that pollute monitoring and mask real issues. There is no legitimate reason to use them in serverless functions.

Response bodies: Always pass a string to Twilio.Response.setBody(), not a plain object. Use JSON.stringify() and set Content-Type: application/json. Passing an object causes Buffer.from(object) TypeError in the runtime.

// WRONG — triggers Buffer TypeError
response.setBody({ success: true });

// RIGHT — explicit JSON serialization
response.appendHeader('Content-Type', 'application/json');
response.setBody(JSON.stringify({ success: true }));

Debugging Callbacks

Two-bug masking: Multiple independent root causes can produce the same debugger alert code. When an error persists after a fix, check whether a second cause is generating the same code. For example, 82005 alerts can come from both a setBody(object) crash AND stray console.error() calls — fixing one doesn't silence the other.

Interpreting responseBody in debugger alerts:

  • responseBody: null → the function crashed before writing a response. Look for runtime errors (TypeError, missing modules, unhandled rejections).
  • responseBody with valid data → the function completed successfully, but something else triggered the alert (e.g., stray console.error or console.warn calls). Look at log statements, not execution flow.

This distinction narrows root cause investigation significantly.

Security

All functions use .protected.js suffix, requiring valid Twilio request signatures. This prevents:

  • Spoofed callback data
  • External access to callback endpoints
  • Invalid test data pollution

Idempotency

Twilio delivers status callbacks at-least-once. On timeout or error, callbacks are retried, which can cause duplicate processing (e.g., sending the same follow-up SMS twice, logging the same recording twice).

Deduplication pattern: Use the resource SID + status as a composite idempotency key:

  • Voice callbacks: {CallSid}-{CallStatus} (e.g., CA123-completed)
  • Recording callbacks: {RecordingSid}-{RecordingStatus} (e.g., RE456-completed)
  • Transcription callbacks: {TranscriptionSid}-{TranscriptionStatus}

Check for the key's existence before processing. A Sync Map with a short TTL (300s) works well for deduplication without requiring cleanup.

See operational-reference.md → "Status Callback Resilience" for scaling patterns, traffic math, and the thin-receiver architecture.

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.