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,61 @@
1
+ /**
2
+ * Non-blocking batching transport.
3
+ *
4
+ * - `enqueue` is O(1), never throws and never awaits; when the queue is full the event is dropped
5
+ * and counted in `stats.dropped`.
6
+ * - A batch is sent when `maxBatchSize` events are queued, or `flushIntervalMs` after the first
7
+ * event of a batch arrived (the timer is unref'd so it never keeps the process alive).
8
+ * - 429 / 5xx / network errors are retried with exponential backoff and jitter (`Retry-After`
9
+ * honoured) until `maxRetryDurationMs` is used up. Other 4xx responses are not retried.
10
+ * - Retries resend the same body, so each event keeps its `event_id` and the server deduplicates.
11
+ */
12
+ import { type ResolvedConfig } from "./config.js";
13
+ import type { IngestEvent } from "./types.js";
14
+ export interface TransportStats {
15
+ enqueued: number;
16
+ /** Events dropped because the queue was full or the transport was shut down. */
17
+ dropped: number;
18
+ /** Events in batches the server answered with 2xx. */
19
+ sent: number;
20
+ accepted: number;
21
+ duplicates: number;
22
+ rejected: number;
23
+ /** Events abandoned after a non-retryable error or when the retry budget ran out. */
24
+ failed: number;
25
+ requests: number;
26
+ retries: number;
27
+ }
28
+ export interface Transport {
29
+ /** Queue an event. Returns false when it was dropped. */
30
+ enqueue(event: IngestEvent): boolean;
31
+ /** Send everything queued. Resolves true when the queue drained within `timeoutMs`. */
32
+ flush(timeoutMs?: number): Promise<boolean>;
33
+ /** Flush, then refuse further events. */
34
+ shutdown(timeoutMs?: number): Promise<boolean>;
35
+ readonly stats: Readonly<TransportStats>;
36
+ readonly pending: number;
37
+ }
38
+ export declare function parseRetryAfter(value: string | null | undefined, now?: number): number | undefined;
39
+ export declare class HttpTransport implements Transport {
40
+ private readonly config;
41
+ readonly stats: TransportStats;
42
+ private readonly url;
43
+ private queue;
44
+ private inflight;
45
+ private draining;
46
+ private timer;
47
+ private closed;
48
+ private abort;
49
+ private authWarned;
50
+ constructor(config: ResolvedConfig);
51
+ get pending(): number;
52
+ enqueue(event: IngestEvent): boolean;
53
+ flush(timeoutMs?: number): Promise<boolean>;
54
+ shutdown(timeoutMs?: number): Promise<boolean>;
55
+ private clearTimer;
56
+ private startDrain;
57
+ private drain;
58
+ private sendWithRetry;
59
+ private sleep;
60
+ private post;
61
+ }
@@ -0,0 +1,226 @@
1
+ /**
2
+ * Non-blocking batching transport.
3
+ *
4
+ * - `enqueue` is O(1), never throws and never awaits; when the queue is full the event is dropped
5
+ * and counted in `stats.dropped`.
6
+ * - A batch is sent when `maxBatchSize` events are queued, or `flushIntervalMs` after the first
7
+ * event of a batch arrived (the timer is unref'd so it never keeps the process alive).
8
+ * - 429 / 5xx / network errors are retried with exponential backoff and jitter (`Retry-After`
9
+ * honoured) until `maxRetryDurationMs` is used up. Other 4xx responses are not retried.
10
+ * - Retries resend the same body, so each event keeps its `event_id` and the server deduplicates.
11
+ */
12
+ import { INGEST_PATH } from "./config.js";
13
+ class Retryable extends Error {
14
+ retryAfterMs;
15
+ constructor(message, retryAfterMs) {
16
+ super(message);
17
+ this.retryAfterMs = retryAfterMs;
18
+ }
19
+ }
20
+ export function parseRetryAfter(value, now = Date.now()) {
21
+ if (!value)
22
+ return undefined;
23
+ const seconds = Number(value);
24
+ if (Number.isFinite(seconds))
25
+ return Math.max(0, seconds * 1000);
26
+ const date = Date.parse(value);
27
+ return Number.isNaN(date) ? undefined : Math.max(0, date - now);
28
+ }
29
+ export class HttpTransport {
30
+ config;
31
+ stats = {
32
+ enqueued: 0,
33
+ dropped: 0,
34
+ sent: 0,
35
+ accepted: 0,
36
+ duplicates: 0,
37
+ rejected: 0,
38
+ failed: 0,
39
+ requests: 0,
40
+ retries: 0,
41
+ };
42
+ url;
43
+ queue = [];
44
+ inflight = 0;
45
+ draining = null;
46
+ timer = null;
47
+ closed = false;
48
+ abort = new AbortController();
49
+ authWarned = false;
50
+ constructor(config) {
51
+ this.config = config;
52
+ this.url = `${config.endpoint}${INGEST_PATH}`;
53
+ }
54
+ get pending() {
55
+ return this.queue.length + this.inflight;
56
+ }
57
+ enqueue(event) {
58
+ try {
59
+ if (this.closed || this.queue.length >= this.config.maxQueueSize) {
60
+ this.stats.dropped += 1;
61
+ return false;
62
+ }
63
+ this.queue.push(event);
64
+ this.stats.enqueued += 1;
65
+ if (this.queue.length >= this.config.maxBatchSize) {
66
+ this.clearTimer();
67
+ this.startDrain();
68
+ }
69
+ else if (!this.timer && !this.draining) {
70
+ this.timer = setTimeout(() => {
71
+ this.timer = null;
72
+ this.startDrain();
73
+ }, this.config.flushIntervalMs);
74
+ this.timer.unref?.();
75
+ }
76
+ return true;
77
+ }
78
+ catch (err) {
79
+ this.config.logger.debug("spendbook: enqueue failed", err);
80
+ return false;
81
+ }
82
+ }
83
+ async flush(timeoutMs = 5_000) {
84
+ this.clearTimer();
85
+ const done = (async () => {
86
+ while (this.queue.length > 0 || this.draining) {
87
+ await this.startDrain();
88
+ }
89
+ })().catch(() => undefined);
90
+ let timeout;
91
+ const timedOut = new Promise((resolve) => {
92
+ timeout = setTimeout(() => resolve("timeout"), timeoutMs);
93
+ });
94
+ const result = await Promise.race([done.then(() => "done"), timedOut]);
95
+ clearTimeout(timeout);
96
+ return result === "done" && this.pending === 0;
97
+ }
98
+ async shutdown(timeoutMs = 5_000) {
99
+ const ok = await this.flush(timeoutMs);
100
+ this.closed = true;
101
+ if (!ok) {
102
+ this.abort.abort();
103
+ this.stats.dropped += this.queue.length;
104
+ this.queue = [];
105
+ }
106
+ return ok;
107
+ }
108
+ clearTimer() {
109
+ if (this.timer) {
110
+ clearTimeout(this.timer);
111
+ this.timer = null;
112
+ }
113
+ }
114
+ startDrain() {
115
+ if (!this.draining) {
116
+ this.draining = this.drain()
117
+ .catch((err) => this.config.logger.debug("spendbook: drain failed", err))
118
+ .finally(() => {
119
+ this.draining = null;
120
+ if (this.queue.length > 0 && !this.timer && !this.closed) {
121
+ this.timer = setTimeout(() => {
122
+ this.timer = null;
123
+ this.startDrain();
124
+ }, this.config.flushIntervalMs);
125
+ this.timer.unref?.();
126
+ }
127
+ });
128
+ }
129
+ return this.draining;
130
+ }
131
+ async drain() {
132
+ while (this.queue.length > 0) {
133
+ const batch = this.queue.splice(0, this.config.maxBatchSize);
134
+ this.inflight = batch.length;
135
+ try {
136
+ await this.sendWithRetry(batch);
137
+ }
138
+ finally {
139
+ this.inflight = 0;
140
+ }
141
+ }
142
+ }
143
+ async sendWithRetry(batch) {
144
+ const body = JSON.stringify({ events: batch });
145
+ const started = Date.now();
146
+ for (let attempt = 0;; attempt += 1) {
147
+ try {
148
+ await this.post(body, batch.length);
149
+ return;
150
+ }
151
+ catch (err) {
152
+ const backoff = Math.min(this.config.retryCapMs, this.config.retryBaseMs * 2 ** attempt);
153
+ const jittered = backoff / 2 + Math.random() * (backoff / 2);
154
+ const delay = err instanceof Retryable && err.retryAfterMs !== undefined ? err.retryAfterMs : jittered;
155
+ const elapsed = Date.now() - started;
156
+ if (!(err instanceof Retryable) || this.abort.signal.aborted || elapsed + delay > this.config.maxRetryDurationMs) {
157
+ this.stats.failed += batch.length;
158
+ this.config.logger.debug(`spendbook: dropping batch of ${batch.length} events`, err);
159
+ return;
160
+ }
161
+ this.stats.retries += 1;
162
+ await this.sleep(delay);
163
+ }
164
+ }
165
+ }
166
+ sleep(ms) {
167
+ return new Promise((resolve) => {
168
+ const t = setTimeout(resolve, ms);
169
+ this.abort.signal.addEventListener("abort", () => {
170
+ clearTimeout(t);
171
+ resolve();
172
+ }, { once: true });
173
+ });
174
+ }
175
+ async post(body, n) {
176
+ const fetchImpl = this.config.fetch;
177
+ if (!fetchImpl)
178
+ throw new Error("fetch unavailable");
179
+ const controller = new AbortController();
180
+ const onAbort = () => controller.abort();
181
+ this.abort.signal.addEventListener("abort", onAbort, { once: true });
182
+ const timeout = setTimeout(() => controller.abort(), this.config.requestTimeoutMs);
183
+ timeout.unref?.();
184
+ this.stats.requests += 1;
185
+ let res;
186
+ try {
187
+ res = await fetchImpl(this.url, {
188
+ method: "POST",
189
+ headers: {
190
+ "Content-Type": "application/json",
191
+ Authorization: `Bearer ${this.config.apiKey}`,
192
+ },
193
+ body,
194
+ signal: controller.signal,
195
+ });
196
+ }
197
+ catch (err) {
198
+ throw new Retryable(`network error: ${String(err)}`);
199
+ }
200
+ finally {
201
+ clearTimeout(timeout);
202
+ this.abort.signal.removeEventListener("abort", onAbort);
203
+ }
204
+ if (res.status === 429 || res.status >= 500) {
205
+ throw new Retryable(`HTTP ${res.status}`, parseRetryAfter(res.headers.get("Retry-After")));
206
+ }
207
+ if (res.status >= 200 && res.status < 300) {
208
+ this.stats.sent += n;
209
+ try {
210
+ const payload = JSON.parse(await res.text());
211
+ this.stats.accepted += typeof payload.accepted === "number" ? payload.accepted : 0;
212
+ this.stats.duplicates += typeof payload.duplicates === "number" ? payload.duplicates : 0;
213
+ this.stats.rejected += Array.isArray(payload.rejected) ? payload.rejected.length : 0;
214
+ }
215
+ catch {
216
+ // Body is informational only.
217
+ }
218
+ return;
219
+ }
220
+ if ((res.status === 401 || res.status === 403) && !this.authWarned) {
221
+ this.authWarned = true;
222
+ this.config.logger.warn(`spendbook: ingestion API returned ${res.status} (check SPENDBOOK_API_KEY)`);
223
+ }
224
+ throw new Error(`HTTP ${res.status}`);
225
+ }
226
+ }
@@ -0,0 +1,51 @@
1
+ /** Wire format of one event, matching the API's `IngestEvent` schema. */
2
+ export type MetaValue = string | number | boolean;
3
+ export type EventStatus = "success" | "error" | "cancelled";
4
+ export interface IngestEvent {
5
+ event_id: string;
6
+ occurred_at: string;
7
+ completed_at?: string;
8
+ provider: string;
9
+ model?: string;
10
+ request_id?: string;
11
+ /** UNCACHED input tokens. */
12
+ input_tokens: number;
13
+ output_tokens: number;
14
+ cache_read_tokens: number;
15
+ cache_write_tokens: number;
16
+ /** Subset of cache_write_tokens written with a 1 hour TTL. */
17
+ cache_write_1h_tokens: number;
18
+ other_tokens?: Record<string, number>;
19
+ latency_ms?: number;
20
+ status: EventStatus;
21
+ error_type?: string;
22
+ customer_id?: string;
23
+ end_user_id?: string;
24
+ feature?: string;
25
+ category?: string;
26
+ workload_type?: string;
27
+ project_id?: string;
28
+ organization_ref?: string;
29
+ service_tier?: string;
30
+ trace_id?: string;
31
+ session_id?: string;
32
+ run_id?: string;
33
+ environment?: string;
34
+ source_reported_cost_micros?: number;
35
+ streamed?: boolean;
36
+ metadata?: Record<string, MetaValue>;
37
+ sdk: {
38
+ name: string;
39
+ version: string;
40
+ };
41
+ }
42
+ /** Token usage normalised to the ingest contract. */
43
+ export interface Usage {
44
+ inputTokens: number;
45
+ outputTokens: number;
46
+ cacheReadTokens: number;
47
+ cacheWriteTokens: number;
48
+ cacheWrite1hTokens: number;
49
+ otherTokens: Record<string, number>;
50
+ }
51
+ export declare function emptyUsage(): Usage;
@@ -0,0 +1,4 @@
1
+ /** Wire format of one event, matching the API's `IngestEvent` schema. */
2
+ export function emptyUsage() {
3
+ return { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, cacheWrite1hTokens: 0, otherTokens: {} };
4
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Provider usage objects -> ingest token fields (same mapping as the Python SDK).
3
+ *
4
+ * - OpenAI reports prompt/input tokens INCLUDING cached tokens: input = prompt - cached.
5
+ * - Anthropic `input_tokens` are already uncached; cache writes come from
6
+ * `cache_creation_input_tokens` (1 hour TTL subset from `cache_creation.ephemeral_1h_input_tokens`).
7
+ * - Gemini `promptTokenCount` INCLUDES cached tokens: input = prompt - cached + toolUsePrompt;
8
+ * thinking tokens are billed as output: output = candidates + thoughts.
9
+ */
10
+ import { type Usage } from "./types.js";
11
+ export declare function n(value: unknown): number;
12
+ export declare function openaiChatUsage(usage: unknown): Usage;
13
+ export declare function openaiResponsesUsage(usage: unknown): Usage;
14
+ export declare function anthropicUsage(usage: unknown): Usage;
15
+ /** Accepts the `@google/genai` camelCase `usageMetadata` (snake_case also read). */
16
+ export declare function geminiUsage(metadata: unknown): Usage;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Provider usage objects -> ingest token fields (same mapping as the Python SDK).
3
+ *
4
+ * - OpenAI reports prompt/input tokens INCLUDING cached tokens: input = prompt - cached.
5
+ * - Anthropic `input_tokens` are already uncached; cache writes come from
6
+ * `cache_creation_input_tokens` (1 hour TTL subset from `cache_creation.ephemeral_1h_input_tokens`).
7
+ * - Gemini `promptTokenCount` INCLUDES cached tokens: input = prompt - cached + toolUsePrompt;
8
+ * thinking tokens are billed as output: output = candidates + thoughts.
9
+ */
10
+ import { emptyUsage } from "./types.js";
11
+ export function n(value) {
12
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
13
+ }
14
+ function obj(value) {
15
+ return value && typeof value === "object" ? value : undefined;
16
+ }
17
+ function put(out, key, value) {
18
+ const v = n(value);
19
+ if (v)
20
+ out.otherTokens[key] = v;
21
+ }
22
+ export function openaiChatUsage(usage) {
23
+ const out = emptyUsage();
24
+ const u = obj(usage);
25
+ if (!u)
26
+ return out;
27
+ const prompt = n(u.prompt_tokens);
28
+ const pd = obj(u.prompt_tokens_details);
29
+ const cached = Math.min(n(pd?.cached_tokens), prompt);
30
+ out.inputTokens = prompt - cached;
31
+ out.cacheReadTokens = cached;
32
+ out.outputTokens = n(u.completion_tokens);
33
+ if (pd) {
34
+ put(out, "input_audio_tokens", pd.audio_tokens);
35
+ put(out, "input_image_tokens", pd.image_tokens);
36
+ put(out, "cache_write_tokens", pd.cache_write_tokens);
37
+ }
38
+ const cd = obj(u.completion_tokens_details);
39
+ if (cd) {
40
+ put(out, "reasoning_tokens", cd.reasoning_tokens);
41
+ put(out, "output_audio_tokens", cd.audio_tokens);
42
+ put(out, "accepted_prediction_tokens", cd.accepted_prediction_tokens);
43
+ put(out, "rejected_prediction_tokens", cd.rejected_prediction_tokens);
44
+ }
45
+ return out;
46
+ }
47
+ export function openaiResponsesUsage(usage) {
48
+ const out = emptyUsage();
49
+ const u = obj(usage);
50
+ if (!u)
51
+ return out;
52
+ const total = n(u.input_tokens);
53
+ const id = obj(u.input_tokens_details);
54
+ const cached = Math.min(n(id?.cached_tokens), total);
55
+ out.inputTokens = total - cached;
56
+ out.cacheReadTokens = cached;
57
+ out.outputTokens = n(u.output_tokens);
58
+ if (id)
59
+ put(out, "cache_write_tokens", id.cache_write_tokens);
60
+ const od = obj(u.output_tokens_details);
61
+ if (od)
62
+ put(out, "reasoning_tokens", od.reasoning_tokens);
63
+ return out;
64
+ }
65
+ export function anthropicUsage(usage) {
66
+ const out = emptyUsage();
67
+ const u = obj(usage);
68
+ if (!u)
69
+ return out;
70
+ out.inputTokens = n(u.input_tokens);
71
+ out.outputTokens = n(u.output_tokens);
72
+ out.cacheReadTokens = n(u.cache_read_input_tokens);
73
+ out.cacheWriteTokens = n(u.cache_creation_input_tokens);
74
+ const breakdown = obj(u.cache_creation);
75
+ if (breakdown) {
76
+ const w1h = n(breakdown.ephemeral_1h_input_tokens);
77
+ const w5m = n(breakdown.ephemeral_5m_input_tokens);
78
+ out.cacheWrite1hTokens = w1h;
79
+ out.cacheWriteTokens = Math.max(out.cacheWriteTokens, w1h + w5m);
80
+ }
81
+ const details = obj(u.output_tokens_details);
82
+ if (details)
83
+ put(out, "thinking_tokens", details.thinking_tokens);
84
+ return out;
85
+ }
86
+ /** Accepts the `@google/genai` camelCase `usageMetadata` (snake_case also read). */
87
+ export function geminiUsage(metadata) {
88
+ const out = emptyUsage();
89
+ const m = obj(metadata);
90
+ if (!m)
91
+ return out;
92
+ const pick = (camel, snake) => n(m[camel] ?? m[snake]);
93
+ const prompt = pick("promptTokenCount", "prompt_token_count");
94
+ const cached = Math.min(pick("cachedContentTokenCount", "cached_content_token_count"), prompt);
95
+ const toolUse = pick("toolUsePromptTokenCount", "tool_use_prompt_token_count");
96
+ const thoughts = pick("thoughtsTokenCount", "thoughts_token_count");
97
+ out.inputTokens = prompt - cached + toolUse;
98
+ out.cacheReadTokens = cached;
99
+ out.outputTokens = pick("candidatesTokenCount", "candidates_token_count") + thoughts;
100
+ put(out, "thinking_tokens", thoughts);
101
+ put(out, "tool_use_prompt_tokens", toolUse);
102
+ return out;
103
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Vercel AI SDK language model middleware: `wrapLanguageModel({ model, middleware: spendbookMiddleware() })`.
3
+ *
4
+ * Reads `usage` from `doGenerate()` results and from the stream's `finish` part. Two usage shapes are
5
+ * read:
6
+ * - structured (AI SDK 6): `inputTokens: { noCache, cacheRead, cacheWrite }`, `outputTokens: { total }`
7
+ * - flat (AI SDK 5): `inputTokens`, `outputTokens`, `cachedInputTokens`, `reasoningTokens`. Here
8
+ * `inputTokens` includes cached tokens for most providers but not for Anthropic, so cached tokens
9
+ * are subtracted except when the provider is Anthropic.
10
+ */
11
+ import { type Usage } from "./types.js";
12
+ import { type WrapOptions } from "./wrappers/span.js";
13
+ type Any = Record<string, any>;
14
+ /** Map an AI SDK provider id (`openai.chat`, `google.vertex.chat`, `amazon-bedrock`) to our provider name. */
15
+ export declare function providerFromModel(model: unknown): string;
16
+ export declare function vercelUsage(usage: unknown, provider: string): Usage;
17
+ export interface SpendbookMiddlewareOptions extends WrapOptions {
18
+ }
19
+ interface MiddlewareArgs {
20
+ doGenerate: () => Promise<Any>;
21
+ doStream: () => Promise<Any>;
22
+ params: Any;
23
+ model: Any;
24
+ }
25
+ export interface SpendbookLanguageModelMiddleware {
26
+ wrapGenerate(args: Pick<MiddlewareArgs, "doGenerate" | "params" | "model">): Promise<Any>;
27
+ wrapStream(args: Pick<MiddlewareArgs, "doStream" | "params" | "model">): Promise<Any>;
28
+ }
29
+ export declare function spendbookMiddleware(opts?: SpendbookMiddlewareOptions): SpendbookLanguageModelMiddleware;
30
+ export {};
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Vercel AI SDK language model middleware: `wrapLanguageModel({ model, middleware: spendbookMiddleware() })`.
3
+ *
4
+ * Reads `usage` from `doGenerate()` results and from the stream's `finish` part. Two usage shapes are
5
+ * read:
6
+ * - structured (AI SDK 6): `inputTokens: { noCache, cacheRead, cacheWrite }`, `outputTokens: { total }`
7
+ * - flat (AI SDK 5): `inputTokens`, `outputTokens`, `cachedInputTokens`, `reasoningTokens`. Here
8
+ * `inputTokens` includes cached tokens for most providers but not for Anthropic, so cached tokens
9
+ * are subtracted except when the provider is Anthropic.
10
+ */
11
+ import { emptyUsage } from "./types.js";
12
+ import { n } from "./usage.js";
13
+ import { startSpan, str } from "./wrappers/span.js";
14
+ /** Map an AI SDK provider id (`openai.chat`, `google.vertex.chat`, `amazon-bedrock`) to our provider name. */
15
+ export function providerFromModel(model) {
16
+ const id = String(model?.provider ?? "unknown").toLowerCase();
17
+ if (id.includes("bedrock"))
18
+ return "bedrock";
19
+ if (id.includes("vertex"))
20
+ return "vertex";
21
+ if (id.startsWith("azure"))
22
+ return "azure_openai";
23
+ const head = id.split(".")[0].replace(/[^a-z0-9_.-]/g, "-");
24
+ return head || "unknown";
25
+ }
26
+ export function vercelUsage(usage, provider) {
27
+ const out = emptyUsage();
28
+ const u = usage;
29
+ if (!u)
30
+ return out;
31
+ if (u.inputTokens && typeof u.inputTokens === "object") {
32
+ const input = u.inputTokens;
33
+ const output = (u.outputTokens ?? {});
34
+ out.cacheReadTokens = n(input.cacheRead);
35
+ out.cacheWriteTokens = n(input.cacheWrite);
36
+ out.inputTokens = input.noCache != null ? n(input.noCache) : Math.max(0, n(input.total) - out.cacheReadTokens - out.cacheWriteTokens);
37
+ out.outputTokens = n(output.total);
38
+ if (n(output.reasoning))
39
+ out.otherTokens.reasoning_tokens = n(output.reasoning);
40
+ return out;
41
+ }
42
+ const cached = n(u.cachedInputTokens);
43
+ const input = n(u.inputTokens ?? u.promptTokens);
44
+ out.cacheReadTokens = cached;
45
+ out.inputTokens = provider === "anthropic" ? input : Math.max(0, input - cached);
46
+ out.outputTokens = n(u.outputTokens ?? u.completionTokens);
47
+ if (n(u.reasoningTokens))
48
+ out.otherTokens.reasoning_tokens = n(u.reasoningTokens);
49
+ return out;
50
+ }
51
+ function finish(span, usage, provider, modelId) {
52
+ span.finish({
53
+ usage: vercelUsage(usage, provider),
54
+ model: str(modelId),
55
+ metadata: usage ? undefined : { usage_missing: true },
56
+ });
57
+ }
58
+ export function spendbookMiddleware(opts = {}) {
59
+ return {
60
+ async wrapGenerate({ doGenerate, model }) {
61
+ const provider = opts.provider ?? providerFromModel(model);
62
+ const span = startSpan(opts, provider, { model: model?.modelId }, false);
63
+ if (!span)
64
+ return doGenerate();
65
+ let result;
66
+ try {
67
+ result = await doGenerate();
68
+ }
69
+ catch (err) {
70
+ span.fail(err);
71
+ throw err;
72
+ }
73
+ try {
74
+ finish(span, result?.usage, provider, result?.response?.modelId ?? model?.modelId);
75
+ }
76
+ catch {
77
+ // never surface telemetry errors
78
+ }
79
+ return result;
80
+ },
81
+ async wrapStream({ doStream, model }) {
82
+ const provider = opts.provider ?? providerFromModel(model);
83
+ const span = startSpan(opts, provider, { model: model?.modelId }, true);
84
+ if (!span)
85
+ return doStream();
86
+ let result;
87
+ try {
88
+ result = await doStream();
89
+ }
90
+ catch (err) {
91
+ span.fail(err);
92
+ throw err;
93
+ }
94
+ let modelId = model?.modelId;
95
+ let usage;
96
+ let errored = false;
97
+ const transform = new TransformStream({
98
+ transform(part, controller) {
99
+ try {
100
+ if (part?.type === "response-metadata" && part.modelId)
101
+ modelId = part.modelId;
102
+ if (part?.type === "finish")
103
+ usage = part.usage;
104
+ if (part?.type === "error")
105
+ errored = true;
106
+ }
107
+ catch {
108
+ // ignore
109
+ }
110
+ controller.enqueue(part);
111
+ },
112
+ flush() {
113
+ if (errored && !usage)
114
+ span.finish({ status: "error", errorType: "StreamError", model: str(modelId) });
115
+ else
116
+ finish(span, usage, provider, modelId);
117
+ },
118
+ cancel() {
119
+ span.finish({ status: "cancelled", model: str(modelId) });
120
+ },
121
+ });
122
+ return { ...result, stream: result.stream.pipeThrough(transform) };
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,2 @@
1
+ export declare const SDK_NAME = "spendbook-node";
2
+ export declare const SDK_VERSION = "0.1.0";
@@ -0,0 +1,2 @@
1
+ export const SDK_NAME = "spendbook-node";
2
+ export const SDK_VERSION = "0.1.0";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Anthropic (`@anthropic-ai/sdk`): `messages.create`, streamed or not. `messages.stream()` calls
3
+ * `create({ stream: true })` on the wrapped resource, so it is recorded through the same path.
4
+ * Provider is `bedrock` for AnthropicBedrock, `vertex` for AnthropicVertex, else `anthropic`.
5
+ */
6
+ import { type WrapOptions } from "./span.js";
7
+ export declare function detectAnthropicProvider(client: unknown): string;
8
+ /** Return a proxy of an `Anthropic` / `AnthropicBedrock` / `AnthropicVertex` client whose calls are recorded. */
9
+ export declare function wrapAnthropic<T extends object>(client: T, opts?: WrapOptions): T;