@agentmbox/plugin-agentmbox 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  AgentMBox email integration plugin for ElizaOS - enables AI agents to send and receive emails via the AgentMBox API.
4
4
 
5
+ **No configuration needed!** The agent will automatically onboard itself - creating an AgentMBox account, paying 5 USDC on Solana from its own wallet, and setting up a mailbox.
6
+
5
7
  ## Features
6
8
 
7
9
  - **Send Emails**: Agents can send emails to any recipient
@@ -23,7 +25,7 @@ Add the plugin to your agent's configuration and set the required environment va
23
25
 
24
26
  | Variable | Required | Description |
25
27
  |----------|----------|-------------|
26
- | `AGENTMBOX_API_KEY` | Yes | Your AgentMBox API key (starts with `ai_`) |
28
+ | `AGENTMBOX_API_KEY` | No | Your AgentMBox API key (starts with `ai_`) - only needed if not using autonomous onboarding |
27
29
  | `AGENTMBOX_MAILBOX` | No | Default mailbox address (e.g., `my-agent@agentmbox.com`) |
28
30
  | `AGENTMBOX_BASE_URL` | No | Custom API base URL (defaults to `https://agentmbox.com/api/v1`) |
29
31
 
@@ -39,22 +41,19 @@ Add the plugin to your agent's configuration and set the required environment va
39
41
 
40
42
  ## Quick Start
41
43
 
42
- ### 1. Create an AgentMBox Account
43
-
44
- Follow the [AgentMBox Quick Start Guide](https://www.agentmbox.com/docs) to:
44
+ ### 1. Configure Your Agent (Optional)
45
45
 
46
- 1. Create an account at https://agentmbox.com
47
- 2. Create an API key
48
- 3. Add payment (5 USDC per 30 days on Solana)
49
- 4. Create a mailbox (e.g., `my-agent@agentmbox.com`)
46
+ The plugin handles autonomous onboarding automatically - it will create an AgentMBox account, pay for subscription using the agent's Solana wallet, and set up a mailbox.
50
47
 
51
- ### 2. Configure Your Agent
52
-
53
- Add the environment variables to your `.env` file:
48
+ Optional environment variables:
54
49
 
55
50
  ```env
56
- AGENTMBOX_API_KEY=ai_your_api_key_here
57
- AGENTMBOX_MAILBOX=my-agent@agentmbox.com
51
+ # Only set these if you want to use an existing mailbox
52
+ # AGENTMBOX_API_KEY=ai_your_existing_api_key
53
+ # AGENTMBOX_MAILBOX=my-existing-mailbox@agentmbox.com
54
+
55
+ # Skip autonomous onboarding if already set up
56
+ # AGENTMBOX_SKIP_ONBOARDING=true
58
57
  ```
59
58
 
60
59
  ### 3. Use in Your Agent
package/dist/index.js CHANGED
@@ -28,10 +28,8 @@ var AgentMBoxService = class _AgentMBoxService extends Service {
28
28
  const apiKey = String(runtime.getSetting("AGENTMBOX_API_KEY") || "");
29
29
  const mailbox = String(runtime.getSetting("AGENTMBOX_MAILBOX") || "");
30
30
  const baseUrl = String(runtime.getSetting("AGENTMBOX_BASE_URL") || "");
31
- if (!apiKey) {
32
- throw new Error(
33
- "AGENTMBOX_API_KEY is required. Get your API key from https://agentmbox.com"
34
- );
31
+ if (apiKey && !apiKey.startsWith("ai_")) {
32
+ logger2.warn("AgentMBox API key should start with 'ai_'");
35
33
  }
36
34
  const agentName = runtime.character?.name?.toLowerCase().replace(/\s+/g, "-") || "agent";
37
35
  const defaultMailbox = mailbox || `${agentName}@agentmbox.com`;
@@ -48,6 +46,11 @@ var AgentMBoxService = class _AgentMBoxService extends Service {
48
46
  logger2.info("AgentMBox service stopped");
49
47
  }
50
48
  async request(endpoint, options = {}) {
49
+ if (!this.apiKey) {
50
+ throw new Error(
51
+ "AgentMBox API key not configured. Ensure onboarding has completed or set AGENTMBOX_API_KEY."
52
+ );
53
+ }
51
54
  const url = `${this.baseUrl}${endpoint}`;
52
55
  const headers = {
53
56
  Authorization: `Bearer ${this.apiKey}`,
@@ -58,7 +61,9 @@ var AgentMBoxService = class _AgentMBoxService extends Service {
58
61
  const data = await response.json();
59
62
  if (!response.ok) {
60
63
  if (isAgentMBoxError(data)) {
61
- throw new Error(`AgentMBox API error (${response.status}): ${data.error}`);
64
+ throw new Error(
65
+ `AgentMBox API error (${response.status}): ${data.error}`
66
+ );
62
67
  }
63
68
  throw new Error(`AgentMBox API error: ${response.status}`);
64
69
  }
@@ -72,7 +77,9 @@ var AgentMBoxService = class _AgentMBoxService extends Service {
72
77
  }
73
78
  async listEmails(limit = 50, offset = 0) {
74
79
  const mailboxParam = this.getMailboxParam();
75
- return this.request("/mail" + mailboxParam + "&limit=" + limit + "&offset=" + offset);
80
+ return this.request(
81
+ "/mail" + mailboxParam + "&limit=" + limit + "&offset=" + offset
82
+ );
76
83
  }
77
84
  async getEmail(emailId) {
78
85
  const mailboxParam = this.getMailboxParam();
@@ -90,9 +97,12 @@ var AgentMBoxService = class _AgentMBoxService extends Service {
90
97
  }
91
98
  async deleteEmail(emailId) {
92
99
  const mailboxParam = this.getMailboxParam();
93
- return this.request("/mail/" + emailId + mailboxParam, {
94
- method: "DELETE"
95
- });
100
+ return this.request(
101
+ "/mail/" + emailId + mailboxParam,
102
+ {
103
+ method: "DELETE"
104
+ }
105
+ );
96
106
  }
97
107
  async listMailboxes() {
98
108
  return this.request("/mailboxes");
@@ -126,9 +136,12 @@ var AgentMBoxService = class _AgentMBoxService extends Service {
126
136
  });
127
137
  }
128
138
  async verifyDomain(domainId) {
129
- return this.request("/domains/" + domainId + "/verify", {
130
- method: "POST"
131
- });
139
+ return this.request(
140
+ "/domains/" + domainId + "/verify",
141
+ {
142
+ method: "POST"
143
+ }
144
+ );
132
145
  }
133
146
  async deleteDomain(domainId) {
134
147
  return this.request("/domains/" + domainId, {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/services/AgentMBoxService.ts","../src/types/index.ts","../src/services/AgentMBoxOnboardingService.ts","../src/actions/sendEmail.ts","../src/actions/getEmails.ts","../src/providers/emailProvider.ts"],"sourcesContent":["/**\n * AgentMBox Plugin for ElizaOS\n * Email integration plugin that enables AI agents to send and receive emails\n * Includes autonomous self-onboarding using the agent's Solana wallet\n */\n\nimport type { Plugin, IAgentRuntime } from \"@elizaos/core\";\nimport { logger } from \"@elizaos/core\";\nimport { AgentMBoxService } from \"./services/AgentMBoxService\";\nimport { AgentMBoxOnboardingService } from \"./services/AgentMBoxOnboardingService\";\nimport { sendEmailAction } from \"./actions/sendEmail\";\nimport { getEmailsAction } from \"./actions/getEmails\";\nimport { emailProvider } from \"./providers/emailProvider\";\n\nexport const agentMBoxPlugin: Plugin = {\n name: \"agentmbox\",\n description:\n \"AgentMBox email integration plugin for ElizaOS - enables AI agents to send/receive emails with autonomous onboarding\",\n actions: [sendEmailAction, getEmailsAction],\n providers: [emailProvider],\n services: [AgentMBoxService, AgentMBoxOnboardingService],\n init: async (config: Record<string, string>, runtime: IAgentRuntime) => {\n logger.info(\"AgentMBox plugin initializing\");\n\n // Check if onboarding is needed\n const existingApiKey = runtime.getSetting(\"AGENTMBOX_API_KEY\");\n const skipOnboarding =\n runtime.getSetting(\"AGENTMBOX_SKIP_ONBOARDING\") === \"true\";\n\n if (!existingApiKey && !skipOnboarding) {\n logger.info(\"Starting AgentMBox autonomous onboarding...\");\n\n try {\n const onboardingService =\n runtime.getService<AgentMBoxOnboardingService>(\n \"agentmbox-onboarding\",\n );\n if (onboardingService) {\n const status = await onboardingService.startOnboarding(runtime);\n\n if (status.stage === \"complete\" && status.mailbox) {\n // Save credentials to runtime settings for persistence\n const apiKey = onboardingService.getApiKey();\n const mailbox = onboardingService.getMailbox();\n if (apiKey) {\n runtime.setSetting(\"AGENTMBOX_API_KEY\", apiKey, true);\n }\n if (mailbox) {\n runtime.setSetting(\"AGENTMBOX_MAILBOX\", mailbox);\n }\n logger.info(\"Onboarding complete! Mailbox: \" + status.mailbox);\n } else if (\n status.stage === \"awaiting_payment\" &&\n status.paymentAddress\n ) {\n logger.warn(\n \"Payment required. Please fund: \" + status.paymentAddress,\n );\n logger.info(\"Required: 5 USDC on Solana + ~0.01 SOL for fees\");\n }\n }\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Onboarding failed: \" + errorMsg);\n }\n } else if (existingApiKey) {\n logger.info(\"Using existing AgentMBox configuration\");\n } else {\n logger.info(\"Onboarding skipped per configuration\");\n }\n\n // Initialize main email service (after onboarding has potentially saved credentials)\n const emailService = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (emailService) {\n try {\n await emailService.initialize(runtime);\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\n \"Failed to initialize AgentMBox email service: \" + errorMsg,\n );\n // Don't fail the whole plugin initialization - the service will be unavailable\n }\n }\n },\n};\n\nexport default agentMBoxPlugin;\n\n// Re-export for convenience\nexport { AgentMBoxService } from \"./services/AgentMBoxService\";\nexport { AgentMBoxOnboardingService } from \"./services/AgentMBoxOnboardingService\";\nexport * from \"./types\";\n","import { Service, type IAgentRuntime, logger } from \"@elizaos/core\";\nimport {\n type AgentMBoxConfig,\n type EmailListResponse,\n type EmailDetailResponse,\n type SendEmailRequest,\n type SendEmailResponse,\n type MailboxListResponse,\n type CreateMailboxRequest,\n type CreateMailboxResponse,\n type PaymentStatus,\n type PaymentCheckResponse,\n type DomainListResponse,\n type DomainResponse,\n type DomainVerifyResponse,\n type ApiKeyResponse,\n isAgentMBoxError,\n} from \"../types\";\n\nexport class AgentMBoxService extends Service {\n private apiKey: string = \"\";\n private mailbox: string | undefined;\n private baseUrl: string = \"https://agentmbox.com/api/v1\";\n\n static serviceName = \"agentmbox\" as const;\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime!);\n }\n\n get serviceName(): string {\n return AgentMBoxService.serviceName;\n }\n\n get capabilityDescription(): string {\n return \"AgentMBox email service - allows sending and receiving emails\";\n }\n\n async initialize(runtime: IAgentRuntime): Promise<void> {\n const apiKey = String(runtime.getSetting(\"AGENTMBOX_API_KEY\") || \"\");\n const mailbox = String(runtime.getSetting(\"AGENTMBOX_MAILBOX\") || \"\");\n const baseUrl = String(runtime.getSetting(\"AGENTMBOX_BASE_URL\") || \"\");\n\n if (!apiKey) {\n throw new Error(\n \"AGENTMBOX_API_KEY is required. Get your API key from https://agentmbox.com\"\n );\n }\n\n const agentName = runtime.character?.name?.toLowerCase().replace(/\\s+/g, \"-\") || \"agent\";\n const defaultMailbox = mailbox || `${agentName}@agentmbox.com`;\n\n this.apiKey = apiKey;\n this.mailbox = defaultMailbox;\n this.baseUrl = baseUrl || \"https://agentmbox.com/api/v1\";\n this.runtime = runtime;\n\n if (!this.apiKey.startsWith(\"ai_\")) {\n logger.warn(\"AgentMBox API key should start with 'ai_'\");\n }\n\n logger.info(\"AgentMBox service initialized for: \" + this.mailbox);\n }\n\n async stop(): Promise<void> {\n logger.info(\"AgentMBox service stopped\");\n }\n\n private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(options.headers as Record<string, string>),\n };\n\n const response = await fetch(url, { ...options, headers });\n const data = await response.json();\n\n if (!response.ok) {\n if (isAgentMBoxError(data)) {\n throw new Error(`AgentMBox API error (${response.status}): ${data.error}`);\n }\n throw new Error(`AgentMBox API error: ${response.status}`);\n }\n\n return data as T;\n }\n\n private getMailboxParam(): string {\n if (!this.mailbox) {\n throw new Error(\"Mailbox not configured\");\n }\n return \"?mailbox=\" + encodeURIComponent(this.mailbox);\n }\n\n async listEmails(limit = 50, offset = 0): Promise<EmailListResponse> {\n const mailboxParam = this.getMailboxParam();\n return this.request<EmailListResponse>(\"/mail\" + mailboxParam + \"&limit=\" + limit + \"&offset=\" + offset);\n }\n\n async getEmail(emailId: string): Promise<EmailDetailResponse> {\n const mailboxParam = this.getMailboxParam();\n return this.request<EmailDetailResponse>(\"/mail/\" + emailId + mailboxParam);\n }\n\n async sendEmail(request: SendEmailRequest): Promise<SendEmailResponse> {\n const from = request.from || this.mailbox;\n if (!from) {\n throw new Error(\"Sender address not specified\");\n }\n\n return this.request<SendEmailResponse>(\"/mail/send\", {\n method: \"POST\",\n body: JSON.stringify({ ...request, from }),\n });\n }\n\n async deleteEmail(emailId: string): Promise<{ success: boolean }> {\n const mailboxParam = this.getMailboxParam();\n return this.request<{ success: boolean }>(\"/mail/\" + emailId + mailboxParam, {\n method: \"DELETE\",\n });\n }\n\n async listMailboxes(): Promise<MailboxListResponse> {\n return this.request<MailboxListResponse>(\"/mailboxes\");\n }\n\n async createMailbox(request: CreateMailboxRequest): Promise<CreateMailboxResponse> {\n return this.request<CreateMailboxResponse>(\"/mailboxes\", {\n method: \"POST\",\n body: JSON.stringify(request),\n });\n }\n\n async deleteMailbox(mailboxId: string): Promise<{ success: boolean }> {\n return this.request<{ success: boolean }>(\"/mailboxes/\" + mailboxId, {\n method: \"DELETE\",\n });\n }\n\n async getPaymentStatus(): Promise<PaymentStatus> {\n return this.request<PaymentStatus>(\"/payment\");\n }\n\n async checkPayment(): Promise<PaymentCheckResponse> {\n return this.request<PaymentCheckResponse>(\"/payment/check\", {\n method: \"POST\",\n });\n }\n\n async listDomains(): Promise<DomainListResponse> {\n return this.request<DomainListResponse>(\"/domains\");\n }\n\n async addDomain(domain: string): Promise<DomainResponse> {\n return this.request<DomainResponse>(\"/domains\", {\n method: \"POST\",\n body: JSON.stringify({ domain }),\n });\n }\n\n async verifyDomain(domainId: string): Promise<DomainVerifyResponse> {\n return this.request<DomainVerifyResponse>(\"/domains/\" + domainId + \"/verify\", {\n method: \"POST\",\n });\n }\n\n async deleteDomain(domainId: string): Promise<{ success: boolean }> {\n return this.request<{ success: boolean }>(\"/domains/\" + domainId, {\n method: \"DELETE\",\n });\n }\n\n async createApiKey(name: string): Promise<ApiKeyResponse> {\n return this.request<ApiKeyResponse>(\"/keys\", {\n method: \"POST\",\n body: JSON.stringify({ name }),\n });\n }\n\n async getStatus(): Promise<{ paid: boolean; paidUntil: string | null }> {\n try {\n const status = await this.getPaymentStatus();\n return { paid: status.paid, paidUntil: status.paidUntil };\n } catch (error) {\n logger.error(\"Failed to get AgentMBox status\");\n return { paid: false, paidUntil: null };\n }\n }\n}\n\nexport default AgentMBoxService;\n","/**\n * AgentMBox Plugin Types\n * TypeScript interfaces for AgentMBox email integration\n */\n\nexport interface AgentMBoxConfig {\n /** API key for AgentMBox (starts with ai_) */\n apiKey: string;\n /** Mailbox address (e.g., my-agent@agentmbox.com) */\n mailbox?: string;\n /** Base URL for AgentMBox API (default: https://agentmbox.com/api/v1) */\n baseUrl?: string;\n}\n\nexport interface EmailAddress {\n name?: string;\n email: string;\n}\n\nexport interface Email {\n id: string;\n from: EmailAddress[];\n to: EmailAddress[];\n cc?: EmailAddress[] | null;\n subject: string;\n receivedAt: string;\n textBody?: string;\n htmlBody?: string;\n preview?: string;\n hasAttachment: boolean;\n isRead: boolean;\n}\n\nexport interface EmailListResponse {\n mailbox: string;\n emails: Email[];\n limit: number;\n offset: number;\n}\n\nexport interface EmailDetailResponse {\n email: Email;\n}\n\nexport interface SendEmailRequest {\n /** Sender address (must be a mailbox you own) */\n from: string;\n /** Recipient(s) - single email or array */\n to: string | string[];\n /** Email subject line */\n subject: string;\n /** Plain text body */\n text?: string;\n /** HTML body */\n html?: string;\n}\n\nexport interface SendEmailResponse {\n success: boolean;\n}\n\nexport interface Mailbox {\n id: string;\n address: string;\n localPart: string;\n domainName: string;\n displayName?: string | null;\n password?: string; // Only shown at creation\n createdAt: string;\n}\n\nexport interface MailboxListResponse {\n mailboxes: Mailbox[];\n}\n\nexport interface CreateMailboxRequest {\n localPart: string;\n domainId?: string;\n displayName?: string;\n}\n\nexport interface CreateMailboxResponse {\n mailbox: Mailbox;\n}\n\nexport interface PaymentStatus {\n paid: boolean;\n paidUntil: string | null;\n solanaAddress: string;\n usdcPerPeriod: number;\n periodDays: number;\n creditedUsdc: number;\n payments: unknown[];\n}\n\nexport interface PaymentCheckResponse {\n paid: boolean;\n paidUntil: string;\n newCredits: number;\n balanceUsdc: number;\n creditedUsdc: number;\n}\n\nexport interface Domain {\n id: string;\n domain: string;\n verified: boolean;\n}\n\nexport interface DomainDNSRecords {\n verification: { type: string; name: string; value: string };\n mx: { type: string; name: string; value: string; priority: number };\n spf: { type: string; name: string; value: string };\n dkim: { type: string; name: string; value: string };\n}\n\nexport interface DomainResponse {\n domain: Domain;\n dnsRecords: DomainDNSRecords;\n}\n\nexport interface DomainVerifyResponse {\n verified: boolean;\n txtVerified: boolean;\n mxVerified: boolean;\n spfVerified: boolean;\n dkimVerified: boolean;\n}\n\nexport interface DomainListResponse {\n domains: (Domain & { dnsRecords?: DomainDNSRecords })[];\n}\n\nexport interface ApiKey {\n id: string;\n name: string;\n key: string;\n keyPrefix: string;\n}\n\nexport interface ApiKeyResponse {\n id: string;\n name: string;\n key: string;\n keyPrefix: string;\n}\n\nexport interface ApiKeyListResponse {\n keys: ApiKey[];\n}\n\nexport interface AgentMBoxError {\n error: string;\n}\n\nexport type AgentMBoxErrorCode = 400 | 401 | 402 | 403 | 404 | 409 | 502;\n\nexport function isAgentMBoxError(\n response: unknown,\n): response is AgentMBoxError {\n return (\n typeof response === \"object\" &&\n response !== null &&\n \"error\" in response &&\n typeof (response as AgentMBoxError).error === \"string\"\n );\n}\n","/**\n * AgentMBox Onboarding Service\n * Handles autonomous account creation and setup for AgentMBox\n * The agent pays for its own subscription using its Solana wallet\n */\n\nimport { Service, type IAgentRuntime, logger } from \"@elizaos/core\";\nimport {\n type PaymentStatus,\n type PaymentCheckResponse,\n type ApiKeyResponse,\n type Mailbox,\n} from \"../types\";\n\nexport interface OnboardingStatus {\n stage:\n | \"pending\"\n | \"account_created\"\n | \"api_key_created\"\n | \"awaiting_payment\"\n | \"paid\"\n | \"mailbox_created\"\n | \"complete\"\n | \"error\";\n paymentAddress?: string;\n mailbox?: string;\n error?: string;\n}\n\nexport class AgentMBoxOnboardingService extends Service {\n private apiKey: string = \"\";\n private mailbox: string | undefined;\n private baseUrl: string = \"https://agentmbox.com/api/v1\";\n private cfg: {\n ownerEmail: string;\n password: string;\n mailboxLocalPart: string;\n } | null = null;\n private status: OnboardingStatus = { stage: \"pending\" };\n\n static serviceName = \"agentmbox-onboarding\" as const;\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime!);\n }\n\n get serviceName(): string {\n return AgentMBoxOnboardingService.serviceName;\n }\n\n get capabilityDescription(): string {\n return \"AgentMBox autonomous onboarding - creates account, pays for subscription, sets up mailbox\";\n }\n\n getApiKey(): string {\n return this.apiKey;\n }\n\n getMailbox(): string | undefined {\n return this.mailbox;\n }\n\n private generatePassword(length: number = 32): string {\n const chars =\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*\";\n let password = \"\";\n const array = new Uint8Array(length);\n crypto.getRandomValues(array);\n for (let i = 0; i < length; i++) {\n password += chars[array[i] % chars.length];\n }\n return password;\n }\n\n private async getAgentWallet(): Promise<{\n publicKey: string;\n privateKey: Uint8Array;\n } | null> {\n if (!this.runtime) return null;\n\n try {\n const privateKeyBase58 = String(\n this.runtime.getSetting(\"SOLANA_PRIVATE_KEY\") || \"\",\n );\n if (privateKeyBase58) {\n const { default: bs58 } = await import(\"bs58\");\n const { Keypair } = await import(\"@solana/web3.js\");\n const privateKey = bs58.decode(privateKeyBase58);\n const keypair = Keypair.fromSecretKey(privateKey);\n return {\n publicKey: keypair.publicKey.toBase58(),\n privateKey,\n };\n }\n\n const walletService = await this.runtime.getService(\"wallet\");\n if (walletService) {\n const keypair = await (walletService as any).getKeypair?.();\n if (keypair) {\n return {\n publicKey: keypair.publicKey.toBase58(),\n privateKey: keypair.secretKey,\n };\n }\n }\n } catch (error) {\n logger.warn(\"Could not get agent wallet\");\n }\n\n return null;\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(options.headers as Record<string, string>),\n };\n\n const response = await fetch(url, { ...options, headers });\n const data = await response.json();\n\n if (!response.ok) {\n const error = (data as { error?: string }).error || `${response.status}`;\n throw new Error(error);\n }\n\n return data as T;\n }\n\n private async authenticatedRequest<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<T> {\n if (!this.apiKey) {\n throw new Error(\"API key not set\");\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(options.headers as Record<string, string>),\n };\n\n const response = await fetch(url, { ...options, headers });\n const data = await response.json();\n\n if (!response.ok) {\n const error = (data as { error?: string }).error || `${response.status}`;\n throw new Error(error);\n }\n\n return data as T;\n }\n\n async startOnboarding(runtime: IAgentRuntime): Promise<OnboardingStatus> {\n this.runtime = runtime;\n\n const existingApiKey = String(\n runtime.getSetting(\"AGENTMBOX_API_KEY\") || \"\",\n );\n if (existingApiKey && existingApiKey.startsWith(\"ai_\")) {\n this.apiKey = existingApiKey;\n return await this.checkExistingSetup();\n }\n\n const agentName =\n runtime.character?.name?.toLowerCase().replace(/\\s+/g, \"-\") || \"agent\";\n const mailboxSetting = String(\n runtime.getSetting(\"AGENTMBOX_MAILBOX\") || \"\",\n );\n this.cfg = {\n ownerEmail:\n String(runtime.getSetting(\"AGENTMBOX_OWNER_EMAIL\")) ||\n `agent-${agentName}@owner.local`,\n password: this.generatePassword(32),\n mailboxLocalPart: mailboxSetting\n ? mailboxSetting.split(\"@\")[0]\n : agentName,\n };\n\n try {\n // Step 1: Create account\n await this.createAccount();\n this.status = { stage: \"account_created\" };\n logger.info(\"AgentMBox account created\");\n\n // Step 2: Create API key\n const apiKeyResponse = await this.createApiKey(agentName);\n this.apiKey = apiKeyResponse.key;\n this.status = { stage: \"api_key_created\" };\n logger.info(\"AgentMBox API key created\");\n\n // Step 3: Get payment address\n const payment = await this.getPaymentStatus();\n this.status = {\n stage: \"awaiting_payment\",\n paymentAddress: payment.solanaAddress,\n };\n logger.info(\"Payment address: \" + payment.solanaAddress);\n\n // Step 4: Pay for subscription\n await this.payForSubscription(payment.solanaAddress, runtime);\n this.status = { stage: \"paid\" };\n logger.info(\"Payment completed\");\n\n // Step 5: Create mailbox\n const mailbox = await this.createMailbox(this.cfg!.mailboxLocalPart);\n this.mailbox = mailbox.address;\n this.status = {\n stage: \"complete\",\n mailbox: mailbox.address,\n };\n logger.info(\"Mailbox created: \" + mailbox.address);\n\n return this.status;\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"AgentMBox onboarding failed: \" + errorMsg);\n this.status = { stage: \"error\", error: errorMsg };\n throw error;\n }\n }\n\n private async checkExistingSetup(): Promise<OnboardingStatus> {\n try {\n const payment = await this.getPaymentStatus();\n\n if (payment.paid) {\n const mailbox = await this.getOrCreateMailbox();\n this.status = mailbox\n ? { stage: \"complete\", mailbox: mailbox.address }\n : { stage: \"paid\" };\n } else {\n const wallet = await this.getAgentWallet();\n if (wallet && this.runtime) {\n await this.payForSubscription(payment.solanaAddress, this.runtime);\n this.status = { stage: \"paid\" };\n const mailbox = await this.getOrCreateMailbox();\n if (mailbox) {\n this.status = { stage: \"complete\", mailbox: mailbox.address };\n }\n } else {\n this.status = {\n stage: \"awaiting_payment\",\n paymentAddress: payment.solanaAddress,\n };\n }\n }\n } catch (error) {\n logger.warn(\"Could not check existing setup\");\n this.status = { stage: \"pending\" };\n }\n\n return this.status;\n }\n\n private async payForSubscription(\n paymentAddress: string,\n runtime: IAgentRuntime,\n ): Promise<void> {\n const wallet = await this.getAgentWallet();\n\n if (!wallet) {\n logger.warn(\"No agent wallet found, waiting for manual payment\");\n await this.waitForPayment();\n return;\n }\n\n logger.info(\"Using agent wallet to pay for subscription\");\n\n try {\n const { Connection, Keypair } = await import(\"@solana/web3.js\");\n const { transfer, getOrCreateAssociatedTokenAccount } =\n await import(\"@solana/spl-token\");\n\n const connection = new Connection(\"https://api.mainnet-beta.solana.com\");\n const signer = Keypair.fromSecretKey(wallet.privateKey);\n\n const usdcMintStr = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGZwyTDt1v\";\n const { PublicKey } = await import(\"@solana/web3.js\");\n const usdcMint = new PublicKey(usdcMintStr);\n const toPublicKey = new PublicKey(paymentAddress);\n\n const fromTokenAccount = await getOrCreateAssociatedTokenAccount(\n connection,\n signer,\n usdcMint,\n signer.publicKey,\n );\n\n const toTokenAccount = await getOrCreateAssociatedTokenAccount(\n connection,\n signer,\n usdcMint,\n toPublicKey,\n );\n\n const amount = 5_000_000;\n\n await transfer(\n connection,\n signer,\n fromTokenAccount.address,\n toTokenAccount.address,\n signer.publicKey,\n amount,\n );\n\n logger.info(\"USDC transfer complete\");\n await this.waitForPayment();\n } catch (error) {\n logger.error(\"Failed to transfer USDC, waiting for manual payment\");\n await this.waitForPayment();\n }\n }\n\n async stop(): Promise<void> {\n logger.info(\"AgentMBox onboarding service stopped\");\n }\n\n private async createAccount(): Promise<void> {\n if (!this.cfg) throw new Error(\"Config not set\");\n\n const response = await this.request<{ id: string }>(\"/auth/signup\", {\n method: \"POST\",\n body: JSON.stringify({\n email: this.cfg.ownerEmail,\n password: this.cfg.password,\n }),\n });\n\n logger.info(\"Account created: \" + response.id);\n }\n\n private async createApiKey(name: string): Promise<ApiKeyResponse> {\n const response = await this.request<ApiKeyResponse>(\"/keys\", {\n method: \"POST\",\n body: JSON.stringify({ name }),\n });\n\n logger.info(\"API key created: \" + response.key.substring(0, 12) + \"...\");\n return response;\n }\n\n private async getPaymentStatus(): Promise<PaymentStatus> {\n return this.authenticatedRequest<PaymentStatus>(\"/payment\");\n }\n\n private async waitForPayment(\n maxAttempts: number = 60,\n intervalMs: number = 5000,\n ): Promise<PaymentCheckResponse> {\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.authenticatedRequest<PaymentCheckResponse>(\n \"/payment/check\",\n {\n method: \"POST\",\n },\n );\n\n if (result.paid) {\n return result;\n }\n\n logger.info(\n \"Waiting for payment... (\" + attempt + \"/\" + maxAttempts + \")\",\n );\n } catch (e) {\n logger.warn(\n \"Payment check failed: \" +\n (e instanceof Error ? e.message : \"unknown\"),\n );\n }\n\n if (attempt < maxAttempts) {\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n }\n\n throw new Error(\"Payment not received after \" + maxAttempts + \" attempts\");\n }\n\n private async createMailbox(localPart: string): Promise<Mailbox> {\n const response = await this.authenticatedRequest<{ mailbox: Mailbox }>(\n \"/mailboxes\",\n {\n method: \"POST\",\n body: JSON.stringify({\n localPart,\n displayName: this.cfg?.mailboxLocalPart || \"Agent Mailbox\",\n }),\n },\n );\n\n return response.mailbox;\n }\n\n async getOrCreateMailbox(): Promise<Mailbox | null> {\n try {\n const response = await this.authenticatedRequest<{\n mailboxes: Mailbox[];\n }>(\"/mailboxes\");\n\n if (response.mailboxes.length > 0) {\n return response.mailboxes[0];\n }\n\n if (this.cfg?.mailboxLocalPart) {\n return await this.createMailbox(this.cfg.mailboxLocalPart);\n }\n\n return null;\n } catch (error) {\n logger.error(\"Failed to get/create mailbox\");\n return null;\n }\n }\n\n getStatus(): OnboardingStatus {\n return this.status;\n }\n\n async getPaymentAddress(): Promise<string | null> {\n if (this.status.paymentAddress) {\n return this.status.paymentAddress;\n }\n\n try {\n const payment = await this.getPaymentStatus();\n return payment.solanaAddress;\n } catch {\n return null;\n }\n }\n\n isOnboardingComplete(): boolean {\n return this.status.stage === \"complete\";\n }\n}\n\nexport default AgentMBoxOnboardingService;\n","/**\n * Send Email Action\n * Allows the agent to send emails via AgentMBox\n */\n\nimport {\n type Action,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n type ActionExample,\n} from \"@elizaos/core\";\nimport { AgentMBoxService } from \"../services/AgentMBoxService\";\n\nexport const sendEmailAction: Action = {\n name: \"SEND_EMAIL\",\n description: \"Send an email to a recipient using AgentMBox email service\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n options: Record<string, unknown>,\n callback?: HandlerCallback\n ) => {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (!service) {\n throw new Error(\"AgentMBox service not initialized\");\n }\n\n const { to, subject, text, html } = options;\n\n if (!to) {\n throw new Error(\"Missing required field: 'to' (recipient email)\");\n }\n\n if (!subject) {\n throw new Error(\"Missing required field: 'subject'\");\n }\n\n const from = options.from as string | undefined;\n\n try {\n const result = await service.sendEmail({\n from,\n to: Array.isArray(to) ? to : to,\n subject,\n text: text as string | undefined,\n html: html as string | undefined,\n });\n\n if (callback) {\n await callback({\n text: `Email sent successfully to ${to}`,\n values: {\n success: result.success,\n recipient: to,\n subject,\n },\n });\n }\n\n return {\n success: true,\n values: {\n sentTo: to,\n subject,\n },\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Failed to send email\", { error: errorMessage });\n\n if (callback) {\n await callback({\n text: `Failed to send email: ${errorMessage}`,\n values: {\n success: false,\n error: errorMessage,\n },\n });\n }\n\n return {\n success: false,\n error: errorMessage,\n };\n }\n },\n validate: async (runtime: IAgentRuntime) => {\n try {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n return !!service;\n } catch {\n return false;\n }\n },\n examples: [\n [\n {\n name: \"user\",\n content: \"Send an email to john@example.com about the project update\",\n },\n {\n name: \"assistant\",\n content: \"I'll send that email for you.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Email the team that the meeting is at 3pm\",\n },\n {\n name: \"assistant\",\n content: \"Sending that email now.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Can you notify alice@example.com that the report is ready?\",\n },\n {\n name: \"assistant\",\n content: \"I'll send her an email right away.\",\n },\n ],\n ] as ActionExample[][],\n};\n\nexport default sendEmailAction;\n","/**\n * Get Emails Action\n * Allows the agent to retrieve emails from the mailbox via AgentMBox\n */\n\nimport {\n type Action,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n type ActionExample,\n} from \"@elizaos/core\";\nimport { AgentMBoxService } from \"../services/AgentMBoxService\";\n\nexport const getEmailsAction: Action = {\n name: \"GET_EMAILS\",\n description: \"Retrieve emails from the AgentMBox mailbox. Can filter by read status and limit results.\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n options: Record<string, unknown>,\n callback?: HandlerCallback\n ) => {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (!service) {\n throw new Error(\"AgentMBox service not initialized\");\n }\n\n const limit = (options.limit as number) || 10;\n const offset = (options.offset as number) || 0;\n const emailId = options.emailId as string | undefined;\n\n try {\n // If emailId is provided, get a specific email\n if (emailId) {\n const emailDetail = await service.getEmail(emailId);\n\n if (callback) {\n await callback({\n text: `Retrieved email: ${emailDetail.email.subject}`,\n values: {\n email: emailDetail.email,\n },\n });\n }\n\n return {\n success: true,\n values: {\n email: emailDetail.email,\n },\n };\n }\n\n // Otherwise, list emails\n const emailList = await service.listEmails(limit, offset);\n\n // Filter by read status if specified\n let emails = emailList.emails;\n const unreadOnly = options.unreadOnly as boolean;\n if (unreadOnly) {\n emails = emails.filter((email) => !email.isRead);\n }\n\n if (callback) {\n const preview = emails\n .slice(0, 5)\n .map((e) => `- ${e.subject} from ${e.from[0]?.email}`)\n .join(\"\\n\");\n await callback({\n text: `Found ${emails.length} emails:\\n${preview}`,\n values: {\n emails: emails,\n total: emailList.emails.length,\n unread: emailList.emails.filter((e) => !e.isRead).length,\n },\n });\n }\n\n return {\n success: true,\n values: {\n emails: emails,\n total: emailList.emails.length,\n limit: emailList.limit,\n offset: emailList.offset,\n },\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Failed to get emails\", { error: errorMessage });\n\n if (callback) {\n await callback({\n text: `Failed to get emails: ${errorMessage}`,\n values: {\n success: false,\n error: errorMessage,\n },\n });\n }\n\n return {\n success: false,\n error: errorMessage,\n };\n }\n },\n validate: async (runtime: IAgentRuntime) => {\n try {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n return !!service;\n } catch {\n return false;\n }\n },\n examples: [\n [\n {\n name: \"user\",\n content: \"Check my inbox for any new emails\",\n },\n {\n name: \"assistant\",\n content: \"Let me check your inbox for new emails.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Show me the last 5 emails I received\",\n },\n {\n name: \"assistant\",\n content: \"I'll retrieve your recent emails.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Get the details of that email about the meeting\",\n },\n {\n name: \"assistant\",\n content: \"Let me fetch that email for you.\",\n },\n ],\n ] as ActionExample[][],\n};\n\nexport default getEmailsAction;\n","/**\n * Email Provider\n * Provides email context to the agent, including unread counts and recent emails\n */\n\nimport {\n type Provider,\n type IAgentRuntime,\n type Memory,\n type State,\n type ProviderResult,\n} from \"@elizaos/core\";\nimport { AgentMBoxService } from \"../services/AgentMBoxService\";\n\nexport const emailProvider: Provider = {\n name: \"email\",\n description: \"Provides email context from AgentMBox including unread counts and recent messages\",\n get: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State\n ): Promise<ProviderResult> => {\n try {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (!service) {\n return {\n text: \"Email service not available\",\n values: {\n available: false,\n },\n };\n }\n\n // Get recent emails\n const emailList = await service.listEmails(10, 0);\n const unreadCount = emailList.emails.filter((e) => !e.isRead).length;\n const recentEmails = emailList.emails.slice(0, 5);\n\n // Format recent emails for context\n const recentEmailsText = recentEmails\n .map(\n (email) =>\n `- From: ${email.from[0]?.name || email.from[0]?.email || \"Unknown\"} | Subject: ${email.subject}${\n !email.isRead ? \" [UNREAD]\" : \"\"\n }`\n )\n .join(\"\\n\");\n\n return {\n text: `Email Status: ${unreadCount} unread of ${emailList.emails.length} total${\n recentEmails.length > 0\n ? `\\n\\nRecent Emails:\\n${recentEmailsText}`\n : \"\\n\\nNo recent emails.\"\n }`,\n values: {\n available: true,\n unreadCount,\n totalEmails: emailList.emails.length,\n recentEmails: recentEmails.map((e) => ({\n id: e.id,\n from: e.from[0],\n subject: e.subject,\n preview: e.preview,\n isRead: e.isRead,\n receivedAt: e.receivedAt,\n })),\n },\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n return {\n text: `Email service error: ${errorMessage}`,\n values: {\n available: false,\n error: errorMessage,\n },\n };\n }\n },\n};\n\nexport default emailProvider;\n"],"mappings":";AAOA,SAAS,UAAAA,eAAc;;;ACPvB,SAAS,SAA6B,UAAAC,eAAc;;;AC6J7C,SAAS,iBACd,UAC4B;AAC5B,SACE,OAAO,aAAa,YACpB,aAAa,QACb,WAAW,YACX,OAAQ,SAA4B,UAAU;AAElD;;;ADnJO,IAAM,mBAAN,MAAM,0BAAyB,QAAQ;AAAA,EACpC,SAAiB;AAAA,EACjB;AAAA,EACA,UAAkB;AAAA,EAE1B,OAAO,cAAc;AAAA,EAErB,YAAY,SAAyB;AACnC,UAAM,OAAQ;AAAA,EAChB;AAAA,EAEA,IAAI,cAAsB;AACxB,WAAO,kBAAiB;AAAA,EAC1B;AAAA,EAEA,IAAI,wBAAgC;AAClC,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAuC;AACtD,UAAM,SAAS,OAAO,QAAQ,WAAW,mBAAmB,KAAK,EAAE;AACnE,UAAM,UAAU,OAAO,QAAQ,WAAW,mBAAmB,KAAK,EAAE;AACpE,UAAM,UAAU,OAAO,QAAQ,WAAW,oBAAoB,KAAK,EAAE;AAErE,QAAI,CAAC,QAAQ;AACX,YAAM,IAAI;AAAA,QACR;AAAA,MACF;AAAA,IACF;AAEA,UAAM,YAAY,QAAQ,WAAW,MAAM,YAAY,EAAE,QAAQ,QAAQ,GAAG,KAAK;AACjF,UAAM,iBAAiB,WAAW,GAAG,SAAS;AAE9C,SAAK,SAAS;AACd,SAAK,UAAU;AACf,SAAK,UAAU,WAAW;AAC1B,SAAK,UAAU;AAEf,QAAI,CAAC,KAAK,OAAO,WAAW,KAAK,GAAG;AAClC,MAAAC,QAAO,KAAK,2CAA2C;AAAA,IACzD;AAEA,IAAAA,QAAO,KAAK,wCAAwC,KAAK,OAAO;AAAA,EAClE;AAAA,EAEA,MAAM,OAAsB;AAC1B,IAAAA,Q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A,cACL,oCAAoC,OAAO;AAAA,YAC7C;AACA,YAAAA,QAAO,KAAK,iDAAiD;AAAA,UAC/D;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,cAAM,WACJ,iBAAiB,QAAQ,MAAM,UAAU;AAC3C,QAAAA,QAAO,MAAM,wBAAwB,QAAQ;AAAA,MAC/C;AAAA,IACF,WAAW,gBAAgB;AACzB,MAAAA,QAAO,KAAK,wCAAwC;AAAA,IACtD,OAAO;AACL,MAAAA,QAAO,KAAK,sCAAsC;AAAA,IACpD;AAGA,UAAM,eAAe,QAAQ,WAA6B,WAAW;AACrE,QAAI,cAAc;AAChB,UAAI;AACF,cAAM,aAAa,WAAW,OAAO;AAAA,MACvC,SAAS,OAAO;AACd,cAAM,WACJ,iBAAiB,QAAQ,MAAM,UAAU;AAC3C,QAAAA,QAAO;AAAA,UACL,mDAAmD;AAAA,QACrD;AAAA,MAEF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["logger","logger","logger","Service","logger","logger"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/services/AgentMBoxService.ts","../src/types/index.ts","../src/services/AgentMBoxOnboardingService.ts","../src/actions/sendEmail.ts","../src/actions/getEmails.ts","../src/providers/emailProvider.ts"],"sourcesContent":["/**\n * AgentMBox Plugin for ElizaOS\n * Email integration plugin that enables AI agents to send and receive emails\n * Includes autonomous self-onboarding using the agent's Solana wallet\n */\n\nimport type { Plugin, IAgentRuntime } from \"@elizaos/core\";\nimport { logger } from \"@elizaos/core\";\nimport { AgentMBoxService } from \"./services/AgentMBoxService\";\nimport { AgentMBoxOnboardingService } from \"./services/AgentMBoxOnboardingService\";\nimport { sendEmailAction } from \"./actions/sendEmail\";\nimport { getEmailsAction } from \"./actions/getEmails\";\nimport { emailProvider } from \"./providers/emailProvider\";\n\nexport const agentMBoxPlugin: Plugin = {\n name: \"agentmbox\",\n description:\n \"AgentMBox email integration plugin for ElizaOS - enables AI agents to send/receive emails with autonomous onboarding\",\n actions: [sendEmailAction, getEmailsAction],\n providers: [emailProvider],\n services: [AgentMBoxService, AgentMBoxOnboardingService],\n init: async (config: Record<string, string>, runtime: IAgentRuntime) => {\n logger.info(\"AgentMBox plugin initializing\");\n\n // Check if onboarding is needed\n const existingApiKey = runtime.getSetting(\"AGENTMBOX_API_KEY\");\n const skipOnboarding =\n runtime.getSetting(\"AGENTMBOX_SKIP_ONBOARDING\") === \"true\";\n\n if (!existingApiKey && !skipOnboarding) {\n logger.info(\"Starting AgentMBox autonomous onboarding...\");\n\n try {\n const onboardingService =\n runtime.getService<AgentMBoxOnboardingService>(\n \"agentmbox-onboarding\",\n );\n if (onboardingService) {\n const status = await onboardingService.startOnboarding(runtime);\n\n if (status.stage === \"complete\" && status.mailbox) {\n // Save credentials to runtime settings for persistence\n const apiKey = onboardingService.getApiKey();\n const mailbox = onboardingService.getMailbox();\n if (apiKey) {\n runtime.setSetting(\"AGENTMBOX_API_KEY\", apiKey, true);\n }\n if (mailbox) {\n runtime.setSetting(\"AGENTMBOX_MAILBOX\", mailbox);\n }\n logger.info(\"Onboarding complete! Mailbox: \" + status.mailbox);\n } else if (\n status.stage === \"awaiting_payment\" &&\n status.paymentAddress\n ) {\n logger.warn(\n \"Payment required. Please fund: \" + status.paymentAddress,\n );\n logger.info(\"Required: 5 USDC on Solana + ~0.01 SOL for fees\");\n }\n }\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Onboarding failed: \" + errorMsg);\n }\n } else if (existingApiKey) {\n logger.info(\"Using existing AgentMBox configuration\");\n } else {\n logger.info(\"Onboarding skipped per configuration\");\n }\n\n // Initialize main email service (after onboarding has potentially saved credentials)\n const emailService = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (emailService) {\n try {\n await emailService.initialize(runtime);\n } catch (error) {\n const errorMsg =\n error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\n \"Failed to initialize AgentMBox email service: \" + errorMsg,\n );\n // Don't fail the whole plugin initialization - the service will be unavailable\n }\n }\n },\n};\n\nexport default agentMBoxPlugin;\n\n// Re-export for convenience\nexport { AgentMBoxService } from \"./services/AgentMBoxService\";\nexport { AgentMBoxOnboardingService } from \"./services/AgentMBoxOnboardingService\";\nexport * from \"./types\";\n","import { Service, type IAgentRuntime, logger } from \"@elizaos/core\";\nimport {\n type AgentMBoxConfig,\n type EmailListResponse,\n type EmailDetailResponse,\n type SendEmailRequest,\n type SendEmailResponse,\n type MailboxListResponse,\n type CreateMailboxRequest,\n type CreateMailboxResponse,\n type PaymentStatus,\n type PaymentCheckResponse,\n type DomainListResponse,\n type DomainResponse,\n type DomainVerifyResponse,\n type ApiKeyResponse,\n isAgentMBoxError,\n} from \"../types\";\n\nexport class AgentMBoxService extends Service {\n private apiKey: string = \"\";\n private mailbox: string | undefined;\n private baseUrl: string = \"https://agentmbox.com/api/v1\";\n\n static serviceName = \"agentmbox\" as const;\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime!);\n }\n\n get serviceName(): string {\n return AgentMBoxService.serviceName;\n }\n\n get capabilityDescription(): string {\n return \"AgentMBox email service - allows sending and receiving emails\";\n }\n\n async initialize(runtime: IAgentRuntime): Promise<void> {\n const apiKey = String(runtime.getSetting(\"AGENTMBOX_API_KEY\") || \"\");\n const mailbox = String(runtime.getSetting(\"AGENTMBOX_MAILBOX\") || \"\");\n const baseUrl = String(runtime.getSetting(\"AGENTMBOX_BASE_URL\") || \"\");\n\n // API key will be set by onboarding if not provided\n // The service will work once onboarding completes\n if (apiKey && !apiKey.startsWith(\"ai_\")) {\n logger.warn(\"AgentMBox API key should start with 'ai_'\");\n }\n\n const agentName =\n runtime.character?.name?.toLowerCase().replace(/\\s+/g, \"-\") || \"agent\";\n const defaultMailbox = mailbox || `${agentName}@agentmbox.com`;\n\n this.apiKey = apiKey;\n this.mailbox = defaultMailbox;\n this.baseUrl = baseUrl || \"https://agentmbox.com/api/v1\";\n this.runtime = runtime;\n\n if (!this.apiKey.startsWith(\"ai_\")) {\n logger.warn(\"AgentMBox API key should start with 'ai_'\");\n }\n\n logger.info(\"AgentMBox service initialized for: \" + this.mailbox);\n }\n\n async stop(): Promise<void> {\n logger.info(\"AgentMBox service stopped\");\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<T> {\n if (!this.apiKey) {\n throw new Error(\n \"AgentMBox API key not configured. Ensure onboarding has completed or set AGENTMBOX_API_KEY.\",\n );\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(options.headers as Record<string, string>),\n };\n\n const response = await fetch(url, { ...options, headers });\n const data = await response.json();\n\n if (!response.ok) {\n if (isAgentMBoxError(data)) {\n throw new Error(\n `AgentMBox API error (${response.status}): ${data.error}`,\n );\n }\n throw new Error(`AgentMBox API error: ${response.status}`);\n }\n\n return data as T;\n }\n\n private getMailboxParam(): string {\n if (!this.mailbox) {\n throw new Error(\"Mailbox not configured\");\n }\n return \"?mailbox=\" + encodeURIComponent(this.mailbox);\n }\n\n async listEmails(limit = 50, offset = 0): Promise<EmailListResponse> {\n const mailboxParam = this.getMailboxParam();\n return this.request<EmailListResponse>(\n \"/mail\" + mailboxParam + \"&limit=\" + limit + \"&offset=\" + offset,\n );\n }\n\n async getEmail(emailId: string): Promise<EmailDetailResponse> {\n const mailboxParam = this.getMailboxParam();\n return this.request<EmailDetailResponse>(\"/mail/\" + emailId + mailboxParam);\n }\n\n async sendEmail(request: SendEmailRequest): Promise<SendEmailResponse> {\n const from = request.from || this.mailbox;\n if (!from) {\n throw new Error(\"Sender address not specified\");\n }\n\n return this.request<SendEmailResponse>(\"/mail/send\", {\n method: \"POST\",\n body: JSON.stringify({ ...request, from }),\n });\n }\n\n async deleteEmail(emailId: string): Promise<{ success: boolean }> {\n const mailboxParam = this.getMailboxParam();\n return this.request<{ success: boolean }>(\n \"/mail/\" + emailId + mailboxParam,\n {\n method: \"DELETE\",\n },\n );\n }\n\n async listMailboxes(): Promise<MailboxListResponse> {\n return this.request<MailboxListResponse>(\"/mailboxes\");\n }\n\n async createMailbox(\n request: CreateMailboxRequest,\n ): Promise<CreateMailboxResponse> {\n return this.request<CreateMailboxResponse>(\"/mailboxes\", {\n method: \"POST\",\n body: JSON.stringify(request),\n });\n }\n\n async deleteMailbox(mailboxId: string): Promise<{ success: boolean }> {\n return this.request<{ success: boolean }>(\"/mailboxes/\" + mailboxId, {\n method: \"DELETE\",\n });\n }\n\n async getPaymentStatus(): Promise<PaymentStatus> {\n return this.request<PaymentStatus>(\"/payment\");\n }\n\n async checkPayment(): Promise<PaymentCheckResponse> {\n return this.request<PaymentCheckResponse>(\"/payment/check\", {\n method: \"POST\",\n });\n }\n\n async listDomains(): Promise<DomainListResponse> {\n return this.request<DomainListResponse>(\"/domains\");\n }\n\n async addDomain(domain: string): Promise<DomainResponse> {\n return this.request<DomainResponse>(\"/domains\", {\n method: \"POST\",\n body: JSON.stringify({ domain }),\n });\n }\n\n async verifyDomain(domainId: string): Promise<DomainVerifyResponse> {\n return this.request<DomainVerifyResponse>(\n \"/domains/\" + domainId + \"/verify\",\n {\n method: \"POST\",\n },\n );\n }\n\n async deleteDomain(domainId: string): Promise<{ success: boolean }> {\n return this.request<{ success: boolean }>(\"/domains/\" + domainId, {\n method: \"DELETE\",\n });\n }\n\n async createApiKey(name: string): Promise<ApiKeyResponse> {\n return this.request<ApiKeyResponse>(\"/keys\", {\n method: \"POST\",\n body: JSON.stringify({ name }),\n });\n }\n\n async getStatus(): Promise<{ paid: boolean; paidUntil: string | null }> {\n try {\n const status = await this.getPaymentStatus();\n return { paid: status.paid, paidUntil: status.paidUntil };\n } catch (error) {\n logger.error(\"Failed to get AgentMBox status\");\n return { paid: false, paidUntil: null };\n }\n }\n}\n\nexport default AgentMBoxService;\n","/**\n * AgentMBox Plugin Types\n * TypeScript interfaces for AgentMBox email integration\n */\n\nexport interface AgentMBoxConfig {\n /** API key for AgentMBox (starts with ai_) */\n apiKey: string;\n /** Mailbox address (e.g., my-agent@agentmbox.com) */\n mailbox?: string;\n /** Base URL for AgentMBox API (default: https://agentmbox.com/api/v1) */\n baseUrl?: string;\n}\n\nexport interface EmailAddress {\n name?: string;\n email: string;\n}\n\nexport interface Email {\n id: string;\n from: EmailAddress[];\n to: EmailAddress[];\n cc?: EmailAddress[] | null;\n subject: string;\n receivedAt: string;\n textBody?: string;\n htmlBody?: string;\n preview?: string;\n hasAttachment: boolean;\n isRead: boolean;\n}\n\nexport interface EmailListResponse {\n mailbox: string;\n emails: Email[];\n limit: number;\n offset: number;\n}\n\nexport interface EmailDetailResponse {\n email: Email;\n}\n\nexport interface SendEmailRequest {\n /** Sender address (must be a mailbox you own) */\n from: string;\n /** Recipient(s) - single email or array */\n to: string | string[];\n /** Email subject line */\n subject: string;\n /** Plain text body */\n text?: string;\n /** HTML body */\n html?: string;\n}\n\nexport interface SendEmailResponse {\n success: boolean;\n}\n\nexport interface Mailbox {\n id: string;\n address: string;\n localPart: string;\n domainName: string;\n displayName?: string | null;\n password?: string; // Only shown at creation\n createdAt: string;\n}\n\nexport interface MailboxListResponse {\n mailboxes: Mailbox[];\n}\n\nexport interface CreateMailboxRequest {\n localPart: string;\n domainId?: string;\n displayName?: string;\n}\n\nexport interface CreateMailboxResponse {\n mailbox: Mailbox;\n}\n\nexport interface PaymentStatus {\n paid: boolean;\n paidUntil: string | null;\n solanaAddress: string;\n usdcPerPeriod: number;\n periodDays: number;\n creditedUsdc: number;\n payments: unknown[];\n}\n\nexport interface PaymentCheckResponse {\n paid: boolean;\n paidUntil: string;\n newCredits: number;\n balanceUsdc: number;\n creditedUsdc: number;\n}\n\nexport interface Domain {\n id: string;\n domain: string;\n verified: boolean;\n}\n\nexport interface DomainDNSRecords {\n verification: { type: string; name: string; value: string };\n mx: { type: string; name: string; value: string; priority: number };\n spf: { type: string; name: string; value: string };\n dkim: { type: string; name: string; value: string };\n}\n\nexport interface DomainResponse {\n domain: Domain;\n dnsRecords: DomainDNSRecords;\n}\n\nexport interface DomainVerifyResponse {\n verified: boolean;\n txtVerified: boolean;\n mxVerified: boolean;\n spfVerified: boolean;\n dkimVerified: boolean;\n}\n\nexport interface DomainListResponse {\n domains: (Domain & { dnsRecords?: DomainDNSRecords })[];\n}\n\nexport interface ApiKey {\n id: string;\n name: string;\n key: string;\n keyPrefix: string;\n}\n\nexport interface ApiKeyResponse {\n id: string;\n name: string;\n key: string;\n keyPrefix: string;\n}\n\nexport interface ApiKeyListResponse {\n keys: ApiKey[];\n}\n\nexport interface AgentMBoxError {\n error: string;\n}\n\nexport type AgentMBoxErrorCode = 400 | 401 | 402 | 403 | 404 | 409 | 502;\n\nexport function isAgentMBoxError(\n response: unknown,\n): response is AgentMBoxError {\n return (\n typeof response === \"object\" &&\n response !== null &&\n \"error\" in response &&\n typeof (response as AgentMBoxError).error === \"string\"\n );\n}\n","/**\n * AgentMBox Onboarding Service\n * Handles autonomous account creation and setup for AgentMBox\n * The agent pays for its own subscription using its Solana wallet\n */\n\nimport { Service, type IAgentRuntime, logger } from \"@elizaos/core\";\nimport {\n type PaymentStatus,\n type PaymentCheckResponse,\n type ApiKeyResponse,\n type Mailbox,\n} from \"../types\";\n\nexport interface OnboardingStatus {\n stage:\n | \"pending\"\n | \"account_created\"\n | \"api_key_created\"\n | \"awaiting_payment\"\n | \"paid\"\n | \"mailbox_created\"\n | \"complete\"\n | \"error\";\n paymentAddress?: string;\n mailbox?: string;\n error?: string;\n}\n\nexport class AgentMBoxOnboardingService extends Service {\n private apiKey: string = \"\";\n private mailbox: string | undefined;\n private baseUrl: string = \"https://agentmbox.com/api/v1\";\n private cfg: {\n ownerEmail: string;\n password: string;\n mailboxLocalPart: string;\n } | null = null;\n private status: OnboardingStatus = { stage: \"pending\" };\n\n static serviceName = \"agentmbox-onboarding\" as const;\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime!);\n }\n\n get serviceName(): string {\n return AgentMBoxOnboardingService.serviceName;\n }\n\n get capabilityDescription(): string {\n return \"AgentMBox autonomous onboarding - creates account, pays for subscription, sets up mailbox\";\n }\n\n getApiKey(): string {\n return this.apiKey;\n }\n\n getMailbox(): string | undefined {\n return this.mailbox;\n }\n\n private generatePassword(length: number = 32): string {\n const chars =\n \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*\";\n let password = \"\";\n const array = new Uint8Array(length);\n crypto.getRandomValues(array);\n for (let i = 0; i < length; i++) {\n password += chars[array[i] % chars.length];\n }\n return password;\n }\n\n private async getAgentWallet(): Promise<{\n publicKey: string;\n privateKey: Uint8Array;\n } | null> {\n if (!this.runtime) return null;\n\n try {\n const privateKeyBase58 = String(\n this.runtime.getSetting(\"SOLANA_PRIVATE_KEY\") || \"\",\n );\n if (privateKeyBase58) {\n const { default: bs58 } = await import(\"bs58\");\n const { Keypair } = await import(\"@solana/web3.js\");\n const privateKey = bs58.decode(privateKeyBase58);\n const keypair = Keypair.fromSecretKey(privateKey);\n return {\n publicKey: keypair.publicKey.toBase58(),\n privateKey,\n };\n }\n\n const walletService = await this.runtime.getService(\"wallet\");\n if (walletService) {\n const keypair = await (walletService as any).getKeypair?.();\n if (keypair) {\n return {\n publicKey: keypair.publicKey.toBase58(),\n privateKey: keypair.secretKey,\n };\n }\n }\n } catch (error) {\n logger.warn(\"Could not get agent wallet\");\n }\n\n return null;\n }\n\n private async request<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<T> {\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n ...(options.headers as Record<string, string>),\n };\n\n const response = await fetch(url, { ...options, headers });\n const data = await response.json();\n\n if (!response.ok) {\n const error = (data as { error?: string }).error || `${response.status}`;\n throw new Error(error);\n }\n\n return data as T;\n }\n\n private async authenticatedRequest<T>(\n endpoint: string,\n options: RequestInit = {},\n ): Promise<T> {\n if (!this.apiKey) {\n throw new Error(\"API key not set\");\n }\n\n const url = `${this.baseUrl}${endpoint}`;\n const headers: Record<string, string> = {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": \"application/json\",\n ...(options.headers as Record<string, string>),\n };\n\n const response = await fetch(url, { ...options, headers });\n const data = await response.json();\n\n if (!response.ok) {\n const error = (data as { error?: string }).error || `${response.status}`;\n throw new Error(error);\n }\n\n return data as T;\n }\n\n async startOnboarding(runtime: IAgentRuntime): Promise<OnboardingStatus> {\n this.runtime = runtime;\n\n const existingApiKey = String(\n runtime.getSetting(\"AGENTMBOX_API_KEY\") || \"\",\n );\n if (existingApiKey && existingApiKey.startsWith(\"ai_\")) {\n this.apiKey = existingApiKey;\n return await this.checkExistingSetup();\n }\n\n const agentName =\n runtime.character?.name?.toLowerCase().replace(/\\s+/g, \"-\") || \"agent\";\n const mailboxSetting = String(\n runtime.getSetting(\"AGENTMBOX_MAILBOX\") || \"\",\n );\n this.cfg = {\n ownerEmail:\n String(runtime.getSetting(\"AGENTMBOX_OWNER_EMAIL\")) ||\n `agent-${agentName}@owner.local`,\n password: this.generatePassword(32),\n mailboxLocalPart: mailboxSetting\n ? mailboxSetting.split(\"@\")[0]\n : agentName,\n };\n\n try {\n // Step 1: Create account\n await this.createAccount();\n this.status = { stage: \"account_created\" };\n logger.info(\"AgentMBox account created\");\n\n // Step 2: Create API key\n const apiKeyResponse = await this.createApiKey(agentName);\n this.apiKey = apiKeyResponse.key;\n this.status = { stage: \"api_key_created\" };\n logger.info(\"AgentMBox API key created\");\n\n // Step 3: Get payment address\n const payment = await this.getPaymentStatus();\n this.status = {\n stage: \"awaiting_payment\",\n paymentAddress: payment.solanaAddress,\n };\n logger.info(\"Payment address: \" + payment.solanaAddress);\n\n // Step 4: Pay for subscription\n await this.payForSubscription(payment.solanaAddress, runtime);\n this.status = { stage: \"paid\" };\n logger.info(\"Payment completed\");\n\n // Step 5: Create mailbox\n const mailbox = await this.createMailbox(this.cfg!.mailboxLocalPart);\n this.mailbox = mailbox.address;\n this.status = {\n stage: \"complete\",\n mailbox: mailbox.address,\n };\n logger.info(\"Mailbox created: \" + mailbox.address);\n\n return this.status;\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"AgentMBox onboarding failed: \" + errorMsg);\n this.status = { stage: \"error\", error: errorMsg };\n throw error;\n }\n }\n\n private async checkExistingSetup(): Promise<OnboardingStatus> {\n try {\n const payment = await this.getPaymentStatus();\n\n if (payment.paid) {\n const mailbox = await this.getOrCreateMailbox();\n this.status = mailbox\n ? { stage: \"complete\", mailbox: mailbox.address }\n : { stage: \"paid\" };\n } else {\n const wallet = await this.getAgentWallet();\n if (wallet && this.runtime) {\n await this.payForSubscription(payment.solanaAddress, this.runtime);\n this.status = { stage: \"paid\" };\n const mailbox = await this.getOrCreateMailbox();\n if (mailbox) {\n this.status = { stage: \"complete\", mailbox: mailbox.address };\n }\n } else {\n this.status = {\n stage: \"awaiting_payment\",\n paymentAddress: payment.solanaAddress,\n };\n }\n }\n } catch (error) {\n logger.warn(\"Could not check existing setup\");\n this.status = { stage: \"pending\" };\n }\n\n return this.status;\n }\n\n private async payForSubscription(\n paymentAddress: string,\n runtime: IAgentRuntime,\n ): Promise<void> {\n const wallet = await this.getAgentWallet();\n\n if (!wallet) {\n logger.warn(\"No agent wallet found, waiting for manual payment\");\n await this.waitForPayment();\n return;\n }\n\n logger.info(\"Using agent wallet to pay for subscription\");\n\n try {\n const { Connection, Keypair } = await import(\"@solana/web3.js\");\n const { transfer, getOrCreateAssociatedTokenAccount } =\n await import(\"@solana/spl-token\");\n\n const connection = new Connection(\"https://api.mainnet-beta.solana.com\");\n const signer = Keypair.fromSecretKey(wallet.privateKey);\n\n const usdcMintStr = \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGZwyTDt1v\";\n const { PublicKey } = await import(\"@solana/web3.js\");\n const usdcMint = new PublicKey(usdcMintStr);\n const toPublicKey = new PublicKey(paymentAddress);\n\n const fromTokenAccount = await getOrCreateAssociatedTokenAccount(\n connection,\n signer,\n usdcMint,\n signer.publicKey,\n );\n\n const toTokenAccount = await getOrCreateAssociatedTokenAccount(\n connection,\n signer,\n usdcMint,\n toPublicKey,\n );\n\n const amount = 5_000_000;\n\n await transfer(\n connection,\n signer,\n fromTokenAccount.address,\n toTokenAccount.address,\n signer.publicKey,\n amount,\n );\n\n logger.info(\"USDC transfer complete\");\n await this.waitForPayment();\n } catch (error) {\n logger.error(\"Failed to transfer USDC, waiting for manual payment\");\n await this.waitForPayment();\n }\n }\n\n async stop(): Promise<void> {\n logger.info(\"AgentMBox onboarding service stopped\");\n }\n\n private async createAccount(): Promise<void> {\n if (!this.cfg) throw new Error(\"Config not set\");\n\n const response = await this.request<{ id: string }>(\"/auth/signup\", {\n method: \"POST\",\n body: JSON.stringify({\n email: this.cfg.ownerEmail,\n password: this.cfg.password,\n }),\n });\n\n logger.info(\"Account created: \" + response.id);\n }\n\n private async createApiKey(name: string): Promise<ApiKeyResponse> {\n const response = await this.request<ApiKeyResponse>(\"/keys\", {\n method: \"POST\",\n body: JSON.stringify({ name }),\n });\n\n logger.info(\"API key created: \" + response.key.substring(0, 12) + \"...\");\n return response;\n }\n\n private async getPaymentStatus(): Promise<PaymentStatus> {\n return this.authenticatedRequest<PaymentStatus>(\"/payment\");\n }\n\n private async waitForPayment(\n maxAttempts: number = 60,\n intervalMs: number = 5000,\n ): Promise<PaymentCheckResponse> {\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.authenticatedRequest<PaymentCheckResponse>(\n \"/payment/check\",\n {\n method: \"POST\",\n },\n );\n\n if (result.paid) {\n return result;\n }\n\n logger.info(\n \"Waiting for payment... (\" + attempt + \"/\" + maxAttempts + \")\",\n );\n } catch (e) {\n logger.warn(\n \"Payment check failed: \" +\n (e instanceof Error ? e.message : \"unknown\"),\n );\n }\n\n if (attempt < maxAttempts) {\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n }\n\n throw new Error(\"Payment not received after \" + maxAttempts + \" attempts\");\n }\n\n private async createMailbox(localPart: string): Promise<Mailbox> {\n const response = await this.authenticatedRequest<{ mailbox: Mailbox }>(\n \"/mailboxes\",\n {\n method: \"POST\",\n body: JSON.stringify({\n localPart,\n displayName: this.cfg?.mailboxLocalPart || \"Agent Mailbox\",\n }),\n },\n );\n\n return response.mailbox;\n }\n\n async getOrCreateMailbox(): Promise<Mailbox | null> {\n try {\n const response = await this.authenticatedRequest<{\n mailboxes: Mailbox[];\n }>(\"/mailboxes\");\n\n if (response.mailboxes.length > 0) {\n return response.mailboxes[0];\n }\n\n if (this.cfg?.mailboxLocalPart) {\n return await this.createMailbox(this.cfg.mailboxLocalPart);\n }\n\n return null;\n } catch (error) {\n logger.error(\"Failed to get/create mailbox\");\n return null;\n }\n }\n\n getStatus(): OnboardingStatus {\n return this.status;\n }\n\n async getPaymentAddress(): Promise<string | null> {\n if (this.status.paymentAddress) {\n return this.status.paymentAddress;\n }\n\n try {\n const payment = await this.getPaymentStatus();\n return payment.solanaAddress;\n } catch {\n return null;\n }\n }\n\n isOnboardingComplete(): boolean {\n return this.status.stage === \"complete\";\n }\n}\n\nexport default AgentMBoxOnboardingService;\n","/**\n * Send Email Action\n * Allows the agent to send emails via AgentMBox\n */\n\nimport {\n type Action,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n type ActionExample,\n} from \"@elizaos/core\";\nimport { AgentMBoxService } from \"../services/AgentMBoxService\";\n\nexport const sendEmailAction: Action = {\n name: \"SEND_EMAIL\",\n description: \"Send an email to a recipient using AgentMBox email service\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n options: Record<string, unknown>,\n callback?: HandlerCallback\n ) => {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (!service) {\n throw new Error(\"AgentMBox service not initialized\");\n }\n\n const { to, subject, text, html } = options;\n\n if (!to) {\n throw new Error(\"Missing required field: 'to' (recipient email)\");\n }\n\n if (!subject) {\n throw new Error(\"Missing required field: 'subject'\");\n }\n\n const from = options.from as string | undefined;\n\n try {\n const result = await service.sendEmail({\n from,\n to: Array.isArray(to) ? to : to,\n subject,\n text: text as string | undefined,\n html: html as string | undefined,\n });\n\n if (callback) {\n await callback({\n text: `Email sent successfully to ${to}`,\n values: {\n success: result.success,\n recipient: to,\n subject,\n },\n });\n }\n\n return {\n success: true,\n values: {\n sentTo: to,\n subject,\n },\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Failed to send email\", { error: errorMessage });\n\n if (callback) {\n await callback({\n text: `Failed to send email: ${errorMessage}`,\n values: {\n success: false,\n error: errorMessage,\n },\n });\n }\n\n return {\n success: false,\n error: errorMessage,\n };\n }\n },\n validate: async (runtime: IAgentRuntime) => {\n try {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n return !!service;\n } catch {\n return false;\n }\n },\n examples: [\n [\n {\n name: \"user\",\n content: \"Send an email to john@example.com about the project update\",\n },\n {\n name: \"assistant\",\n content: \"I'll send that email for you.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Email the team that the meeting is at 3pm\",\n },\n {\n name: \"assistant\",\n content: \"Sending that email now.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Can you notify alice@example.com that the report is ready?\",\n },\n {\n name: \"assistant\",\n content: \"I'll send her an email right away.\",\n },\n ],\n ] as ActionExample[][],\n};\n\nexport default sendEmailAction;\n","/**\n * Get Emails Action\n * Allows the agent to retrieve emails from the mailbox via AgentMBox\n */\n\nimport {\n type Action,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n type ActionExample,\n} from \"@elizaos/core\";\nimport { AgentMBoxService } from \"../services/AgentMBoxService\";\n\nexport const getEmailsAction: Action = {\n name: \"GET_EMAILS\",\n description: \"Retrieve emails from the AgentMBox mailbox. Can filter by read status and limit results.\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n options: Record<string, unknown>,\n callback?: HandlerCallback\n ) => {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (!service) {\n throw new Error(\"AgentMBox service not initialized\");\n }\n\n const limit = (options.limit as number) || 10;\n const offset = (options.offset as number) || 0;\n const emailId = options.emailId as string | undefined;\n\n try {\n // If emailId is provided, get a specific email\n if (emailId) {\n const emailDetail = await service.getEmail(emailId);\n\n if (callback) {\n await callback({\n text: `Retrieved email: ${emailDetail.email.subject}`,\n values: {\n email: emailDetail.email,\n },\n });\n }\n\n return {\n success: true,\n values: {\n email: emailDetail.email,\n },\n };\n }\n\n // Otherwise, list emails\n const emailList = await service.listEmails(limit, offset);\n\n // Filter by read status if specified\n let emails = emailList.emails;\n const unreadOnly = options.unreadOnly as boolean;\n if (unreadOnly) {\n emails = emails.filter((email) => !email.isRead);\n }\n\n if (callback) {\n const preview = emails\n .slice(0, 5)\n .map((e) => `- ${e.subject} from ${e.from[0]?.email}`)\n .join(\"\\n\");\n await callback({\n text: `Found ${emails.length} emails:\\n${preview}`,\n values: {\n emails: emails,\n total: emailList.emails.length,\n unread: emailList.emails.filter((e) => !e.isRead).length,\n },\n });\n }\n\n return {\n success: true,\n values: {\n emails: emails,\n total: emailList.emails.length,\n limit: emailList.limit,\n offset: emailList.offset,\n },\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n logger.error(\"Failed to get emails\", { error: errorMessage });\n\n if (callback) {\n await callback({\n text: `Failed to get emails: ${errorMessage}`,\n values: {\n success: false,\n error: errorMessage,\n },\n });\n }\n\n return {\n success: false,\n error: errorMessage,\n };\n }\n },\n validate: async (runtime: IAgentRuntime) => {\n try {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n return !!service;\n } catch {\n return false;\n }\n },\n examples: [\n [\n {\n name: \"user\",\n content: \"Check my inbox for any new emails\",\n },\n {\n name: \"assistant\",\n content: \"Let me check your inbox for new emails.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Show me the last 5 emails I received\",\n },\n {\n name: \"assistant\",\n content: \"I'll retrieve your recent emails.\",\n },\n ],\n [\n {\n name: \"user\",\n content: \"Get the details of that email about the meeting\",\n },\n {\n name: \"assistant\",\n content: \"Let me fetch that email for you.\",\n },\n ],\n ] as ActionExample[][],\n};\n\nexport default getEmailsAction;\n","/**\n * Email Provider\n * Provides email context to the agent, including unread counts and recent emails\n */\n\nimport {\n type Provider,\n type IAgentRuntime,\n type Memory,\n type State,\n type ProviderResult,\n} from \"@elizaos/core\";\nimport { AgentMBoxService } from \"../services/AgentMBoxService\";\n\nexport const emailProvider: Provider = {\n name: \"email\",\n description: \"Provides email context from AgentMBox including unread counts and recent messages\",\n get: async (\n runtime: IAgentRuntime,\n message: Memory,\n _state: State\n ): Promise<ProviderResult> => {\n try {\n const service = runtime.getService<AgentMBoxService>(\"agentmbox\");\n if (!service) {\n return {\n text: \"Email service not available\",\n values: {\n available: false,\n },\n };\n }\n\n // Get recent emails\n const emailList = await service.listEmails(10, 0);\n const unreadCount = emailList.emails.filter((e) => !e.isRead).length;\n const recentEmails = emailList.emails.slice(0, 5);\n\n // Format recent emails for context\n const recentEmailsText = recentEmails\n .map(\n (email) =>\n `- From: ${email.from[0]?.name || email.from[0]?.email || \"Unknown\"} | Subject: ${email.subject}${\n !email.isRead ? \" [UNREAD]\" : \"\"\n }`\n )\n .join(\"\\n\");\n\n return {\n text: `Email Status: ${unreadCount} unread of ${emailList.emails.length} total${\n recentEmails.length > 0\n ? `\\n\\nRecent Emails:\\n${recentEmailsText}`\n : \"\\n\\nNo recent emails.\"\n }`,\n values: {\n available: true,\n unreadCount,\n totalEmails: emailList.emails.length,\n recentEmails: recentEmails.map((e) => ({\n id: e.id,\n from: e.from[0],\n subject: e.subject,\n preview: e.preview,\n isRead: e.isRead,\n receivedAt: e.receivedAt,\n })),\n },\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : \"Unknown error\";\n return {\n text: `Email service error: ${errorMessage}`,\n values: {\n available: false,\n error: errorMessage,\n },\n };\n }\n },\n};\n\nexport default emailProvider;\n"],"mappings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,gBACP;AACA,YAAAA,QAAO;AAAA,cACL,oCAAoC,OAAO;AAAA,YAC7C;AACA,YAAAA,QAAO,KAAK,iDAAiD;AAAA,UAC/D;AAAA,QACF;AAAA,MACF,SAAS,OAAO;AACd,cAAM,WACJ,iBAAiB,QAAQ,MAAM,UAAU;AAC3C,QAAAA,QAAO,MAAM,wBAAwB,QAAQ;AAAA,MAC/C;AAAA,IACF,WAAW,gBAAgB;AACzB,MAAAA,QAAO,KAAK,wCAAwC;AAAA,IACtD,OAAO;AACL,MAAAA,QAAO,KAAK,sCAAsC;AAAA,IACpD;AAGA,UAAM,eAAe,QAAQ,WAA6B,WAAW;AACrE,QAAI,cAAc;AAChB,UAAI;AACF,cAAM,aAAa,WAAW,OAAO;AAAA,MACvC,SAAS,OAAO;AACd,cAAM,WACJ,iBAAiB,QAAQ,MAAM,UAAU;AAC3C,QAAAA,QAAO;AAAA,UACL,mDAAmD;AAAA,QACrD;AAAA,MAEF;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;","names":["logger","logger","logger","Service","logger","logger"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agentmbox/plugin-agentmbox",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "description": "AgentMBox email integration plugin for ElizaOS - enables AI agents to send and receive emails",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -41,13 +41,14 @@ export class AgentMBoxService extends Service {
41
41
  const mailbox = String(runtime.getSetting("AGENTMBOX_MAILBOX") || "");
42
42
  const baseUrl = String(runtime.getSetting("AGENTMBOX_BASE_URL") || "");
43
43
 
44
- if (!apiKey) {
45
- throw new Error(
46
- "AGENTMBOX_API_KEY is required. Get your API key from https://agentmbox.com"
47
- );
44
+ // API key will be set by onboarding if not provided
45
+ // The service will work once onboarding completes
46
+ if (apiKey && !apiKey.startsWith("ai_")) {
47
+ logger.warn("AgentMBox API key should start with 'ai_'");
48
48
  }
49
49
 
50
- const agentName = runtime.character?.name?.toLowerCase().replace(/\s+/g, "-") || "agent";
50
+ const agentName =
51
+ runtime.character?.name?.toLowerCase().replace(/\s+/g, "-") || "agent";
51
52
  const defaultMailbox = mailbox || `${agentName}@agentmbox.com`;
52
53
 
53
54
  this.apiKey = apiKey;
@@ -66,7 +67,16 @@ export class AgentMBoxService extends Service {
66
67
  logger.info("AgentMBox service stopped");
67
68
  }
68
69
 
69
- private async request<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
70
+ private async request<T>(
71
+ endpoint: string,
72
+ options: RequestInit = {},
73
+ ): Promise<T> {
74
+ if (!this.apiKey) {
75
+ throw new Error(
76
+ "AgentMBox API key not configured. Ensure onboarding has completed or set AGENTMBOX_API_KEY.",
77
+ );
78
+ }
79
+
70
80
  const url = `${this.baseUrl}${endpoint}`;
71
81
  const headers: Record<string, string> = {
72
82
  Authorization: `Bearer ${this.apiKey}`,
@@ -79,7 +89,9 @@ export class AgentMBoxService extends Service {
79
89
 
80
90
  if (!response.ok) {
81
91
  if (isAgentMBoxError(data)) {
82
- throw new Error(`AgentMBox API error (${response.status}): ${data.error}`);
92
+ throw new Error(
93
+ `AgentMBox API error (${response.status}): ${data.error}`,
94
+ );
83
95
  }
84
96
  throw new Error(`AgentMBox API error: ${response.status}`);
85
97
  }
@@ -96,7 +108,9 @@ export class AgentMBoxService extends Service {
96
108
 
97
109
  async listEmails(limit = 50, offset = 0): Promise<EmailListResponse> {
98
110
  const mailboxParam = this.getMailboxParam();
99
- return this.request<EmailListResponse>("/mail" + mailboxParam + "&limit=" + limit + "&offset=" + offset);
111
+ return this.request<EmailListResponse>(
112
+ "/mail" + mailboxParam + "&limit=" + limit + "&offset=" + offset,
113
+ );
100
114
  }
101
115
 
102
116
  async getEmail(emailId: string): Promise<EmailDetailResponse> {
@@ -118,16 +132,21 @@ export class AgentMBoxService extends Service {
118
132
 
119
133
  async deleteEmail(emailId: string): Promise<{ success: boolean }> {
120
134
  const mailboxParam = this.getMailboxParam();
121
- return this.request<{ success: boolean }>("/mail/" + emailId + mailboxParam, {
122
- method: "DELETE",
123
- });
135
+ return this.request<{ success: boolean }>(
136
+ "/mail/" + emailId + mailboxParam,
137
+ {
138
+ method: "DELETE",
139
+ },
140
+ );
124
141
  }
125
142
 
126
143
  async listMailboxes(): Promise<MailboxListResponse> {
127
144
  return this.request<MailboxListResponse>("/mailboxes");
128
145
  }
129
146
 
130
- async createMailbox(request: CreateMailboxRequest): Promise<CreateMailboxResponse> {
147
+ async createMailbox(
148
+ request: CreateMailboxRequest,
149
+ ): Promise<CreateMailboxResponse> {
131
150
  return this.request<CreateMailboxResponse>("/mailboxes", {
132
151
  method: "POST",
133
152
  body: JSON.stringify(request),
@@ -162,9 +181,12 @@ export class AgentMBoxService extends Service {
162
181
  }
163
182
 
164
183
  async verifyDomain(domainId: string): Promise<DomainVerifyResponse> {
165
- return this.request<DomainVerifyResponse>("/domains/" + domainId + "/verify", {
166
- method: "POST",
167
- });
184
+ return this.request<DomainVerifyResponse>(
185
+ "/domains/" + domainId + "/verify",
186
+ {
187
+ method: "POST",
188
+ },
189
+ );
168
190
  }
169
191
 
170
192
  async deleteDomain(domainId: string): Promise<{ success: boolean }> {