{"_id":"@aithreads/sdk","name":"@aithreads/sdk","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@aithreads/sdk","version":"1.0.0","description":"Official TypeScript/JavaScript SDK for aithreads.io - Email infrastructure for AI agents","main":"dist/index.js","module":"dist/index.mjs","types":"dist/index.d.ts","exports":{".":{"types":"./dist/index.d.ts","import":"./dist/index.mjs","require":"./dist/index.js"}},"scripts":{"build":"tsup","dev":"tsup --watch","test":"vitest","test:run":"vitest run","typecheck":"tsc --noEmit","lint":"eslint src","clean":"rm -rf dist"},"keywords":["aithreads","email","ai","agents","sdk","api","typescript"],"author":{"name":"aithreads.io"},"license":"MIT","repository":{"type":"git","url":"git+https://github.com/aithreads/sdk-js.git"},"homepage":"https://aithreads.io","bugs":{"url":"https://github.com/aithreads/sdk-js/issues"},"engines":{"node":">=18"},"devDependencies":{"@types/node":"^20.0.0","tsup":"^8.0.0","typescript":"^5.0.0","vitest":"^1.0.0"},"_id":"@aithreads/sdk@1.0.0","gitHead":"e38deff06491cce7d6ebfa452816c1b752dc1089","_nodeVersion":"22.16.0","_npmVersion":"10.9.2","dist":{"integrity":"sha512-7qse/jvSviB6LT3M0Lxw6t1OylTuKZ843x+VZAR0K0W6RAVEPSF2CK5ZurBAQlqWjLu+vxpEOdpvaAonItu9gw==","shasum":"81a9ac2909fb4264239dcfeff7b8c49fe423b885","tarball":"https://registry.npmjs.org/@aithreads/sdk/-/sdk-1.0.0.tgz","fileCount":8,"unpackedSize":251920,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIQC25UUy/aAAyC1BQAga30P8vsa1i3Kfc+VzT+eyFpS2OQIgOtWcx7rNvUFkDH7b3Ijnq0YqiJk9Ox/PaLUNxT3jliw="}]},"_npmUser":{"name":"heyarviind","email":"heyarviind@gmail.com"},"directories":{},"maintainers":[{"name":"heyarviind","email":"heyarviind@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/sdk_1.0.0_1764402402483_0.9971714111409229"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-29T07:46:42.312Z","1.0.0":"2025-11-29T07:46:42.697Z","modified":"2025-11-29T07:46:43.083Z"},"maintainers":[{"name":"heyarviind","email":"heyarviind@gmail.com"}],"description":"Official TypeScript/JavaScript SDK for aithreads.io - Email infrastructure for AI agents","homepage":"https://aithreads.io","keywords":["aithreads","email","ai","agents","sdk","api","typescript"],"repository":{"type":"git","url":"git+https://github.com/aithreads/sdk-js.git"},"author":{"name":"aithreads.io"},"bugs":{"url":"https://github.com/aithreads/sdk-js/issues"},"license":"MIT","readme":"# @aithreads/sdk\n\nOfficial TypeScript/JavaScript SDK for [aithreads.io](https://aithreads.io) - Email infrastructure for AI agents.\n\n## Installation\n\n```bash\nnpm install @aithreads/sdk\n# or\npnpm add @aithreads/sdk\n# or\nyarn add @aithreads/sdk\n```\n\n## Quick Start\n\n```typescript\nimport { AIThreadsClient } from '@aithreads/sdk';\n\nconst client = new AIThreadsClient({\n  apiKey: 'ait_xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',\n});\n\n// Get an inbox by email address\nconst inbox = await client.inboxes.get('support@aithreads.io');\n\n// Send an email (simplified syntax)\nawait inbox.send({\n  to: 'user@example.com',\n  subject: 'Hello from AI',\n  text: 'This is a test email from my AI agent.',\n});\n\n// Get threads and reply\nconst threads = await inbox.getThreads({ is_read: false });\nconst thread = threads.data[0];\n\nconst messages = await thread.getMessages();\nawait thread.reply({ text: 'Thanks for reaching out!' });\nawait thread.markAsRead();\n```\n\n## Features\n\n- 📬 **Inbox Management**: Create and manage email inboxes for your AI agents\n- 📧 **Email Operations**: Send and receive emails with full threading support\n- 🧵 **Thread Management**: Organize conversations with automatic threading\n- 🏷️ **Labels**: Categorize threads with custom labels\n- 📚 **Knowledge Base**: Upload documents for AI context\n- 🔍 **Search**: Find threads by participant email address\n- 🔐 **Webhook Verification**: Cryptographic signature verification for webhooks\n- ⚡ **TypeScript First**: Full type safety with comprehensive types\n- 🎯 **Fluent API**: Chainable, intuitive methods on inbox and thread objects\n\n## API Reference\n\n### Client Initialization\n\n```typescript\nimport { AIThreadsClient, VERSION } from '@aithreads/sdk';\n\nconsole.log('SDK Version:', VERSION); // e.g., \"1.0.0\"\n\nconst client = new AIThreadsClient({\n  apiKey: 'ait_...',           // Required: Your API key\n  baseUrl: 'https://...',      // Optional: API base URL (default: https://api.aithreads.io/v1)\n  timeout: 30000,              // Optional: Request timeout in ms (default: 30000)\n  retries: 3,                  // Optional: Number of retries (default: 3)\n});\n```\n\n### Inboxes (Fluent API)\n\n```typescript\n// Get inbox by email address or ID\nconst inbox = await client.inboxes.get('support@aithreads.io');\n// or\nconst inbox = await client.inboxes.get('inbox-uuid');\n\n// Send email directly from inbox (simplified syntax)\nawait inbox.send({\n  to: 'user@example.com',              // String, array of strings, or objects\n  subject: 'Hello',\n  text: 'Plain text body',\n  html: '<p>HTML body</p>',            // Optional\n  cc: ['cc@example.com'],              // Optional\n  bcc: [{ email: 'bcc@example.com' }], // Optional\n});\n\n// Get threads from inbox\nconst threads = await inbox.getThreads({\n  is_read: false,\n  is_archived: false,\n  labels: ['important'],\n  participant: 'user@example.com',\n  limit: 20,\n  offset: 0,\n});\n\n// Get a specific thread\nconst thread = await inbox.getThread('thread-uuid');\n\n// Update inbox\nawait inbox.update({\n  display_name: 'Support Agent',\n  agent_prompt: 'You are a helpful support agent...',\n});\n\n// Delete inbox\nawait inbox.delete();\n```\n\n### Threads (Fluent API)\n\n```typescript\nconst threads = await inbox.getThreads({ is_read: false });\nconst thread = threads.data[0];\n\n// Get all messages in a thread\nconst messages = await thread.getMessages();\n\n// Reply to thread (sends to all participants)\nawait thread.reply({\n  text: 'Thanks for your email!',\n  html: '<p>Thanks for your email!</p>',\n  cc: 'manager@example.com',  // Optional\n});\n\n// Thread actions\nawait thread.markAsRead();\nawait thread.markAsUnread();\nawait thread.archive();\nawait thread.unarchive();\n\n// Manage labels\nawait thread.addLabels(['urgent', 'follow-up']);\nawait thread.removeLabels(['urgent']);\nawait thread.update({ labels: ['resolved'] });\n\n// Delete thread\nawait thread.delete();\n```\n\n### Traditional API (Still Available)\n\n```typescript\n// List all inboxes\nconst inboxes = await client.inboxes.list();\n\n// Create an inbox\nconst inbox = await client.inboxes.create({\n  username: 'support',\n  name: 'Support Agent',\n  webhook_url: 'https://example.com/webhook',\n});\n\n// Update inbox by ID\nawait client.inboxes.update('inbox-id', {\n  display_name: 'Updated Name',\n});\n\n// Thread operations by ID\nconst threads = await client.threads.list('inbox-id', {\n  limit: 20,\n  is_read: false,\n});\n\nawait client.threads.markAsRead('inbox-id', 'thread-id');\nawait client.threads.archive('inbox-id', 'thread-id');\n\n// Send email by inbox ID\nawait client.emails.send('inbox-id', {\n  to: [{ email: 'user@example.com', name: 'User' }],\n  subject: 'Hello',\n  text: 'Message body',\n});\n```\n\n### Labels\n\n```typescript\n// Organization-level labels\nconst labels = await client.labels.list();\nconst label = await client.labels.create({\n  name: 'Important',\n  color: '#FF5733',\n  description: 'High priority items',\n});\nawait client.labels.update('label-id', { color: '#00FF00' });\nawait client.labels.delete('label-id');\n\n// Inbox-specific labels\nconst inboxLabels = await client.inboxLabels.list('inbox-id');\nawait client.inboxLabels.create('inbox-id', {\n  name: 'Resolved',\n  color: '#00FF00',\n});\n```\n\n### Documents (Knowledge Base)\n\n```typescript\n// List documents\nconst docs = await client.documents.list('inbox-id');\n\n// Upload a document (browser)\nconst file = new File(['content'], 'document.txt', { type: 'text/plain' });\nawait client.documents.upload('inbox-id', file, 'My Document');\n\n// Search documents\nconst results = await client.documents.search('inbox-id', 'refund policy');\n\n// Get AI context from documents\nconst context = await client.documents.getContext('inbox-id', 'How do I process refunds?', 5);\n\n// Delete document\nawait client.documents.delete('inbox-id', 'doc-id');\n```\n\n## Webhook Verification\n\nWhen you set up a webhook URL for an inbox, AIThreads signs all webhook payloads so you can verify they're authentic:\n\n```typescript\nimport { constructWebhookEvent, verifyWebhookSignature } from '@aithreads/sdk';\n\n// Express.js example\napp.post('/webhook', express.raw({ type: 'application/json' }), (req, res) => {\n  try {\n    const event = constructWebhookEvent(\n      req.body,\n      req.headers,\n      process.env.WEBHOOK_SECRET!\n    );\n\n    console.log(`Received ${event.event} for email ${event.email_id}`);\n    \n    // Handle the event\n    switch (event.event) {\n      case 'email.received':\n        // Process incoming email\n        break;\n    }\n\n    res.json({ received: true });\n  } catch (error) {\n    console.error('Webhook verification failed:', error.message);\n    res.status(401).json({ error: 'Invalid signature' });\n  }\n});\n```\n\n### Verification Options\n\n```typescript\nimport { verifyWebhookSignature, verifyWebhook } from '@aithreads/sdk';\n\n// Option 1: Get result object (doesn't throw)\nconst result = verifyWebhookSignature(payload, signature, secret, {\n  maxAge: 300, // Max age in seconds (default: 5 minutes)\n});\n\nif (result.valid) {\n  console.log('Event:', result.payload.event);\n} else {\n  console.error('Error:', result.error);\n}\n\n// Option 2: Throws on failure\ntry {\n  const payload = verifyWebhook(body, signature, secret);\n  console.log('Event:', payload.event);\n} catch (error) {\n  console.error('Invalid:', error.message);\n}\n```\n\n### Webhook Payload\n\n```typescript\ninterface WebhookPayload {\n  event: 'email.received' | 'email.sent' | 'thread.created';\n  email_id: string;\n  thread_id: string;\n  inbox_id: string;\n  subject: string;\n  from: string;\n  timestamp: string; // ISO 8601\n}\n```\n\n### Getting Your Webhook Secret\n\nWhen you create an inbox with a webhook URL, a webhook secret is automatically generated. You can retrieve or regenerate it:\n\n```typescript\n// Create inbox with webhook\nconst inbox = await client.inboxes.create({\n  username: 'support',\n  webhook_url: 'https://example.com/webhook',\n});\n// The webhook_secret is returned on creation\n\n// Regenerate webhook secret (via API)\n// POST /v1/organizations/:org_id/inboxes/:inbox_id/webhook-secret\n```\n\n## Error Handling\n\nThe SDK provides typed errors with type guards for easy handling:\n\n```typescript\nimport {\n  AIThreadsError,\n  NotFoundError,\n  PaymentRequiredError,\n  RateLimitError,\n  // Type guards\n  isNotFoundError,\n  isPaymentRequiredError,\n  isRateLimitError,\n} from '@aithreads/sdk';\n\ntry {\n  await inbox.send({ to: 'user@example.com', subject: 'Hi', text: 'Hello' });\n} catch (error) {\n  // Using type guards (recommended)\n  if (isNotFoundError(error)) {\n    console.log('Inbox not found');\n  } else if (isPaymentRequiredError(error)) {\n    console.log(`Upgrade required. Current plan: ${error.plan}`);\n  } else if (isRateLimitError(error)) {\n    console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);\n  }\n\n  // Or using instanceof\n  if (error instanceof AIThreadsError) {\n    console.log(`Error: ${error.message} (${error.code})`);\n    console.log(`Status: ${error.status}`);\n    console.log(`Details:`, error.details);\n  }\n}\n```\n\n### Error Types\n\n| Error | Status | Description |\n|-------|--------|-------------|\n| `ValidationError` | 400 | Invalid request data |\n| `AuthenticationError` | 401 | Invalid or missing API key |\n| `PaymentRequiredError` | 402 | Plan limits exceeded or subscription issue |\n| `ForbiddenError` | 403 | Permission denied |\n| `NotFoundError` | 404 | Resource not found |\n| `ConflictError` | 409 | Resource conflict (e.g., duplicate) |\n| `RateLimitError` | 429 | Too many requests |\n| `ServerError` | 5xx | Server-side error |\n\n## TypeScript Support\n\nAll types are exported for full TypeScript support:\n\n```typescript\nimport type {\n  // Inbox types\n  Inbox,\n  InboxResponse,\n  InboxInstance,\n  SimpleSendEmailOptions,\n  // Thread types\n  Thread,\n  ThreadResponse,\n  ThreadInstance,\n  ThreadReplyOptions,\n  // Email types\n  Email,\n  SendEmailRequest,\n  SendEmailResponse,\n  // Webhook types\n  WebhookPayload,\n  WebhookEventType,\n  VerifyWebhookOptions,\n  WebhookVerificationResult,\n  // Common types\n  PaginatedResponse,\n  Label,\n} from '@aithreads/sdk';\n```\n\n## Requirements\n\n- Node.js 18+\n- Modern browser with Fetch API support\n\n## License\n\nMIT\n","readmeFilename":"README.md","_rev":"1-fb56f411eaa78d28d2baf7eb74dbc6ef"}