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
@@ -0,0 +1,190 @@
1
+ "use strict";
2
+ /**
3
+ * Shared wrapper machinery. Every helper swallows its own errors so telemetry can never change
4
+ * the behaviour of the host application's provider call.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.CallSpan = void 0;
8
+ exports.str = str;
9
+ exports.startSpan = startSpan;
10
+ exports.safe = safe;
11
+ exports.observeResult = observeResult;
12
+ exports.isAsyncIterable = isAsyncIterable;
13
+ exports.observeStream = observeStream;
14
+ exports.wrapPath = wrapPath;
15
+ const client_js_1 = require("../client.js");
16
+ const context_js_1 = require("../context.js");
17
+ class CallSpan {
18
+ client;
19
+ provider;
20
+ requestModel;
21
+ streamed;
22
+ started = Date.now();
23
+ occurredAt = new Date();
24
+ attribution = (0, context_js_1.getContext)();
25
+ done = false;
26
+ constructor(client, provider, requestModel, streamed) {
27
+ this.client = client;
28
+ this.provider = provider;
29
+ this.requestModel = requestModel;
30
+ this.streamed = streamed;
31
+ }
32
+ finish(input = {}) {
33
+ if (this.done)
34
+ return;
35
+ this.done = true;
36
+ try {
37
+ const record = {
38
+ provider: this.provider,
39
+ model: input.model || this.requestModel,
40
+ occurredAt: this.occurredAt,
41
+ completedAt: new Date(),
42
+ latencyMs: Date.now() - this.started,
43
+ status: input.status ?? "success",
44
+ errorType: input.errorType,
45
+ requestId: input.requestId,
46
+ serviceTier: input.serviceTier,
47
+ streamed: this.streamed,
48
+ metadata: input.metadata,
49
+ attribution: this.attribution,
50
+ ...(input.usage ?? {}),
51
+ };
52
+ this.client.record(record);
53
+ }
54
+ catch {
55
+ // never surface telemetry errors
56
+ }
57
+ }
58
+ fail(err) {
59
+ const name = err?.name;
60
+ const aborted = name === "AbortError" || name === "APIUserAbortError";
61
+ this.finish({
62
+ status: aborted ? "cancelled" : "error",
63
+ errorType: typeof name === "string" ? name : "Error",
64
+ requestId: str(err?.requestID ?? err?.request_id),
65
+ });
66
+ }
67
+ }
68
+ exports.CallSpan = CallSpan;
69
+ function str(value) {
70
+ return typeof value === "string" && value ? value : undefined;
71
+ }
72
+ function startSpan(opts, provider, params, streamed) {
73
+ try {
74
+ const client = opts.client ?? (0, client_js_1.getClient)();
75
+ if (!client?.active)
76
+ return null;
77
+ const model = params?.model;
78
+ return new CallSpan(client, opts.provider ?? provider, typeof model === "string" ? model : undefined, streamed);
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ }
84
+ function safe(fn) {
85
+ try {
86
+ fn();
87
+ }
88
+ catch {
89
+ // ignore
90
+ }
91
+ }
92
+ function isThenable(value) {
93
+ return Boolean(value) && typeof value.then === "function";
94
+ }
95
+ /**
96
+ * Observe a call's result without replacing it: the original promise (e.g. an OpenAI APIPromise
97
+ * with `.withResponse()`) is returned unchanged. Our `then` runs before the caller's, so a stream
98
+ * is instrumented before the caller iterates it.
99
+ */
100
+ function observeResult(result, span, onValue) {
101
+ if (isThenable(result)) {
102
+ result.then((value) => safe(() => onValue(value)), (err) => safe(() => span.fail(err)));
103
+ return result;
104
+ }
105
+ safe(() => onValue(result));
106
+ return result;
107
+ }
108
+ function isAsyncIterable(value) {
109
+ return Boolean(value) && typeof value[Symbol.asyncIterator] === "function";
110
+ }
111
+ /**
112
+ * Instrument an async-iterable stream in place (same object returned to the caller): records
113
+ * success when iteration completes, error when it throws, cancelled on early `return()`.
114
+ */
115
+ function observeStream(stream, observer, span) {
116
+ const target = stream;
117
+ const original = target?.[Symbol.asyncIterator];
118
+ if (typeof original !== "function") {
119
+ span.finish({ metadata: { usage_missing: true } });
120
+ return;
121
+ }
122
+ const end = (status, errorType) => {
123
+ if (span.done)
124
+ return;
125
+ let input = {};
126
+ safe(() => {
127
+ input = observer.finish();
128
+ });
129
+ span.finish({ ...input, status: status === "success" ? input.status ?? "success" : status, errorType: errorType ?? input.errorType });
130
+ };
131
+ Object.defineProperty(target, Symbol.asyncIterator, {
132
+ configurable: true,
133
+ writable: true,
134
+ value: function observed() {
135
+ const inner = original.call(this);
136
+ const wrapped = {
137
+ async next(...args) {
138
+ try {
139
+ const res = await inner.next(...args);
140
+ if (res.done)
141
+ end("success");
142
+ else
143
+ safe(() => observer.observe(res.value));
144
+ return res;
145
+ }
146
+ catch (err) {
147
+ const name = err?.name;
148
+ end(name === "AbortError" || name === "APIUserAbortError" ? "cancelled" : "error", typeof name === "string" ? name : "Error");
149
+ throw err;
150
+ }
151
+ },
152
+ async return(value) {
153
+ end("cancelled");
154
+ return inner.return ? inner.return(value) : { done: true, value };
155
+ },
156
+ async throw(err) {
157
+ end("error", err?.name ?? "Error");
158
+ if (inner.throw)
159
+ return inner.throw(err);
160
+ throw err;
161
+ },
162
+ };
163
+ return wrapped;
164
+ },
165
+ });
166
+ }
167
+ /** Proxy `target` so the methods named in `spec` (nested by property path) are wrapped. */
168
+ function wrapPath(target, spec) {
169
+ const cache = new Map();
170
+ return new Proxy(target, {
171
+ get(obj, prop, receiver) {
172
+ const value = Reflect.get(obj, prop, receiver);
173
+ const entry = typeof prop === "string" ? spec[prop] : undefined;
174
+ if (!entry || value === null || value === undefined)
175
+ return value;
176
+ const cached = cache.get(prop);
177
+ if (cached && cached.src === value)
178
+ return cached.out;
179
+ let out = value;
180
+ if (typeof entry === "function" && typeof value === "function") {
181
+ out = entry(value, obj);
182
+ }
183
+ else if (typeof entry === "object" && typeof value === "object") {
184
+ out = wrapPath(value, entry);
185
+ }
186
+ cache.set(prop, { src: value, out });
187
+ return out;
188
+ },
189
+ });
190
+ }
@@ -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,187 @@
1
+ /** Client: builds ingest events from usage + attribution and hands them to a Transport. */
2
+ import { randomUUID } from "node:crypto";
3
+ import { redactKey, resolveConfig } from "./config.js";
4
+ import { getContext, mergeAttribution } from "./context.js";
5
+ import { HttpTransport } from "./transport.js";
6
+ import { SDK_NAME, SDK_VERSION } from "./version.js";
7
+ const FIELD_LIMITS = {
8
+ customer_id: 200,
9
+ end_user_id: 200,
10
+ feature: 200,
11
+ category: 100,
12
+ workload_type: 100,
13
+ project_id: 200,
14
+ organization_ref: 200,
15
+ trace_id: 200,
16
+ session_id: 200,
17
+ run_id: 200,
18
+ environment: 64,
19
+ model: 200,
20
+ provider: 64,
21
+ request_id: 300,
22
+ service_tier: 32,
23
+ error_type: 100,
24
+ };
25
+ const STATUSES = ["success", "error", "cancelled"];
26
+ function tokens(value) {
27
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
28
+ }
29
+ function sanitizeMetadata(meta) {
30
+ const out = {};
31
+ for (const [key, value] of Object.entries(meta)) {
32
+ if (Object.keys(out).length >= 20)
33
+ break;
34
+ if (!key || key.length > 64)
35
+ continue;
36
+ if (typeof value === "string")
37
+ out[key] = value.slice(0, 256);
38
+ else if (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value)))
39
+ out[key] = value;
40
+ }
41
+ return Object.keys(out).length ? out : undefined;
42
+ }
43
+ export class SpendbookClient {
44
+ config;
45
+ transport;
46
+ constructor(options = {}, deps = {}) {
47
+ this.config = resolveConfig(options);
48
+ this.transport = this.config.active ? deps.transport ?? new HttpTransport(this.config) : null;
49
+ }
50
+ get active() {
51
+ return this.transport !== null;
52
+ }
53
+ get stats() {
54
+ return this.transport ? { ...this.transport.stats } : {};
55
+ }
56
+ toString() {
57
+ return `SpendbookClient(endpoint=${this.config.endpoint ?? "none"}, apiKey=${redactKey(this.config.apiKey)}, active=${this.active})`;
58
+ }
59
+ buildEvent(input) {
60
+ const attr = input.attribution ? mergeAttribution(getContext(), input.attribution) : getContext();
61
+ const completedAt = input.completedAt ?? new Date();
62
+ const occurredAt = input.occurredAt ?? new Date(completedAt.getTime() - (input.latencyMs ?? 0));
63
+ const event = {
64
+ event_id: input.eventId ?? randomUUID(),
65
+ occurred_at: occurredAt.toISOString(),
66
+ completed_at: completedAt.toISOString(),
67
+ provider: String(input.provider).toLowerCase(),
68
+ status: input.status && STATUSES.includes(input.status) ? input.status : "success",
69
+ streamed: Boolean(input.streamed),
70
+ input_tokens: tokens(input.inputTokens),
71
+ output_tokens: tokens(input.outputTokens),
72
+ cache_read_tokens: tokens(input.cacheReadTokens),
73
+ cache_write_tokens: tokens(input.cacheWriteTokens),
74
+ cache_write_1h_tokens: tokens(input.cacheWrite1hTokens),
75
+ sdk: { name: SDK_NAME, version: SDK_VERSION },
76
+ };
77
+ if (event.cache_write_1h_tokens > event.cache_write_tokens)
78
+ event.cache_write_tokens = event.cache_write_1h_tokens;
79
+ const latency = input.latencyMs ?? (input.occurredAt ? completedAt.getTime() - occurredAt.getTime() : undefined);
80
+ if (latency !== undefined && Number.isFinite(latency))
81
+ event.latency_ms = Math.max(0, Math.round(latency));
82
+ const other = {};
83
+ for (const [key, value] of Object.entries(input.otherTokens ?? {})) {
84
+ if (tokens(value) > 0 && Object.keys(other).length < 20)
85
+ other[key.slice(0, 64)] = tokens(value);
86
+ }
87
+ if (Object.keys(other).length)
88
+ event.other_tokens = other;
89
+ if (input.sourceReportedCostMicros !== undefined)
90
+ event.source_reported_cost_micros = tokens(input.sourceReportedCostMicros);
91
+ const strings = {
92
+ model: input.model,
93
+ request_id: input.requestId,
94
+ service_tier: input.serviceTier,
95
+ error_type: input.errorType,
96
+ customer_id: attr.customerId,
97
+ end_user_id: attr.userId,
98
+ feature: attr.feature,
99
+ category: attr.category,
100
+ workload_type: attr.workloadType,
101
+ project_id: attr.projectId,
102
+ organization_ref: attr.organizationRef,
103
+ trace_id: attr.traceId,
104
+ session_id: attr.sessionId,
105
+ run_id: attr.runId,
106
+ environment: attr.environment,
107
+ };
108
+ for (const [key, value] of Object.entries(strings)) {
109
+ if (value !== undefined && value !== null && value !== "") {
110
+ event[key] = String(value).slice(0, FIELD_LIMITS[key] ?? 200);
111
+ }
112
+ }
113
+ event.provider = event.provider.slice(0, FIELD_LIMITS.provider);
114
+ const meta = sanitizeMetadata({ ...(attr.metadata ?? {}), ...(input.metadata ?? {}) });
115
+ if (meta)
116
+ event.metadata = meta;
117
+ return event;
118
+ }
119
+ /** Build and enqueue an event. Returns its event_id, or undefined when inactive. Never throws. */
120
+ record(input) {
121
+ if (!this.transport)
122
+ return undefined;
123
+ try {
124
+ const event = this.buildEvent(input);
125
+ this.transport.enqueue(event);
126
+ return event.event_id;
127
+ }
128
+ catch (err) {
129
+ this.config.logger.debug("spendbook: record failed", err);
130
+ return undefined;
131
+ }
132
+ }
133
+ flush(timeoutMs) {
134
+ return this.transport ? this.transport.flush(timeoutMs) : Promise.resolve(true);
135
+ }
136
+ shutdown(timeoutMs) {
137
+ return this.transport ? this.transport.shutdown(timeoutMs) : Promise.resolve(true);
138
+ }
139
+ }
140
+ // -- global client --------------------------------------------------------------------------------
141
+ let globalClient = null;
142
+ let exitHookRegistered = false;
143
+ function registerExitHook() {
144
+ if (exitHookRegistered || typeof process === "undefined" || typeof process.on !== "function")
145
+ return;
146
+ exitHookRegistered = true;
147
+ // beforeExit fires when the event loop empties; flushing schedules work, so only flush when
148
+ // something is pending to avoid an endless beforeExit loop.
149
+ process.on("beforeExit", () => {
150
+ const client = globalClient;
151
+ if (client?.transport && client.config.flushOnExit && client.transport.pending > 0) {
152
+ void client.flush().catch(() => undefined);
153
+ }
154
+ });
155
+ }
156
+ /** Configure the global client. Calling it again replaces (and flushes) the previous client. */
157
+ export function init(options = {}, deps = {}) {
158
+ const client = new SpendbookClient(options, deps);
159
+ const previous = globalClient;
160
+ globalClient = client;
161
+ if (previous)
162
+ void previous.shutdown().catch(() => undefined);
163
+ if (client.config.enabled && !client.active) {
164
+ client.config.logger.warn(`spendbook: missing ${!client.config.apiKey ? "apiKey (SPENDBOOK_API_KEY)" : "endpoint (SPENDBOOK_ENDPOINT)"}; tracking disabled`);
165
+ }
166
+ if (client.active && client.config.flushOnExit)
167
+ registerExitHook();
168
+ return client;
169
+ }
170
+ export function getClient() {
171
+ return globalClient;
172
+ }
173
+ /** Record usage for a call the SDK does not wrap. Returns the event_id or undefined. Never throws. */
174
+ export function record(input) {
175
+ return globalClient?.record(input);
176
+ }
177
+ export function flush(timeoutMs) {
178
+ return globalClient ? globalClient.flush(timeoutMs) : Promise.resolve(true);
179
+ }
180
+ /** Flush and stop the global client; further events are dropped until `init` runs again. */
181
+ export function shutdown(timeoutMs) {
182
+ return globalClient ? globalClient.shutdown(timeoutMs) : Promise.resolve(true);
183
+ }
184
+ /** @internal test helper */
185
+ export function resetForTests() {
186
+ globalClient = null;
187
+ }
@@ -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,54 @@
1
+ /** SDK configuration: explicit options override environment variables. */
2
+ export const ENV_API_KEY = "SPENDBOOK_API_KEY";
3
+ export const ENV_ENDPOINT = "SPENDBOOK_ENDPOINT";
4
+ export const ENV_DISABLED = "SPENDBOOK_DISABLED";
5
+ /** Path of the batch ingestion endpoint, appended to `endpoint`. */
6
+ export const INGEST_PATH = "/api/v1/ingest/batch";
7
+ /** Server-side limit on events per batch request. */
8
+ export const MAX_EVENTS_PER_REQUEST = 500;
9
+ export const DEFAULTS = {
10
+ maxQueueSize: 10_000,
11
+ maxBatchSize: 100,
12
+ flushIntervalMs: 2_000,
13
+ requestTimeoutMs: 10_000,
14
+ maxRetryDurationMs: 60_000,
15
+ retryBaseMs: 500,
16
+ retryCapMs: 30_000,
17
+ };
18
+ const silentLogger = { debug: () => undefined, warn: () => undefined };
19
+ function truthy(value) {
20
+ return ["1", "true", "yes", "on"].includes((value ?? "").trim().toLowerCase());
21
+ }
22
+ function num(value, fallback, min) {
23
+ return typeof value === "number" && Number.isFinite(value) ? Math.max(min, value) : fallback;
24
+ }
25
+ export function resolveConfig(options = {}, env = typeof process !== "undefined" ? process.env : {}) {
26
+ const apiKey = options.apiKey ?? (env[ENV_API_KEY] || undefined);
27
+ const rawEndpoint = options.endpoint ?? (env[ENV_ENDPOINT] || undefined);
28
+ const endpoint = rawEndpoint ? rawEndpoint.replace(/\/+$/, "") : undefined;
29
+ const enabled = truthy(env[ENV_DISABLED]) ? false : options.enabled ?? true;
30
+ const fetchImpl = options.fetch ?? (typeof fetch === "function" ? fetch : undefined);
31
+ return {
32
+ apiKey,
33
+ endpoint,
34
+ enabled,
35
+ maxQueueSize: Math.floor(num(options.maxQueueSize, DEFAULTS.maxQueueSize, 1)),
36
+ maxBatchSize: Math.min(Math.floor(num(options.maxBatchSize, DEFAULTS.maxBatchSize, 1)), MAX_EVENTS_PER_REQUEST),
37
+ flushIntervalMs: num(options.flushIntervalMs, DEFAULTS.flushIntervalMs, 0),
38
+ requestTimeoutMs: num(options.requestTimeoutMs, DEFAULTS.requestTimeoutMs, 1),
39
+ maxRetryDurationMs: num(options.maxRetryDurationMs, DEFAULTS.maxRetryDurationMs, 0),
40
+ retryBaseMs: num(options.retryBaseMs, DEFAULTS.retryBaseMs, 0),
41
+ retryCapMs: num(options.retryCapMs, DEFAULTS.retryCapMs, 0),
42
+ fetch: fetchImpl,
43
+ logger: options.logger ?? silentLogger,
44
+ flushOnExit: options.flushOnExit ?? true,
45
+ active: Boolean(enabled && apiKey && endpoint && fetchImpl),
46
+ };
47
+ }
48
+ /** Render an API key safely: keep the prefix only (e.g. `afk_****`). */
49
+ export function redactKey(key) {
50
+ if (!key)
51
+ return "none";
52
+ const idx = key.indexOf("_");
53
+ return idx > 0 && idx < 8 ? `${key.slice(0, idx + 1)}****` : "****";
54
+ }
@@ -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,23 @@
1
+ /** Request-scoped attribution on AsyncLocalStorage: never leaks between concurrent requests. */
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ const storage = new AsyncLocalStorage();
4
+ /** Inner non-undefined values override outer ones; metadata objects merge. */
5
+ export function mergeAttribution(outer, inner) {
6
+ const merged = { ...outer };
7
+ for (const [key, value] of Object.entries(inner)) {
8
+ if (key === "metadata" || value === undefined || value === null)
9
+ continue;
10
+ merged[key] = String(value);
11
+ }
12
+ if (inner.metadata)
13
+ merged.metadata = { ...(outer.metadata ?? {}), ...inner.metadata };
14
+ return merged;
15
+ }
16
+ /** Run `fn` with attribution applied to every AI call made inside it (sync or async). */
17
+ export function withContext(attribution, fn) {
18
+ return storage.run(mergeAttribution(storage.getStore() ?? {}, attribution), fn);
19
+ }
20
+ /** The attribution active in the current async context (empty object if none). */
21
+ export function getContext() {
22
+ return storage.getStore() ?? {};
23
+ }
@@ -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";
@@ -0,0 +1,19 @@
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 { DEFAULTS, ENV_API_KEY, ENV_DISABLED, ENV_ENDPOINT, INGEST_PATH, MAX_EVENTS_PER_REQUEST, resolveConfig } from "./config.js";
12
+ export { getContext, withContext } from "./context.js";
13
+ export { HttpTransport } from "./transport.js";
14
+ export { anthropicUsage, geminiUsage, openaiChatUsage, openaiResponsesUsage } from "./usage.js";
15
+ export { SDK_NAME, SDK_VERSION } from "./version.js";
16
+ export { providerFromModel, spendbookMiddleware, vercelUsage } from "./vercel.js";
17
+ export { detectAnthropicProvider, wrapAnthropic } from "./wrappers/anthropic.js";
18
+ export { detectGoogleProvider, wrapGoogleGenAI } from "./wrappers/google.js";
19
+ export { detectOpenAIProvider, wrapOpenAI } from "./wrappers/openai.js";