@tensorcost/sdk 1.2.0 → 1.3.1

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 (66) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +33 -1
  3. package/dist/errors.d.ts +12 -0
  4. package/dist/errors.d.ts.map +1 -1
  5. package/dist/errors.js +14 -0
  6. package/dist/errors.js.map +1 -1
  7. package/dist/index.d.ts +2 -2
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/index.js.map +1 -1
  11. package/dist/providers/anthropic.d.ts.map +1 -1
  12. package/dist/providers/anthropic.js +78 -34
  13. package/dist/providers/anthropic.js.map +1 -1
  14. package/dist/providers/bedrock.d.ts +7 -6
  15. package/dist/providers/bedrock.d.ts.map +1 -1
  16. package/dist/providers/bedrock.js +42 -10
  17. package/dist/providers/bedrock.js.map +1 -1
  18. package/dist/providers/openai.d.ts.map +1 -1
  19. package/dist/providers/openai.js +87 -14
  20. package/dist/providers/openai.js.map +1 -1
  21. package/dist/providers/vertex.d.ts.map +1 -1
  22. package/dist/providers/vertex.js +5 -2
  23. package/dist/providers/vertex.js.map +1 -1
  24. package/dist/proxy-client.d.ts.map +1 -1
  25. package/dist/proxy-client.js +265 -5
  26. package/dist/proxy-client.js.map +1 -1
  27. package/dist/trace-link.d.ts +24 -0
  28. package/dist/trace-link.d.ts.map +1 -0
  29. package/dist/trace-link.js +61 -0
  30. package/dist/trace-link.js.map +1 -0
  31. package/dist/types.d.ts +7 -0
  32. package/dist/types.d.ts.map +1 -1
  33. package/dist/version.d.ts +1 -1
  34. package/dist/version.js +1 -1
  35. package/dist/wrap.d.ts.map +1 -1
  36. package/dist/wrap.js +1 -0
  37. package/dist/wrap.js.map +1 -1
  38. package/package.json +6 -1
  39. package/dist/adapters/crewai.d.ts +0 -4
  40. package/dist/adapters/langchain.d.ts +0 -4
  41. package/dist/adapters/llamaindex.d.ts +0 -4
  42. package/dist/adapters/vercel-ai.d.ts +0 -4
  43. package/dist/admit-client.d.ts +0 -40
  44. package/dist/applied.d.ts +0 -104
  45. package/dist/circuit-observations.d.ts +0 -12
  46. package/dist/circuit.d.ts +0 -67
  47. package/dist/compliance-guard.d.ts +0 -16
  48. package/dist/compliance-team.d.ts +0 -11
  49. package/dist/config.d.ts +0 -28
  50. package/dist/decision.d.ts +0 -11
  51. package/dist/dlp.d.ts +0 -16
  52. package/dist/layer.d.ts +0 -54
  53. package/dist/prewarm.d.ts +0 -14
  54. package/dist/providers/anthropic.d.ts +0 -41
  55. package/dist/providers/detect.d.ts +0 -19
  56. package/dist/providers/index.d.ts +0 -6
  57. package/dist/providers/openai.d.ts +0 -46
  58. package/dist/providers/vertex.d.ts +0 -14
  59. package/dist/proxy-client.d.ts +0 -114
  60. package/dist/retry.d.ts +0 -50
  61. package/dist/runtime.d.ts +0 -24
  62. package/dist/sdk-layer.d.ts +0 -38
  63. package/dist/telemetry.d.ts +0 -70
  64. package/dist/transport.d.ts +0 -68
  65. package/dist/wrap-overhead.d.ts +0 -32
  66. package/dist/wrap.d.ts +0 -24
package/dist/retry.d.ts DELETED
@@ -1,50 +0,0 @@
1
- /**
2
- * Retry utilities for the TensorCost applied-mode request path.
3
- *
4
- * Retries use jittered exponential backoff:
5
- *
6
- * delay = min(maxDelayMs, baseDelayMs * 2^attempt) * (0.5 + Math.random() * 0.5)
7
- *
8
- * where `attempt` is 0-indexed. With defaults (baseDelayMs=500, maxDelayMs=30 000),
9
- * the sequence of *maximum* delays is:
10
- * attempt 1: 500ms
11
- * attempt 2: 1 000ms
12
- * attempt 3: 2 000ms
13
- * attempt 4: 4 000ms
14
- * attempt 5: 8 000ms
15
- * The jitter factor halves the minimum so actual delays are 50–100% of those
16
- * maximums. This matches the posture used by the OpenAI Node SDK.
17
- *
18
- * Rules:
19
- * - Never retry 4xx responses (except 429).
20
- * - Always retry 5xx responses and network errors.
21
- * - On 429: honour the `Retry-After` response header when present
22
- * (overrides the backoff delay).
23
- * - Non-idempotent verbs (POST without `stream:false` is still idempotent
24
- * at the proxy level — the proxy is stateless) default to idempotent for
25
- * all chat/completions calls.
26
- */
27
- export interface RetryConfig {
28
- /** Maximum number of total attempts (1 = no retries). Default: 5. */
29
- maxAttempts: number;
30
- /** Base backoff interval in milliseconds. Default: 500. */
31
- baseDelayMs: number;
32
- /** Cap on any single backoff interval. Default: 30 000 (30s). */
33
- maxDelayMs: number;
34
- }
35
- export declare const DEFAULT_RETRY_CONFIG: RetryConfig;
36
- /**
37
- * Compute the delay before the next attempt.
38
- *
39
- * When `retryAfterMs` is provided (from a 429 Retry-After header) it
40
- * overrides the exponential calculation but is still capped at maxDelayMs.
41
- */
42
- export declare function computeDelay(attempt: number, // 0-indexed
43
- config: RetryConfig, retryAfterMs?: number): number;
44
- /** True for HTTP status codes the SDK should retry on. */
45
- export declare function isRetryableStatus(status: number): boolean;
46
- /** Extract Retry-After delay in milliseconds from a fetch Response. */
47
- export declare function retryAfterMs(resp: Response): number | undefined;
48
- /** Sleep for `ms` milliseconds (abortable). */
49
- export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
50
- //# sourceMappingURL=retry.d.ts.map
package/dist/runtime.d.ts DELETED
@@ -1,24 +0,0 @@
1
- /**
2
- * Process-wide shared transport + sdk-layer clients so `prewarm()` and
3
- * `wrap()` reuse the same JWT and published-layer cache.
4
- */
5
- import { SdkLayerClient } from "./sdk-layer.js";
6
- import { ObservationTransport } from "./transport.js";
7
- import type { ResolvedConfig, WrapOptions } from "./types.js";
8
- export interface TensorCostRuntime {
9
- transport: ObservationTransport;
10
- sdkLayer: SdkLayerClient;
11
- }
12
- export declare function sharedRuntimeKey(config: {
13
- baseUrl: string;
14
- apiKey: string;
15
- tenantId: string | null;
16
- failOpen?: boolean;
17
- }): string;
18
- export declare function getSharedRuntime(options: WrapOptions | ResolvedConfig): TensorCostRuntime;
19
- /** Fire-and-forget JWT + sdk-layer warmup on the shared runtime. */
20
- export declare function warmupSharedRuntime(config: ResolvedConfig): void;
21
- export declare const __test__: {
22
- clearRuntimes(): void;
23
- };
24
- //# sourceMappingURL=runtime.d.ts.map
@@ -1,38 +0,0 @@
1
- /**
2
- * Fetches the console-published control layer with a 30s cache.
3
- * Decays to govern when the endpoint is unreachable for SDK_LAYER_DECAY_MS.
4
- *
5
- * Refresh never blocks an agent call once a snapshot exists: expired cache
6
- * is served immediately (stale-while-revalidate). Cold fetch is capped at
7
- * SDK_LAYER_FETCH_TIMEOUT_MS so a hung TensorCost cannot stall the model call.
8
- */
9
- import type { CompiledComplianceSnapshot, ControlLayer } from "./layer.js";
10
- import { type DataGrant } from "./layer.js";
11
- export interface SdkLayerClientOptions {
12
- baseUrl: string;
13
- getToken: () => Promise<string>;
14
- /** Optional team scope for compliance overlay (narrow-only). */
15
- teamId?: string | null;
16
- fetchImpl?: typeof fetch;
17
- }
18
- export declare class SdkLayerClient {
19
- private readonly baseUrl;
20
- private readonly getToken;
21
- private readonly teamId;
22
- private readonly fetchImpl;
23
- private cache;
24
- /** 0 until the first successful fetch — cold start must not skip decay-to-govern. */
25
- private lastSuccessAt;
26
- private refreshInflight;
27
- constructor(opts: SdkLayerClientOptions);
28
- /** Compiled compliance snapshot (cached with sdk-layer). */
29
- getComplianceSnapshot(codeMaxLayer?: ControlLayer): Promise<CompiledComplianceSnapshot | null>;
30
- /** effective = min(codeMaxLayer, published). */
31
- effectiveLayer(codeMaxLayer: ControlLayer): Promise<ControlLayer>;
32
- /** intersect(codeMaxGrants, console.data_grants). Absent codeMax = all console grants. */
33
- effectiveGrants(codeMaxGrants?: readonly DataGrant[], codeMaxLayer?: ControlLayer): Promise<DataGrant[]>;
34
- private fetchPublishedSnapshot;
35
- private scheduleRefresh;
36
- private refreshNow;
37
- }
38
- //# sourceMappingURL=sdk-layer.d.ts.map
@@ -1,70 +0,0 @@
1
- /**
2
- * Telemetry hook types for the TensorCost Node SDK.
3
- *
4
- * Customers pass `onLifecycleEvent` in WrapOptions to receive typed events
5
- * at each stage of a request lifecycle. The default is no-op — not providing
6
- * the callback adds zero overhead to the hot path.
7
- *
8
- * What's included in every event:
9
- * - provider, model, operation — request identity
10
- * - attemptNumber — 1-based; increments on each retry
11
- * - elapsedMs — wall-clock time since the first attempt began
12
- *
13
- * What is never included:
14
- * - prompt / completion content
15
- * - request or response bodies
16
- * - credentials
17
- *
18
- * The five event kinds map to the lifecycle stages:
19
- *
20
- * before_request fires before each attempt (including retried ones)
21
- * after_response fires when a request completes successfully
22
- * on_retry fires when a request is going to be retried, with the
23
- * reason and how long the SDK will wait before the next
24
- * attempt
25
- * on_error fires when the SDK gives up (all retries exhausted or
26
- * a non-retriable error occurred)
27
- * on_fallback fires when the circuit breaker opens and the SDK routes
28
- * to the provider directly instead of the proxy
29
- */
30
- export type Provider = "openai" | "anthropic";
31
- /** Common fields shared by every lifecycle event. */
32
- export interface TelemetryBase {
33
- provider: Provider;
34
- model: string;
35
- operation: string;
36
- attemptNumber: number;
37
- /** Wall-clock milliseconds since the first attempt for this call began. */
38
- elapsedMs: number;
39
- }
40
- export interface BeforeRequestEvent extends TelemetryBase {
41
- kind: "before_request";
42
- }
43
- export interface AfterResponseEvent extends TelemetryBase {
44
- kind: "after_response";
45
- status: number;
46
- /** Request ID from the X-TC-Request-ID header, when the proxy set it. */
47
- requestId: string | null;
48
- }
49
- export interface OnRetryEvent extends TelemetryBase {
50
- kind: "on_retry";
51
- reason: "5xx" | "network_error" | "quota_429";
52
- status: number | null;
53
- /** How many milliseconds the SDK will wait before the next attempt. */
54
- delayMs: number;
55
- }
56
- export interface OnErrorEvent extends TelemetryBase {
57
- kind: "on_error";
58
- errorClass: string;
59
- status: number | null;
60
- }
61
- export interface OnFallbackEvent extends TelemetryBase {
62
- kind: "on_fallback";
63
- /** Number of consecutive proxy failures that tripped the circuit. */
64
- consecutiveFailures: number;
65
- }
66
- export type LifecycleEvent = BeforeRequestEvent | AfterResponseEvent | OnRetryEvent | OnErrorEvent | OnFallbackEvent;
67
- export type LifecycleEventCallback = (event: LifecycleEvent) => void;
68
- /** Call `cb` if defined — errors in the callback are always swallowed. */
69
- export declare function emitEvent(cb: LifecycleEventCallback | undefined, event: LifecycleEvent): void;
70
- //# sourceMappingURL=telemetry.d.ts.map
@@ -1,68 +0,0 @@
1
- /**
2
- * Fire-and-forget HTTP transport for observation events.
3
- *
4
- * Design:
5
- *
6
- * * `post(observation)` returns synchronously the moment the observation
7
- * is enqueued. The actual fetch runs on the microtask queue via
8
- * `queueMicrotask`, so the customer's hot path is never blocked on
9
- * network IO.
10
- * * If the in-flight queue saturates (>= MAX_QUEUE_DEPTH), we drop the
11
- * oldest observation rather than block. Losing one observation is
12
- * strictly preferable to slowing down the customer's request loop.
13
- * * A short-lived JWT is fetched once via
14
- * `POST /api/inference-proxy/sdk-token/exchange` using the long-lived
15
- * API key.
16
- * The token is cached in-memory and refreshed when within
17
- * TOKEN_REFRESH_LEEWAY_MS of expiry.
18
- * * All errors during posting are swallowed when `failOpen` is true
19
- * (the default) and surfaced via console.warn. The customer's call
20
- * site never sees an exception.
21
- */
22
- import type { Observation } from "./types.js";
23
- export interface TransportOptions {
24
- baseUrl: string;
25
- apiKey: string;
26
- /** Required for token exchange against current inference-proxy DTO. */
27
- tenantId?: string | null;
28
- timeoutMs?: number;
29
- failOpen?: boolean;
30
- /** Optional fetch override for testing. Defaults to global fetch. */
31
- fetchImpl?: typeof fetch;
32
- }
33
- export declare class ObservationTransport {
34
- private readonly baseUrl;
35
- private readonly apiKey;
36
- private readonly tenantId;
37
- private readonly timeoutMs;
38
- private readonly failOpen;
39
- private readonly fetchImpl;
40
- private pending;
41
- private tokenCache;
42
- /** In-flight token-exchange promise; coalesces concurrent refreshes. */
43
- private tokenInflight;
44
- constructor(opts: TransportOptions);
45
- /**
46
- * Enqueue an observation for fire-and-forget delivery. Returns
47
- * immediately (synchronously). Errors are logged via console.warn,
48
- * never thrown, when failOpen is true.
49
- */
50
- post(observation: Observation): void;
51
- private deliver;
52
- /** Exchange or return cached JWT for proxy/admit/sdk-layer calls. */
53
- getToken(): Promise<string>;
54
- /** In-flight observation POST count (microtask queue + network). */
55
- get pendingCount(): number;
56
- /**
57
- * Wait for queued observations to finish (Lambda shutdown / test teardown).
58
- * Does not throw when the deadline is hit — best-effort only.
59
- */
60
- flush(timeoutMs?: number): Promise<void>;
61
- private fetchToken;
62
- private exchangeToken;
63
- }
64
- export declare const __test__: {
65
- SDK_VERSION: string;
66
- MAX_QUEUE_DEPTH: number;
67
- };
68
- //# sourceMappingURL=transport.d.ts.map
@@ -1,32 +0,0 @@
1
- /**
2
- * Measures synchronous SDK wrap overhead in the customer process.
3
- *
4
- * All awaited I/O (layer fetch, admit, proxy, provider) must run inside
5
- * `withAwaitExcluded` so RTT is not counted. Sync work before/after those
6
- * hops — token extraction, observation enqueue — is included. The async
7
- * HTTP delivery inside `transport.post`'s microtask is excluded.
8
- */
9
- import type { Observation } from "./types.js";
10
- import type { ObservationTransport } from "./transport.js";
11
- export declare class WrapOverhead {
12
- private readonly hookStart;
13
- private accumulatedMs;
14
- private activeStart;
15
- /** Pause the sync clock before an awaited hop. */
16
- pauseForAwait(): void;
17
- /** Resume the sync clock after an awaited hop returns. */
18
- resumeAfterAwait(): void;
19
- /** Milliseconds of synchronous wrap work (rounded, non-negative). */
20
- sdkAddedMs(): number;
21
- }
22
- /** Run awaited work with wrap clock paused — use for every external I/O hop. */
23
- export declare function withAwaitExcluded<T>(overhead: WrapOverhead, fn: () => Promise<T>): Promise<T>;
24
- /**
25
- * Enqueue an observation with `sdk_added_ms` stamped. Fail-open — never throws.
26
- * Call after building the observation (token extraction included in overhead).
27
- */
28
- export declare function postObservation(transport: ObservationTransport, overhead: WrapOverhead, obs: Observation): void;
29
- export declare const __test__: {
30
- WrapOverhead: typeof WrapOverhead;
31
- };
32
- //# sourceMappingURL=wrap-overhead.d.ts.map
package/dist/wrap.d.ts DELETED
@@ -1,24 +0,0 @@
1
- /**
2
- * The single public entry point: `wrap(client, options?)`.
3
- *
4
- * Returns the SAME client reference (mutates in place), per the SDK
5
- * ergonomics non-negotiable: customer changes one line, no other code
6
- * paths shift.
7
- *
8
- * Control layers:
9
- * off — client returned unchanged (no transport, no hooks)
10
- * observe — telemetry only
11
- * govern — admit (metadata) then direct provider call
12
- * steer/route — proxy in request path (OpenAI / Anthropic only)
13
- */
14
- import { TensorCostConfigError } from "./config.js";
15
- import { layerRank } from "./layer.js";
16
- import type { WrapOptions } from "./types.js";
17
- declare function steerRouteUnsupportedError(provider: string, maxLayer: string): TensorCostConfigError;
18
- export declare function wrap<T>(client: T, options?: WrapOptions): T;
19
- export declare const __test__: {
20
- layerRank: typeof layerRank;
21
- steerRouteUnsupportedError: typeof steerRouteUnsupportedError;
22
- };
23
- export {};
24
- //# sourceMappingURL=wrap.d.ts.map