Skip to content

About

Official TypeScript SDK for Layrcake: go-to-market infrastructure for AI agents. Find leads, verify emails, read signals, run approved campaigns.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Layrcake TypeScript SDK

Go-to-market infrastructure for AI agents: find leads, enrich and verify emails, read buying signals, research companies, and run email campaigns that a person approves before anything sends.

This is the official TypeScript client for the Layrcake API. It has no runtime dependencies. It works in Node 18 or later, Bun, Deno, Cloudflare Workers, Vercel Edge and other runtimes with fetch.

Install

npm install layrcake

Quickstart

Get an API key at layrcake.dev and set LAYRCAKE_API_KEY.

import { Layrcake, getApproval } from "layrcake";

const layrcake = new Layrcake(); // reads LAYRCAKE_API_KEY

const { result: found } = await layrcake.findLeads({ audience: "Heads of sales at US software companies with 50 to 500 staff", titles: ["Head of Sales"], locations: ["United States"], industries: ["Software Development"], company_headcount: { min: 50, max: 500 }, limit: 5 });
const lead = found.leads[0]!;
const { result: enriched } = await layrcake.enrich({ person: { full_name: lead.full_name!, company_domain: lead.company_domain! }, want: ["work_email"] });
const email = enriched.contact?.work_email ?? lead.work_email!;
const { result: check } = await layrcake.verifyEmail({ email });
if (check.status !== "valid") throw new Error(`${email} is ${check.status}`);
const { result: draft } = await layrcake.createCampaign({ name: "Q4 sales leaders", leads: [{ email }], steps: [{ subject: "Your outbound this quarter", body: "Hi {{first_name}}, ..." }] });
const preview = await layrcake.launchCampaign({ campaign_id: draft.campaign_id });
console.log("Ask a person to approve:", getApproval(preview)?.approvalUrl);

The last call sends nothing. It returns a preview and an approval link. Emails go out only after a signed-in person approves in the Layrcake console.

Configuration

const layrcake = new Layrcake({
  apiKey: "lc_...", // default: the LAYRCAKE_API_KEY environment variable
  baseUrl: "https://api.layrcake.dev", // default
  maxRetries: 2, // default
  timeoutMs: 60_000, // per attempt, default
  fetch: customFetch, // default: the global fetch
});

The constructor throws if it finds no key. Keep the key on a server. Do not ship it to a browser.

Every method also takes per-call options as its last argument:

await layrcake.getMe({ timeoutMs: 5_000, maxRetries: 0, signal: controller.signal });

Methods

Every method returns { result, layrcake, requestId }.

  • result is the outcome, typed from the OpenAPI spec.
  • layrcake holds billing facts on metered calls: request_id, credits_charged and credits_available. It is null on endpoints that return none.
  • requestId is the request id. Quote it to support.

Credit amounts are decimal strings, exactly as the API sends them, such as "1.250000". The SDK never turns them into floating point numbers. Use a decimal library if you need to do arithmetic.

Method Endpoint What it does
verifyEmail(params) POST /v1/verify_email Check whether one email address can receive mail, including catch-all analysis.
enrich(params) POST /v1/enrich Find a person's work email, mobile or profile from an email, LinkedIn URL, or name and company.
findLeads(params) POST /v1/find_leads Find people who match an audience description and filters.
findIntent(params) POST /v1/find_intent Find hiring, funding, news and job-change signals for a list of company domains.
checkCompanies(params) POST /v1/check_companies Answer one yes or no question about each company in a list, with evidence.
findCompanies(params) POST /v1/find_companies Find companies that match a description and filters.
enrichCompany(params) POST /v1/enrich_company Get profile, technology, funding or relationship data for one company domain.
findPosts(params) POST /v1/find_posts Find social posts by topic, author or company, or the people engaging with given posts.
setupSending(params) POST /v1/setup_sending Quote, then buy after human approval, warmed domains and mailboxes for sending.
createCampaign(params) POST /v1/campaigns Create a draft email campaign with leads and sequence steps. Nothing sends yet.
addLeads(params) POST /v1/add_leads Add leads to a campaign. Adding to an active campaign needs human approval.
launchCampaign(params) POST /v1/launch_campaign Launch a draft campaign. Returns a preview first. A person approves before anything sends.
getReplies(params) POST /v1/get_replies List campaign replies, newest first. Free.
getReply(params) POST /v1/get_reply Read one reply in full, including its body and lead state. Free.
setLeadStatus(params) POST /v1/set_lead_status Record a lead's interest status, such as interested or meeting_booked. Free.
replyToThread(params) POST /v1/reply_to_thread Reply in an existing thread. Returns a preview first. A person approves before it sends.
researchCompany(params) POST /v1/research_company Run source-backed research on one company in the background.
prospectPicture(params) POST /v1/prospect_picture Build one picture of a person, a company, or both, in the background.
llm(params) POST /v1/llm/chat Chat with a hosted model through Layrcake.
getMe() GET /v1/me Who this key is and what it may do.
getTrail(query) GET /v1/trail Your workspace's outcome record, newest first, typed per kind.
exportTrailCsv(query) GET /v1/trail/export.csv Complete bounded trail CSV.
getCampaignProof(id) GET /v1/campaigns/{id}/proof Whole retained campaign proof as safe JSON.
tightenKeyPolicy(id, params) PATCH /v1/keys/{id} Tighten another key's policy (lower caps/limits, drop scopes).
importDoNotContact(params) POST /v1/do_not_contact Add up to 5,000 emails to the workspace do-not-contact list.
killSending(params) POST /v1/kill Stop sending for the whole workspace: pauses every launching/active campaign (provider-verified) and blocks new launches, purchases and replies until an owner clears it in the console.
pauseCampaign(id) POST /v1/campaigns/{id}/pause Pause one campaign through verified containment.
getOperation(id, query) GET /v1/operations/{id} Read the state, progress and result of a background operation.

Dry runs

Most paid verbs accept dry_run: true. The call returns a plan instead: the most it can cost, how many sources could answer, and any limit it would trip. Nothing is looked up, reserved or charged. The return type follows the flag.

const { result } = await layrcake.findLeads({ audience: "CFOs at UK fintechs", titles: ["CFO"], locations: ["United Kingdom"], industries: ["Financial Services"], dry_run: true });
console.log(result.plan.would.maximum_credits);

budget_credits sets a spend ceiling for one call. A call that could cost more is refused before anything is charged.

Idempotency

Paid and external calls take an Idempotency-Key. If you do not pass one, the SDK generates a UUID for each call and reuses it across its automatic retries. The API then returns the first outcome instead of running or charging twice.

Pass your own key when you may retry later, for example after a crash or a timeout:

await layrcake.createCampaign(params, { idempotencyKey: `campaign-${jobId}` });

When a call fails, error.idempotencyKey holds the key that was sent. Retry with it to get the original outcome. Endpoints without an idempotency key, such as getMe, never get one.

Retries

The SDK retries 429, 502, 503 and 504 responses and network errors, up to maxRetries times (default 2). It waits with exponential backoff and jitter. It honours Retry-After and the API's details.retry_after_seconds. If the server asks for a wait longer than 60 seconds, the SDK throws instead so you can decide.

It never retries any other 4xx. A POST is retried only when it carries an idempotency key, so a retry cannot act twice. Every write endpoint in the API takes one, and the SDK always sends one.

Errors

Every error is a LayrcakeError with status, code, message, details, requestId and idempotencyKey. Subclasses let you catch by kind:

Class When
AuthenticationError 401. The key is missing, wrong, revoked or expired.
PermissionDeniedError 403. A missing scope, a paused agent, or a disabled feature.
ApprovalError confirmation_required, or an approval that was declined, expired, superseded, cancelled or changed.
InsufficientCreditsError 402, or a run budget reached. Top up or raise the budget.
ValidationError 400 or 422. details usually names the field.
NotFoundError 404.
ConflictError 409, such as an idempotency key reused with different parameters.
RateLimitError 429. retryAfterSeconds says when to try again.
ServerError 5xx, such as provider_unavailable.
APIConnectionError No response arrived.
APITimeoutError The request passed timeoutMs.
OperationTimeoutError waitForOperation ran out of time.
import { InsufficientCreditsError, LayrcakeError } from "layrcake";

try {
  await layrcake.findLeads({ audience: "CTOs at US startups", titles: ["CTO"], locations: ["United States"] });
} catch (error) {
  if (error instanceof InsufficientCreditsError) console.log("Top up at https://layrcake.dev");
  else if (error instanceof LayrcakeError) console.log(error.code, error.message, error.requestId);
  else throw error;
}

code is typed with every code in the spec, such as insufficient_credits or provider_unavailable. Branch on code for detail. API_ERROR_CODES lists them all.

Background operations

Some calls start work that finishes later and return an operation_id. Examples are researchCompany, prospectPicture and a confirmed setupSending. Wait for it with waitForOperation:

const { result } = await layrcake.researchCompany({ company_domain: "acme.com" });
const operation = await layrcake.waitForOperation(result.operation_id, { intervalMs: 2_000, timeoutMs: 600_000 });
if (operation.state === "succeeded") console.log(operation.result);

It polls GET /v1/operations/{id} until the state is succeeded, partially_succeeded, failed, cancelled or unknown, then returns the operation. It does not throw on failed, so check state. unknown means a provider's outcome could not be confirmed and Layrcake is reconciling it. Do not repeat the action while it is unknown. Pass signal to stop waiting.

Approvals

Nothing reaches a real person until a person on your side says yes. launchCampaign, setupSending, replyToThread, and addLeads on an active campaign first return a preview with a confirmation_token and an approval_url. A signed-in person approves in the Layrcake console. Then you repeat the call with the token, or the server runs it.

import { getApproval } from "layrcake";

const preview = await layrcake.launchCampaign({ campaign_id });
const approval = getApproval(preview);
if (approval) {
  console.log("Approve here:", approval.approvalUrl);
  // Later, after the person approves:
  await layrcake.launchCampaign(
    { campaign_id, confirmation_token: approval.confirmationToken },
    { idempotencyKey: `launch-${campaign_id}` },
  );
}

isApprovalRequired(response) is the same check as a type guard. The SDK never approves anything and has no way to.

Agent tools

layrcake/agent-tools turns the rules for agents at layrcake.dev/agents.md into five tools that any agent framework can call: find_leads, enrich, verify_email, create_campaign and launch_campaign. It ships in this package and has no dependencies.

import { createAgentTools } from "layrcake/agent-tools";

const { tools, summary, shouldStop } = createAgentTools({ budget: 100 }); // reads LAYRCAKE_API_KEY

const people = await tools.find_leads.execute({ audience: "Heads of sales at London software companies", titles: ["Head of Sales"], locations: ["London, United Kingdom"] });
// ... the model calls the other tools until shouldStop() is true ...
console.log(summary()); // { found, kept, catchAll, spent, approvalUrl, launchError }

Each tool has a name, a description that includes its price, an inputSchema and an execute function. inputSchema implements Standard Schema with JSON Schema output, so the Vercel AI SDK (7 or later) and Mastra (1.11 or later) take it as is, with no zod. parameters holds the same schema as plain JSON Schema for function-calling APIs that want one.

The rules live in code, so a prompt cannot turn them off:

  • Every paid call sends budget_credits set to what is left of budget. Paid calls run one at a time, even when the model calls tools in parallel, so the running total stays exact. Once the budget is spent, paid tools refuse.
  • dryRun: true sends dry_run: true on every call. Each call returns a plan with the most it could cost and charges nothing.
  • Every call carries an idempotency key built from runId and its arguments. A repeated call returns the first result instead of charging twice.
  • create_campaign takes only addresses that passed verify_email in this run.
  • launch_campaign takes only campaign_id. It has no confirmation_token argument, so the model can ask for approval but cannot give it. After it returns an approval link, every tool refuses, and shouldStop() turns true so you can end the loop.

A refused call throws AgentToolRefusal before anything reaches the API. Its code is approval_pending, budget_spent, unverified, missing_filter or invalid_input, and its message tells the model what to do next. API errors arrive as the usual LayrcakeError.

Option Default What it does
budget required Credit ceiling for the whole run. 1 credit is $0.01.
client new Layrcake() The client the tools call.
dryRun false Send dry_run: true on every call.
runId random UUID Prefix for idempotency keys. Keep it stable across retries of the same run.

If your agent calls the hosted MCP server instead, for example through hooks in the Claude Agent SDK, createAgentRun({ budget, dryRun, runId }) gives the same run state on its own: ceiling() for the next budget_credits, charge(), recordVerification(), unverified(), recordLaunch(), refusal(), idempotencyKey() and summary().

Framework packages built on this module: @layrcake/ai-sdk for the Vercel AI SDK and @layrcake/mastra for Mastra.

layrcake/agent-tools uses Web Crypto for idempotency keys. It runs on Node 20 or later, Bun, Deno, Cloudflare Workers and Vercel Edge. On Node 18, start Node with --experimental-global-webcrypto.

Pricing

Calls are billed in credits. See docs.layrcake.dev/pricing.html. getMe() is free and shows your balance.

Links

Development

npm install
npm run generate         # regenerate types and methods from openapi.json
npm run check-generated  # fail if generated code is stale
npm run typecheck
npm test
npm run build

To update the API surface, replace openapi.json with the live spec and run npm run generate.

License

MIT

About

Official TypeScript SDK for Layrcake: go-to-market infrastructure for AI agents. Find leads, verify emails, read signals, run approved campaigns.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages