aispendbook 0.0.0-stage → 0.1.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.
Files changed (56) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/dist/cjs/client.d.ts +48 -0
  4. package/dist/cjs/client.js +197 -0
  5. package/dist/cjs/config.d.ts +80 -0
  6. package/dist/cjs/config.js +59 -0
  7. package/dist/cjs/context.d.ts +22 -0
  8. package/dist/cjs/context.js +28 -0
  9. package/dist/cjs/index.d.ts +26 -0
  10. package/dist/cjs/index.js +53 -0
  11. package/dist/cjs/package.json +1 -0
  12. package/dist/cjs/transport.d.ts +61 -0
  13. package/dist/cjs/transport.js +231 -0
  14. package/dist/cjs/types.d.ts +51 -0
  15. package/dist/cjs/types.js +7 -0
  16. package/dist/cjs/usage.d.ts +16 -0
  17. package/dist/cjs/usage.js +110 -0
  18. package/dist/cjs/vercel.d.ts +30 -0
  19. package/dist/cjs/vercel.js +130 -0
  20. package/dist/cjs/version.d.ts +2 -0
  21. package/dist/cjs/version.js +5 -0
  22. package/dist/cjs/wrappers/anthropic.d.ts +9 -0
  23. package/dist/cjs/wrappers/anthropic.js +106 -0
  24. package/dist/cjs/wrappers/google.d.ts +9 -0
  25. package/dist/cjs/wrappers/google.js +74 -0
  26. package/dist/cjs/wrappers/openai.d.ts +10 -0
  27. package/dist/cjs/wrappers/openai.js +136 -0
  28. package/dist/cjs/wrappers/span.d.ts +60 -0
  29. package/dist/cjs/wrappers/span.js +190 -0
  30. package/dist/esm/client.d.ts +48 -0
  31. package/dist/esm/client.js +187 -0
  32. package/dist/esm/config.d.ts +80 -0
  33. package/dist/esm/config.js +54 -0
  34. package/dist/esm/context.d.ts +22 -0
  35. package/dist/esm/context.js +23 -0
  36. package/dist/esm/index.d.ts +26 -0
  37. package/dist/esm/index.js +19 -0
  38. package/dist/esm/transport.d.ts +61 -0
  39. package/dist/esm/transport.js +226 -0
  40. package/dist/esm/types.d.ts +51 -0
  41. package/dist/esm/types.js +4 -0
  42. package/dist/esm/usage.d.ts +16 -0
  43. package/dist/esm/usage.js +103 -0
  44. package/dist/esm/vercel.d.ts +30 -0
  45. package/dist/esm/vercel.js +125 -0
  46. package/dist/esm/version.d.ts +2 -0
  47. package/dist/esm/version.js +2 -0
  48. package/dist/esm/wrappers/anthropic.d.ts +9 -0
  49. package/dist/esm/wrappers/anthropic.js +102 -0
  50. package/dist/esm/wrappers/google.d.ts +9 -0
  51. package/dist/esm/wrappers/google.js +70 -0
  52. package/dist/esm/wrappers/openai.d.ts +10 -0
  53. package/dist/esm/wrappers/openai.js +132 -0
  54. package/dist/esm/wrappers/span.d.ts +60 -0
  55. package/dist/esm/wrappers/span.js +179 -0
  56. package/package.json +85 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AI Spendbook
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 CHANGED
@@ -1,3 +1,146 @@
1
- # Temporary Holding Version
1
+ # aispendbook (Node.js SDK)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Attribute OpenAI, Anthropic and Google Gemini token usage to your customers, features and
4
+ environments, and send it to AI Spendbook. Works with the Vercel AI SDK too.
5
+
6
+ The SDK never sits in your request path: events go into an in-memory queue and are sent in the
7
+ background in batches.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install github:AISpendbook/aispendbook-node
13
+ ```
14
+
15
+ The SDK installs from GitHub ([AISpendbook/aispendbook-node](https://github.com/AISpendbook/aispendbook-node)).
16
+ It is not published to npm yet.
17
+
18
+ Node 18 or newer. ESM and CommonJS builds with TypeScript types are included. The provider SDKs
19
+ (`openai`, `@anthropic-ai/sdk`, `@google/genai`, `ai`) are optional peer dependencies: install the
20
+ ones you use.
21
+
22
+ ## Set up
23
+
24
+ Create an ingestion key in AI Spendbook (Settings, Ingestion keys), then:
25
+
26
+ ```bash
27
+ export SPENDBOOK_API_KEY=afk_...
28
+ export SPENDBOOK_ENDPOINT=https://<your AI Spendbook API URL>
29
+ ```
30
+
31
+ ```ts
32
+ import { init } from "aispendbook";
33
+
34
+ init(); // reads SPENDBOOK_API_KEY / SPENDBOOK_ENDPOINT, or pass { apiKey, endpoint }
35
+ ```
36
+
37
+ `SPENDBOOK_DISABLED=1` (or `init({ enabled: false })`) turns the SDK into a no-op. Without a key
38
+ or endpoint it is also a no-op and logs one warning through the `logger` option.
39
+
40
+ ## Wrap your clients
41
+
42
+ ```ts
43
+ import OpenAI from "openai";
44
+ import Anthropic from "@anthropic-ai/sdk";
45
+ import { GoogleGenAI } from "@google/genai";
46
+ import { wrapAnthropic, wrapGoogleGenAI, wrapOpenAI, withContext } from "aispendbook";
47
+
48
+ const openai = wrapOpenAI(new OpenAI());
49
+ const anthropic = wrapAnthropic(new Anthropic());
50
+ const gemini = wrapGoogleGenAI(new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY }));
51
+
52
+ await withContext({ customerId: "company_456", feature: "diet_generation", environment: "prod" }, async () => {
53
+ await openai.chat.completions.create({ model: "gpt-4.1-mini", messages });
54
+ await anthropic.messages.create({ model: "claude-sonnet-4-5", max_tokens: 512, messages });
55
+ await gemini.models.generateContent({ model: "gemini-2.5-flash", contents: "Hello" });
56
+ });
57
+ ```
58
+
59
+ Wrapped calls return exactly what the original client returns (including `.withResponse()` and
60
+ stream objects). What is recorded:
61
+
62
+ | Client | Methods | Provider reported |
63
+ | --- | --- | --- |
64
+ | `OpenAI` | `chat.completions.create`, `responses.create` (streamed or not) | `openai` |
65
+ | `AzureOpenAI` | same | `azure_openai` |
66
+ | `Anthropic` | `messages.create` (streamed or not), `messages.stream` | `anthropic` |
67
+ | `AnthropicBedrock` / `AnthropicVertex` | same | `bedrock` / `vertex` |
68
+ | `GoogleGenAI` | `models.generateContent`, `models.generateContentStream` | `google` (`vertex` with `vertexai: true`) |
69
+
70
+ Override the provider with `wrapOpenAI(client, { provider: "my_gateway" })`.
71
+
72
+ `withContext` uses `AsyncLocalStorage`, so attribution follows the async call chain and never leaks
73
+ between concurrent requests. Nested contexts merge (inner values win, `metadata` objects merge).
74
+ Fields: `customerId`, `userId`, `feature`, `category`, `workloadType`, `projectId`,
75
+ `organizationRef`, `traceId`, `sessionId`, `runId`, `environment`, `metadata`.
76
+
77
+ ## Vercel AI SDK
78
+
79
+ ```ts
80
+ import { openai } from "@ai-sdk/openai";
81
+ import { generateText, wrapLanguageModel } from "ai";
82
+ import { spendbookMiddleware, withContext } from "aispendbook";
83
+
84
+ const model = wrapLanguageModel({ model: openai("gpt-4.1-mini"), middleware: spendbookMiddleware() });
85
+
86
+ await withContext({ customerId: "company_456", feature: "chat" }, () => generateText({ model, prompt: "Hi" }));
87
+ ```
88
+
89
+ The middleware reads `usage` from `generateText` results and from the stream's `finish` part.
90
+
91
+ ## Record anything else
92
+
93
+ ```ts
94
+ import { record } from "aispendbook";
95
+
96
+ record({
97
+ provider: "mistral",
98
+ model: "mistral-large-latest",
99
+ inputTokens: 1200, // uncached input
100
+ outputTokens: 300,
101
+ cacheReadTokens: 0,
102
+ latencyMs: 840,
103
+ attribution: { customerId: "company_456", feature: "search" },
104
+ });
105
+ ```
106
+
107
+ ## Delivery
108
+
109
+ - Events are queued in memory and sent to `POST {endpoint}/api/v1/ingest/batch` when
110
+ `maxBatchSize` events are queued (default 100, max 500) or `flushIntervalMs` after the first
111
+ queued event (default 2000). The timer does not keep your process alive.
112
+ - 429, 5xx and network errors are retried with exponential backoff and jitter, honouring
113
+ `Retry-After`, for up to `maxRetryDurationMs` (default 60000). Every event keeps its `event_id`,
114
+ so the API deduplicates retries.
115
+ - When the queue holds `maxQueueSize` events (default 10000), new events are dropped and counted
116
+ in `getClient()?.stats.dropped`.
117
+ - Queued events are flushed on `beforeExit`. For serverless functions and on `SIGTERM`, call
118
+ `await flush()` or `await shutdown()` yourself before the process ends.
119
+
120
+ ## Token mapping
121
+
122
+ `input_tokens` are uncached input tokens.
123
+
124
+ - OpenAI: input = `prompt_tokens - cached_tokens`; reasoning tokens are part of output and also
125
+ listed in `other_tokens`.
126
+ - Anthropic: `input_tokens` as reported; cache writes from `cache_creation_input_tokens`, with the
127
+ 1 hour TTL share from `cache_creation.ephemeral_1h_input_tokens`.
128
+ - Gemini: input = `promptTokenCount - cachedContentTokenCount + toolUsePromptTokenCount`; output
129
+ includes `thoughtsTokenCount`.
130
+
131
+ ## Limits
132
+
133
+ - Streamed OpenAI chat completions only include usage when you pass
134
+ `stream_options: { include_usage: true }`. Without it the event is recorded with zero tokens and
135
+ `metadata.usage_missing = true`.
136
+ - Only the methods in the table are wrapped. Embeddings, images, audio, batch and realtime calls,
137
+ and Gemini `chats`, are not recorded automatically: use `record()`.
138
+ - Vercel AI SDK 5 reports `inputTokens` including cached tokens for most providers but not for
139
+ Anthropic; the middleware subtracts cached tokens except for Anthropic. AI SDK 6 structured usage
140
+ is read directly.
141
+ - Token counts are what the provider returned. AI Spendbook prices them as estimates; billed cost
142
+ comes from provider billing connectors.
143
+
144
+ ## Licence
145
+
146
+ MIT
@@ -0,0 +1,48 @@
1
+ /** Client: builds ingest events from usage + attribution and hands them to a Transport. */
2
+ import { type ResolvedConfig, type SpendbookOptions } from "./config.js";
3
+ import { type Attribution } from "./context.js";
4
+ import { type Transport, type TransportStats } from "./transport.js";
5
+ import type { EventStatus, IngestEvent, MetaValue, Usage } from "./types.js";
6
+ export interface RecordInput extends Partial<Usage> {
7
+ provider: string;
8
+ model?: string;
9
+ occurredAt?: Date;
10
+ completedAt?: Date;
11
+ latencyMs?: number;
12
+ status?: EventStatus;
13
+ errorType?: string;
14
+ requestId?: string;
15
+ serviceTier?: string;
16
+ streamed?: boolean;
17
+ sourceReportedCostMicros?: number;
18
+ eventId?: string;
19
+ metadata?: Record<string, MetaValue>;
20
+ /** Overrides the active `withContext` attribution for this event. */
21
+ attribution?: Attribution;
22
+ }
23
+ export interface SpendbookClientDeps {
24
+ transport?: Transport;
25
+ }
26
+ export declare class SpendbookClient {
27
+ readonly config: ResolvedConfig;
28
+ readonly transport: Transport | null;
29
+ constructor(options?: SpendbookOptions, deps?: SpendbookClientDeps);
30
+ get active(): boolean;
31
+ get stats(): Readonly<TransportStats> | Record<string, never>;
32
+ toString(): string;
33
+ buildEvent(input: RecordInput): IngestEvent;
34
+ /** Build and enqueue an event. Returns its event_id, or undefined when inactive. Never throws. */
35
+ record(input: RecordInput): string | undefined;
36
+ flush(timeoutMs?: number): Promise<boolean>;
37
+ shutdown(timeoutMs?: number): Promise<boolean>;
38
+ }
39
+ /** Configure the global client. Calling it again replaces (and flushes) the previous client. */
40
+ export declare function init(options?: SpendbookOptions, deps?: SpendbookClientDeps): SpendbookClient;
41
+ export declare function getClient(): SpendbookClient | null;
42
+ /** Record usage for a call the SDK does not wrap. Returns the event_id or undefined. Never throws. */
43
+ export declare function record(input: RecordInput): string | undefined;
44
+ export declare function flush(timeoutMs?: number): Promise<boolean>;
45
+ /** Flush and stop the global client; further events are dropped until `init` runs again. */
46
+ export declare function shutdown(timeoutMs?: number): Promise<boolean>;
47
+ /** @internal test helper */
48
+ export declare function resetForTests(): void;
@@ -0,0 +1,197 @@
1
+ "use strict";
2
+ /** Client: builds ingest events from usage + attribution and hands them to a Transport. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.SpendbookClient = void 0;
5
+ exports.init = init;
6
+ exports.getClient = getClient;
7
+ exports.record = record;
8
+ exports.flush = flush;
9
+ exports.shutdown = shutdown;
10
+ exports.resetForTests = resetForTests;
11
+ const node_crypto_1 = require("node:crypto");
12
+ const config_js_1 = require("./config.js");
13
+ const context_js_1 = require("./context.js");
14
+ const transport_js_1 = require("./transport.js");
15
+ const version_js_1 = require("./version.js");
16
+ const FIELD_LIMITS = {
17
+ customer_id: 200,
18
+ end_user_id: 200,
19
+ feature: 200,
20
+ category: 100,
21
+ workload_type: 100,
22
+ project_id: 200,
23
+ organization_ref: 200,
24
+ trace_id: 200,
25
+ session_id: 200,
26
+ run_id: 200,
27
+ environment: 64,
28
+ model: 200,
29
+ provider: 64,
30
+ request_id: 300,
31
+ service_tier: 32,
32
+ error_type: 100,
33
+ };
34
+ const STATUSES = ["success", "error", "cancelled"];
35
+ function tokens(value) {
36
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
37
+ }
38
+ function sanitizeMetadata(meta) {
39
+ const out = {};
40
+ for (const [key, value] of Object.entries(meta)) {
41
+ if (Object.keys(out).length >= 20)
42
+ break;
43
+ if (!key || key.length > 64)
44
+ continue;
45
+ if (typeof value === "string")
46
+ out[key] = value.slice(0, 256);
47
+ else if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))
48
+ out[key] = value;
49
+ }
50
+ return Object.keys(out).length ? out : undefined;
51
+ }
52
+ class SpendbookClient {
53
+ config;
54
+ transport;
55
+ constructor(options = {}, deps = {}) {
56
+ this.config = (0, config_js_1.resolveConfig)(options);
57
+ this.transport = this.config.active ? deps.transport ?? new transport_js_1.HttpTransport(this.config) : null;
58
+ }
59
+ get active() {
60
+ return this.transport !== null;
61
+ }
62
+ get stats() {
63
+ return this.transport ? { ...this.transport.stats } : {};
64
+ }
65
+ toString() {
66
+ return `SpendbookClient(endpoint=${this.config.endpoint ?? "none"}, apiKey=${(0, config_js_1.redactKey)(this.config.apiKey)}, active=${this.active})`;
67
+ }
68
+ buildEvent(input) {
69
+ const attr = input.attribution ? (0, context_js_1.mergeAttribution)((0, context_js_1.getContext)(), input.attribution) : (0, context_js_1.getContext)();
70
+ const completedAt = input.completedAt ?? new Date();
71
+ const occurredAt = input.occurredAt ?? new Date(completedAt.getTime() - (input.latencyMs ?? 0));
72
+ const event = {
73
+ event_id: input.eventId ?? (0, node_crypto_1.randomUUID)(),
74
+ occurred_at: occurredAt.toISOString(),
75
+ completed_at: completedAt.toISOString(),
76
+ provider: String(input.provider).toLowerCase(),
77
+ status: input.status && STATUSES.includes(input.status) ? input.status : "success",
78
+ streamed: Boolean(input.streamed),
79
+ input_tokens: tokens(input.inputTokens),
80
+ output_tokens: tokens(input.outputTokens),
81
+ cache_read_tokens: tokens(input.cacheReadTokens),
82
+ cache_write_tokens: tokens(input.cacheWriteTokens),
83
+ cache_write_1h_tokens: tokens(input.cacheWrite1hTokens),
84
+ sdk: { name: version_js_1.SDK_NAME, version: version_js_1.SDK_VERSION },
85
+ };
86
+ if (event.cache_write_1h_tokens > event.cache_write_tokens)
87
+ event.cache_write_tokens = event.cache_write_1h_tokens;
88
+ const latency = input.latencyMs ?? (input.occurredAt ? completedAt.getTime() - occurredAt.getTime() : undefined);
89
+ if (latency !== undefined && Number.isFinite(latency))
90
+ event.latency_ms = Math.max(0, Math.round(latency));
91
+ const other = {};
92
+ for (const [key, value] of Object.entries(input.otherTokens ?? {})) {
93
+ if (tokens(value) > 0 && Object.keys(other).length < 20)
94
+ other[key.slice(0, 64)] = tokens(value);
95
+ }
96
+ if (Object.keys(other).length)
97
+ event.other_tokens = other;
98
+ if (input.sourceReportedCostMicros !== undefined)
99
+ event.source_reported_cost_micros = tokens(input.sourceReportedCostMicros);
100
+ const strings = {
101
+ model: input.model,
102
+ request_id: input.requestId,
103
+ service_tier: input.serviceTier,
104
+ error_type: input.errorType,
105
+ customer_id: attr.customerId,
106
+ end_user_id: attr.userId,
107
+ feature: attr.feature,
108
+ category: attr.category,
109
+ workload_type: attr.workloadType,
110
+ project_id: attr.projectId,
111
+ organization_ref: attr.organizationRef,
112
+ trace_id: attr.traceId,
113
+ session_id: attr.sessionId,
114
+ run_id: attr.runId,
115
+ environment: attr.environment,
116
+ };
117
+ for (const [key, value] of Object.entries(strings)) {
118
+ if (value !== undefined && value !== null && value !== "") {
119
+ event[key] = String(value).slice(0, FIELD_LIMITS[key] ?? 200);
120
+ }
121
+ }
122
+ event.provider = event.provider.slice(0, FIELD_LIMITS.provider);
123
+ const meta = sanitizeMetadata({ ...(attr.metadata ?? {}), ...(input.metadata ?? {}) });
124
+ if (meta)
125
+ event.metadata = meta;
126
+ return event;
127
+ }
128
+ /** Build and enqueue an event. Returns its event_id, or undefined when inactive. Never throws. */
129
+ record(input) {
130
+ if (!this.transport)
131
+ return undefined;
132
+ try {
133
+ const event = this.buildEvent(input);
134
+ this.transport.enqueue(event);
135
+ return event.event_id;
136
+ }
137
+ catch (err) {
138
+ this.config.logger.debug("spendbook: record failed", err);
139
+ return undefined;
140
+ }
141
+ }
142
+ flush(timeoutMs) {
143
+ return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
144
+ }
145
+ shutdown(timeoutMs) {
146
+ return this.transport ? this.transport.shutdown(timeoutMs) : Promise.resolve(true);
147
+ }
148
+ }
149
+ exports.SpendbookClient = SpendbookClient;
150
+ // -- global client --------------------------------------------------------------------------------
151
+ let globalClient = null;
152
+ let exitHookRegistered = false;
153
+ function registerExitHook() {
154
+ if (exitHookRegistered || typeof process === "undefined" || typeof process.on !== "function")
155
+ return;
156
+ exitHookRegistered = true;
157
+ // beforeExit fires when the event loop empties; flushing schedules work, so only flush when
158
+ // something is pending to avoid an endless beforeExit loop.
159
+ process.on("beforeExit", () => {
160
+ const client = globalClient;
161
+ if (client?.transport && client.config.flushOnExit && client.transport.pending > 0) {
162
+ void client.flush().catch(() => undefined);
163
+ }
164
+ });
165
+ }
166
+ /** Configure the global client. Calling it again replaces (and flushes) the previous client. */
167
+ function init(options = {}, deps = {}) {
168
+ const client = new SpendbookClient(options, deps);
169
+ const previous = globalClient;
170
+ globalClient = client;
171
+ if (previous)
172
+ void previous.shutdown().catch(() => undefined);
173
+ if (client.config.enabled && !client.active) {
174
+ client.config.logger.warn(`spendbook: missing ${!client.config.apiKey ? "apiKey (SPENDBOOK_API_KEY)" : "endpoint (SPENDBOOK_ENDPOINT)"}; tracking disabled`);
175
+ }
176
+ if (client.active && client.config.flushOnExit)
177
+ registerExitHook();
178
+ return client;
179
+ }
180
+ function getClient() {
181
+ return globalClient;
182
+ }
183
+ /** Record usage for a call the SDK does not wrap. Returns the event_id or undefined. Never throws. */
184
+ function record(input) {
185
+ return globalClient?.record(input);
186
+ }
187
+ function flush(timeoutMs) {
188
+ return globalClient ? globalClient.flush(timeoutMs) : Promise.resolve(true);
189
+ }
190
+ /** Flush and stop the global client; further events are dropped until `init` runs again. */
191
+ function shutdown(timeoutMs) {
192
+ return globalClient ? globalClient.shutdown(timeoutMs) : Promise.resolve(true);
193
+ }
194
+ /** @internal test helper */
195
+ function resetForTests() {
196
+ globalClient = null;
197
+ }
@@ -0,0 +1,80 @@
1
+ /** SDK configuration: explicit options override environment variables. */
2
+ export declare const ENV_API_KEY = "SPENDBOOK_API_KEY";
3
+ export declare const ENV_ENDPOINT = "SPENDBOOK_ENDPOINT";
4
+ export declare const ENV_DISABLED = "SPENDBOOK_DISABLED";
5
+ /** Path of the batch ingestion endpoint, appended to `endpoint`. */
6
+ export declare const INGEST_PATH = "/api/v1/ingest/batch";
7
+ /** Server-side limit on events per batch request. */
8
+ export declare const MAX_EVENTS_PER_REQUEST = 500;
9
+ export type FetchLike = (url: string, init: {
10
+ method: string;
11
+ headers: Record<string, string>;
12
+ body: string;
13
+ signal?: AbortSignal;
14
+ }) => Promise<{
15
+ status: number;
16
+ headers: {
17
+ get(name: string): string | null;
18
+ };
19
+ text(): Promise<string>;
20
+ }>;
21
+ export interface Logger {
22
+ debug(message: string, ...args: unknown[]): void;
23
+ warn(message: string, ...args: unknown[]): void;
24
+ }
25
+ export interface SpendbookOptions {
26
+ /** Ingestion key (`afk_...`). Defaults to `SPENDBOOK_API_KEY`. */
27
+ apiKey?: string;
28
+ /** Base URL of the AI Spendbook API. Defaults to `SPENDBOOK_ENDPOINT`. */
29
+ endpoint?: string;
30
+ /** `false` (or `SPENDBOOK_DISABLED=1`) turns the SDK into a no-op. */
31
+ enabled?: boolean;
32
+ /** Events held in memory before new ones are dropped (and counted). */
33
+ maxQueueSize?: number;
34
+ /** Events per request; capped at 500. A full batch is sent immediately. */
35
+ maxBatchSize?: number;
36
+ /** Milliseconds after the first queued event before a partial batch is sent. */
37
+ flushIntervalMs?: number;
38
+ /** Per-request timeout in milliseconds. */
39
+ requestTimeoutMs?: number;
40
+ /** Total time a batch is retried (429 / 5xx / network errors) before it is abandoned. */
41
+ maxRetryDurationMs?: number;
42
+ /** Base delay of the exponential backoff, in milliseconds. */
43
+ retryBaseMs?: number;
44
+ /** Upper bound of a single backoff delay, in milliseconds. */
45
+ retryCapMs?: number;
46
+ /** Fetch implementation (defaults to the global `fetch`). */
47
+ fetch?: FetchLike;
48
+ logger?: Logger;
49
+ /** Register a `beforeExit` hook that flushes queued events. Default true. */
50
+ flushOnExit?: boolean;
51
+ }
52
+ export interface ResolvedConfig {
53
+ apiKey?: string;
54
+ endpoint?: string;
55
+ enabled: boolean;
56
+ maxQueueSize: number;
57
+ maxBatchSize: number;
58
+ flushIntervalMs: number;
59
+ requestTimeoutMs: number;
60
+ maxRetryDurationMs: number;
61
+ retryBaseMs: number;
62
+ retryCapMs: number;
63
+ fetch?: FetchLike;
64
+ logger: Logger;
65
+ flushOnExit: boolean;
66
+ /** True when events will actually be sent. */
67
+ active: boolean;
68
+ }
69
+ export declare const DEFAULTS: {
70
+ readonly maxQueueSize: 10000;
71
+ readonly maxBatchSize: 100;
72
+ readonly flushIntervalMs: 2000;
73
+ readonly requestTimeoutMs: 10000;
74
+ readonly maxRetryDurationMs: 60000;
75
+ readonly retryBaseMs: 500;
76
+ readonly retryCapMs: 30000;
77
+ };
78
+ export declare function resolveConfig(options?: SpendbookOptions, env?: Record<string, string | undefined>): ResolvedConfig;
79
+ /** Render an API key safely: keep the prefix only (e.g. `afk_****`). */
80
+ export declare function redactKey(key: string | undefined): string;
@@ -0,0 +1,59 @@
1
+ "use strict";
2
+ /** SDK configuration: explicit options override environment variables. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.DEFAULTS = exports.MAX_EVENTS_PER_REQUEST = exports.INGEST_PATH = exports.ENV_DISABLED = exports.ENV_ENDPOINT = exports.ENV_API_KEY = void 0;
5
+ exports.resolveConfig = resolveConfig;
6
+ exports.redactKey = redactKey;
7
+ exports.ENV_API_KEY = "SPENDBOOK_API_KEY";
8
+ exports.ENV_ENDPOINT = "SPENDBOOK_ENDPOINT";
9
+ exports.ENV_DISABLED = "SPENDBOOK_DISABLED";
10
+ /** Path of the batch ingestion endpoint, appended to `endpoint`. */
11
+ exports.INGEST_PATH = "/api/v1/ingest/batch";
12
+ /** Server-side limit on events per batch request. */
13
+ exports.MAX_EVENTS_PER_REQUEST = 500;
14
+ exports.DEFAULTS = {
15
+ maxQueueSize: 10_000,
16
+ maxBatchSize: 100,
17
+ flushIntervalMs: 2_000,
18
+ requestTimeoutMs: 10_000,
19
+ maxRetryDurationMs: 60_000,
20
+ retryBaseMs: 500,
21
+ retryCapMs: 30_000,
22
+ };
23
+ const silentLogger = { debug: () => undefined, warn: () => undefined };
24
+ function truthy(value) {
25
+ return ["1", "true", "yes", "on"].includes((value ?? "").trim().toLowerCase());
26
+ }
27
+ function num(value, fallback, min) {
28
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(min, value) : fallback;
29
+ }
30
+ function resolveConfig(options = {}, env = typeof process !== "undefined" ? process.env : {}) {
31
+ const apiKey = options.apiKey ?? (env[exports.ENV_API_KEY] || undefined);
32
+ const rawEndpoint = options.endpoint ?? (env[exports.ENV_ENDPOINT] || undefined);
33
+ const endpoint = rawEndpoint ? rawEndpoint.replace(/\/+$/, "") : undefined;
34
+ const enabled = truthy(env[exports.ENV_DISABLED]) ? false : options.enabled ?? true;
35
+ const fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch : undefined);
36
+ return {
37
+ apiKey,
38
+ endpoint,
39
+ enabled,
40
+ maxQueueSize: Math.floor(num(options.maxQueueSize, exports.DEFAULTS.maxQueueSize, 1)),
41
+ maxBatchSize: Math.min(Math.floor(num(options.maxBatchSize, exports.DEFAULTS.maxBatchSize, 1)), exports.MAX_EVENTS_PER_REQUEST),
42
+ flushIntervalMs: num(options.flushIntervalMs, exports.DEFAULTS.flushIntervalMs, 0),
43
+ requestTimeoutMs: num(options.requestTimeoutMs, exports.DEFAULTS.requestTimeoutMs, 1),
44
+ maxRetryDurationMs: num(options.maxRetryDurationMs, exports.DEFAULTS.maxRetryDurationMs, 0),
45
+ retryBaseMs: num(options.retryBaseMs, exports.DEFAULTS.retryBaseMs, 0),
46
+ retryCapMs: num(options.retryCapMs, exports.DEFAULTS.retryCapMs, 0),
47
+ fetch: fetchImpl,
48
+ logger: options.logger ?? silentLogger,
49
+ flushOnExit: options.flushOnExit ?? true,
50
+ active: Boolean(enabled && apiKey && endpoint && fetchImpl),
51
+ };
52
+ }
53
+ /** Render an API key safely: keep the prefix only (e.g. `afk_****`). */
54
+ function redactKey(key) {
55
+ if (!key)
56
+ return "none";
57
+ const idx = key.indexOf("_");
58
+ return idx > 0 && idx < 8 ? `${key.slice(0, idx + 1)}****` : "****";
59
+ }
@@ -0,0 +1,22 @@
1
+ /** Request-scoped attribution on AsyncLocalStorage: never leaks between concurrent requests. */
2
+ import type { MetaValue } from "./types.js";
3
+ export interface Attribution {
4
+ customerId?: string;
5
+ userId?: string;
6
+ feature?: string;
7
+ category?: string;
8
+ workloadType?: string;
9
+ projectId?: string;
10
+ organizationRef?: string;
11
+ traceId?: string;
12
+ sessionId?: string;
13
+ runId?: string;
14
+ environment?: string;
15
+ metadata?: Record<string, MetaValue>;
16
+ }
17
+ /** Inner non-undefined values override outer ones; metadata objects merge. */
18
+ export declare function mergeAttribution(outer: Attribution, inner: Attribution): Attribution;
19
+ /** Run `fn` with attribution applied to every AI call made inside it (sync or async). */
20
+ export declare function withContext<T>(attribution: Attribution, fn: () => T): T;
21
+ /** The attribution active in the current async context (empty object if none). */
22
+ export declare function getContext(): Attribution;
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ /** Request-scoped attribution on AsyncLocalStorage: never leaks between concurrent requests. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.mergeAttribution = mergeAttribution;
5
+ exports.withContext = withContext;
6
+ exports.getContext = getContext;
7
+ const node_async_hooks_1 = require("node:async_hooks");
8
+ const storage = new node_async_hooks_1.AsyncLocalStorage();
9
+ /** Inner non-undefined values override outer ones; metadata objects merge. */
10
+ function mergeAttribution(outer, inner) {
11
+ const merged = { ...outer };
12
+ for (const [key, value] of Object.entries(inner)) {
13
+ if (key === "metadata" || value === undefined || value === null)
14
+ continue;
15
+ merged[key] = String(value);
16
+ }
17
+ if (inner.metadata)
18
+ merged.metadata = { ...(outer.metadata ?? {}), ...inner.metadata };
19
+ return merged;
20
+ }
21
+ /** Run `fn` with attribution applied to every AI call made inside it (sync or async). */
22
+ function withContext(attribution, fn) {
23
+ return storage.run(mergeAttribution(storage.getStore() ?? {}, attribution), fn);
24
+ }
25
+ /** The attribution active in the current async context (empty object if none). */
26
+ function getContext() {
27
+ return storage.getStore() ?? {};
28
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * AI Spendbook tracking SDK for Node.js.
3
+ *
4
+ * import { init, wrapOpenAI, withContext } from "aispendbook";
5
+ * init({ apiKey: process.env.SPENDBOOK_API_KEY, endpoint: process.env.SPENDBOOK_ENDPOINT });
6
+ * const openai = wrapOpenAI(new OpenAI());
7
+ * await withContext({ customerId: "company_456", feature: "diet_generation" }, () =>
8
+ * openai.chat.completions.create({ model: "gpt-4.1-mini", messages }));
9
+ */
10
+ export { SpendbookClient, flush, getClient, init, record, shutdown } from "./client.js";
11
+ export type { RecordInput, SpendbookClientDeps } from "./client.js";
12
+ export { DEFAULTS, ENV_API_KEY, ENV_DISABLED, ENV_ENDPOINT, INGEST_PATH, MAX_EVENTS_PER_REQUEST, resolveConfig } from "./config.js";
13
+ export type { FetchLike, Logger, ResolvedConfig, SpendbookOptions } from "./config.js";
14
+ export { getContext, withContext } from "./context.js";
15
+ export type { Attribution } from "./context.js";
16
+ export { HttpTransport } from "./transport.js";
17
+ export type { Transport, TransportStats } from "./transport.js";
18
+ export type { EventStatus, IngestEvent, MetaValue, Usage } from "./types.js";
19
+ export { anthropicUsage, geminiUsage, openaiChatUsage, openaiResponsesUsage } from "./usage.js";
20
+ export { SDK_NAME, SDK_VERSION } from "./version.js";
21
+ export { providerFromModel, spendbookMiddleware, vercelUsage } from "./vercel.js";
22
+ export type { SpendbookLanguageModelMiddleware, SpendbookMiddlewareOptions } from "./vercel.js";
23
+ export { detectAnthropicProvider, wrapAnthropic } from "./wrappers/anthropic.js";
24
+ export { detectGoogleProvider, wrapGoogleGenAI } from "./wrappers/google.js";
25
+ export { detectOpenAIProvider, wrapOpenAI } from "./wrappers/openai.js";
26
+ export type { WrapOptions } from "./wrappers/span.js";