Skip to content
oneshot-agentPublic

About

Action Layer for AI Agents. Tools, Payments & Compute in OneShot.

Resources

Stars

115 stars

Watchers

1 watching

Forks

Latest commit

 

History

148 Commits

Folders and files

Repository files navigation

@oneshot-agent/sdk

Your agent can think. This lets it act: send email, make calls, research, buy, build sites. It pays per action, gets a signed receipt, and spends nothing you did not allow.

Install

npm install @oneshot-agent/sdk

No code? Use the MCP server in Claude, Cursor or Claude Code: npx -y @oneshot-agent/mcp-server (setup). Teach your coding agent the tools: npx skills add oneshot-agent/agent-skills (skills).

Start

import { OneShot } from '@oneshot-agent/sdk';

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

await agent.email({ to: 'user@example.com', subject: 'Hello', body: 'Hello world.' });
const report = await agent.research({ topic: 'AI agents', depth: 'deep' });
const usdc = await agent.getBalance(agent.usdcAddress);

Paid calls quote, pay and wait for the result. You write one line.

Subscribe to a platform task

Save as subscribe.ts; run bun subscribe.ts with AGENT_PRIVATE_KEY and TASK_ID (an existing compute goal UUID) in the environment:

import { OneShot } from '@oneshot-agent/sdk';

const agent = new OneShot({ privateKey: process.env.AGENT_PRIVATE_KEY! });
for await (const event of agent.subscribeToTask(process.env.TASK_ID!)) console.log(event.kind, event.status.state);

The platform /a2a/rpc subscription uses the client's read proof or access token and yields the initial Task and status updates. It stops at a terminal event or server EOF (at most five minutes). EOF need not mean completion; reconnect explicitly. A clock-window proof refusal before the stream opens is retried once with a corrected proof, inside the same deadline. Per-soul subscriptions are unsupported. Pass { signal } to abort a pending read, or break to close the stream. HTTP failures without a JSON-RPC error throw ToolError. Responses containing a JSON-RPC error throw A2AError with code and optional data, including a missing-task HTTP 404 response.

What it does

Area Methods
Talk email voice sms inboxList inboxGet smsInboxList smsInboxGet notifications markNotificationRead
Send from your domains quoteDomain buyDomain listDomains pauseDomain resumeDomain
Find people and companies personFind personProfile personEmail personEmailStatus personDossier personSocialAccounts personArticles personPosts personInterests personFollowers companyFind companyProfile businessFind businessResolve recordSolicitationsFind
Think research predict solve
Web and buying webSearch webRead productFind commerceBuy physicalMail
Browser browser createBrowserProfile startBrowserProfileSetup createBrowserProfileSetupLink getBrowserProfileSetup finishBrowserProfileSetup listBrowserProfiles deleteBrowserProfile
Connected systems listConnections, then route('POST', '/v1/tools/ledger/invoices', { paid: true, body: { connection_id } }) for each read
LinkedIn linkedinConnect linkedinInvite linkedinWithdrawInvitation linkedinMessage linkedinReply reconnectLinkedInAccount and more
Build build updateBuild
Goals compute waitForComputeGoal getComputeGoal getComputeTasks getComputeOutputs getComputeOutputsPage getComputeOutput respondToComputeTask pauseComputeGoal resumeComputeGoal cancelComputeGoal fundComputeGoal createTaskPushNotificationConfig getTaskPushNotificationConfig listTaskPushNotificationConfigs deleteTaskPushNotificationConfig
Money and receipts getBalance getUnifiedBalance budgets topUpCredits spendBreakdown rocs receiptsList tagReceiptValue
Anything else tool(name, input) for any tool, route(method, path, { params, query, body, paid }) for any declared route

Output pagination. getComputeOutputs(goalId) returns the first page as an array. getComputeOutputsPage(goalId, { limit, cursor }) returns { outputs, next_cursor }: process outputs, then pass the opaque next_cursor back unchanged until it is null. Omit cursor initially; limit defaults to 100 (1–500). getComputeOutput(goalId, key) reads individual content. Traversal example.

Money

  • It pays in USDC on Base mainnet (agent.chainId is 8453). Fund the wallet first.
  • A call costs what the quote says, or it does not run.
  • maxCost sets your ceiling. Above it, the SDK refuses to sign.
  • currency: 'ETH' pays from ETH. The SDK swaps into USDC only when the wallet is short, buys swapBufferMultiplier × the charge (default 10) so one swap covers many calls. Calls in one process never double-swap. Run one process per wallet. Not with cdp.

Budgets cap what a runaway loop can spend.

const agent = await OneShot.create({
  cdp: true,
  budgets: { daily: 50, perTransaction: 5, alertAt: 0.8, pauseAt: 1.0 },
  alerts: { email: 'you@example.com' },
});
  • Budgets live on the server. Every process using the wallet shares them.
  • If the server cannot confirm them, nothing is paid: BudgetSyncError.
  • At pauseAt, paid calls throw BudgetExceededError until UTC midnight.
  • Omit budgets and the stored ones stay as they are. No budget means no limit.

Access tokens are for code that must not hold the key: a hosted MCP client, a cloud runner, someone else's platform.

const { token } = await agent.createAccessToken({ name: 'hosted-agent', expires_in_days: 30 }); // from the wallet session
const hosted = await OneShot.create({ accessToken: token });
await hosted.webSearch({ query: '…' }); // paid from credits
  • Optional expires_in_days is a positive whole number of days. Without it or an organization cap, new tokens expire after 90 days; existing tokens keep their expiry. An organization cap (up to 730 days) requires an explicit lifetime within the cap (400 token_lifetime_exceeds_policy). Expired tokens return 401 access_token_expired. Lists include expires_at and created_by; OAuth bridge tokens are exempt from the cap.
  • A token spends prepaid credits only. It never signs a payment.
  • Short of credits, it throws InsufficientCreditsError (required, balance, shortfall). Top up from the wallet session with topUpCredits(amount).
  • A token reads budgets but cannot change them, and cannot mint or revoke tokens.

Trust

Every paid call returns a receipt, signed with Ed25519. Check it offline:

import { verifyReceipt, receiptFromWire } from '@oneshot-agent/sdk/receipt';

const jwks = await fetch('https://win.oneshotagent.com/.well-known/oneshot-receipts.json').then(r => r.json());
const result = verifyReceipt(receiptFromWire(wireReceipt), jwks);
// result.valid, or result.reason: 'malformed_receipt' | 'key_not_found' | 'digest_mismatch' | 'signature_invalid'

Or from a shell: npx @oneshot-agent/sdk receipt.json (exit 0 valid, 1 invalid, 2 bad input). Old keys stay in the key set, so old receipts keep verifying.

Reads of private data (inbox, notifications, balances, browser profiles) carry a signed proof that you hold the wallet. A wallet address is public; your inbox is not. The SDK signs it for you and asks the runtime for a connection of its own per proof (Connection: close, keepalive: false), so in Bun the fetch has no pooled socket to re-send it on. A browser's fetch ignores both controls (Connection is a forbidden request header there), so in a browser the HTTP stack keeps its own retry rules. If the server says your clock is off, the SDK corrects once and retries. If the server says a read's proof was already used (something between you and the API delivered it twice), it signs a fresh proof and reads once more; a write is never repeated.

Failure

import { JobError, JobTimeoutError, ToolError, ValidationError, ContentBlockedError } from '@oneshot-agent/sdk';

try {
  await agent.voice({ objective: 'Book a table for 2 at 7pm', target_number: '+14155551234' });
} catch (error) {
  if (error instanceof JobError) {
    // Branch on error.code, never on the message.
    if (['rate_limited', 'service_unavailable', 'internal_error'].includes(error.code)) { /* retry */ }
    else { /* fix the input or the funding; retrying as is will not help */ }
  } else if (error instanceof ToolError && error.statusCode === 429) {
    // error.retryAfterMs is the server's hint. The SDK never retries for you.
  }
  throw error;
}
  • JobError.code is one of insufficient_funds payment_failed invalid_input content_blocked rate_limited service_unavailable service_auth enrichment_exhausted target_unreachable source_unsupported checkout_failed internal_error. What each means.
  • Input the SDK can check throws ValidationError before anything is paid.
  • Emergency numbers are refused: EmergencyNumberError.

Waiting and stopping

  • approvals.waitFor(id, { signal, timeoutMs, intervalMs }) bounds signing, fetch and response-body reads. Its timeout defaults to 24 hours. Aborting rejects with OneShotError('Operation cancelled') and stops polling without withdrawing the approval.
  • Approval waits return the latest snapshot on timeout, or throw OneShotError('Approval wait timed out') if none arrived. They also return the latest snapshot when another polling interval would exceed the budget. Check status before retrying a held action: the snapshot may still be pending.
  • Paid calls wait by default. wait: false returns the request_id; waitForResult(requestId) picks the result up later.
  • An AbortSignal stops the call before payment and nothing is charged. After payment, the work happens and is billed. Aborting only stops your wait.
  • An abort rejects with OneShotError('Operation cancelled') for commerceBuy, voice, sms, build, refineBuild, updateBuild and browser; the other calls reject with the signal's reason. Handle both.
  • timeout is how long you wait, in seconds. It never limits the job. agent.tool() uses the manifest timeout (Company Dossier: 1020 seconds), or 120 seconds when absent. Typed methods share it unless they specify their own default. An explicit timeout wins.
  • browser() waits up to 1,920 seconds by default: the worker's 1,800-second execution window plus 120 seconds for settlement. MCP inherits this default. An explicit timeout can shorten the wait; wait: false and cancellation still stop waiting without stopping an accepted job.
  • compute({ ..., onQuote }) exposes price.hires: each bound soul's public display_name and soul_slug, service_name and service_slug, nullable need, and server-read fixed price_usd. A specialist entry in requirements carries the unmatched need and the owner's question; starting the goal proceeds without that specialist.
  • Goals run longer than calls. Watch one with waitForComputeGoal:
const goal = await agent.compute({ objective: 'Research battery recycling', budget_usdc: 5 });
// Or be called back: the goal's terminal status is POSTed to your URL while the hook stays registered. get and list read the hooks.
const hook = await agent.createTaskPushNotificationConfig({ taskId: goal.goal_id, url: 'https://example.com/hooks/oneshot', token: 'my-token' });
const done = await agent.waitForComputeGoal(goal.goal_id, { timeout: 300, onStatusUpdate: (status) => console.log(status) });

Keep the hook after the wait returns: a finished poll does not mean the callback was delivered. Clean up later, once your webhook receiver confirms it received the callback:

await agent.deleteTaskPushNotificationConfig(goalId, hookId); // deleting drops a notification not yet sent
  • waitForComputeGoal resolves on completed and throws JobError on failed or cancelled (code is the end_reason). awaiting_confirmation, awaiting_connection, awaiting_budget, awaiting_tool, awaiting_setup and paused wait for you; they do not end the wait.
  • Setup holds wait for the account need reader to report ready. Setup is a separate account purchase; cancelling the goal never removes a bought domain. After 7 days held the goal ends cancelled/setup_timeout and its unused budget is credited.
  • Budget exhaustion holds the goal in awaiting_budget; fundComputeGoal resumes it. After 7 days unanswered it ends budget_exhausted and unused funds are credited. An already failed budget goal also comes back after funding. Call waitForComputeGoal again; the old wait does not resume.
  • Timeout defaults to 120 seconds and throws JobTimeoutError. It stops your polling, not the goal. Stop the goal with cancelComputeGoal.

Tool notes

  • Email setup and sending. quoteDomain(name, { mailbox_mode, addresses }) prices a name without sending. relay (the default) gives addresses that send and receive with no hosted inbox, free per address; mailbox gives each address a hosted inbox, warmed before it sends, with a one-time fee per address. addresses defaults to ['agent']; the first is the main address. Review total_cost and billing, then buyDomain(name, quote_id) buys that exact quote. Quote a domain you already have with new addresses to add them. Wait for verification before sending. A domain sends and receives only at its addresses. email() answers confirmation_required with the setup quote when the domain or address is not set up yet, and setup_required with requirements when the agent has no domain; nothing is sent or charged. email({ ..., confirmNewDomain: quote_id }) buys that setup only and returns setup_pending. Goals and MCP models cannot buy setup. Details. Omit from_domain and the server rotates across your domains, sending from each one's main address. Pin one and you skip the warmup gates; the send goes out with a warning. There is no shared sender. Details.
  • People search. An empty result means nobody matched. A failed search throws; it never pretends to be empty. limit (default 25, max 500) is what you pay for, found or not, and a search can return fewer rows. Page with offset. A search that hits its time limit returns what it found; rows whose phone lookup ran out of time say _phone_enrich_reason: 'time_budget_exhausted'. Details.
  • Phone lookup is off by default. includePhone: true is charged for each person you ask for (the search limit), found or not; a failed job is refunded. waitForPhones: true waits for numbers still arriving. It never buys any. Check phones_pending. Price.
  • Stored records. A person, company or business record looked up recently may come from OneShot's store of earlier lookups (profiles, dossiers, social accounts, email finds, company profiles and resolves up to 30 days old; email status and searches 7 days; posts, articles, followers and interests 3 days), at the same price. The result says cached and fetched_at; fresh: true on any person, company or business method asks again and refreshes the copy.
  • Account login. startBrowserProfileSetup returns a setup_url. It opens once and expires in 10 minutes. Give it only to the account's owner, never open it yourself, keep it out of logs and prompts. Poll getBrowserProfileSetup until completed_at is set. You get cookie names back, never values. Details.
  • LinkedIn. Invitations are capped at 25 per account per UTC day; withdrawing one does not give the slot back. Use OneShot's invitation_id. A session that expired comes back with reconnectLinkedInAccount; a deleted account throws LinkedInConnectRequiredError and needs linkedinConnect again. Reuse your idempotency key on retries. Details.
  • Connected systems. The reads of your accounting, CRM, tax, shipping and spend systems have no typed method: call them with route('POST', <path>, { paid: true, body }). Each takes connection_id; listConnections() lists the agent's connections, pick one by system and account_label. Another agent's connection is refused before payment. Details.
  • Physical mail. U.S. letters and postcards. Look at the proof and the price, then approve each quote yourself. Nothing approves it for you. Persist the idempotencyKey before send. Details.

Links

Discover tools

await agent.discoverTools({ query: "send a printed letter" }) searches the public catalog for free. Omit options for category counts, or pass { category: "email" } to browse five tools at a time. Pass nextCursor as cursor with the same query and category. Results use MCP names and include purposes and required inputs; your token grants filter the catalog before search.

Untrusted tool content

Tool result objects carrying third-party text (web, browser, inbox, research and source lookups) carry untrusted_content: true, selected by a per-tool registry flag. Computed results such as predict and solve, quotes, receipts, job acknowledgements and account data keep their original shape. Treat their content as third-party data, never as instructions. Array-returning SDK methods preserve the array and mark its object entries. MCP marks its result envelope and successful JSON text payload.

Web reads and inbox reads also report hidden_removed. Filtering removes HTML comments, inline-hidden elements (including off-screen positioning), image alt text, zero-width characters and bidi controls. Inbox list counts sum the counts on its returned messages; omitted bodies are not counted. Stored emails and attachments are unchanged. Filtering is not a trust guarantee: visible instructions, external stylesheets and image pixels are not classified by this filter.

License

MIT

About

Action Layer for AI Agents. Tools, Payments & Compute in OneShot.

Resources

Stars

115 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages