agentleFS
wittyreferencewittyreference/twilio-claude-plugin/skills/agent-connect/SKILL.md

agent-connect

Skill2 starsChanged 8 months agoMITView on GitHub

Twilio development skill: agent-connect

  • Reads credentials
  • Installs packages

The file

We split this skill into the rules it gives an agent

7 rules. About 0 are common, 3 are distinctive, and 4 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.

  • 4

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Create and manage conversations automatically via Conversations Orchestrator

    line 28
  2. Distinctive:

    Write to Customer Memory via MemoryClient (observations, traits — added post-initial-docs)

    line 29
  3. Very specific:

    ngrok free plan URL changes on restart: Must update phone number webhook config each restart.

    line 179
  4. Very specific:

    SMS retrieves memory automatically per inbound message: No opt-out — if TWILIO_TAC_MEMORY_STORE_ID is set, every SMS triggers a Recall.

    line 186
  5. Very specific:

    TwiML <Redirect> causes double conversation creation: When a TwiML router returns <Redirect> to /twiml, Twilio makes two POST requests.

    line 192
  6. Very specific:

    createHandoffTool() requires destination configuration: Must pre-configure which queue/number/agent pool receives escalated calls.

    line 198
  7. Distinctive:

    Handoff context carries Memory profile: When handing off to a human agent, the profile ID and Recall context are available to the receiving …

    line 199

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

name: agent-connect description: Twilio Agent Connect (TAC) SDK development guide. Use when building LLM-powered voice/SMS agents with automatic Customer Memory retrieval and Conversations Orchestrator integration. Do NOT use for direct Conversations layer API calls (use /customer-memory, /conversations-v2, /conversational-intelligence instead). allowed-tools: mcp__twilio__*, Read, Grep, Glob, Bash

Twilio Agent Connect (TAC)

SDK middleware that orchestrates voice (ConversationRelay) and SMS (Conversations API) channels with automatic Customer Memory retrieval and Intelligence analysis. You bring the LLM; TAC handles channel I/O, session management, memory retrieval, and conversation tracking.

Generally available — TypeScript (Node 20+) and Python (3.9+). Not PCI/HIPAA compliant.

Evidence: Assertion audit sourced from TAC documentation (2026-03-25) + live integration testing. See references/assertion-audit.md for provenance. Note: assertions are DOC-VERIFIED, not SID-backed. Live testing recommended for production decisions.

Scope

CAN

  1. Orchestrate voice calls via ConversationRelay WebSocket — STT/TTS handled by Twilio
  2. Orchestrate SMS via Conversations API webhooks — message routing automated
  3. Retrieve Customer Memory (observations, summaries, communications) per message/utterance
  4. Provide unified callback: same handleMessageReady(userMessage, context, memoryResponse?) across channels
  5. Create and manage conversations automatically via Conversations Orchestrator
  6. Write to Customer Memory via MemoryClient (observations, traits — added post-initial-docs)
  7. Handoff to human agents via createHandoffTool() and onHandoff callback
  8. Support any LLM provider (OpenAI, Anthropic, Bedrock, LangChain)
  9. Active voice ingestion via TWILIO_TAC_ENABLE_VOICE_ACTIVE_HYDRATION=true

CANNOT

  1. No custom STT/TTS — Uses ConversationRelay defaults; cannot specify Deepgram, ElevenLabs, etc. For custom providers, use ConversationRelay directly.
  2. No raw audio access — WebSocket is abstracted; only transcribed text exposed. Use Media Streams if you need audio.
  3. No ConversationRelay protocol events — setup, interrupt, dtmf events are not passed through to your callback. Only transcribed speech arrives.
  4. No WhatsApp/Email/Chat channels — Only voice and SMS. For other channels, use the Conversations layer API directly (see Twilio Conversations documentation and the /conversations-v2 skill).
  5. No MCP tools — TAC SDK is not wrapped in the MCP server. Interact via the SDK directly in your application code.
  6. No mid-conversation provider switch — Cannot change LLM or TTS mid-call through TAC.
  7. Voice memory auto-retrieval is broken — TWILIO_TAC_ENABLE_VOICE_ACTIVE_HYDRATION is documented but has a known bug where context returns undefined. Use manual Recall via Customer Memory API at call setup instead.

Quick Decision

NeedUseWhy
LLM agent with voice + SMS + auto memoryAgent ConnectPurpose-built SDK, unified callback
LLM voice agent with custom STT/TTSConversationRelay directlyTAC doesn't expose provider config
LLM agent with WhatsApp/Email/ChatConversations API directlyTAC only supports voice + SMS
Simple IVR without LLMTwiML <Gather>No LLM needed
Memory retrieval without TAC orchestrationCustomer Memory APIDirect REST calls, full control
Agent assist during human callsIntelligence v3 webhooksTAC is for AI-first agents, not human assist

Decision Frameworks

TAC SDK vs Direct API

CriterionTAC SDKDirect Conversations API
Setup effortLow — npm install + env varsHigh — implement WebSocket handler, webhook routing, Memory calls manually
Channel supportVoice + SMS onlyAll 6 channels (SMS, Voice, WhatsApp, RCS, Chat, Email)
Memory controlAutomatic retrieval, configurable limitsFull control — choose when/what to Recall
Provider configNo control (TAC defaults)Full control — choose STT/TTS/model
Context budgetTAC defaults (obs:10, sum:5, session:3)You set limits per Recall call
HandoffBuilt-in createHandoffTool()Implement yourself (add HUMAN_AGENT participant)
IntelligenceAutomatic via Conversations configSame — linked at config level
Best forQuick prototypes, standard voice/SMS agentsProduction systems needing full control

Context Budget Management

TAC passes full memory context to your LLM with no built-in truncation. Default limits:

ParameterTAC DefaultRecall API DefaultRecommendation
observation_limit1020Keep TAC default for voice (latency)
summary_limit55Sufficient for most agents
session_limit3N/A (TAC-only)Increase for long customer histories
queryNone (fast path)NoneAdd semantic query for focused retrieval

Estimated token impact (per turn):

ScenarioObservationsSummariesEst. Tokens% of 128K
First-time caller00~100<0.1%
Returning customer102~2,000-3,000~2%
Long-term customer (full limits)105~3,000-5,000~3%

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     Your Application                         │
│  ┌─────────────┐  ┌──────────────────────────────────────┐  │
│  │  Your LLM   │  │  handleMessageReady() callback       │  │
│  │  (OpenAI,   │◄─┤  - userMessage: string               │  │
│  │  Anthropic, │  │  - context: ConversationSession       │  │
│  │  Bedrock)   │  │  - memoryResponse?: MemoryResponse    │  │
│  └──────┬──────┘  └──────────────────┬───────────────────┘  │
│         │ response                   │                       │
│         ▼                            │                       │
│  voiceChannel.sendResponse()    smsChannel.sendResponse()   │
└─────────┼─────────────────────────────────────────┼─────────┘
          │                                         │
          ▼                                         ▼
  ┌───────────────┐  ┌──────────────┐  ┌───────────────────┐
  │ Twilio Voice  │  │   Twilio     │  │  Twilio Customer  │
  │ Conversation  │  │ Conversations│  │  Memory Service   │
  │ Relay (WSS)   │  │  API (HTTP)  │  │  (HTTP)           │
  └───────────────┘  └──────────────┘  └───────────────────┘

Setup

Prerequisites

  • Node 20+ (TypeScript) or Python 3.9+
  • Twilio Account SID + Auth Token (or API Key + Secret)
  • Phone number with voice webhook → your server /twiml
  • Conversations Configuration with phone number assigned for SMS → webhook /webhook
  • ngrok or public URL for webhook delivery
  • (Optional) Customer Memory Store ID for memory features

TypeScript Quickstart

npm install twilio-agent-connect
import { AgentConnect, VoiceChannel, SMSChannel } from 'twilio-agent-connect';

const agent = new AgentConnect({
  accountSid: process.env.TWILIO_ACCOUNT_SID,
  authToken: process.env.TWILIO_AUTH_TOKEN,
  memoryStoreId: process.env.TWILIO_TAC_MEMORY_STORE_ID, // Optional
});

const voiceChannel = new VoiceChannel(agent);
const smsChannel = new SMSChannel(agent);

async function handleMessageReady(
  userMessage: string,
  context: ConversationSession,
  memoryResponse?: MemoryRetrievalResponse,
): Promise<void> {
  // Your LLM logic here
  const response = await myLLM.chat(userMessage, {
    systemPrompt: buildPrompt(memoryResponse),
  });

  if (context.channel === 'voice') {
    voiceChannel.sendResponse(context.conversationId, response);
  } else {
    smsChannel.sendResponse(context.conversationId, response);
  }
}

// Voice: /twiml endpoint returns <Connect><ConversationRelay> TwiML
// SMS: /webhook endpoint receives Conversations API webhooks

Environment Variables

VariableRequiredDescription
TWILIO_ACCOUNT_SIDYesAccount SID
TWILIO_AUTH_TOKENYesAuth Token (or use API Key)
TWILIO_TAC_MEMORY_STORE_IDNoMemory Store ID for auto-retrieval
TWILIO_TAC_ENABLE_VOICE_ACTIVE_HYDRATIONNotrue to enable voice memory (buggy — see gotcha #6)
ENVIRONMENTNoMust be prod or omitted. dev breaks DNS resolution.

Gotchas

Environment & Setup

  1. ENVIRONMENT must be prod or omitted: TAC SDK reads this env var and constructs hostnames like conversations.dev-us1.twilio.com which don't resolve. Always use prod. [conversations-invariants.md]
  2. Swapping /webhook and /twiml paths produces silent failures: Voice expects ConversationRelay TwiML at /twiml; SMS expects webhook POST at /webhook. Swapping them results in no errors but no functionality.
  3. ngrok free plan URL changes on restart: Must update phone number webhook config each restart. Use ngrok http 8000 --url=your-static-domain for stable URLs (requires paid plan).
  4. Verify ngrok tunnel before debugging: A dead tunnel returns HTML 404 that mimics server 404. Verify: curl -s -o /dev/null -w "%{http_code}" -X POST https://DOMAIN/health must return 200. [conversations-invariants.md]

Memory & Context

  1. Memory retrieval is all-or-nothing per the default config: TAC retrieves observations + summaries + communications in one call. Configure limits via env vars or SDK options.
  2. Voice memory auto-retrieval is broken: TWILIO_TAC_ENABLE_VOICE_ACTIVE_HYDRATION=true documented but returns undefined for memory context. Workaround: Call Customer Memory Recall API manually during WebSocket setup event.
  3. SMS retrieves memory automatically per inbound message: No opt-out — if TWILIO_TAC_MEMORY_STORE_ID is set, every SMS triggers a Recall. Budget accordingly.
  4. TAC defaults: obs=10, sum=5, session=3: Lower than direct Recall API defaults (obs=20, sum=5, comms=0). For richer context, use direct API instead.
  5. No query parameter in TAC memory retrieval: TAC uses fast-path Recall (~37ms, no semantic search). For semantic Recall, bypass TAC and call the API directly.

Voice Channel

  1. TwiML <Redirect> causes double conversation creation: When a TwiML router returns <Redirect> to /twiml, Twilio makes two POST requests. Both hit TAC and each creates a conversation (409 Conflict on second). Serve ConversationRelay TwiML directly from the router instead. [conversations-invariants.md]
  2. ConversationRelay gotchas apply to TAC voice: TAC uses CR under the hood — interruption handling, DTMF detection, and TTS behavior all follow CR rules. See ConversationRelay skill for details.
  3. No intermediate STT confidence scores: TAC only exposes final transcribed text, not partial results or confidence levels.

Handoff

  1. createHandoffTool() requires destination configuration: Must pre-configure which queue/number/agent pool receives escalated calls.
  2. Handoff context carries Memory profile: When handing off to a human agent, the profile ID and Recall context are available to the receiving agent via the Conversations API.

Integration Patterns

Manual Memory Retrieval (Voice — Workaround for Gotcha #6)

// Since TAC voice auto-retrieval is broken, manually fetch at call setup
import { recallMemory, resolveCustomer } from './conversations-client';

voiceChannel.onSetup(async (callSid, from) => {
  const profileId = await lookupProfile(config, 'phone', from);
  if (profileId) {
    const memory = await recallMemory(config, profileId);
    // Store in session state for use in handleMessageReady
    sessions.set(callSid, { memory });
  }
});

Direct Conversations API for Extra Channels

For WhatsApp, Email, Chat — TAC doesn't support these, but you can build the same pattern using the Conversations layer directly. See the Twilio Conversations documentation and the /conversations-v2 skill for the full API surface needed (profile lookup, Recall, and communication injection across all 6 channel types).

LLM Provider Selection

TAC is LLM-agnostic — you bring your own model via the handleMessageReady() callback. The demos in this project support configurable LLM endpoints.

Decision Tree

ScenarioProviderConfig
Default / fastest setupAnthropicNo env changes needed
Customer requires Azure deployment (BAA)Azure OpenAILLM_PROVIDER=openai-compatible, LLM_BASE_URL=https://...azure.com/...
Air-gapped / on-premvLLM or OllamaLLM_PROVIDER=openai-compatible, LLM_BASE_URL=http://internal:8000/v1
Local development (zero cost)OllamaLLM_PROVIDER=openai-compatible, LLM_BASE_URL=http://localhost:11434/v1

Environment Variables

Set LLM_PROVIDER=openai-compatible plus LLM_BASE_URL, LLM_API_KEY, and LLM_MODEL to target any OpenAI-compatible endpoint. See the ConversationRelay skill for the full env var reference and example configurations.

Implementation

A shared LLM client pattern can provide streaming and non-streaming functions for both Anthropic and OpenAI-compatible endpoints, then be imported by both voice (ConversationRelay WebSocket handler) and SMS (Conversations webhook handler) for unified message processing across channels.

Related Resources

  • /conversationrelay skill — Voice AI WebSocket protocol details
  • /customer-memory skill — Memory API deep dive
  • /conversations-v2 skill — Conversation Orchestrator integration
  • /conversational-intelligence skill — Real-time analysis on top of conversations
  • Twilio Agent Connect docs
  • twilio-agent-connect npm package

Reference Files

TopicFileWhen to read
Architecture & callbacksreferences/architecture-and-callbacks.mdUnderstanding TAC internals, ConversationSession fields, channel lifecycles
Assertion auditreferences/assertion-audit.mdVerifying claim provenance (DOC-VERIFIED, not live-tested)

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.