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.
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/dist/cjs/client.d.ts +48 -0
- package/dist/cjs/client.js +197 -0
- package/dist/cjs/config.d.ts +80 -0
- package/dist/cjs/config.js +59 -0
- package/dist/cjs/context.d.ts +22 -0
- package/dist/cjs/context.js +28 -0
- package/dist/cjs/index.d.ts +26 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/transport.d.ts +61 -0
- package/dist/cjs/transport.js +231 -0
- package/dist/cjs/types.d.ts +51 -0
- package/dist/cjs/types.js +7 -0
- package/dist/cjs/usage.d.ts +16 -0
- package/dist/cjs/usage.js +110 -0
- package/dist/cjs/vercel.d.ts +30 -0
- package/dist/cjs/vercel.js +130 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/wrappers/anthropic.d.ts +9 -0
- package/dist/cjs/wrappers/anthropic.js +106 -0
- package/dist/cjs/wrappers/google.d.ts +9 -0
- package/dist/cjs/wrappers/google.js +74 -0
- package/dist/cjs/wrappers/openai.d.ts +10 -0
- package/dist/cjs/wrappers/openai.js +136 -0
- package/dist/cjs/wrappers/span.d.ts +60 -0
- package/dist/cjs/wrappers/span.js +190 -0
- package/dist/esm/client.d.ts +48 -0
- package/dist/esm/client.js +187 -0
- package/dist/esm/config.d.ts +80 -0
- package/dist/esm/config.js +54 -0
- package/dist/esm/context.d.ts +22 -0
- package/dist/esm/context.js +23 -0
- package/dist/esm/index.d.ts +26 -0
- package/dist/esm/index.js +19 -0
- package/dist/esm/transport.d.ts +61 -0
- package/dist/esm/transport.js +226 -0
- package/dist/esm/types.d.ts +51 -0
- package/dist/esm/types.js +4 -0
- package/dist/esm/usage.d.ts +16 -0
- package/dist/esm/usage.js +103 -0
- package/dist/esm/vercel.d.ts +30 -0
- package/dist/esm/vercel.js +125 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/wrappers/anthropic.d.ts +9 -0
- package/dist/esm/wrappers/anthropic.js +102 -0
- package/dist/esm/wrappers/google.d.ts +9 -0
- package/dist/esm/wrappers/google.js +70 -0
- package/dist/esm/wrappers/openai.d.ts +10 -0
- package/dist/esm/wrappers/openai.js +132 -0
- package/dist/esm/wrappers/span.d.ts +60 -0
- package/dist/esm/wrappers/span.js +179 -0
- package/package.json +85 -4
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* AI Spendbook tracking SDK for Node.js.
|
|
4
|
+
*
|
|
5
|
+
* import { init, wrapOpenAI, withContext } from "aispendbook";
|
|
6
|
+
* init({ apiKey: process.env.SPENDBOOK_API_KEY, endpoint: process.env.SPENDBOOK_ENDPOINT });
|
|
7
|
+
* const openai = wrapOpenAI(new OpenAI());
|
|
8
|
+
* await withContext({ customerId: "company_456", feature: "diet_generation" }, () =>
|
|
9
|
+
* openai.chat.completions.create({ model: "gpt-4.1-mini", messages }));
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.wrapOpenAI = exports.detectOpenAIProvider = exports.wrapGoogleGenAI = exports.detectGoogleProvider = exports.wrapAnthropic = exports.detectAnthropicProvider = exports.vercelUsage = exports.spendbookMiddleware = exports.providerFromModel = exports.SDK_VERSION = exports.SDK_NAME = exports.openaiResponsesUsage = exports.openaiChatUsage = exports.geminiUsage = exports.anthropicUsage = exports.HttpTransport = exports.withContext = exports.getContext = exports.resolveConfig = exports.MAX_EVENTS_PER_REQUEST = exports.INGEST_PATH = exports.ENV_ENDPOINT = exports.ENV_DISABLED = exports.ENV_API_KEY = exports.DEFAULTS = exports.shutdown = exports.record = exports.init = exports.getClient = exports.flush = exports.SpendbookClient = void 0;
|
|
13
|
+
var client_js_1 = require("./client.js");
|
|
14
|
+
Object.defineProperty(exports, "SpendbookClient", { enumerable: true, get: function () { return client_js_1.SpendbookClient; } });
|
|
15
|
+
Object.defineProperty(exports, "flush", { enumerable: true, get: function () { return client_js_1.flush; } });
|
|
16
|
+
Object.defineProperty(exports, "getClient", { enumerable: true, get: function () { return client_js_1.getClient; } });
|
|
17
|
+
Object.defineProperty(exports, "init", { enumerable: true, get: function () { return client_js_1.init; } });
|
|
18
|
+
Object.defineProperty(exports, "record", { enumerable: true, get: function () { return client_js_1.record; } });
|
|
19
|
+
Object.defineProperty(exports, "shutdown", { enumerable: true, get: function () { return client_js_1.shutdown; } });
|
|
20
|
+
var config_js_1 = require("./config.js");
|
|
21
|
+
Object.defineProperty(exports, "DEFAULTS", { enumerable: true, get: function () { return config_js_1.DEFAULTS; } });
|
|
22
|
+
Object.defineProperty(exports, "ENV_API_KEY", { enumerable: true, get: function () { return config_js_1.ENV_API_KEY; } });
|
|
23
|
+
Object.defineProperty(exports, "ENV_DISABLED", { enumerable: true, get: function () { return config_js_1.ENV_DISABLED; } });
|
|
24
|
+
Object.defineProperty(exports, "ENV_ENDPOINT", { enumerable: true, get: function () { return config_js_1.ENV_ENDPOINT; } });
|
|
25
|
+
Object.defineProperty(exports, "INGEST_PATH", { enumerable: true, get: function () { return config_js_1.INGEST_PATH; } });
|
|
26
|
+
Object.defineProperty(exports, "MAX_EVENTS_PER_REQUEST", { enumerable: true, get: function () { return config_js_1.MAX_EVENTS_PER_REQUEST; } });
|
|
27
|
+
Object.defineProperty(exports, "resolveConfig", { enumerable: true, get: function () { return config_js_1.resolveConfig; } });
|
|
28
|
+
var context_js_1 = require("./context.js");
|
|
29
|
+
Object.defineProperty(exports, "getContext", { enumerable: true, get: function () { return context_js_1.getContext; } });
|
|
30
|
+
Object.defineProperty(exports, "withContext", { enumerable: true, get: function () { return context_js_1.withContext; } });
|
|
31
|
+
var transport_js_1 = require("./transport.js");
|
|
32
|
+
Object.defineProperty(exports, "HttpTransport", { enumerable: true, get: function () { return transport_js_1.HttpTransport; } });
|
|
33
|
+
var usage_js_1 = require("./usage.js");
|
|
34
|
+
Object.defineProperty(exports, "anthropicUsage", { enumerable: true, get: function () { return usage_js_1.anthropicUsage; } });
|
|
35
|
+
Object.defineProperty(exports, "geminiUsage", { enumerable: true, get: function () { return usage_js_1.geminiUsage; } });
|
|
36
|
+
Object.defineProperty(exports, "openaiChatUsage", { enumerable: true, get: function () { return usage_js_1.openaiChatUsage; } });
|
|
37
|
+
Object.defineProperty(exports, "openaiResponsesUsage", { enumerable: true, get: function () { return usage_js_1.openaiResponsesUsage; } });
|
|
38
|
+
var version_js_1 = require("./version.js");
|
|
39
|
+
Object.defineProperty(exports, "SDK_NAME", { enumerable: true, get: function () { return version_js_1.SDK_NAME; } });
|
|
40
|
+
Object.defineProperty(exports, "SDK_VERSION", { enumerable: true, get: function () { return version_js_1.SDK_VERSION; } });
|
|
41
|
+
var vercel_js_1 = require("./vercel.js");
|
|
42
|
+
Object.defineProperty(exports, "providerFromModel", { enumerable: true, get: function () { return vercel_js_1.providerFromModel; } });
|
|
43
|
+
Object.defineProperty(exports, "spendbookMiddleware", { enumerable: true, get: function () { return vercel_js_1.spendbookMiddleware; } });
|
|
44
|
+
Object.defineProperty(exports, "vercelUsage", { enumerable: true, get: function () { return vercel_js_1.vercelUsage; } });
|
|
45
|
+
var anthropic_js_1 = require("./wrappers/anthropic.js");
|
|
46
|
+
Object.defineProperty(exports, "detectAnthropicProvider", { enumerable: true, get: function () { return anthropic_js_1.detectAnthropicProvider; } });
|
|
47
|
+
Object.defineProperty(exports, "wrapAnthropic", { enumerable: true, get: function () { return anthropic_js_1.wrapAnthropic; } });
|
|
48
|
+
var google_js_1 = require("./wrappers/google.js");
|
|
49
|
+
Object.defineProperty(exports, "detectGoogleProvider", { enumerable: true, get: function () { return google_js_1.detectGoogleProvider; } });
|
|
50
|
+
Object.defineProperty(exports, "wrapGoogleGenAI", { enumerable: true, get: function () { return google_js_1.wrapGoogleGenAI; } });
|
|
51
|
+
var openai_js_1 = require("./wrappers/openai.js");
|
|
52
|
+
Object.defineProperty(exports, "detectOpenAIProvider", { enumerable: true, get: function () { return openai_js_1.detectOpenAIProvider; } });
|
|
53
|
+
Object.defineProperty(exports, "wrapOpenAI", { enumerable: true, get: function () { return openai_js_1.wrapOpenAI; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -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,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Non-blocking batching transport.
|
|
4
|
+
*
|
|
5
|
+
* - `enqueue` is O(1), never throws and never awaits; when the queue is full the event is dropped
|
|
6
|
+
* and counted in `stats.dropped`.
|
|
7
|
+
* - A batch is sent when `maxBatchSize` events are queued, or `flushIntervalMs` after the first
|
|
8
|
+
* event of a batch arrived (the timer is unref'd so it never keeps the process alive).
|
|
9
|
+
* - 429 / 5xx / network errors are retried with exponential backoff and jitter (`Retry-After`
|
|
10
|
+
* honoured) until `maxRetryDurationMs` is used up. Other 4xx responses are not retried.
|
|
11
|
+
* - Retries resend the same body, so each event keeps its `event_id` and the server deduplicates.
|
|
12
|
+
*/
|
|
13
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
14
|
+
exports.HttpTransport = void 0;
|
|
15
|
+
exports.parseRetryAfter = parseRetryAfter;
|
|
16
|
+
const config_js_1 = require("./config.js");
|
|
17
|
+
class Retryable extends Error {
|
|
18
|
+
retryAfterMs;
|
|
19
|
+
constructor(message, retryAfterMs) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.retryAfterMs = retryAfterMs;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function parseRetryAfter(value, now = Date.now()) {
|
|
25
|
+
if (!value)
|
|
26
|
+
return undefined;
|
|
27
|
+
const seconds = Number(value);
|
|
28
|
+
if (Number.isFinite(seconds))
|
|
29
|
+
return Math.max(0, seconds * 1000);
|
|
30
|
+
const date = Date.parse(value);
|
|
31
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - now);
|
|
32
|
+
}
|
|
33
|
+
class HttpTransport {
|
|
34
|
+
config;
|
|
35
|
+
stats = {
|
|
36
|
+
enqueued: 0,
|
|
37
|
+
dropped: 0,
|
|
38
|
+
sent: 0,
|
|
39
|
+
accepted: 0,
|
|
40
|
+
duplicates: 0,
|
|
41
|
+
rejected: 0,
|
|
42
|
+
failed: 0,
|
|
43
|
+
requests: 0,
|
|
44
|
+
retries: 0,
|
|
45
|
+
};
|
|
46
|
+
url;
|
|
47
|
+
queue = [];
|
|
48
|
+
inflight = 0;
|
|
49
|
+
draining = null;
|
|
50
|
+
timer = null;
|
|
51
|
+
closed = false;
|
|
52
|
+
abort = new AbortController();
|
|
53
|
+
authWarned = false;
|
|
54
|
+
constructor(config) {
|
|
55
|
+
this.config = config;
|
|
56
|
+
this.url = `${config.endpoint}${config_js_1.INGEST_PATH}`;
|
|
57
|
+
}
|
|
58
|
+
get pending() {
|
|
59
|
+
return this.queue.length + this.inflight;
|
|
60
|
+
}
|
|
61
|
+
enqueue(event) {
|
|
62
|
+
try {
|
|
63
|
+
if (this.closed || this.queue.length >= this.config.maxQueueSize) {
|
|
64
|
+
this.stats.dropped += 1;
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
this.queue.push(event);
|
|
68
|
+
this.stats.enqueued += 1;
|
|
69
|
+
if (this.queue.length >= this.config.maxBatchSize) {
|
|
70
|
+
this.clearTimer();
|
|
71
|
+
this.startDrain();
|
|
72
|
+
}
|
|
73
|
+
else if (!this.timer && !this.draining) {
|
|
74
|
+
this.timer = setTimeout(() => {
|
|
75
|
+
this.timer = null;
|
|
76
|
+
this.startDrain();
|
|
77
|
+
}, this.config.flushIntervalMs);
|
|
78
|
+
this.timer.unref?.();
|
|
79
|
+
}
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
catch (err) {
|
|
83
|
+
this.config.logger.debug("spendbook: enqueue failed", err);
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
async flush(timeoutMs = 5_000) {
|
|
88
|
+
this.clearTimer();
|
|
89
|
+
const done = (async () => {
|
|
90
|
+
while (this.queue.length > 0 || this.draining) {
|
|
91
|
+
await this.startDrain();
|
|
92
|
+
}
|
|
93
|
+
})().catch(() => undefined);
|
|
94
|
+
let timeout;
|
|
95
|
+
const timedOut = new Promise((resolve) => {
|
|
96
|
+
timeout = setTimeout(() => resolve("timeout"), timeoutMs);
|
|
97
|
+
});
|
|
98
|
+
const result = await Promise.race([done.then(() => "done"), timedOut]);
|
|
99
|
+
clearTimeout(timeout);
|
|
100
|
+
return result === "done" && this.pending === 0;
|
|
101
|
+
}
|
|
102
|
+
async shutdown(timeoutMs = 5_000) {
|
|
103
|
+
const ok = await this.flush(timeoutMs);
|
|
104
|
+
this.closed = true;
|
|
105
|
+
if (!ok) {
|
|
106
|
+
this.abort.abort();
|
|
107
|
+
this.stats.dropped += this.queue.length;
|
|
108
|
+
this.queue = [];
|
|
109
|
+
}
|
|
110
|
+
return ok;
|
|
111
|
+
}
|
|
112
|
+
clearTimer() {
|
|
113
|
+
if (this.timer) {
|
|
114
|
+
clearTimeout(this.timer);
|
|
115
|
+
this.timer = null;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
startDrain() {
|
|
119
|
+
if (!this.draining) {
|
|
120
|
+
this.draining = this.drain()
|
|
121
|
+
.catch((err) => this.config.logger.debug("spendbook: drain failed", err))
|
|
122
|
+
.finally(() => {
|
|
123
|
+
this.draining = null;
|
|
124
|
+
if (this.queue.length > 0 && !this.timer && !this.closed) {
|
|
125
|
+
this.timer = setTimeout(() => {
|
|
126
|
+
this.timer = null;
|
|
127
|
+
this.startDrain();
|
|
128
|
+
}, this.config.flushIntervalMs);
|
|
129
|
+
this.timer.unref?.();
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
return this.draining;
|
|
134
|
+
}
|
|
135
|
+
async drain() {
|
|
136
|
+
while (this.queue.length > 0) {
|
|
137
|
+
const batch = this.queue.splice(0, this.config.maxBatchSize);
|
|
138
|
+
this.inflight = batch.length;
|
|
139
|
+
try {
|
|
140
|
+
await this.sendWithRetry(batch);
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
this.inflight = 0;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async sendWithRetry(batch) {
|
|
148
|
+
const body = JSON.stringify({ events: batch });
|
|
149
|
+
const started = Date.now();
|
|
150
|
+
for (let attempt = 0;; attempt += 1) {
|
|
151
|
+
try {
|
|
152
|
+
await this.post(body, batch.length);
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
const backoff = Math.min(this.config.retryCapMs, this.config.retryBaseMs * 2 ** attempt);
|
|
157
|
+
const jittered = backoff / 2 + Math.random() * (backoff / 2);
|
|
158
|
+
const delay = err instanceof Retryable && err.retryAfterMs !== undefined ? err.retryAfterMs : jittered;
|
|
159
|
+
const elapsed = Date.now() - started;
|
|
160
|
+
if (!(err instanceof Retryable) || this.abort.signal.aborted || elapsed + delay > this.config.maxRetryDurationMs) {
|
|
161
|
+
this.stats.failed += batch.length;
|
|
162
|
+
this.config.logger.debug(`spendbook: dropping batch of ${batch.length} events`, err);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
this.stats.retries += 1;
|
|
166
|
+
await this.sleep(delay);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
sleep(ms) {
|
|
171
|
+
return new Promise((resolve) => {
|
|
172
|
+
const t = setTimeout(resolve, ms);
|
|
173
|
+
this.abort.signal.addEventListener("abort", () => {
|
|
174
|
+
clearTimeout(t);
|
|
175
|
+
resolve();
|
|
176
|
+
}, { once: true });
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
async post(body, n) {
|
|
180
|
+
const fetchImpl = this.config.fetch;
|
|
181
|
+
if (!fetchImpl)
|
|
182
|
+
throw new Error("fetch unavailable");
|
|
183
|
+
const controller = new AbortController();
|
|
184
|
+
const onAbort = () => controller.abort();
|
|
185
|
+
this.abort.signal.addEventListener("abort", onAbort, { once: true });
|
|
186
|
+
const timeout = setTimeout(() => controller.abort(), this.config.requestTimeoutMs);
|
|
187
|
+
timeout.unref?.();
|
|
188
|
+
this.stats.requests += 1;
|
|
189
|
+
let res;
|
|
190
|
+
try {
|
|
191
|
+
res = await fetchImpl(this.url, {
|
|
192
|
+
method: "POST",
|
|
193
|
+
headers: {
|
|
194
|
+
"Content-Type": "application/json",
|
|
195
|
+
Authorization: `Bearer ${this.config.apiKey}`,
|
|
196
|
+
},
|
|
197
|
+
body,
|
|
198
|
+
signal: controller.signal,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
catch (err) {
|
|
202
|
+
throw new Retryable(`network error: ${String(err)}`);
|
|
203
|
+
}
|
|
204
|
+
finally {
|
|
205
|
+
clearTimeout(timeout);
|
|
206
|
+
this.abort.signal.removeEventListener("abort", onAbort);
|
|
207
|
+
}
|
|
208
|
+
if (res.status === 429 || res.status >= 500) {
|
|
209
|
+
throw new Retryable(`HTTP ${res.status}`, parseRetryAfter(res.headers.get("Retry-After")));
|
|
210
|
+
}
|
|
211
|
+
if (res.status >= 200 && res.status < 300) {
|
|
212
|
+
this.stats.sent += n;
|
|
213
|
+
try {
|
|
214
|
+
const payload = JSON.parse(await res.text());
|
|
215
|
+
this.stats.accepted += typeof payload.accepted === "number" ? payload.accepted : 0;
|
|
216
|
+
this.stats.duplicates += typeof payload.duplicates === "number" ? payload.duplicates : 0;
|
|
217
|
+
this.stats.rejected += Array.isArray(payload.rejected) ? payload.rejected.length : 0;
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
// Body is informational only.
|
|
221
|
+
}
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
if ((res.status === 401 || res.status === 403) && !this.authWarned) {
|
|
225
|
+
this.authWarned = true;
|
|
226
|
+
this.config.logger.warn(`spendbook: ingestion API returned ${res.status} (check SPENDBOOK_API_KEY)`);
|
|
227
|
+
}
|
|
228
|
+
throw new Error(`HTTP ${res.status}`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
exports.HttpTransport = HttpTransport;
|
|
@@ -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,7 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** Wire format of one event, matching the API's `IngestEvent` schema. */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.emptyUsage = emptyUsage;
|
|
5
|
+
function emptyUsage() {
|
|
6
|
+
return { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, cacheWrite1hTokens: 0, otherTokens: {} };
|
|
7
|
+
}
|
|
@@ -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,110 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Provider usage objects -> ingest token fields (same mapping as the Python SDK).
|
|
4
|
+
*
|
|
5
|
+
* - OpenAI reports prompt/input tokens INCLUDING cached tokens: input = prompt - cached.
|
|
6
|
+
* - Anthropic `input_tokens` are already uncached; cache writes come from
|
|
7
|
+
* `cache_creation_input_tokens` (1 hour TTL subset from `cache_creation.ephemeral_1h_input_tokens`).
|
|
8
|
+
* - Gemini `promptTokenCount` INCLUDES cached tokens: input = prompt - cached + toolUsePrompt;
|
|
9
|
+
* thinking tokens are billed as output: output = candidates + thoughts.
|
|
10
|
+
*/
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.n = n;
|
|
13
|
+
exports.openaiChatUsage = openaiChatUsage;
|
|
14
|
+
exports.openaiResponsesUsage = openaiResponsesUsage;
|
|
15
|
+
exports.anthropicUsage = anthropicUsage;
|
|
16
|
+
exports.geminiUsage = geminiUsage;
|
|
17
|
+
const types_js_1 = require("./types.js");
|
|
18
|
+
function n(value) {
|
|
19
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
|
|
20
|
+
}
|
|
21
|
+
function obj(value) {
|
|
22
|
+
return value && typeof value === "object" ? value : undefined;
|
|
23
|
+
}
|
|
24
|
+
function put(out, key, value) {
|
|
25
|
+
const v = n(value);
|
|
26
|
+
if (v)
|
|
27
|
+
out.otherTokens[key] = v;
|
|
28
|
+
}
|
|
29
|
+
function openaiChatUsage(usage) {
|
|
30
|
+
const out = (0, types_js_1.emptyUsage)();
|
|
31
|
+
const u = obj(usage);
|
|
32
|
+
if (!u)
|
|
33
|
+
return out;
|
|
34
|
+
const prompt = n(u.prompt_tokens);
|
|
35
|
+
const pd = obj(u.prompt_tokens_details);
|
|
36
|
+
const cached = Math.min(n(pd?.cached_tokens), prompt);
|
|
37
|
+
out.inputTokens = prompt - cached;
|
|
38
|
+
out.cacheReadTokens = cached;
|
|
39
|
+
out.outputTokens = n(u.completion_tokens);
|
|
40
|
+
if (pd) {
|
|
41
|
+
put(out, "input_audio_tokens", pd.audio_tokens);
|
|
42
|
+
put(out, "input_image_tokens", pd.image_tokens);
|
|
43
|
+
put(out, "cache_write_tokens", pd.cache_write_tokens);
|
|
44
|
+
}
|
|
45
|
+
const cd = obj(u.completion_tokens_details);
|
|
46
|
+
if (cd) {
|
|
47
|
+
put(out, "reasoning_tokens", cd.reasoning_tokens);
|
|
48
|
+
put(out, "output_audio_tokens", cd.audio_tokens);
|
|
49
|
+
put(out, "accepted_prediction_tokens", cd.accepted_prediction_tokens);
|
|
50
|
+
put(out, "rejected_prediction_tokens", cd.rejected_prediction_tokens);
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
function openaiResponsesUsage(usage) {
|
|
55
|
+
const out = (0, types_js_1.emptyUsage)();
|
|
56
|
+
const u = obj(usage);
|
|
57
|
+
if (!u)
|
|
58
|
+
return out;
|
|
59
|
+
const total = n(u.input_tokens);
|
|
60
|
+
const id = obj(u.input_tokens_details);
|
|
61
|
+
const cached = Math.min(n(id?.cached_tokens), total);
|
|
62
|
+
out.inputTokens = total - cached;
|
|
63
|
+
out.cacheReadTokens = cached;
|
|
64
|
+
out.outputTokens = n(u.output_tokens);
|
|
65
|
+
if (id)
|
|
66
|
+
put(out, "cache_write_tokens", id.cache_write_tokens);
|
|
67
|
+
const od = obj(u.output_tokens_details);
|
|
68
|
+
if (od)
|
|
69
|
+
put(out, "reasoning_tokens", od.reasoning_tokens);
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
function anthropicUsage(usage) {
|
|
73
|
+
const out = (0, types_js_1.emptyUsage)();
|
|
74
|
+
const u = obj(usage);
|
|
75
|
+
if (!u)
|
|
76
|
+
return out;
|
|
77
|
+
out.inputTokens = n(u.input_tokens);
|
|
78
|
+
out.outputTokens = n(u.output_tokens);
|
|
79
|
+
out.cacheReadTokens = n(u.cache_read_input_tokens);
|
|
80
|
+
out.cacheWriteTokens = n(u.cache_creation_input_tokens);
|
|
81
|
+
const breakdown = obj(u.cache_creation);
|
|
82
|
+
if (breakdown) {
|
|
83
|
+
const w1h = n(breakdown.ephemeral_1h_input_tokens);
|
|
84
|
+
const w5m = n(breakdown.ephemeral_5m_input_tokens);
|
|
85
|
+
out.cacheWrite1hTokens = w1h;
|
|
86
|
+
out.cacheWriteTokens = Math.max(out.cacheWriteTokens, w1h + w5m);
|
|
87
|
+
}
|
|
88
|
+
const details = obj(u.output_tokens_details);
|
|
89
|
+
if (details)
|
|
90
|
+
put(out, "thinking_tokens", details.thinking_tokens);
|
|
91
|
+
return out;
|
|
92
|
+
}
|
|
93
|
+
/** Accepts the `@google/genai` camelCase `usageMetadata` (snake_case also read). */
|
|
94
|
+
function geminiUsage(metadata) {
|
|
95
|
+
const out = (0, types_js_1.emptyUsage)();
|
|
96
|
+
const m = obj(metadata);
|
|
97
|
+
if (!m)
|
|
98
|
+
return out;
|
|
99
|
+
const pick = (camel, snake) => n(m[camel] ?? m[snake]);
|
|
100
|
+
const prompt = pick("promptTokenCount", "prompt_token_count");
|
|
101
|
+
const cached = Math.min(pick("cachedContentTokenCount", "cached_content_token_count"), prompt);
|
|
102
|
+
const toolUse = pick("toolUsePromptTokenCount", "tool_use_prompt_token_count");
|
|
103
|
+
const thoughts = pick("thoughtsTokenCount", "thoughts_token_count");
|
|
104
|
+
out.inputTokens = prompt - cached + toolUse;
|
|
105
|
+
out.cacheReadTokens = cached;
|
|
106
|
+
out.outputTokens = pick("candidatesTokenCount", "candidates_token_count") + thoughts;
|
|
107
|
+
put(out, "thinking_tokens", thoughts);
|
|
108
|
+
put(out, "tool_use_prompt_tokens", toolUse);
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
@@ -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 {};
|