@tensorcost/sdk 0.3.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 (44) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +201 -0
  3. package/README.md +119 -0
  4. package/dist/applied.d.ts +98 -0
  5. package/dist/applied.d.ts.map +1 -0
  6. package/dist/applied.js +174 -0
  7. package/dist/applied.js.map +1 -0
  8. package/dist/config.d.ts +29 -0
  9. package/dist/config.d.ts.map +1 -0
  10. package/dist/config.js +86 -0
  11. package/dist/config.js.map +1 -0
  12. package/dist/index.d.ts +6 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +5 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/providers/anthropic.d.ts +13 -0
  17. package/dist/providers/anthropic.d.ts.map +1 -0
  18. package/dist/providers/anthropic.js +119 -0
  19. package/dist/providers/anthropic.js.map +1 -0
  20. package/dist/providers/detect.d.ts +13 -0
  21. package/dist/providers/detect.d.ts.map +1 -0
  22. package/dist/providers/detect.js +39 -0
  23. package/dist/providers/detect.js.map +1 -0
  24. package/dist/providers/index.d.ts +4 -0
  25. package/dist/providers/index.d.ts.map +1 -0
  26. package/dist/providers/index.js +4 -0
  27. package/dist/providers/index.js.map +1 -0
  28. package/dist/providers/openai.d.ts +16 -0
  29. package/dist/providers/openai.d.ts.map +1 -0
  30. package/dist/providers/openai.js +137 -0
  31. package/dist/providers/openai.js.map +1 -0
  32. package/dist/transport.d.ts +56 -0
  33. package/dist/transport.d.ts.map +1 -0
  34. package/dist/transport.js +150 -0
  35. package/dist/transport.js.map +1 -0
  36. package/dist/types.d.ts +143 -0
  37. package/dist/types.d.ts.map +1 -0
  38. package/dist/types.js +9 -0
  39. package/dist/types.js.map +1 -0
  40. package/dist/wrap.d.ts +16 -0
  41. package/dist/wrap.d.ts.map +1 -0
  42. package/dist/wrap.js +48 -0
  43. package/dist/wrap.js.map +1 -0
  44. package/package.json +48 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,36 @@
1
+ # Changelog
2
+
3
+ ## 0.3.0 — 2026-05-12
4
+
5
+ - Added: `appliedMode` config flag. When true and `proxyUrl` (or `TENSORCOST_PROXY_URL`) is set, requests route through the TensorCost inference-proxy. See `docs/features/inference-proxy-applied-mode.md`.
6
+ - Added: `TensorCostConfigError` — thrown at `wrap()` time when `appliedMode=true` and no proxy URL is configured.
7
+ - AWS Bedrock clients throw immediately at `wrap()` time when `appliedMode=true` (v1 limitation — SigV4 signing is not interceptable in the same pattern; observe-only mode still works).
8
+ - No breaking changes to the 0.2.x observe-only API.
9
+
10
+ ## 0.2.1 — 2026-05-05
11
+
12
+ Phase A4 batch 4 — `connectionId` support. Stamps `connection_id` on every observation envelope when the SDK is initialised with `wrap(client, { connectionId })` or `TENSORCOST_CONNECTION_ID`. The backend uses this as a fallback for environment resolution when the `environment` field is absent.
13
+
14
+ ## 0.1.1 — 2026-05-05
15
+
16
+ ### Fixed
17
+ - Observation transport now POSTs to `/api/inference-proxy/observation`
18
+ (and exchanges tokens at `/api/inference-proxy/sdk-token/exchange`),
19
+ matching the inference-proxy-service controller mount per the
20
+ `/api/<svc>/<feature>` routing convention. The 0.1.0 paths
21
+ (`/api/proxy/...`) returned 404 against every TensorCost deployment,
22
+ so customer-side observations never landed.
23
+
24
+ ## 0.1.0 — 2026-05-05
25
+
26
+ Initial release.
27
+
28
+ - `wrap(client, options?)` one-line entry point.
29
+ - OpenAI provider — wraps `chat.completions.create` and `completions.create`.
30
+ - Anthropic provider — wraps `messages.create`.
31
+ - Fire-and-forget HTTP transport over native `fetch` (Node 18+).
32
+ - Short-lived JWT exchange against `POST /api/inference-proxy/sdk-token/exchange` (the 0.1.0 paste-up said `/api/proxy/...`; corrected to the real route in 0.1.1), cached + auto-refreshed.
33
+ - Bounded queue (1024) with drop-on-saturation backpressure.
34
+ - Fail-open by default. The single exception: missing `apiKey` throws `MissingConfigError` at `wrap()` time.
35
+ - Zero runtime dependencies.
36
+ - TypeScript-first; ships with `.d.ts`.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Vaadh Labs, Inc. (TensorCost)
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # @tensorcost/sdk
2
+
3
+ One-line wrapper SDK for TensorCost — fire-and-forget LLM observability for OpenAI and Anthropic clients in Node.js.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @tensorcost/sdk
9
+ # or
10
+ pnpm add @tensorcost/sdk
11
+ ```
12
+
13
+ Requires Node.js 18+ (uses native `fetch`).
14
+
15
+ ## Use
16
+
17
+ ```ts
18
+ import OpenAI from "openai";
19
+ import { wrap } from "@tensorcost/sdk";
20
+
21
+ const client = wrap(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }));
22
+
23
+ // Use the client exactly as before — TensorCost observes every call
24
+ // and ships fire-and-forget observations to the platform.
25
+ const resp = await client.chat.completions.create({
26
+ model: "gpt-4o-mini",
27
+ messages: [{ role: "user", content: "hi" }],
28
+ });
29
+ ```
30
+
31
+ Anthropic is just as simple:
32
+
33
+ ```ts
34
+ import Anthropic from "@anthropic-ai/sdk";
35
+ import { wrap } from "@tensorcost/sdk";
36
+
37
+ const client = wrap(new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY }));
38
+
39
+ await client.messages.create({
40
+ model: "claude-3-5-sonnet-20241022",
41
+ max_tokens: 256,
42
+ messages: [{ role: "user", content: "hi" }],
43
+ });
44
+ ```
45
+
46
+ ## Configuration
47
+
48
+ `wrap()` reads from the environment by default:
49
+
50
+ | Variable | Purpose | Required |
51
+ |---|---|---|
52
+ | `TENSORCOST_API_KEY` | Long-lived API key from the TensorCost console | Yes |
53
+ | `TENSORCOST_BASE_URL` | Backend base URL | No (default `https://api.tensorcost.com`) |
54
+ | `TENSORCOST_TENANT_ID` | Optional explicit tenant id | No |
55
+ | `TENSORCOST_PROXY_URL` | Proxy base URL for applied mode | Required when `appliedMode: true` |
56
+ | `TENSORCOST_ENVIRONMENT` | Environment tag stamped on every observation | No |
57
+ | `TENSORCOST_CONNECTION_ID` | Provider-connection identifier | No |
58
+
59
+ Or pass explicitly:
60
+
61
+ ```ts
62
+ const client = wrap(new OpenAI(...), {
63
+ apiKey: "tc_live_xxx",
64
+ baseUrl: "https://api.tensorcost.com",
65
+ });
66
+ ```
67
+
68
+ ## Applied mode (Layer 2)
69
+
70
+ When you enable applied mode, the SDK routes inference requests through the TensorCost inference-proxy instead of directly to the AI provider. The proxy decides per-request whether to re-route to an alternate provider or pass through unchanged — the SDK doesn't make that call.
71
+
72
+ ```ts
73
+ const client = wrap(new OpenAI({ apiKey: process.env.OPENAI_API_KEY }), {
74
+ apiKey: "tc_live_xxx",
75
+ appliedMode: true,
76
+ proxyUrl: "https://proxy.tensorcost.com", // or set TENSORCOST_PROXY_URL
77
+ });
78
+
79
+ // Use normally — the SDK redirects the client to the proxy transparently.
80
+ // Observe-only telemetry still fires after every call.
81
+ const resp = await client.chat.completions.create({
82
+ model: "gpt-4o-mini",
83
+ messages: [{ role: "user", content: "hi" }],
84
+ });
85
+ ```
86
+
87
+ `wrap()` throws `TensorCostConfigError` at import time if `appliedMode: true` and neither `proxyUrl` nor `TENSORCOST_PROXY_URL` is set. AWS Bedrock is not yet supported in applied mode (SigV4 signing can't be intercepted in the same pattern); observe-only mode works fine for Bedrock.
88
+
89
+ See [`docs/features/inference-proxy-applied-mode.md`](../../docs/features/inference-proxy-applied-mode.md) for the proxy-side design.
90
+
91
+ ## Fail-open guarantee
92
+
93
+ If TensorCost is slow, down, or misconfigured, your customer call STILL succeeds. The SDK swallows internal errors and surfaces them via `console.warn`. The one exception: a missing API key throws `MissingConfigError` at `wrap()` time — silently dropping every observation would be worse than a loud import-time failure.
94
+
95
+ ## What is captured
96
+
97
+ Only metadata — never prompt or completion content:
98
+
99
+ - Provider + model
100
+ - Operation (`chat.completions`, `completions`, `messages`)
101
+ - Request / response timestamps
102
+ - Input / output token counts (from the provider's `usage` field)
103
+ - Status (`success` / `error`) and error class/message on failure
104
+ - A correlation UUID
105
+
106
+ ## Currently supported
107
+
108
+ - OpenAI (`openai` >= 4.x) — `chat.completions.create`, `completions.create`
109
+ - Anthropic (`@anthropic-ai/sdk` >= 0.x) — `messages.create`
110
+
111
+ ## Coming soon
112
+
113
+ - Bedrock, Azure OpenAI, Vertex
114
+ - Streaming responses (`stream: true`)
115
+ - Tool / function calling (multi-call trace stitching)
116
+
117
+ ## License
118
+
119
+ Proprietary — Vaadh Labs / TensorCost.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Applied-mode wiring — Layer 2.
3
+ *
4
+ * When the customer opts into applied mode, the SDK routes every inference
5
+ * request through the TensorCost inference-proxy instead of directly to the
6
+ * upstream AI provider. The proxy decides per-request whether to re-route
7
+ * or pass through unchanged; the SDK doesn't make that call.
8
+ *
9
+ * The mechanism is straightforward: at `wrap()` time we read the
10
+ * provider's original baseURL and auth from the client, permanently
11
+ * redirect the client's baseURL to the proxy endpoint, and inject two
12
+ * custom headers the proxy expects:
13
+ *
14
+ * x-tc-provider-url — the original provider base URL
15
+ * x-tc-provider-auth — the auth header value to forward upstream
16
+ *
17
+ * Both the OpenAI SDK and the Anthropic SDK expose `baseURL` and
18
+ * `defaultHeaders` as first-class properties, so we can set them
19
+ * without monkey-patching the HTTP layer.
20
+ *
21
+ * Bedrock is not supported in v1. The AWS SDK uses SigV4 signing on
22
+ * regional endpoints and doesn't expose baseURL / defaultHeaders in
23
+ * the same shape. Passing a Bedrock-shaped client with appliedMode=true
24
+ * throws `TensorCostConfigError` at wrap time.
25
+ *
26
+ * Observe-only telemetry (the 0.2.x substrate) continues to fire
27
+ * after every call regardless of this setting.
28
+ */
29
+ /**
30
+ * Client shapes we understand. All detection is duck-typed; no import
31
+ * of the actual openai or @anthropic-ai/sdk packages.
32
+ */
33
+ /** Header value the proxy expects for OpenAI + Azure OpenAI. */
34
+ declare function bearerAuth(apiKey: string): string;
35
+ /** Header value the proxy expects for Anthropic. */
36
+ declare function anthropicAuth(apiKey: string): string;
37
+ /**
38
+ * Read the original baseURL from a duck-typed client. Both the OpenAI
39
+ * and Anthropic SDKs expose a `baseURL` string property on the client
40
+ * instance (the actual HTTP origin, e.g. "https://api.openai.com/v1").
41
+ * Returns null when the property is absent or not a string.
42
+ */
43
+ declare function readBaseUrl(client: Record<string, unknown>): string | null;
44
+ /**
45
+ * Read the API key from the client. OpenAI SDK exposes `client.apiKey`;
46
+ * Anthropic SDK exposes `client.apiKey` too. Returns null when absent.
47
+ */
48
+ declare function readApiKey(client: Record<string, unknown>): string | null;
49
+ /**
50
+ * Detect whether this client looks like an Azure OpenAI client (the
51
+ * openai package's `AzureOpenAI` subclass). Azure uses `api-key` header
52
+ * auth and a custom endpoint URL, so the auth value we forward differs
53
+ * from vanilla OpenAI.
54
+ *
55
+ * Detection: Azure clients have an `azure` property set to true, OR
56
+ * their baseURL contains `.openai.azure.com`.
57
+ */
58
+ declare function isAzureOpenAI(client: Record<string, unknown>): boolean;
59
+ /**
60
+ * Azure OpenAI uses an `api-key` header rather than `Authorization: Bearer`.
61
+ * The proxy forwards `x-tc-provider-auth` verbatim as the upstream auth
62
+ * header, so we need to format it as the proxy expects: "api-key <value>".
63
+ *
64
+ * Note: The proxy currently only supports `Authorization` and `api-key`
65
+ * style headers. This value is forwarded in the `x-tc-provider-auth`
66
+ * header and then sent by the proxy as the upstream Authorization.
67
+ */
68
+ declare function azureAuth(apiKey: string): string;
69
+ /**
70
+ * Install applied-mode routing on the client. Called once by `wrap()`.
71
+ *
72
+ * Mutates `client.baseURL` to point at the proxy endpoint and injects
73
+ * `x-tc-provider-url` / `x-tc-provider-auth` into `client.defaultHeaders`.
74
+ * These headers survive for the lifetime of the client — every subsequent
75
+ * request automatically carries them.
76
+ *
77
+ * @param client - The customer's AI SDK client (duck-typed).
78
+ * @param proxyUrl - The TensorCost proxy base URL (already stripped of trailing slash).
79
+ * @param provider - "openai" | "anthropic", as detected by detectProvider().
80
+ *
81
+ * @throws TensorCostConfigError
82
+ * - If the client doesn't expose `baseURL` (can't determine the original
83
+ * provider URL to forward in `x-tc-provider-url`).
84
+ * - If the client doesn't expose `apiKey` (can't build `x-tc-provider-auth`).
85
+ * - If the provider is "bedrock" (not yet supported in v1).
86
+ */
87
+ export declare function installAppliedMode(client: unknown, proxyUrl: string, provider: "openai" | "anthropic"): void;
88
+ export declare const PROXY_PATH_SUFFIX = "/api/inference-proxy/v1/chat/completions";
89
+ export declare const __test__: {
90
+ readBaseUrl: typeof readBaseUrl;
91
+ readApiKey: typeof readApiKey;
92
+ isAzureOpenAI: typeof isAzureOpenAI;
93
+ bearerAuth: typeof bearerAuth;
94
+ anthropicAuth: typeof anthropicAuth;
95
+ azureAuth: typeof azureAuth;
96
+ };
97
+ export {};
98
+ //# sourceMappingURL=applied.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"applied.d.ts","sourceRoot":"","sources":["../src/applied.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAOH;;;GAGG;AAEH,gEAAgE;AAChE,iBAAS,UAAU,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE1C;AAED,oDAAoD;AACpD,iBAAS,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAE7C;AAED;;;;;GAKG;AACH,iBAAS,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,IAAI,CAMnE;AAED;;;GAGG;AACH,iBAAS,UAAU,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,GAAG,IAAI,CAGlE;AAED;;;;;;;;GAQG;AACH,iBAAS,aAAa,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAI/D;AAED;;;;;;;;GAQG;AACH,iBAAS,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,CAEzC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,OAAO,EACf,QAAQ,EAAE,MAAM,EAChB,QAAQ,EAAE,QAAQ,GAAG,WAAW,GAC/B,IAAI,CAiEN;AAED,eAAO,MAAM,iBAAiB,6CAAa,CAAC;AAE5C,eAAO,MAAM,QAAQ;;;;;;;CAOpB,CAAC"}
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Applied-mode wiring — Layer 2.
3
+ *
4
+ * When the customer opts into applied mode, the SDK routes every inference
5
+ * request through the TensorCost inference-proxy instead of directly to the
6
+ * upstream AI provider. The proxy decides per-request whether to re-route
7
+ * or pass through unchanged; the SDK doesn't make that call.
8
+ *
9
+ * The mechanism is straightforward: at `wrap()` time we read the
10
+ * provider's original baseURL and auth from the client, permanently
11
+ * redirect the client's baseURL to the proxy endpoint, and inject two
12
+ * custom headers the proxy expects:
13
+ *
14
+ * x-tc-provider-url — the original provider base URL
15
+ * x-tc-provider-auth — the auth header value to forward upstream
16
+ *
17
+ * Both the OpenAI SDK and the Anthropic SDK expose `baseURL` and
18
+ * `defaultHeaders` as first-class properties, so we can set them
19
+ * without monkey-patching the HTTP layer.
20
+ *
21
+ * Bedrock is not supported in v1. The AWS SDK uses SigV4 signing on
22
+ * regional endpoints and doesn't expose baseURL / defaultHeaders in
23
+ * the same shape. Passing a Bedrock-shaped client with appliedMode=true
24
+ * throws `TensorCostConfigError` at wrap time.
25
+ *
26
+ * Observe-only telemetry (the 0.2.x substrate) continues to fire
27
+ * after every call regardless of this setting.
28
+ */
29
+ import { TensorCostConfigError } from "./config.js";
30
+ /** Proxy chat-completions path — fixed in v1. */
31
+ const PROXY_PATH = "/api/inference-proxy/v1/chat/completions";
32
+ /**
33
+ * Client shapes we understand. All detection is duck-typed; no import
34
+ * of the actual openai or @anthropic-ai/sdk packages.
35
+ */
36
+ /** Header value the proxy expects for OpenAI + Azure OpenAI. */
37
+ function bearerAuth(apiKey) {
38
+ return `Bearer ${apiKey}`;
39
+ }
40
+ /** Header value the proxy expects for Anthropic. */
41
+ function anthropicAuth(apiKey) {
42
+ return `x-api-key ${apiKey}`;
43
+ }
44
+ /**
45
+ * Read the original baseURL from a duck-typed client. Both the OpenAI
46
+ * and Anthropic SDKs expose a `baseURL` string property on the client
47
+ * instance (the actual HTTP origin, e.g. "https://api.openai.com/v1").
48
+ * Returns null when the property is absent or not a string.
49
+ */
50
+ function readBaseUrl(client) {
51
+ const raw = client["baseURL"];
52
+ if (typeof raw === "string" && raw.length > 0) {
53
+ return raw.replace(/\/+$/, "");
54
+ }
55
+ return null;
56
+ }
57
+ /**
58
+ * Read the API key from the client. OpenAI SDK exposes `client.apiKey`;
59
+ * Anthropic SDK exposes `client.apiKey` too. Returns null when absent.
60
+ */
61
+ function readApiKey(client) {
62
+ const raw = client["apiKey"];
63
+ return typeof raw === "string" && raw.length > 0 ? raw : null;
64
+ }
65
+ /**
66
+ * Detect whether this client looks like an Azure OpenAI client (the
67
+ * openai package's `AzureOpenAI` subclass). Azure uses `api-key` header
68
+ * auth and a custom endpoint URL, so the auth value we forward differs
69
+ * from vanilla OpenAI.
70
+ *
71
+ * Detection: Azure clients have an `azure` property set to true, OR
72
+ * their baseURL contains `.openai.azure.com`.
73
+ */
74
+ function isAzureOpenAI(client) {
75
+ if (client["azure"] === true)
76
+ return true;
77
+ const url = readBaseUrl(client) ?? "";
78
+ return url.includes(".openai.azure.com");
79
+ }
80
+ /**
81
+ * Azure OpenAI uses an `api-key` header rather than `Authorization: Bearer`.
82
+ * The proxy forwards `x-tc-provider-auth` verbatim as the upstream auth
83
+ * header, so we need to format it as the proxy expects: "api-key <value>".
84
+ *
85
+ * Note: The proxy currently only supports `Authorization` and `api-key`
86
+ * style headers. This value is forwarded in the `x-tc-provider-auth`
87
+ * header and then sent by the proxy as the upstream Authorization.
88
+ */
89
+ function azureAuth(apiKey) {
90
+ return `api-key ${apiKey}`;
91
+ }
92
+ /**
93
+ * Install applied-mode routing on the client. Called once by `wrap()`.
94
+ *
95
+ * Mutates `client.baseURL` to point at the proxy endpoint and injects
96
+ * `x-tc-provider-url` / `x-tc-provider-auth` into `client.defaultHeaders`.
97
+ * These headers survive for the lifetime of the client — every subsequent
98
+ * request automatically carries them.
99
+ *
100
+ * @param client - The customer's AI SDK client (duck-typed).
101
+ * @param proxyUrl - The TensorCost proxy base URL (already stripped of trailing slash).
102
+ * @param provider - "openai" | "anthropic", as detected by detectProvider().
103
+ *
104
+ * @throws TensorCostConfigError
105
+ * - If the client doesn't expose `baseURL` (can't determine the original
106
+ * provider URL to forward in `x-tc-provider-url`).
107
+ * - If the client doesn't expose `apiKey` (can't build `x-tc-provider-auth`).
108
+ * - If the provider is "bedrock" (not yet supported in v1).
109
+ */
110
+ export function installAppliedMode(client, proxyUrl, provider) {
111
+ if (provider === "bedrock") {
112
+ // Bedrock uses SigV4 signing on regional HTTPS endpoints. The AWS
113
+ // SDK does not expose baseURL / defaultHeaders in the same shape,
114
+ // so we can't intercept the request path in v1. Pass-through-only
115
+ // mode is the correct posture; applied mode for Bedrock is a
116
+ // follow-up workstream.
117
+ throw new TensorCostConfigError("TensorCost applied mode is not yet supported for AWS Bedrock clients. " +
118
+ "Set appliedMode: false to continue with observe-only mode, or use " +
119
+ "an OpenAI / Anthropic client.");
120
+ }
121
+ const c = client;
122
+ const originalBaseUrl = readBaseUrl(c);
123
+ if (!originalBaseUrl) {
124
+ throw new TensorCostConfigError("TensorCost applied mode requires a client with a readable `baseURL` " +
125
+ "property (the original provider endpoint). The client passed to " +
126
+ "wrap() does not expose one.");
127
+ }
128
+ const apiKey = readApiKey(c);
129
+ if (!apiKey) {
130
+ throw new TensorCostConfigError("TensorCost applied mode requires a client with a readable `apiKey` " +
131
+ "property to forward provider auth. The client passed to wrap() does " +
132
+ "not expose one.");
133
+ }
134
+ // Build the auth header value to forward. The proxy sends this value
135
+ // as the upstream Authorization (or api-key) header verbatim.
136
+ let providerAuth;
137
+ if (provider === "anthropic") {
138
+ providerAuth = anthropicAuth(apiKey);
139
+ }
140
+ else if (isAzureOpenAI(c)) {
141
+ providerAuth = azureAuth(apiKey);
142
+ }
143
+ else {
144
+ providerAuth = bearerAuth(apiKey);
145
+ }
146
+ // Redirect the client's base URL to the proxy. The path suffix
147
+ // (/api/inference-proxy/v1) is appended here so that the OpenAI-compatible
148
+ // client doesn't double-prepend its own /v1 path. Both the OpenAI and
149
+ // Anthropic SDKs append the method path to baseURL; the proxy endpoint is
150
+ // OpenAI-compatible, so the client will build:
151
+ // baseURL + "/chat/completions"
152
+ // We set baseURL to the proxy's parent path to get the right URL.
153
+ const cleanProxyUrl = proxyUrl.replace(/\/+$/, "");
154
+ c["baseURL"] = `${cleanProxyUrl}/api/inference-proxy/v1`;
155
+ // Inject the custom headers into the client's defaultHeaders object.
156
+ // Both SDKs merge defaultHeaders with every outgoing request.
157
+ const existing = c["defaultHeaders"];
158
+ const headers = existing && typeof existing === "object" && !Array.isArray(existing)
159
+ ? existing
160
+ : {};
161
+ headers["x-tc-provider-url"] = originalBaseUrl;
162
+ headers["x-tc-provider-auth"] = providerAuth;
163
+ c["defaultHeaders"] = headers;
164
+ }
165
+ export const PROXY_PATH_SUFFIX = PROXY_PATH;
166
+ export const __test__ = {
167
+ readBaseUrl,
168
+ readApiKey,
169
+ isAzureOpenAI,
170
+ bearerAuth,
171
+ anthropicAuth,
172
+ azureAuth,
173
+ };
174
+ //# sourceMappingURL=applied.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"applied.js","sourceRoot":"","sources":["../src/applied.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAEpD,iDAAiD;AACjD,MAAM,UAAU,GAAG,0CAA0C,CAAC;AAE9D;;;GAGG;AAEH,gEAAgE;AAChE,SAAS,UAAU,CAAC,MAAc;IAChC,OAAO,UAAU,MAAM,EAAE,CAAC;A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C,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC;QAClE,CAAC,CAAE,QAAmC;QACtC,CAAC,CAAC,EAAE,CAAC;IACT,OAAO,CAAC,mBAAmB,CAAC,GAAG,eAAe,CAAC;IAC/C,OAAO,CAAC,oBAAoB,CAAC,GAAG,YAAY,CAAC;IAC7C,CAAC,CAAC,gBAAgB,CAAC,GAAG,OAAO,CAAC;AAChC,CAAC;AAED,MAAM,CAAC,MAAM,iBAAiB,GAAG,UAAU,CAAC;AAE5C,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,WAAW;IACX,UAAU;IACV,aAAa;IACb,UAAU;IACV,aAAa;IACb,SAAS;CACV,CAAC"}
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Configuration resolution for the SDK.
3
+ *
4
+ * Resolution order:
5
+ * 1. Explicit options to wrap()
6
+ * 2. Environment variables (TENSORCOST_API_KEY, TENSORCOST_BASE_URL,
7
+ * TENSORCOST_TENANT_ID, TENSORCOST_PROXY_URL)
8
+ * 3. Defaults (only for baseUrl)
9
+ *
10
+ * If apiKey is still missing after resolution, MissingConfigError is
11
+ * raised. This is the *one* case the SDK does not fail open — it means
12
+ * the SDK was never configured at all, and silently dropping every
13
+ * observation would be worse than a loud import-time failure.
14
+ *
15
+ * If appliedMode=true and proxyUrl is missing from both options and env,
16
+ * TensorCostConfigError is thrown. Applied mode needs an explicit proxy
17
+ * URL; there is no safe default.
18
+ */
19
+ import type { ResolvedConfig, WrapOptions } from "./types.js";
20
+ export declare const DEFAULT_BASE_URL = "https://api.tensorcost.com";
21
+ export declare class MissingConfigError extends Error {
22
+ constructor(message: string);
23
+ }
24
+ /** Thrown when applied mode is enabled but required config is absent. */
25
+ export declare class TensorCostConfigError extends Error {
26
+ constructor(message: string);
27
+ }
28
+ export declare function resolveConfig(options?: WrapOptions): ResolvedConfig;
29
+ //# sourceMappingURL=config.d.ts.map