@tokenite/sdk 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Eran Broder
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,454 @@
1
+ # @tokenite/sdk
2
+
3
+ One wallet for all your AI apps. Users store their Anthropic, OpenAI, and Google API keys in Tokenite, then grant your app metered access via OAuth. You pay nothing for AI usage.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @tokenite/sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { Tokenite, isProxyError } from '@tokenite/sdk';
15
+
16
+ const tw = Tokenite({
17
+ clientId: 'your-app-id',
18
+ clientSecret: 'your-app-secret',
19
+ redirectUri: 'https://yourapp.com/callback',
20
+ });
21
+
22
+ // 1. Redirect the user to the consent screen
23
+ app.get('/login', (req, res) => res.redirect(tk.getAuthorizeUrl()));
24
+
25
+ // 2. Exchange the OAuth code for an access token in your callback
26
+ app.get('/callback', async (req, res) => {
27
+ const { access_token } = await tk.exchangeCode(req.query.code as string);
28
+ req.session.tokeniteToken = access_token;
29
+ res.redirect('/');
30
+ });
31
+
32
+ // 3. Call the LLM through the proxy
33
+ app.post('/chat', async (req, res) => {
34
+ const result = await tk.call({
35
+ accessToken: req.session.tokeniteToken,
36
+ provider: 'anthropic',
37
+ path: '/v1/messages',
38
+ body: {
39
+ model: 'claude-3-5-sonnet-latest',
40
+ max_tokens: 1024,
41
+ messages: [{ role: 'user', content: req.body.prompt }],
42
+ },
43
+ });
44
+
45
+ if (isProxyError(result)) {
46
+ return res.status(400).json({ error: result.error });
47
+ }
48
+
49
+ res.json({ model: result.model, usage: result.usage, data: result.data });
50
+ });
51
+ ```
52
+
53
+ The same `tk.call(...)` works for OpenAI and Google — change `provider` and `path`:
54
+
55
+ ```typescript
56
+ await tk.call({
57
+ accessToken,
58
+ provider: 'openai',
59
+ path: '/v1/chat/completions',
60
+ body: { model: 'gpt-4o', messages: [...] },
61
+ });
62
+
63
+ await tk.call({
64
+ accessToken,
65
+ provider: 'google',
66
+ path: '/v1beta/models/gemini-1.5-pro:generateContent',
67
+ body: { contents: [...] },
68
+ });
69
+ ```
70
+
71
+ ### Modal flow (single-page apps)
72
+
73
+ If your app is a SPA, open the consent screen in an iframe modal:
74
+
75
+ ```typescript
76
+ const { code } = await tk.popup({ suggestedBudget: 5 });
77
+
78
+ // Send the code to your backend, which calls tk.exchangeCode(code).
79
+ // The exchange requires clientSecret and must never run in browser code.
80
+ await fetch('/api/auth/exchange', {
81
+ method: 'POST',
82
+ body: JSON.stringify({ code }),
83
+ });
84
+ ```
85
+
86
+ ### Managed agents (Anthropic)
87
+
88
+ Tokenite proxies Anthropic's [Managed Agents](https://platform.claude.com/docs/en/managed-agents/overview) 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 `tk.proxyUrl('anthropic')`; the proxy injects the managed-agents beta header and forwards calls to the user's Anthropic org.
89
+
90
+ **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:
91
+
92
+ ```typescript
93
+ await admin.apps.create({
94
+ name: 'Life Coach',
95
+ callbackUrl: 'https://lifecoach.ai/callback',
96
+ requiredProviders: ['anthropic'],
97
+ allowsManagedAgents: true, // ← opt in
98
+ });
99
+ ```
100
+
101
+ Without it, every agent endpoint returns `403 AGENT_SCOPE_MISSING`.
102
+
103
+ ```typescript
104
+ import Anthropic from '@anthropic-ai/sdk';
105
+
106
+ const anthropic = new Anthropic({
107
+ apiKey: accessToken,
108
+ baseURL: tk.proxyUrl('anthropic'),
109
+ });
110
+
111
+ // Provision once per user.
112
+ const agent = await anthropic.beta.agents.create({
113
+ name: 'Life Coach',
114
+ model: 'claude-haiku-4-5',
115
+ system: 'You are a terse life coach.',
116
+ tools: [{ type: 'agent_toolset_20260401' }],
117
+ });
118
+
119
+ // Spin up a session.
120
+ const env = await anthropic.beta.environments.create({ name: 'prod' });
121
+ const session = await anthropic.beta.sessions.create({
122
+ agent: agent.id,
123
+ environment_id: env.id,
124
+ });
125
+
126
+ // Send events, stream responses — all proxied.
127
+ await anthropic.beta.sessions.events.post(session.id, {
128
+ type: 'user.message', content: 'What should I focus on today?',
129
+ });
130
+
131
+ for await (const event of anthropic.beta.sessions.events.stream(session.id)) {
132
+ // ...
133
+ }
134
+
135
+ // Archive when done. This is what triggers Tokenite to pull the final
136
+ // usage totals from Anthropic and debit tokens + runtime against the budget.
137
+ await anthropic.beta.sessions.archive(session.id);
138
+ ```
139
+
140
+ Tokenite tracks each session for attribution and auto-terminates running sessions when the user revokes the connection — otherwise Anthropic would keep billing `$0.08/hr` for the session runtime on top of tokens. The proxy bills the user's wallet at archive time using Anthropic's reported cumulative usage and runtime, plus the standard token rate from the model's pricing.
141
+
142
+ Budget is checked pre-call but not enforced mid-session: a session that started under budget can run past it. Revoke is the user's hard kill switch.
143
+
144
+ ### Streaming responses
145
+
146
+ `tk.call()` is for non-streaming requests. Streaming responses bypass the unified envelope and are forwarded as-is, so use any vendor SDK with `baseURL: tk.proxyUrl(...)`:
147
+
148
+ ```typescript
149
+ import Anthropic from '@anthropic-ai/sdk';
150
+
151
+ const anthropic = new Anthropic({
152
+ apiKey: accessToken,
153
+ baseURL: tk.proxyUrl('anthropic'),
154
+ });
155
+
156
+ const stream = await anthropic.messages.stream({
157
+ model: 'claude-3-5-sonnet-latest',
158
+ max_tokens: 1024,
159
+ messages: [{ role: 'user', content: 'Tell me a story.' }],
160
+ });
161
+
162
+ for await (const event of stream) {
163
+ if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
164
+ process.stdout.write(event.delta.text);
165
+ }
166
+ }
167
+ ```
168
+
169
+ ## API
170
+
171
+ <!-- GEN:API -->
172
+ ### `.getAuthorizeUrl(options?: AuthorizeOptions) => string`
173
+
174
+ Build the authorization URL for a full-page redirect. Supports optional suggested budget that pre-fills the consent screen.
175
+
176
+ ### `.popup(options?: PopupOptions) => Promise<PopupResult>`
177
+
178
+ Open the consent screen and resolve with an OAuth authorization code when the user approves. The code must then be exchanged server-side via `tk.exchangeCode(code)` (the exchange requires `clientSecret`, which must never run in browser code).
179
+
180
+ ### `.exchangeCode(code: string) => Promise<TokenResponse>`
181
+
182
+ Exchange an authorization code for an access token. Call this server-side in your callback handler. Requires clientSecret to be set in config.
183
+
184
+ ### `.call(options: ProxyCallOptions) => Promise<ProxyResponse>`
185
+
186
+ Make an authenticated, non-streaming request through the proxy. Returns a unified envelope: `ProxySuccess` on success, `ProxyError` on failure. Narrow the result with `isProxyError` / `isProxySuccess`.
187
+
188
+ ### `.proxyUrl(provider: Provider) => string`
189
+
190
+ Get the proxy URL for a specific provider. Use as `baseURL` in a vendor SDK for streaming requests, which bypass the unified envelope.
191
+
192
+ ### `.baseUrl`: `string`
193
+
194
+ The Tokenite dashboard base URL
195
+
196
+ ### `.proxyBase`: `string`
197
+
198
+ The Tokenite proxy base URL
199
+ <!-- /GEN:API -->
200
+
201
+ ## Types
202
+
203
+ <!-- GEN:TYPES -->
204
+ ```typescript
205
+ export type TokeniteConfig = {
206
+ /** Your app's client ID (from the Tokenite dashboard) */
207
+ readonly clientId: string;
208
+ /** Your app's client secret — only needed for server-side code exchange */
209
+ readonly clientSecret?: string;
210
+ /** The URL Tokenite redirects back to after authorization */
211
+ readonly redirectUri: string;
212
+ /** Tokenite base URL. Default: https://tokenite.ai */
213
+ readonly baseUrl?: string;
214
+ /** Tokenite proxy URL. Default: https://api.tokenite.ai */
215
+ readonly proxyUrl?: string;
216
+ };
217
+
218
+ export type AuthorizeOptions = {
219
+ /** Custom state parameter for CSRF protection. Auto-generated if not provided. */
220
+ readonly state?: string;
221
+ /** Suggested budget amount (user can override on consent screen) */
222
+ readonly suggestedBudget?: number;
223
+ };
224
+
225
+ export type PopupOptions = {
226
+ /** Suggested budget amount (user can override on consent screen) */
227
+ readonly suggestedBudget?: number;
228
+ /**
229
+ * How to host the consent screen.
230
+ *
231
+ * - `'iframe'` (default) — overlay an iframe modal in the current
232
+ * window. Requires the dashboard to allow being framed by your
233
+ * origin (`Content-Security-Policy: frame-ancestors`). Cleaner UX
234
+ * but blocked by `X-Frame-Options: DENY`.
235
+ * - `'window'` — open a separate browser popup window via
236
+ * `window.open`. Works regardless of frame policy, but the user
237
+ * may be prompted by their popup blocker.
238
+ */
239
+ readonly mode?: 'iframe' | 'window';
240
+ /** Modal/popup width in pixels. Default: 480 */
241
+ readonly width?: number;
242
+ /** Modal/popup height in pixels. Default: 620 */
243
+ readonly height?: number;
244
+ };
245
+
246
+ export type PopupResult = {
247
+ /**
248
+ * OAuth authorization code returned by the consent screen.
249
+ * Send this to your backend, which exchanges it for an access token
250
+ * via `tk.exchangeCode(code)`. The exchange requires `clientSecret`
251
+ * and must never run in browser code.
252
+ */
253
+ readonly code: string;
254
+ };
255
+
256
+ export type TokenResponse = {
257
+ readonly access_token: string;
258
+ readonly token_type: string;
259
+ };
260
+
261
+ export type Provider = 'anthropic' | 'openai' | 'google' | 'grok' | 'bedrock';
262
+
263
+ export type ProxyCallOptions = {
264
+ /** The user's Tokenite access token (returned by `tk.exchangeCode()`) */
265
+ readonly accessToken: string;
266
+ /** Which LLM provider to call */
267
+ readonly provider: Provider;
268
+ /** Path on the provider's API (e.g. `/v1/messages`, `/v1/chat/completions`) */
269
+ readonly path: string;
270
+ /** HTTP method. Default: `POST` */
271
+ readonly method?: string;
272
+ /** Request body — the vendor's request shape, JSON-serialised by the SDK */
273
+ readonly body: unknown;
274
+ };
275
+
276
+ // ─── Unified proxy response types ───
277
+ //
278
+ // Every non-streaming response from the Tokenite proxy returns one of
279
+ // these shapes. SDK consumers can always check for `.error` to distinguish
280
+ // success from failure — no vendor-specific parsing required.
281
+
282
+ /** Normalised token counts (identical across all providers) */
283
+ export type ProxyUsage = {
284
+ /** Number of tokens in the prompt / input */
285
+ readonly inputTokens: number;
286
+ /** Number of tokens in the completion / output */
287
+ readonly outputTokens: number;
288
+ };
289
+
290
+ /**
291
+ * Successful proxy response.
292
+ *
293
+ * `data` contains the original vendor response body (e.g. Anthropic's
294
+ * message object, OpenAI's chat completion, etc.). `provider`, `model`,
295
+ * and `usage` are extracted and normalised by the proxy so you don't
296
+ * need to parse vendor-specific fields.
297
+ */
298
+ export type ProxySuccess = {
299
+ /** Which LLM provider handled the request */
300
+ readonly provider: Provider;
301
+ /** The model that generated the response */
302
+ readonly model: string;
303
+ /** Normalised token usage, or null if the provider didn't report it */
304
+ readonly usage: ProxyUsage | null;
305
+ /** The original, unmodified response body from the LLM provider */
306
+ readonly data: unknown;
307
+ };
308
+
309
+ /**
310
+ * Where the error originated.
311
+ *
312
+ * - `"proxy"` — Tokenite rejected the request (auth, budget, config).
313
+ * - `"provider"` — The upstream LLM returned an error (rate limit, overload, etc.).
314
+ */
315
+ export type ErrorSource = 'proxy' | 'provider';
316
+
317
+ /**
318
+ * Error response (both proxy-level and provider-level errors share this shape).
319
+ *
320
+ * **Proxy error codes** (`source: "proxy"`):
321
+ * | Code | HTTP | Description |
322
+ * |---|---|---|
323
+ * | `TOKEN_INVALID` | 401 | Missing or invalid bearer token |
324
+ * | `TOKEN_REVOKED` | 401 | Access token was revoked by the user |
325
+ * | `TOKEN_SUSPENDED` | 403 | Access suspended by the user |
326
+ * | `TOKEN_EXPIRED` | 401 | Access token past its expiration date |
327
+ * | `BUDGET_EXCEEDED` | 402 | Spending reached the user-defined budget limit |
328
+ * | `PROVIDER_KEY_MISSING` | 402 | No API key or credits available for the provider |
329
+ * | `CREDITS_DEPLETED` | 402 | Insufficient platform credits |
330
+ * | `APP_NOT_FOUND` | 404 | Application not found |
331
+ * | `MODEL_NOT_ALLOWED` | 403 | Model not in the app's allowed models list |
332
+ *
333
+ * **Provider error codes** (`source: "provider"`):
334
+ * | Code | HTTP | Description |
335
+ * |---|---|---|
336
+ * | `RATE_LIMITED` | 429 | Upstream rate limit hit — retry after backoff |
337
+ * | `CONTEXT_LENGTH_EXCEEDED` | 400 | Request exceeds model's context window |
338
+ * | `INVALID_REQUEST` | 400 | Provider rejected the request as malformed |
339
+ * | `AUTHENTICATION_FAILED` | 401 | Provider rejected the API key |
340
+ * | `PROVIDER_OVERLOADED` | 503 | Provider temporarily overloaded |
341
+ * | `CONTENT_FILTERED` | 400 | Content blocked by safety filter |
342
+ * | `PROVIDER_TIMEOUT` | 504 | Provider did not respond in time |
343
+ * | `PROVIDER_ERROR` | 502 | Catch-all for other provider errors |
344
+ */
345
+ export type ProxyError = {
346
+ readonly error: {
347
+ /** Machine-readable error code */
348
+ readonly code: string;
349
+ /** Human-readable description */
350
+ readonly message: string;
351
+ /** Where the error originated */
352
+ readonly source: ErrorSource;
353
+ /** Optional structured context (e.g. `retryAfter`, `provider`, `providerMessage`) */
354
+ readonly details?: Record<string, unknown>;
355
+ };
356
+ };
357
+
358
+ /** Discriminated union for all non-streaming proxy responses */
359
+ export type ProxyResponse = ProxySuccess | ProxyError;
360
+
361
+ /** Type guard: returns true if the response is an error */
362
+ export const isProxyError = (response: ProxyResponse): response is ProxyError =>
363
+ 'error' in response;
364
+
365
+ /** Type guard: returns true if the response is a success */
366
+ export const isProxySuccess = (response: ProxyResponse): response is ProxySuccess =>
367
+ 'provider' in response;
368
+
369
+ // ─── Access context (tk.getAllowedProviders) ───
370
+
371
+ /** Visual + identity metadata for a single provider */
372
+ export type ProviderInfo = {
373
+ /** Stable provider id (same value as the `Provider` union) */
374
+ readonly id: Provider;
375
+ /** Human-readable name, e.g. "Anthropic" */
376
+ readonly displayName: string;
377
+ /** Brand colour (hex string, e.g. "#d97706") */
378
+ readonly color: string;
379
+ /** Absolute URL to the provider's logo (PNG or SVG) */
380
+ readonly logoUrl: string;
381
+ /** Whether the logo is a glyph/symbol or a full wordmark */
382
+ readonly logoStyle: 'symbol' | 'wordmark';
383
+ };
384
+
385
+ /** Summary of the app the access token belongs to */
386
+ export type AppInfo = {
387
+ readonly id: string;
388
+ readonly name: string;
389
+ readonly description: string | null;
390
+ readonly websiteUrl: string | null;
391
+ /** Absolute URL to the app's icon (PNG/SVG). null when the developer hasn't set one — render initials or a generic glyph. */
392
+ readonly iconUrl: string | null;
393
+ /** Providers the app declares it needs */
394
+ readonly requiredProviders: readonly Provider[];
395
+ /** Fallback order when `allowSubstitution` is true */
396
+ readonly preferredProviders: readonly Provider[];
397
+ /** Whether the app accepts substitute providers when a required one isn't available */
398
+ readonly allowSubstitution: boolean;
399
+ };
400
+
401
+ /**
402
+ * Full access context for a single access token.
403
+ *
404
+ * `providers` lists only the providers the user has an active key for —
405
+ * exactly the set that will succeed through `tk.call()` (budget permitting).
406
+ */
407
+ export type AllowedProvidersResponse = {
408
+ readonly app: AppInfo;
409
+ readonly providers: readonly ProviderInfo[];
410
+ };
411
+ ```
412
+ <!-- /GEN:TYPES -->
413
+
414
+ ## Error Codes
415
+
416
+ Non-streaming proxy responses return a unified error envelope:
417
+
418
+ ```json
419
+ { "error": { "code": "...", "message": "...", "source": "proxy" | "provider", "details": { } } }
420
+ ```
421
+
422
+ `source` distinguishes errors raised by the Tokenite proxy from errors forwarded from the upstream LLM. Use the `isProxyError` type guard to narrow a `ProxyResponse` before reading `error.code`.
423
+
424
+ ### Proxy errors (`source: "proxy"`)
425
+
426
+ | Code | Status | Meaning |
427
+ |------|--------|---------|
428
+ | `TOKEN_INVALID` | 401 | Missing or unrecognized access token |
429
+ | `TOKEN_REVOKED` | 401 | User revoked access |
430
+ | `TOKEN_EXPIRED` | 401 | Token expired (30-day lifetime) |
431
+ | `TOKEN_SUSPENDED` | 403 | User temporarily suspended access |
432
+ | `BUDGET_EXCEEDED` | 402 | Spending limit reached |
433
+ | `PROVIDER_KEY_MISSING` | 402 | No API key or credits available for the provider |
434
+ | `CREDITS_DEPLETED` | 402 | Insufficient platform credits |
435
+ | `MODEL_NOT_ALLOWED` | 403 | Model not in your app's allowed list |
436
+ | `AGENT_SCOPE_MISSING` | 403 | App doesn't have the managed-agents scope (set `allowsManagedAgents: true` at app creation) |
437
+ | `APP_NOT_FOUND` | 404 | Application not found |
438
+
439
+ ### Provider errors (`source: "provider"`)
440
+
441
+ | Code | Status | Meaning |
442
+ |------|--------|---------|
443
+ | `RATE_LIMITED` | 429 | Upstream rate limit hit — retry after backoff |
444
+ | `CONTEXT_LENGTH_EXCEEDED` | 400 | Request exceeds the model's context window |
445
+ | `INVALID_REQUEST` | 400 | Provider rejected the request as malformed |
446
+ | `CONTENT_FILTERED` | 400 | Content blocked by the provider's safety filter |
447
+ | `AUTHENTICATION_FAILED` | 401 | Provider rejected the API key |
448
+ | `PROVIDER_OVERLOADED` | 503 | Provider temporarily overloaded |
449
+ | `PROVIDER_TIMEOUT` | 504 | Provider did not respond in time |
450
+ | `PROVIDER_ERROR` | 502 | Catch-all for other provider errors |
451
+
452
+ ## License
453
+
454
+ MIT
@@ -0,0 +1,28 @@
1
+ import type { AdminClient } from './client.js';
2
+ import type { AccountRecord, CreateAccountInput, UpdateAccountInput, InvitationRecord, InvitationWithClaim, CreateInvitationInput, MemberRecord, UpdateMemberInput, ClaimInvitationInput, ClaimInvitationResult } from './types.js';
3
+ export declare const createAccountsApi: (client: AdminClient) => {
4
+ list: () => Promise<AccountRecord[]>;
5
+ create: (input: CreateAccountInput) => Promise<AccountRecord>;
6
+ get: (id: string) => Promise<AccountRecord & {
7
+ role: "owner" | "member";
8
+ }>;
9
+ update: (id: string, input: UpdateAccountInput) => Promise<AccountRecord>;
10
+ delete: (id: string) => Promise<{
11
+ ok: true;
12
+ }>;
13
+ invite: (accountId: string, input: CreateInvitationInput) => Promise<InvitationWithClaim>;
14
+ invitations: (accountId: string) => Promise<InvitationRecord[]>;
15
+ cancelInvite: (accountId: string, invitationId: string) => Promise<{
16
+ ok: true;
17
+ }>;
18
+ members: (accountId: string) => Promise<MemberRecord[]>;
19
+ updateMember: (accountId: string, userId: string, input: UpdateMemberInput) => Promise<MemberRecord>;
20
+ removeMember: (accountId: string, userId: string) => Promise<{
21
+ ok: true;
22
+ }>;
23
+ leave: (accountId: string) => Promise<{
24
+ ok: true;
25
+ }>;
26
+ claim: (input: ClaimInvitationInput) => Promise<ClaimInvitationResult>;
27
+ };
28
+ //# sourceMappingURL=accounts.d.ts.map
@@ -0,0 +1,16 @@
1
+ export const createAccountsApi = (client) => ({
2
+ list: () => client.request('GET', '/api/accounts'),
3
+ create: (input) => client.request('POST', '/api/accounts', input),
4
+ get: (id) => client.request('GET', `/api/accounts/${id}`, undefined, { accountId: id }),
5
+ update: (id, input) => client.request('PATCH', `/api/accounts/${id}`, input, { accountId: id }),
6
+ delete: (id) => client.request('DELETE', `/api/accounts/${id}`, undefined, { accountId: id }),
7
+ invite: (accountId, input) => client.request('POST', `/api/accounts/${accountId}/invitations`, input, { accountId }),
8
+ invitations: (accountId) => client.request('GET', `/api/accounts/${accountId}/invitations`, undefined, { accountId }),
9
+ cancelInvite: (accountId, invitationId) => client.request('DELETE', `/api/accounts/${accountId}/invitations/${invitationId}`, undefined, { accountId }),
10
+ members: (accountId) => client.request('GET', `/api/accounts/${accountId}/members`, undefined, { accountId }),
11
+ updateMember: (accountId, userId, input) => client.request('PATCH', `/api/accounts/${accountId}/members/${userId}`, input, { accountId }),
12
+ removeMember: (accountId, userId) => client.request('DELETE', `/api/accounts/${accountId}/members/${userId}`, undefined, { accountId }),
13
+ leave: (accountId) => client.request('POST', `/api/accounts/${accountId}/leave`, undefined, { accountId }),
14
+ claim: (input) => client.request('POST', '/api/invitations/claim', input),
15
+ });
16
+ //# sourceMappingURL=accounts.js.map
@@ -0,0 +1,15 @@
1
+ import type { AdminClient } from './client.js';
2
+ import type { AppRecord, CreatedApp, CreateAppInput, UpdateAppInput } from './types.js';
3
+ export declare const createAppsApi: (client: AdminClient) => {
4
+ create: (input: CreateAppInput) => Promise<CreatedApp>;
5
+ list: () => Promise<AppRecord[]>;
6
+ get: (id: string) => Promise<AppRecord>;
7
+ update: (id: string, input: UpdateAppInput) => Promise<AppRecord>;
8
+ rotateSecret: (id: string) => Promise<{
9
+ appSecret: string;
10
+ }>;
11
+ delete: (id: string) => Promise<{
12
+ ok: true;
13
+ }>;
14
+ };
15
+ //# sourceMappingURL=apps.d.ts.map
@@ -0,0 +1,9 @@
1
+ export const createAppsApi = (client) => ({
2
+ create: (input) => client.request('POST', '/api/apps', input),
3
+ list: () => client.request('GET', '/api/apps'),
4
+ get: (id) => client.request('GET', `/api/apps/${id}`),
5
+ update: (id, input) => client.request('PATCH', `/api/apps/${id}`, input),
6
+ rotateSecret: (id) => client.request('POST', `/api/apps/${id}/rotate-secret`),
7
+ delete: (id) => client.request('DELETE', `/api/apps/${id}`),
8
+ });
9
+ //# sourceMappingURL=apps.js.map
@@ -0,0 +1,13 @@
1
+ import type { AdminClient } from './client.js';
2
+ import type { RegisterUserInput, RegisterUserResult, LoginInput, LoginResult, Me, CreateTokenInput, CreatedPat, PatRecord } from './types.js';
3
+ export declare const createAuthApi: (client: AdminClient) => {
4
+ register: (input: RegisterUserInput) => Promise<RegisterUserResult>;
5
+ login: (input: LoginInput) => Promise<LoginResult>;
6
+ me: () => Promise<Me>;
7
+ createToken: (input: CreateTokenInput) => Promise<CreatedPat>;
8
+ listTokens: () => Promise<PatRecord[]>;
9
+ revokeToken: (tokenId: string) => Promise<{
10
+ ok: true;
11
+ }>;
12
+ };
13
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1,9 @@
1
+ export const createAuthApi = (client) => ({
2
+ register: (input) => client.request('POST', '/api/auth/register', input),
3
+ login: (input) => client.request('POST', '/api/auth/login', input),
4
+ me: () => client.request('GET', '/api/auth/me'),
5
+ createToken: (input) => client.request('POST', '/api/auth/tokens', input),
6
+ listTokens: () => client.request('GET', '/api/auth/tokens'),
7
+ revokeToken: (tokenId) => client.request('DELETE', `/api/auth/tokens/${tokenId}`),
8
+ });
9
+ //# sourceMappingURL=auth.js.map
@@ -0,0 +1,22 @@
1
+ export type AdminClientConfig = {
2
+ readonly baseUrl: string;
3
+ readonly apiKey: string;
4
+ readonly accountId?: string;
5
+ };
6
+ export type AdminClient = {
7
+ readonly request: <T>(method: string, path: string, body?: unknown, overrides?: RequestOverrides) => Promise<T>;
8
+ };
9
+ export type RequestOverrides = {
10
+ readonly accountId?: string;
11
+ };
12
+ export declare const createAdminClient: (config: {
13
+ baseUrl?: string;
14
+ apiKey: string;
15
+ accountId?: string;
16
+ }) => AdminClient;
17
+ export declare class AdminClientError extends Error {
18
+ readonly status: number;
19
+ readonly body: unknown;
20
+ constructor(message: string, status: number, body: unknown);
21
+ }
22
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,59 @@
1
+ const DEFAULT_BASE_URL = 'https://api.tokenite.ai';
2
+ export const createAdminClient = (config) => {
3
+ const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
4
+ const apiKey = config.apiKey;
5
+ const defaultAccountId = config.accountId;
6
+ const request = async (method, path, body, overrides) => {
7
+ const accountId = overrides?.accountId ?? defaultAccountId;
8
+ const headers = {
9
+ authorization: `Bearer ${apiKey}`,
10
+ };
11
+ if (body !== undefined)
12
+ headers['content-type'] = 'application/json';
13
+ if (accountId)
14
+ headers['x-account-id'] = accountId;
15
+ const response = await fetch(`${baseUrl}${path}`, {
16
+ method,
17
+ headers,
18
+ body: body !== undefined ? JSON.stringify(body) : undefined,
19
+ });
20
+ const text = await response.text();
21
+ const parsed = text ? safeJsonParse(text) : null;
22
+ if (!response.ok) {
23
+ const message = errorMessage(parsed) ?? `${method} ${path} failed (${response.status})`;
24
+ throw new AdminClientError(message, response.status, parsed);
25
+ }
26
+ return parsed;
27
+ };
28
+ return { request };
29
+ };
30
+ export class AdminClientError extends Error {
31
+ status;
32
+ body;
33
+ constructor(message, status, body) {
34
+ super(message);
35
+ this.name = 'AdminClientError';
36
+ this.status = status;
37
+ this.body = body;
38
+ }
39
+ }
40
+ const safeJsonParse = (text) => {
41
+ try {
42
+ return JSON.parse(text);
43
+ }
44
+ catch {
45
+ return text;
46
+ }
47
+ };
48
+ const errorMessage = (parsed) => {
49
+ if (typeof parsed !== 'object' || parsed === null)
50
+ return undefined;
51
+ const error = parsed['error'];
52
+ if (typeof error === 'object' && error !== null) {
53
+ const message = error['message'];
54
+ if (typeof message === 'string')
55
+ return message;
56
+ }
57
+ return undefined;
58
+ };
59
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,19 @@
1
+ import type { AdminClient } from './client.js';
2
+ import type { ConnectionRecord, ConnectionStats } from './types.js';
3
+ export declare const createConnectionsApi: (client: AdminClient) => {
4
+ list: () => Promise<ConnectionRecord[]>;
5
+ stats: (id: string) => Promise<ConnectionStats>;
6
+ setBudget: (id: string, budgetLimit: number) => Promise<{
7
+ ok: true;
8
+ }>;
9
+ suspend: (id: string) => Promise<{
10
+ ok: true;
11
+ }>;
12
+ resume: (id: string) => Promise<{
13
+ ok: true;
14
+ }>;
15
+ revoke: (id: string) => Promise<{
16
+ ok: true;
17
+ }>;
18
+ };
19
+ //# sourceMappingURL=connections.d.ts.map