@tokenrein/sdk 0.0.0-stage → 0.1.2
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 +202 -0
- package/README.md +32 -2
- package/dist/clients.d.ts +57 -0
- package/dist/clients.js +357 -0
- package/dist/direct.d.ts +52 -0
- package/dist/direct.js +229 -0
- package/dist/env.d.ts +5 -0
- package/dist/env.js +17 -0
- package/dist/errors.d.ts +51 -0
- package/dist/errors.js +90 -0
- package/dist/guard.d.ts +16 -0
- package/dist/guard.js +38 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +4 -0
- package/dist/run.d.ts +52 -0
- package/dist/run.js +93 -0
- package/package.json +54 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,33 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tokenrein/sdk (TypeScript)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Budgets, run tracing and spend reports for AI agents, in one line around your existing OpenAI
|
|
4
|
+
or Anthropic client. By default (direct mode) the client keeps calling its provider and only
|
|
5
|
+
token usage goes to [Tokenrein](https://tokenrein.com); `mode="proxy"` sends calls through the Tokenrein
|
|
6
|
+
proxy instead. Errors: `BudgetExceeded`, `RunPaused`, `RunKilled`. Works with any
|
|
7
|
+
OpenAI-compatible provider (Gemini, Groq, Mistral, DeepSeek, OpenRouter, Ollama, ...).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @tokenrein/sdk openai # or @anthropic-ai/sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import OpenAI from 'openai';
|
|
15
|
+
import { guard, BudgetExceeded } from '@tokenrein/sdk';
|
|
16
|
+
|
|
17
|
+
const client = guard.openai(new OpenAI(), { agent: 'support-bot' }); // TOKENREIN_API_KEY, TOKENREIN_BASE_URL
|
|
18
|
+
await guard.run({ runId: 'ticket-4812', budgetUsd: 5 }, async () => {
|
|
19
|
+
await guard.run({ budgetUsd: 1 }, () => // sub-agent: parent set automatically
|
|
20
|
+
client.chat.completions.create({ model: 'gpt-4o-mini', messages: [{ role: 'user', content: 'hi' }] }),
|
|
21
|
+
);
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Node ≥ 20 (uses `AsyncLocalStorage`). See [the SDK guide](https://github.com/tokenrein/tokenrein/blob/main/sdk/README.md) for the full API.
|
|
26
|
+
|
|
27
|
+
## Develop
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install && npm run typecheck && npm test && npm run build
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
License: Apache-2.0.
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wrap OpenAI / Anthropic SDK clients for Tokenrein.
|
|
3
|
+
*
|
|
4
|
+
* Two modes:
|
|
5
|
+
* - **direct** (default): the client keeps calling its provider. Before each call it asks
|
|
6
|
+
* Tokenrein whether the run may continue; after each response it reports token usage in the
|
|
7
|
+
* background. Works with any provider the `openai` SDK reaches (Gemini, Groq, Mistral,
|
|
8
|
+
* DeepSeek, OpenRouter, Ollama, ...). See `direct.ts`.
|
|
9
|
+
* - **proxy**: the client calls the Tokenrein proxy, which checks every call before sending it.
|
|
10
|
+
*
|
|
11
|
+
* In proxy mode the guarded client is a `withOptions()` copy of the caller's client whose prototype is
|
|
12
|
+
* swapped for a subclass that:
|
|
13
|
+
* - adds the `x-tr-*` headers of the current run to every request it builds, and counts
|
|
14
|
+
* the call against any local `maxCalls` cap;
|
|
15
|
+
* - re-labels the proxy's 402/403 responses as Tokenrein errors.
|
|
16
|
+
* Later `withOptions()` copies construct the same subclass, so they stay guarded.
|
|
17
|
+
*/
|
|
18
|
+
export declare const DEFAULT_BASE_URL = "http://127.0.0.1:8787";
|
|
19
|
+
export interface GuardOptions {
|
|
20
|
+
/** Agent name sent as `x-tr-agent` (per-agent daily budget). */
|
|
21
|
+
agent?: string;
|
|
22
|
+
/** Person or service the agent works for, sent as `x-tr-user` (spend reports). */
|
|
23
|
+
user?: string;
|
|
24
|
+
/** Tokenrein virtual key; defaults to `process.env.TOKENREIN_API_KEY`. */
|
|
25
|
+
apiKey?: string;
|
|
26
|
+
/** Tokenrein URL; defaults to `process.env.TOKENREIN_BASE_URL` or `http://127.0.0.1:8787`. */
|
|
27
|
+
baseURL?: string;
|
|
28
|
+
/**
|
|
29
|
+
* `'direct'` (default, or `process.env.TOKENREIN_MODE`): the client keeps calling its provider;
|
|
30
|
+
* Tokenrein checks each call first and receives token usage afterwards, never prompts.
|
|
31
|
+
* `'proxy'`: calls go through the Tokenrein proxy, which checks every call before sending it.
|
|
32
|
+
*/
|
|
33
|
+
mode?: 'direct' | 'proxy';
|
|
34
|
+
/**
|
|
35
|
+
* Direct mode only. Ask Tokenrein before each call (default). `false` skips the round trip
|
|
36
|
+
* and only stops runs that previous usage reports showed are over an enforced limit.
|
|
37
|
+
*/
|
|
38
|
+
check?: boolean;
|
|
39
|
+
}
|
|
40
|
+
export declare function resolveBaseURL(baseURL?: string): string;
|
|
41
|
+
export declare function resolveApiKey(apiKey?: string): string;
|
|
42
|
+
export declare function wrap<T>(client: T, opts: GuardOptions, provider: 'openai' | 'anthropic'): T;
|
|
43
|
+
/**
|
|
44
|
+
* A hash of the model and the last message, so Tokenrein can spot a run repeating itself. Only
|
|
45
|
+
* the hash is sent.
|
|
46
|
+
*/
|
|
47
|
+
export declare function fingerprint(body: Record<string, any>): string | undefined;
|
|
48
|
+
interface DirectWrapOptions {
|
|
49
|
+
tokenreinURL: string;
|
|
50
|
+
apiKey: string;
|
|
51
|
+
agent: string | undefined;
|
|
52
|
+
user: string | undefined;
|
|
53
|
+
defaultProvider: string;
|
|
54
|
+
check: boolean;
|
|
55
|
+
}
|
|
56
|
+
export declare function wrapDirect<T>(client: T, o: DirectWrapOptions, kind: 'openai' | 'anthropic'): T;
|
|
57
|
+
export {};
|
package/dist/clients.js
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wrap OpenAI / Anthropic SDK clients for Tokenrein.
|
|
3
|
+
*
|
|
4
|
+
* Two modes:
|
|
5
|
+
* - **direct** (default): the client keeps calling its provider. Before each call it asks
|
|
6
|
+
* Tokenrein whether the run may continue; after each response it reports token usage in the
|
|
7
|
+
* background. Works with any provider the `openai` SDK reaches (Gemini, Groq, Mistral,
|
|
8
|
+
* DeepSeek, OpenRouter, Ollama, ...). See `direct.ts`.
|
|
9
|
+
* - **proxy**: the client calls the Tokenrein proxy, which checks every call before sending it.
|
|
10
|
+
*
|
|
11
|
+
* In proxy mode the guarded client is a `withOptions()` copy of the caller's client whose prototype is
|
|
12
|
+
* swapped for a subclass that:
|
|
13
|
+
* - adds the `x-tr-*` headers of the current run to every request it builds, and counts
|
|
14
|
+
* the call against any local `maxCalls` cap;
|
|
15
|
+
* - re-labels the proxy's 402/403 responses as Tokenrein errors.
|
|
16
|
+
* Later `withOptions()` copies construct the same subclass, so they stay guarded.
|
|
17
|
+
*/
|
|
18
|
+
import { createHash } from 'node:crypto';
|
|
19
|
+
import { envVar } from './env.js';
|
|
20
|
+
import { StreamUsage, providerFor, reporterFor, usageFrom, verdictError, } from './direct.js';
|
|
21
|
+
import { BUDGET_EXCEEDED, RUN_KILLED, RUN_PAUSED, relabel } from './errors.js';
|
|
22
|
+
import { currentRun, validateId, validateUser } from './run.js';
|
|
23
|
+
export const DEFAULT_BASE_URL = 'http://127.0.0.1:8787';
|
|
24
|
+
/** On a guarded class: the SDK class it extends (so re-wrapping does not stack guards). */
|
|
25
|
+
const UNGUARDED = Symbol('tokenrein.unguarded');
|
|
26
|
+
export function resolveBaseURL(baseURL) {
|
|
27
|
+
let url = (baseURL || envVar('BASE_URL') || DEFAULT_BASE_URL).replace(/\/+$/, '');
|
|
28
|
+
// Accept either the proxy root or its /v1 URL.
|
|
29
|
+
if (url.endsWith('/v1'))
|
|
30
|
+
url = url.slice(0, -'/v1'.length);
|
|
31
|
+
return url;
|
|
32
|
+
}
|
|
33
|
+
export function resolveApiKey(apiKey) {
|
|
34
|
+
const key = apiKey || envVar('API_KEY');
|
|
35
|
+
if (!key)
|
|
36
|
+
throw new TypeError('Tokenrein virtual key missing: pass apiKey or set TOKENREIN_API_KEY');
|
|
37
|
+
return key;
|
|
38
|
+
}
|
|
39
|
+
function hasHeader(h, name) {
|
|
40
|
+
if (typeof h.has === 'function')
|
|
41
|
+
return h.has(name);
|
|
42
|
+
return Object.keys(h).some((k) => k.toLowerCase() === name && h[k] != null);
|
|
43
|
+
}
|
|
44
|
+
function getHeader(h, name) {
|
|
45
|
+
if (!h)
|
|
46
|
+
return undefined;
|
|
47
|
+
if (typeof h.get === 'function')
|
|
48
|
+
return h.get(name) ?? undefined;
|
|
49
|
+
const k = Object.keys(h).find((k) => k.toLowerCase() === name);
|
|
50
|
+
return k ? (h[k] ?? undefined) : undefined;
|
|
51
|
+
}
|
|
52
|
+
function setHeader(h, name, value) {
|
|
53
|
+
if (typeof h.set === 'function')
|
|
54
|
+
h.set(name, value);
|
|
55
|
+
else
|
|
56
|
+
h[name] = value;
|
|
57
|
+
}
|
|
58
|
+
function deleteHeader(h, name) {
|
|
59
|
+
if (typeof h.delete === 'function') {
|
|
60
|
+
h.delete(name);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
for (const k of Object.keys(h))
|
|
64
|
+
if (k.toLowerCase() === name)
|
|
65
|
+
delete h[k];
|
|
66
|
+
}
|
|
67
|
+
function tlHeaders(agent, user) {
|
|
68
|
+
const run = currentRun();
|
|
69
|
+
const h = run ? run.headers() : {};
|
|
70
|
+
const name = agent ?? run?.agent;
|
|
71
|
+
if (name)
|
|
72
|
+
h['x-tr-agent'] = name;
|
|
73
|
+
const who = user ?? run?.user;
|
|
74
|
+
if (who)
|
|
75
|
+
h['x-tr-user'] = who;
|
|
76
|
+
return h;
|
|
77
|
+
}
|
|
78
|
+
function guardedClass(Base, agent, user, stripBearer) {
|
|
79
|
+
// Request options objects already counted. SDK retries reuse the options object; older
|
|
80
|
+
// SDKs (openai < 4.6x) do not pass `retryCount`, so this is how their retries are skipped.
|
|
81
|
+
const counted = new WeakSet();
|
|
82
|
+
const guardRequest = (built, options, opts) => {
|
|
83
|
+
const req = built.req;
|
|
84
|
+
req.headers ??= {};
|
|
85
|
+
for (const [name, value] of Object.entries(tlHeaders(agent, user))) {
|
|
86
|
+
// Headers the caller set explicitly (request headers / defaultHeaders) win.
|
|
87
|
+
if (!hasHeader(req.headers, name))
|
|
88
|
+
setHeader(req.headers, name, value);
|
|
89
|
+
}
|
|
90
|
+
if (stripBearer) {
|
|
91
|
+
// The proxy reads `Authorization: Bearer` before `x-api-key`; never forward a provider
|
|
92
|
+
// token (authToken, ANTHROPIC_AUTH_TOKEN, credential providers) in place of the Tokenrein key.
|
|
93
|
+
deleteHeader(req.headers, 'authorization');
|
|
94
|
+
}
|
|
95
|
+
const first = !opts.retryCount && !(typeof options === 'object' && options !== null && counted.has(options));
|
|
96
|
+
if (first) {
|
|
97
|
+
currentRun()?.recordCall();
|
|
98
|
+
if (typeof options === 'object' && options !== null)
|
|
99
|
+
counted.add(options);
|
|
100
|
+
}
|
|
101
|
+
return built;
|
|
102
|
+
};
|
|
103
|
+
return class Guarded extends Base {
|
|
104
|
+
static [UNGUARDED] = Base;
|
|
105
|
+
static get name() {
|
|
106
|
+
return Base.name;
|
|
107
|
+
}
|
|
108
|
+
// Newer SDKs build requests asynchronously, older ones (openai v4) synchronously.
|
|
109
|
+
buildRequest(options, opts = {}) {
|
|
110
|
+
const built = super.buildRequest(options, opts);
|
|
111
|
+
return built instanceof Promise
|
|
112
|
+
? built.then((b) => guardRequest(b, options, opts))
|
|
113
|
+
: guardRequest(built, options, opts);
|
|
114
|
+
}
|
|
115
|
+
makeStatusError(status, error, message, headers) {
|
|
116
|
+
const err = super.makeStatusError(status, error, message, headers);
|
|
117
|
+
// The proxy echoes the run id; fall back to the one this request carried.
|
|
118
|
+
const runId = getHeader(headers, 'x-tr-run-id') ?? currentRun()?.runId;
|
|
119
|
+
return relabel(err, status, error, runId);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
export function wrap(client, opts, provider) {
|
|
124
|
+
const c = client;
|
|
125
|
+
if (!c || typeof c.buildRequest !== 'function' || typeof c.makeStatusError !== 'function') {
|
|
126
|
+
throw new TypeError(`guard.${provider}() needs an ${provider === 'openai' ? 'OpenAI' : 'Anthropic'} client instance`);
|
|
127
|
+
}
|
|
128
|
+
if (opts.agent !== undefined)
|
|
129
|
+
validateId(opts.agent, 'agent');
|
|
130
|
+
if (opts.user !== undefined)
|
|
131
|
+
validateUser(opts.user);
|
|
132
|
+
const stripBearer = provider === 'anthropic';
|
|
133
|
+
const root = resolveBaseURL(opts.baseURL);
|
|
134
|
+
const overrides = {
|
|
135
|
+
apiKey: resolveApiKey(opts.apiKey),
|
|
136
|
+
baseURL: provider === 'openai' ? `${root}/v1` : root,
|
|
137
|
+
...(stripBearer ? { authToken: null } : {}),
|
|
138
|
+
};
|
|
139
|
+
const Base = c.constructor[UNGUARDED] ?? c.constructor;
|
|
140
|
+
const Guarded = guardedClass(Base, opts.agent, opts.user, stripBearer);
|
|
141
|
+
if (typeof c.withOptions !== 'function') {
|
|
142
|
+
return new Guarded({ ...c._options, ...overrides });
|
|
143
|
+
}
|
|
144
|
+
const copy = c.withOptions(overrides);
|
|
145
|
+
Object.setPrototypeOf(copy, Guarded.prototype);
|
|
146
|
+
return copy;
|
|
147
|
+
}
|
|
148
|
+
// --- Direct mode ---------------------------------------------------------------------------
|
|
149
|
+
/**
|
|
150
|
+
* A hash of the model and the last message, so Tokenrein can spot a run repeating itself. Only
|
|
151
|
+
* the hash is sent.
|
|
152
|
+
*/
|
|
153
|
+
export function fingerprint(body) {
|
|
154
|
+
const input = body.input;
|
|
155
|
+
const last = Array.isArray(body.messages) && body.messages.length ? body.messages.at(-1)
|
|
156
|
+
: Array.isArray(input) && input.length ? input.at(-1)
|
|
157
|
+
: typeof input === 'string' ? input : undefined;
|
|
158
|
+
if (last === undefined)
|
|
159
|
+
return undefined;
|
|
160
|
+
const h = createHash('sha256');
|
|
161
|
+
for (const part of [String(body.model ?? ''), JSON.stringify(last)])
|
|
162
|
+
h.update(part).update('\0');
|
|
163
|
+
return h.digest('hex').slice(0, 32);
|
|
164
|
+
}
|
|
165
|
+
const MAX_OUTPUT_FIELDS = ['max_tokens', 'max_completion_tokens', 'max_output_tokens'];
|
|
166
|
+
function who(cfg) {
|
|
167
|
+
const run = currentRun();
|
|
168
|
+
const out = { source: 'typescript-sdk' };
|
|
169
|
+
if (run) {
|
|
170
|
+
out.run_id = run.runId;
|
|
171
|
+
if (run.parent)
|
|
172
|
+
out.parent_run_id = run.parent.runId;
|
|
173
|
+
if (run.budgetUsd !== undefined)
|
|
174
|
+
out.run_budget_usd = run.budgetUsd;
|
|
175
|
+
}
|
|
176
|
+
const agent = cfg.agent ?? run?.agent;
|
|
177
|
+
const user = cfg.user ?? run?.user;
|
|
178
|
+
if (agent)
|
|
179
|
+
out.agent = agent;
|
|
180
|
+
if (user)
|
|
181
|
+
out.user = user;
|
|
182
|
+
return out;
|
|
183
|
+
}
|
|
184
|
+
function denyIfOver(cfg) {
|
|
185
|
+
const run = currentRun();
|
|
186
|
+
const agent = cfg.agent ?? run?.agent;
|
|
187
|
+
for (const label of cfg.reporter.over.keys()) {
|
|
188
|
+
const [kind, rest = ''] = label.split(/:(.*)/s);
|
|
189
|
+
const hit = (kind === 'run' && rest === run?.runId) ||
|
|
190
|
+
(kind === 'agent_daily' && agent !== undefined && rest.endsWith(`/${agent}`)) ||
|
|
191
|
+
kind === 'project_monthly' ||
|
|
192
|
+
kind === 'org_monthly';
|
|
193
|
+
if (hit)
|
|
194
|
+
throw verdictError({ allowed: false, reason: `Tokenrein: the ${label} budget is used up` }, run?.runId);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
function report(cfg, w, model, usage, started, stream) {
|
|
198
|
+
if (!usage)
|
|
199
|
+
return;
|
|
200
|
+
cfg.reporter.report({ ...w, ...usage, model: model ?? 'unknown', provider: cfg.provider, duration_ms: Date.now() - started, stream });
|
|
201
|
+
}
|
|
202
|
+
/** Read a response body (web ReadableStream or Node stream) chunk by chunk. */
|
|
203
|
+
async function* bodyChunks(body) {
|
|
204
|
+
if (body && typeof body.getReader === 'function') {
|
|
205
|
+
const reader = body.getReader();
|
|
206
|
+
for (;;) {
|
|
207
|
+
const { done, value } = await reader.read();
|
|
208
|
+
if (done)
|
|
209
|
+
return;
|
|
210
|
+
yield value;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
else if (body && typeof body[Symbol.asyncIterator] === 'function') {
|
|
214
|
+
for await (const chunk of body)
|
|
215
|
+
yield typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** A provider-shaped error response; the SDK raises it and `makeStatusError` relabels it. */
|
|
219
|
+
function refusal(v, kind) {
|
|
220
|
+
const type = v.run_state === 'killed' ? RUN_KILLED : v.run_state === 'paused' ? RUN_PAUSED : BUDGET_EXCEEDED;
|
|
221
|
+
const error = { type, message: v.reason ?? 'Tokenrein refused the call' };
|
|
222
|
+
const body = kind === 'anthropic' ? { type: 'error', error } : { error: { ...error, code: type, param: null } };
|
|
223
|
+
const headers = { 'content-type': 'application/json' };
|
|
224
|
+
if (v.run_id)
|
|
225
|
+
headers['x-tr-run-id'] = v.run_id;
|
|
226
|
+
return new Response(JSON.stringify(body), { status: v.run_state ? 403 : 402, headers });
|
|
227
|
+
}
|
|
228
|
+
function overVerdict(cfg) {
|
|
229
|
+
try {
|
|
230
|
+
denyIfOver(cfg);
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
catch (e) {
|
|
234
|
+
return { allowed: false, reason: e.message, run_id: currentRun()?.runId };
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Wraps the client's fetch, which every SDK version supports: checks the budget before the call
|
|
239
|
+
* (refusing with a provider-shaped 402/403 without calling the provider), asks OpenAI-style
|
|
240
|
+
* streams for usage, and reads usage from JSON bodies and event streams.
|
|
241
|
+
*/
|
|
242
|
+
function observingFetch(inner, cfg, kind) {
|
|
243
|
+
return async (input, init) => {
|
|
244
|
+
const w = who(cfg);
|
|
245
|
+
const url = String(typeof input === 'string' ? input : (input?.url ?? input));
|
|
246
|
+
let body;
|
|
247
|
+
if (typeof init?.body === 'string') {
|
|
248
|
+
try {
|
|
249
|
+
body = JSON.parse(init.body);
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
body = undefined;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (cfg.provider !== 'anthropic' &&
|
|
256
|
+
body && body.stream === true && body.stream_options === undefined &&
|
|
257
|
+
new URL(url, 'http://x').pathname.endsWith('/chat/completions')) {
|
|
258
|
+
body.stream_options = { include_usage: true };
|
|
259
|
+
init = { ...init, body: JSON.stringify(body) };
|
|
260
|
+
}
|
|
261
|
+
if (body && typeof body.model === 'string') {
|
|
262
|
+
let v;
|
|
263
|
+
if (cfg.check) {
|
|
264
|
+
const req = { ...w, model: body.model, provider: cfg.provider };
|
|
265
|
+
const max = MAX_OUTPUT_FIELDS.map((f) => body[f]).find((x) => typeof x === 'number');
|
|
266
|
+
if (max !== undefined)
|
|
267
|
+
req.max_output_tokens = max;
|
|
268
|
+
const fp = fingerprint(body);
|
|
269
|
+
if (fp)
|
|
270
|
+
req.fingerprint = fp;
|
|
271
|
+
v = await cfg.reporter.check(req);
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
v = overVerdict(cfg);
|
|
275
|
+
}
|
|
276
|
+
if (v && !v.allowed)
|
|
277
|
+
return refusal({ ...v, run_id: v.run_id ?? w.run_id }, kind);
|
|
278
|
+
}
|
|
279
|
+
const started = Date.now();
|
|
280
|
+
const res = await inner(input, init);
|
|
281
|
+
if (!res.ok || !res.body)
|
|
282
|
+
return res;
|
|
283
|
+
const ctype = res.headers.get('content-type') ?? '';
|
|
284
|
+
if (ctype.includes('text/event-stream')) {
|
|
285
|
+
const copy = res.clone();
|
|
286
|
+
const parser = new StreamUsage();
|
|
287
|
+
void (async () => {
|
|
288
|
+
const decoder = new TextDecoder();
|
|
289
|
+
try {
|
|
290
|
+
for await (const chunk of bodyChunks(copy.body))
|
|
291
|
+
parser.feed(decoder.decode(chunk, { stream: true }));
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
// stream aborted; report what was seen
|
|
295
|
+
}
|
|
296
|
+
report(cfg, w, parser.model, parser.usage, started, true);
|
|
297
|
+
})();
|
|
298
|
+
}
|
|
299
|
+
else if (ctype.includes('json')) {
|
|
300
|
+
res
|
|
301
|
+
.clone()
|
|
302
|
+
.json()
|
|
303
|
+
.then((b) => report(cfg, w, b?.model, usageFrom(b), started, false))
|
|
304
|
+
.catch(() => { });
|
|
305
|
+
}
|
|
306
|
+
return res;
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
function directClass(Base) {
|
|
310
|
+
return class Direct extends Base {
|
|
311
|
+
static [UNGUARDED] = Base;
|
|
312
|
+
static get name() {
|
|
313
|
+
return Base.name;
|
|
314
|
+
}
|
|
315
|
+
buildRequest(options, opts = {}) {
|
|
316
|
+
const built = super.buildRequest(options, opts);
|
|
317
|
+
const count = (b) => {
|
|
318
|
+
if (!opts.retryCount)
|
|
319
|
+
currentRun()?.recordCall();
|
|
320
|
+
return b;
|
|
321
|
+
};
|
|
322
|
+
return built instanceof Promise ? built.then(count) : count(built);
|
|
323
|
+
}
|
|
324
|
+
makeStatusError(status, error, message, headers) {
|
|
325
|
+
const err = super.makeStatusError(status, error, message, headers);
|
|
326
|
+
const runId = getHeader(headers, 'x-tr-run-id') ?? currentRun()?.runId;
|
|
327
|
+
return relabel(err, status, error, runId);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
export function wrapDirect(client, o, kind) {
|
|
332
|
+
const c = client;
|
|
333
|
+
if (!c || typeof c.buildRequest !== 'function') {
|
|
334
|
+
throw new TypeError(`guard.${kind}() needs an ${kind === 'openai' ? 'OpenAI' : 'Anthropic'} client instance`);
|
|
335
|
+
}
|
|
336
|
+
if (o.agent !== undefined)
|
|
337
|
+
validateId(o.agent, 'agent');
|
|
338
|
+
if (o.user !== undefined)
|
|
339
|
+
validateUser(o.user);
|
|
340
|
+
const cfg = {
|
|
341
|
+
agent: o.agent,
|
|
342
|
+
user: o.user,
|
|
343
|
+
provider: providerFor(String(c.baseURL ?? ''), o.defaultProvider),
|
|
344
|
+
check: o.check,
|
|
345
|
+
reporter: reporterFor(o.tokenreinURL, o.apiKey),
|
|
346
|
+
};
|
|
347
|
+
const inner = (c.fetch ?? globalThis.fetch).bind(globalThis);
|
|
348
|
+
const fetchOverride = { fetch: observingFetch(inner, cfg, kind) };
|
|
349
|
+
const Base = c.constructor[UNGUARDED] ?? c.constructor;
|
|
350
|
+
const Direct = directClass(Base);
|
|
351
|
+
if (typeof c.withOptions !== 'function') {
|
|
352
|
+
return new Direct({ ...c._options, ...fetchOverride });
|
|
353
|
+
}
|
|
354
|
+
const copy = c.withOptions(fetchOverride);
|
|
355
|
+
Object.setPrototypeOf(copy, Direct.prototype);
|
|
356
|
+
return copy;
|
|
357
|
+
}
|