> ## Documentation Index
> Fetch the complete documentation index at: https://docs.oneshotagent.com/llms.txt
> Use this file to discover all available pages before exploring further.

# OneShot SDK Code Examples - Email, Voice, Build & More

> Complete TypeScript code examples for the OneShot SDK. Learn to send emails, make calls, build websites, conduct research, and more.

## Initialize

<Tabs>
  <Tab title="CDP Wallet (Recommended)">
    ```typescript theme={null}
    import { OneShot } from "@oneshot-agent/sdk";

    // No private keys — signing in Coinbase's secure enclave
    const agent = await OneShot.create({ cdp: true });
    ```
  </Tab>

  <Tab title="Private Key">
    ```typescript theme={null}
    import { OneShot } from "@oneshot-agent/sdk";

    const agent = new OneShot({
      privateKey: process.env.AGENT_PRIVATE_KEY,
    });
    ```
  </Tab>
</Tabs>

All examples below work with either initialization method.

## Send Email

```typescript theme={null}
// Simple email
await agent.email({
  to: "user@example.com",
  subject: "Hello from OneShot",
  body: "This email was sent autonomously!",
});

// Email with attachments
await agent.email({
  to: "user@example.com",
  subject: "Report attached",
  body: "Please find the report attached.",
  attachments: [
    {
      filename: "report.pdf",
      content: base64Content,
      content_type: "application/pdf",
    },
  ],
});

// Custom sender — display name, mailbox, and domain.
// Renders as: From: Jane Doe <jane@acme.com>
await agent.email({
  to: "user@example.com",
  subject: "Hello",
  body: "Sent from a custom sender.",
  from_name: "Jane Doe",     // display name (optional)
  from_mailbox: "jane",      // local-part, defaults to "agent"
  from_domain: "acme.com",   // defaults to "oneshotagent.com"
});
```

<Note>
  `from_domain` must be a domain you've provisioned through OneShot.
  `from_mailbox` defaults to `agent` and `from_domain` to `oneshotagent.com`,
  so the default sender is `agent@oneshotagent.com`. `from_name` is the
  human-readable name recipients see; omit it to send from the bare address.
</Note>

<Note>
  **Dedicated mailboxes** — pass `mailbox_mode: "mailbox"` when **first
  provisioning a new `from_domain`** to give each address a real dedicated
  mailbox (better deliverability + per-address warmup) instead of the default
  `relay` (header-only) send. It adds a one-time `mailbox_provisioning_fee` to
  the quote. It only applies at first setup — an already-provisioned domain
  keeps the mode it was created with, and requesting `mailbox` on an existing
  relay domain returns `400 mailbox_mode_conflict`.
</Note>

## Bulk Email

Send the same email to multiple recipients:

```typescript theme={null}
import { OneShot } from "@oneshot-agent/sdk";

const agent = new OneShot({
  privateKey: process.env.AGENT_PRIVATE_KEY,
});

// Send to multiple recipients
await agent.email({
  to: ["alice@example.com", "bob@example.com", "charlie@example.com"],
  subject: "Weekly Team Update",
  body: "Here is this week's progress report...",
});

// Each recipient gets an individual email (not CC/BCC)
```

<Note>
  The SDK automatically handles bulk quoting and pricing. Service fees scale
  with the number of recipients.
</Note>

## Voice Calls

Make phone calls that can accomplish objectives autonomously:

```typescript theme={null}
import { OneShot } from "@oneshot-agent/sdk";

const agent = new OneShot({
  privateKey: process.env.AGENT_PRIVATE_KEY,
});

// Simple call - make a restaurant reservation
const result = await agent.voice({
  objective: "Make a dinner reservation for 2 at 7pm tonight",
  target_number: "+14155551234",
  caller_persona: "A polite assistant making a reservation",
  context: "Italian restaurant, prefer outdoor seating",
});

console.log("Transcript:", result.transcript);
console.log("Summary:", result.summary);
console.log("Success:", result.success_evaluation);

// Conference call - connect multiple parties
const conference = await agent.voice({
  objective: "Connect the buyer and seller to negotiate the final price",
  target_number: ["+14155551234", "+14155555678"],
  caller_persona: "A professional meeting facilitator",
});
```

## SMS Messages

Send text messages to one or multiple recipients:

```typescript theme={null}
import { OneShot } from "@oneshot-agent/sdk";

const agent = new OneShot({
  privateKey: process.env.AGENT_PRIVATE_KEY,
});

// Single recipient
const result = await agent.sms({
  message: "Your order has shipped! Track it at example.com/track/123",
  to_number: "+14155551234",
});

// Multiple recipients (up to 10)
const bulkResult = await agent.sms({
  message: "Team meeting moved to 3pm",
  to_number: ["+14155551234", "+14155555678", "+14155559012"],
});

// Check SMS inbox for replies
const inbox = await agent.smsInboxList({ limit: 10 });

for (const msg of inbox.messages) {
  console.log(`From ${msg.from}: ${msg.body}`);
}

// Get a specific message
const message = await agent.smsInboxGet("msg_abc123");
```

## Deep Research

```typescript theme={null}
// Quick research (5-10 sources, 2-3 minutes)
const quickReport = await agent.research({
  topic: "Latest developments in AI agents",
  depth: "quick",
});

console.log(quickReport.report_content);
console.log(`Sources: ${quickReport.sources_count}`);

// Comprehensive research (20+ sources, 5-10 minutes)
const deepReport = await agent.research({
  topic: "Blockchain scalability solutions",
  depth: "deep",
});

console.log(deepReport.report_content);
console.log(`Report saved to: ${deepReport.report_gcs_uri}`);
```

## Poll Inbox

```typescript theme={null}
// List recent emails
const inbox = await agent.inboxList({
  include_body: true,
  limit: 10,
});

for (const email of inbox.emails) {
  console.log(`From: ${email.from}`);
  console.log(`Subject: ${email.subject}`);
  console.log(`Body: ${email.body}`);

  // Process attachments
  if (email.attachments) {
    for (const att of email.attachments) {
      const buffer = Buffer.from(att.content, "base64");
      // Process attachment...
    }
  }
}

// Get emails since a specific time
const recentInbox = await agent.inboxList({
  since: "2024-01-01T00:00:00Z",
  include_body: true,
});

// Get a specific email by ID
const specificEmail = await agent.inboxGet("email-id-here");
```

## People Search & Enrichment

```typescript theme={null}
// Search for people by criteria
const results = await agent.peopleSearch({
  job_titles: ["CEO", "CTO", "VP Engineering"],
  company_domains: ["stripe.com", "anthropic.com"],
  location: ["San Francisco"],
  limit: 20,
});

console.log(`Found ${results.total_found} people`);

for (const person of results.results) {
  console.log(`${person.full_name} - ${person.title} at ${person.company}`);

  // Enrich profile for more details
  const profile = await agent.enrichProfile({
    linkedin_url: person.linkedin_url,
  });

  console.log(`Skills: ${profile.profile.skills?.join(", ")}`);
}
```

## Email Finder & Verification

```typescript theme={null}
// Find email for a person
const found = await agent.findEmail({
  full_name: "Dario Amodei",
  company_domain: "anthropic.com",
});

if (found.found) {
  console.log(`Found email: ${found.email}`);

  // Verify before sending
  const verification = await agent.verifyEmail({
    email: found.email,
  });

  if (verification.deliverable) {
    await agent.email({
      to: found.email,
      subject: "Hello",
      body: "Your message here...",
    });
  }
}
```

## Commerce - Search & Buy

```typescript theme={null}
// Search for products
const products = await agent.commerceSearch({
  query: "USB-C hub multiport",
  limit: 5,
});

console.log(`Found ${products.count} products`);

// Buy the first result
const order = await agent.commerceBuy({
  product_url: products.products[0].product_url,
  shipping_address: {
    first_name: "John",
    last_name: "Doe",
    street: "123 Main St",
    city: "San Francisco",
    state: "CA",
    zip_code: "94102",
    country: "US",
    phone: "4155550100",
    email: "john@example.com",
  },
  quantity: 1,
  maxCost: 100, // Fail if total exceeds $100
});

console.log(`Order submitted: ${order.request_id}`);
```

## Web Search

Search the web and get structured results instantly (synchronous — no polling):

```typescript theme={null}
// Quick web search
const results = await agent.webSearch({
  query: "best AI agent frameworks 2026",
  max_results: 10,
});

for (const result of results.results) {
  console.log(`${result.title}: ${result.url}`);
}
```

## Web Read

Read any web page and get markdown content with a screenshot:

```typescript theme={null}
// Read a web page
const page = await agent.webRead({
  url: "https://news.ycombinator.com",
});

console.log(page.markdown);          // Page content as markdown
console.log(page.screenshot_url);    // Screenshot of the page
console.log(page.metadata.title);    // Page title
```

## Browser Automation

Navigate websites, fill forms, extract structured data, and interact with web apps:

```typescript theme={null}
// Extract structured data from a website
const result = await agent.browser({
  task: "Go to producthunt.com and extract the top 5 AI products launched today",
  output_schema: {
    products: [{
      name: "string",
      description: "string",
      upvotes: "number"
    }]
  }
});

console.log("Products:", result.output.products);
console.log("Steps taken:", result.steps.length);
console.log("Cost:", result.cost, "USDC");

// Resume a previous browser session (preserves cookies/login state)
const followUp = await agent.browser({
  task: "Click on the first product and extract the full description",
  session_id: result.session_id,
});
```

## Person Intelligence

Look up anyone by email, name, or social URL. Each method runs async and returns when the job finishes.

```typescript theme={null}
// Full background report on a person (takes 2-5 minutes)
const dossier = await agent.deepResearchPerson({
  email: "satya@microsoft.com",
  name: "Satya Nadella",
  company: "Microsoft",
});

// Emails and phones are nested inside result.enrichment
const enrichment = dossier.result.enrichment;
console.log("Work email:", enrichment.best_work_email);
console.log("Personal email:", enrichment.best_personal_email);
console.log("All emails:", enrichment.altemails);
console.log("Phone:", enrichment.fullphone?.[0]?.fullphone);
console.log("Company:", enrichment.organizations?.[0]?.name);
console.log("LinkedIn:", enrichment.social_profiles?.linkedin?.url);

// Articles from the deep research
console.log("Articles:", dossier.result.articles);

// Find their accounts on LinkedIn, Twitter, GitHub, etc
const socials = await agent.socialProfiles({
  email: "satya@microsoft.com",
});

console.log(socials.result);

// Articles and interviews mentioning them
const articles = await agent.articleSearch({
  name: "Satya Nadella",
  company: "Microsoft",
  sort: "recent",
  limit: 5,
});

console.log(articles.result);

// Recent posts with likes, replies, shares
const feed = await agent.personNewsfeed({
  social_media_url: "https://twitter.com/sataborasu",
});

console.log(feed.result);

// What they care about (sports, tech, politics, etc)
const interests = await agent.personInterests({
  email: "satya@microsoft.com",
});

console.log(interests.result);

// Who they follow and who follows them
const interactions = await agent.personInteractions({
  social_media_url: "https://twitter.com/sataborasu",
  type: "followers,following",
  max_results: 50,
});

console.log(interactions.result);
```

## Universal Tool Method

Call any OneShot tool using the universal `tool()` method:

```typescript theme={null}
// Email quote
const quote = await agent.tool("email/quote", {
  from_address: "agent@oneshotagent.com",
  to_address: "user@example.com",
  subject: "Test",
  body: "Hello",
});

console.log(`Cost: $${quote.total_cost}`);

// Email send (with quote ID)
const send = await agent.toolWithQuote(
  "email/send",
  {
    from_address: "agent@oneshotagent.com",
    to_address: "user@example.com",
    subject: "Test",
    body: "Hello",
  },
  quote.quote_id,
);
```

## Check Wallet Balance

```typescript theme={null}
const agent = new OneShot({
  privateKey: process.env.AGENT_PRIVATE_KEY,
});

console.log("Agent address:", agent.address);

const balance = await agent.getBalance(agent.usdcAddress);
console.log(`Wallet balance: ${balance} USDC`);

if (parseFloat(balance) < 1.0) {
  console.warn("Low balance! Please fund your wallet.");
}
```

<Tip>
  The `agent.usdcAddress` getter returns the USDC contract address on Base Mainnet: `0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`.
</Tip>

## Error Handling

```typescript theme={null}
import {
  OneShot,
  ContentBlockedError,
  EmergencyNumberError,
} from "@oneshot-agent/sdk";

try {
  await agent.sms({
    message: "Your appointment is confirmed",
    to_number: "+14155551234",
  });
} catch (error) {
  if (error instanceof ContentBlockedError) {
    // Message flagged by content safety
    console.error("Content blocked:", error.categories);
  } else if (error instanceof EmergencyNumberError) {
    // Attempted to contact emergency services
    console.error("Emergency number blocked:", error.blockedNumber);
  } else if (error.message.includes("Insufficient balance")) {
    console.error("Not enough funds in wallet");
  } else if (error.message.includes("domain_unavailable")) {
    console.error("Domain is not available");
  } else {
    console.error("Error:", error.message);
  }
}
```

## Build Production Websites

Generate and deploy fully-functional websites from product descriptions:

```typescript theme={null}
import { OneShot } from "@oneshot-agent/sdk";

const agent = new OneShot({
  privateKey: process.env.AGENT_PRIVATE_KEY,
});

// Build a SaaS landing page
const result = await agent.build({
  type: "saas",
  product: {
    name: "TaskFlow",
    description: "AI-powered task management for remote teams. Automate workflows, track progress, and collaborate seamlessly.",
    industry: "Productivity",
    pricing: "Free tier, Pro $12/mo, Team $29/mo"
  },
  lead_capture: { enabled: true },
  brand: {
    primary_color: "#4F46E5",
    tone: "professional"
  }
});

console.log("Website live at:", result.production_url);
console.log("Preview:", result.preview_url);
```

## Update Existing Website

Iterate on an existing website with new content:

```typescript theme={null}
import { OneShot } from "@oneshot-agent/sdk";

const agent = new OneShot({
  privateKey: process.env.AGENT_PRIVATE_KEY,
});

// Update with new content
const result = await agent.updateBuild({
  build_id: "550e8400-e29b-41d4-a716-446655440000", // from original build
  product: {
    name: "TaskFlow 2.0",
    description: "Now with AI automation! Task management reimagined for modern teams.",
    pricing: "Free tier, Pro $15/mo, Team $35/mo"
  }
});

console.log("Updated:", result.production_url);
```

## Complete Agent Example

```typescript theme={null}
import { OneShot } from "@oneshot-agent/sdk";

class EmailAgent {
  private agent: OneShot;
  private lastCheck: string;

  private constructor(agent: OneShot) {
    this.agent = agent;
    this.lastCheck = new Date().toISOString();
  }

  static async create() {
    // CDP wallet — no private keys in config
    const agent = await OneShot.create({ cdp: true });
    return new EmailAgent(agent);
  }

  async start() {
    console.log(`Agent started: ${this.agent.address}`);

    // Poll inbox every minute
    setInterval(() => this.pollInbox(), 60000);
  }

  async pollInbox() {
    try {
      const inbox = await this.agent.inboxList({
        since: this.lastCheck,
        include_body: true,
        limit: 50,
      });

      if (inbox.count > 0) {
        console.log(`Received ${inbox.count} new email(s)`);

        for (const email of inbox.emails) {
          await this.processEmail(email);
        }

        this.lastCheck = new Date().toISOString();
      }
    } catch (error) {
      console.error("Error polling inbox:", error);
    }
  }

  async processEmail(email: any) {
    console.log(`Processing email from ${email.from}`);

    const reply = await this.generateReply(email);

    await this.agent.email({
      to: email.from,
      subject: `Re: ${email.subject}`,
      body: reply,
    });

    console.log(`Replied to ${email.from}`);
  }

  async generateReply(email: any): Promise<string> {
    // Use your LLM here to generate a reply
    return `Thank you for your email. I'll get back to you soon!`;
  }
}

// Start the agent
const agent = await EmailAgent.create();
agent.start();
```

## Next Steps

<CardGroup cols={2}>
  <Card title="API Reference" icon="code" href="/api-reference/email/quote">
    Explore all available endpoints
  </Card>

  <Card title="SDK Source" icon="github" href="https://github.com/oneshot-agent/sdk">
    View SDK source code on GitHub
  </Card>
</CardGroup>
