intercom-sdk-patterns
Apply production-ready intercom-client SDK patterns for TypeScript. Use when implementing Intercom integrations, refactoring SDK usage, or establishing team coding standards for Intercom API calls. Trigger with phrases like "intercom SDK patterns", "intercom best practices", "intercom code patterns", "idiomatic intercom", "intercom typescript".
What this skill does
# Intercom SDK Patterns
## Overview
Production-ready patterns for the `intercom-client` TypeScript SDK covering client initialization, pagination, error handling, and type safety.
## Prerequisites
- `intercom-client` package installed
- TypeScript 5.0+ project
- Familiarity with async/await and generators
## Instructions
### Step 1: Type-Safe Client Wrapper
```typescript
// src/intercom/client.ts
import { IntercomClient } from "intercom-client";
import { Intercom } from "intercom-client";
let instance: IntercomClient | null = null;
export function getClient(): IntercomClient {
if (!instance) {
instance = new IntercomClient({
token: process.env.INTERCOM_ACCESS_TOKEN!,
});
}
return instance;
}
// Type-safe contact creation helper
export async function createContact(
params: Intercom.CreateContactRequest
): Promise<Intercom.Contact> {
return getClient().contacts.create(params);
}
// Type-safe search helper
export async function searchContacts(
query: Intercom.SearchRequest
): Promise<Intercom.ContactList> {
return getClient().contacts.search(query);
}
```
### Step 2: Cursor-Based Pagination
Intercom uses cursor-based pagination. The `starting_after` parameter points to the next page.
```typescript
// Generic paginator for any list endpoint
async function* paginateContacts(
client: IntercomClient,
perPage = 50
): AsyncGenerator<Intercom.Contact> {
let startingAfter: string | undefined;
do {
const page = await client.contacts.list({
perPage,
startingAfter,
});
for (const contact of page.data) {
yield contact;
}
// Cursor for next page
startingAfter = page.pages?.next?.startingAfter ?? undefined;
} while (startingAfter);
}
// Usage
const client = getClient();
for await (const contact of paginateContacts(client)) {
console.log(contact.email);
}
```
The SDK also supports built-in iteration:
```typescript
// SDK auto-pagination (articles, contacts, etc.)
const response = await client.articles.list();
for await (const article of response) {
console.log(article.title);
}
```
### Step 3: Error Handling with IntercomError
```typescript
import { IntercomError } from "intercom-client";
async function safeIntercomCall<T>(
operation: () => Promise<T>,
context: string
): Promise<{ data: T | null; error: IntercomError | null }> {
try {
const data = await operation();
return { data, error: null };
} catch (err) {
if (err instanceof IntercomError) {
console.error(`[Intercom:${context}] ${err.statusCode}: ${err.message}`, {
requestId: err.body?.request_id,
errors: err.body?.errors,
});
// Specific error handling
switch (err.statusCode) {
case 401:
console.error("Token invalid or expired. Regenerate access token.");
break;
case 404:
console.error("Resource not found. Verify the ID.");
break;
case 409:
console.error("Conflict: resource already exists.");
break;
case 422:
console.error("Validation failed:", err.body?.errors);
break;
case 429:
console.error("Rate limited. Back off and retry.");
break;
}
return { data: null, error: err };
}
throw err; // Re-throw non-Intercom errors
}
}
// Usage
const { data: contact, error } = await safeIntercomCall(
() => client.contacts.find({ contactId: "abc123" }),
"findContact"
);
```
### Step 4: Retry with Exponential Backoff
```typescript
async function withRetry<T>(
operation: () => Promise<T>,
config = { maxRetries: 3, baseDelayMs: 1000 }
): Promise<T> {
for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
try {
return await operation();
} catch (err) {
if (err instanceof IntercomError) {
// Only retry on rate limits and server errors
if (err.statusCode !== 429 && (err.statusCode ?? 0) < 500) {
throw err;
}
if (attempt === config.maxRetries) throw err;
// Use Retry-After header if available, otherwise exponential backoff
const retryAfter = err.headers?.["retry-after"];
const delay = retryAfter
? parseInt(retryAfter) * 1000
: config.baseDelayMs * Math.pow(2, attempt) + Math.random() * 500;
console.log(`Retry ${attempt + 1}/${config.maxRetries} in ${delay}ms`);
await new Promise((r) => setTimeout(r, delay));
} else {
throw err;
}
}
}
throw new Error("Unreachable");
}
```
### Step 5: Contact Search with Compound Queries
```typescript
// Search with multiple conditions (AND/OR)
const results = await client.contacts.search({
query: {
operator: "AND",
value: [
{ field: "role", operator: "=", value: "user" },
{ field: "custom_attributes.plan", operator: "=", value: "pro" },
{
operator: "OR",
value: [
{ field: "email", operator: "~", value: "@acme.com" },
{ field: "email", operator: "~", value: "@bigcorp.com" },
],
},
],
},
pagination: { per_page: 25 },
sort: { field: "created_at", order: "descending" },
});
```
### Step 6: Multi-Tenant Client Factory
```typescript
const clientCache = new Map<string, IntercomClient>();
export function getClientForWorkspace(
workspaceToken: string
): IntercomClient {
if (!clientCache.has(workspaceToken)) {
clientCache.set(
workspaceToken,
new IntercomClient({ token: workspaceToken })
);
}
return clientCache.get(workspaceToken)!;
}
```
## Intercom Search Operators
| Operator | Meaning | Example |
|----------|---------|---------|
| `=` | Equals | `email = "[email protected]"` |
| `!=` | Not equals | `role != "lead"` |
| `~` | Contains | `email ~ "@acme.com"` |
| `!~` | Not contains | `name !~ "test"` |
| `>` | Greater than | `created_at > 1700000000` |
| `<` | Less than | `last_seen_at < 1700000000` |
| `IN` | In list | `tag_id IN ["tag1", "tag2"]` |
| `NIN` | Not in list | `segment_id NIN ["seg1"]` |
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| `safeIntercomCall` wrapper | All API calls | Prevents uncaught exceptions |
| `withRetry` | Transient failures (429, 5xx) | Automatic recovery |
| Cursor pagination generator | Large data sets | Memory-efficient streaming |
| Client factory | Multi-tenant apps | Workspace isolation |
## Resources
- [intercom-client npm](https://www.npmjs.com/package/intercom-client)
- [Intercom API Reference](https://developers.intercom.com/docs/references/rest-api/api.intercom.io)
- [Search Contacts](https://developers.intercom.com/docs/references/rest-api/api.intercom.io/contacts/searchcontacts)
## Next Steps
Apply patterns in `intercom-core-workflow-a` for contact management workflows.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.