@token-wallet/sdk
v0.3.2
Published
SDK for integrating "Login with Token Wallet" into your app. Your users bring their own AI tokens — you pay nothing.
Maintainers
Readme
@token-wallet/sdk
One wallet for all your AI apps. Users store their Anthropic, OpenAI, and Google API keys in Token Wallet, then grant your app metered access via OAuth. You pay nothing for AI usage.
Install
npm install @token-wallet/sdkQuick Start
import { TokenWallet, isProxyError } from '@token-wallet/sdk';
const tw = TokenWallet({
clientId: 'your-app-id',
clientSecret: 'your-app-secret',
redirectUri: 'https://yourapp.com/callback',
});
// 1. Redirect the user to the consent screen
app.get('/login', (req, res) => res.redirect(tw.getAuthorizeUrl()));
// 2. Exchange the OAuth code for an access token in your callback
app.get('/callback', async (req, res) => {
const { access_token } = await tw.exchangeCode(req.query.code as string);
req.session.tokenWalletToken = access_token;
res.redirect('/');
});
// 3. Call the LLM through the proxy
app.post('/chat', async (req, res) => {
const result = await tw.call({
accessToken: req.session.tokenWalletToken,
provider: 'anthropic',
path: '/v1/messages',
body: {
model: 'claude-3-5-sonnet-latest',
max_tokens: 1024,
messages: [{ role: 'user', content: req.body.prompt }],
},
});
if (isProxyError(result)) {
return res.status(400).json({ error: result.error });
}
res.json({ model: result.model, usage: result.usage, data: result.data });
});The same tw.call(...) works for OpenAI and Google — change provider and path:
await tw.call({
accessToken,
provider: 'openai',
path: '/v1/chat/completions',
body: { model: 'gpt-4o', messages: [...] },
});
await tw.call({
accessToken,
provider: 'google',
path: '/v1beta/models/gemini-1.5-pro:generateContent',
body: { contents: [...] },
});Modal flow (single-page apps)
If your app is a SPA, open the consent screen in an iframe modal:
const { code } = await tw.popup({ suggestedBudget: 5 });
// Send the code to your backend, which calls tw.exchangeCode(code).
// The exchange requires clientSecret and must never run in browser code.
await fetch('/api/auth/exchange', {
method: 'POST',
body: JSON.stringify({ code }),
});Managed agents (Anthropic)
Token Wallet proxies Anthropic's Managed Agents surface — the /v1/agents, /v1/environments, /v1/sessions, /v1/vaults, and /v1/files endpoints — under the same BYOK model as Messages. The app points the Anthropic SDK at tw.proxyUrl('anthropic'); the proxy injects the managed-agents beta header and forwards calls to the user's Anthropic org.
Explicit consent required. Because agent sessions run long-lived, billable server-side work on Anthropic ($0.08/hr session runtime on top of tokens), the proxy rejects agent-surface calls unless the app was created with allowsManagedAgents: true. The flag sits alongside the other app fields on creation:
await admin.apps.create({
name: 'Life Coach',
callbackUrl: 'https://lifecoach.ai/callback',
requiredProviders: ['anthropic'],
allowsManagedAgents: true, // ← opt in
});Without it, every agent endpoint returns 403 AGENT_SCOPE_MISSING.
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: accessToken,
baseURL: tw.proxyUrl('anthropic'),
});
// Provision once per user.
const agent = await anthropic.beta.agents.create({
name: 'Life Coach',
model: 'claude-haiku-4-5',
system: 'You are a terse life coach.',
tools: [{ type: 'agent_toolset_20260401' }],
});
// Spin up a session.
const env = await anthropic.beta.environments.create({ name: 'prod' });
const session = await anthropic.beta.sessions.create({
agent: agent.id,
environment_id: env.id,
});
// Send events, stream responses — all proxied.
await anthropic.beta.sessions.events.post(session.id, {
type: 'user.message', content: 'What should I focus on today?',
});
for await (const event of anthropic.beta.sessions.events.stream(session.id)) {
// ...
}
// Archive when done. This is what triggers Token Wallet to pull the final
// usage totals from Anthropic and debit tokens + runtime against the budget.
await anthropic.beta.sessions.archive(session.id);Token Wallet tracks each session in its own agent_sessions table keyed on the access token for attribution and auto-terminates running sessions when the user revokes the connection (otherwise Anthropic would keep billing $0.08/hr). That rate lives in code as AGENT_RUNTIME_USD_PER_HOUR in packages/shared/src/catalog/agent-runtime.ts — if Anthropic changes it, update the constant there and every consumer follows. See the full Managed Agents design doc for lifecycle details, limitations, and billing.
Both files also ship inside the npm tarball under node_modules/@token-wallet/sdk/docs/ (managed-agents.md and agent-runtime.ts), so you can read them offline without leaving your project.
Streaming responses
tw.call() is for non-streaming requests. Streaming responses bypass the unified envelope and are forwarded as-is, so use any vendor SDK with baseURL: tw.proxyUrl(...):
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({
apiKey: accessToken,
baseURL: tw.proxyUrl('anthropic'),
});
const stream = await anthropic.messages.stream({
model: 'claude-3-5-sonnet-latest',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Tell me a story.' }],
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
process.stdout.write(event.delta.text);
}
}API
Types
Error Codes
Non-streaming proxy responses return a unified error envelope:
{ "error": { "code": "...", "message": "...", "source": "proxy" | "provider", "details": { } } }source distinguishes errors raised by the Token Wallet proxy from errors forwarded from the upstream LLM. Use the isProxyError type guard to narrow a ProxyResponse before reading error.code.
Proxy errors (source: "proxy")
| Code | Status | Meaning |
|------|--------|---------|
| TOKEN_INVALID | 401 | Missing or unrecognized access token |
| TOKEN_REVOKED | 401 | User revoked access |
| TOKEN_EXPIRED | 401 | Token expired (30-day lifetime) |
| TOKEN_SUSPENDED | 403 | User temporarily suspended access |
| BUDGET_EXCEEDED | 402 | Spending limit reached |
| PROVIDER_KEY_MISSING | 402 | No API key or credits available for the provider |
| CREDITS_DEPLETED | 402 | Insufficient platform credits |
| MODEL_NOT_ALLOWED | 403 | Model not in your app's allowed list |
| AGENT_SCOPE_MISSING | 403 | App doesn't have the managed-agents scope (set allowsManagedAgents: true at app creation) |
| APP_NOT_FOUND | 404 | Application not found |
Provider errors (source: "provider")
| Code | Status | Meaning |
|------|--------|---------|
| RATE_LIMITED | 429 | Upstream rate limit hit — retry after backoff |
| CONTEXT_LENGTH_EXCEEDED | 400 | Request exceeds the model's context window |
| INVALID_REQUEST | 400 | Provider rejected the request as malformed |
| CONTENT_FILTERED | 400 | Content blocked by the provider's safety filter |
| AUTHENTICATION_FAILED | 401 | Provider rejected the API key |
| PROVIDER_OVERLOADED | 503 | Provider temporarily overloaded |
| PROVIDER_TIMEOUT | 504 | Provider did not respond in time |
| PROVIDER_ERROR | 502 | Catch-all for other provider errors |
License
MIT
