@latens/sdk 0.0.0-stage → 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LATENS Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,109 @@
1
- # Temporary Holding Version
1
+ # `@latens/sdk`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript SDK, GPU hardware taxonomy normalizer, 15-minute GPU price history client, deterministic LLM VRAM sizing estimator, multi-offer TCO ranker, and `$LTNS` on-chain utility client for the **LATENS Read-Only Agent API v1** ([https://latens.trade](https://latens.trade)).
4
+
5
+ ## Capabilities
6
+
7
+ - **Read-Only Multi-Cloud Discovery with Pagination**: Query and paginate normalized GPU offers across **Vast.ai**, **Runpod**, **CUDO Compute**, **Vultr Cloud GPU**, **Akash Network**, **Lambda Cloud**, **Crusoe Cloud**, and **Scaleway** with `offset`, `limit` (up to 100), `sort` (`price_asc` default, `price_desc`, `vram_desc`), `total`, and `next_offset`.
8
+ - **Genuine Recorded GPU Price History (`getPriceHistory`)**: Fetch real 15-minute, hourly, or daily min/median/max price series from `/api/v1/agent/models/history` across `24h`, `7d`, and `30d` windows with zero backfill and zero interpolation.
9
+ - **Deterministic LLM VRAM Estimator (`estimateLlmVramRequirements`)**: Computes parameter weights, GQA-aware KV cache, LoRA or full fine-tuning optimizer overhead, CUDA headroom, and compatible multi-GPU hardware layouts for any parameter count and quantization (`fp32`, `fp16`, `bf16`, `fp8`, `int8`, `q8_0`, `q4_k_m`, `int4`).
10
+ - **Multi-Offer TCO Ranker (`rankOffersByTco` & `compareLiveOffersForWorkload`)**: Filters out unavailable or catalog-only listings, computes full TCO (hourly compute + persistent storage amortization + outbound egress), applies optional `$LTNS` Private Desk fee schedules, and reports exact savings spread across providers.
11
+ - **$LTNS Holder Standing & Throughput Scaling**: Pass `walletAddress` to attach `X-Latens-Wallet` automatically on every request (scaling rate limits from `60` up to `600` read RPM and `900` calculation RPM on Robinhood Chain `4663`), inspect live wallet standing via `getTokenStanding()`, and compute OTC Desk fee bps deterministically.
12
+ - **Strict Security Boundary**: Read-only client design with zero wallet custody, zero delegated spending, and zero access to encrypted Private Compute Desk payloads.
13
+
14
+ ## Installation
15
+
16
+ Install from npm (zero runtime dependencies):
17
+
18
+ ```bash
19
+ npm install @latens/sdk
20
+ ```
21
+
22
+ Or install directly from GitHub:
23
+
24
+ ```bash
25
+ npm install github:LatensRbh/latens-sdk
26
+ ```
27
+
28
+ ## Quick Start
29
+
30
+ ```ts
31
+ import {
32
+ LatensReadOnlyClient,
33
+ estimateLlmVramRequirements,
34
+ rankOffersByTco,
35
+ } from "@latens/sdk";
36
+
37
+ const client = new LatensReadOnlyClient({
38
+ baseUrl: "https://latens.trade",
39
+ walletAddress: "0xe5e702641ea86f4ae6cc3cdaed2b886f976be044",
40
+ });
41
+
42
+ // 1. Query recorded 15-minute GPU price history
43
+ const history = await client.getPriceHistory({
44
+ model: "H100",
45
+ window: "24h",
46
+ interval: "15m",
47
+ });
48
+ console.log(history.first_recorded_at, history.coverage_hours, history.points);
49
+
50
+ // 2. Paginate through live offers (sorted by price_asc by default)
51
+ const page1 = await client.listOffers({
52
+ min_vram_gb: 80,
53
+ sort: "price_asc",
54
+ offset: 0,
55
+ limit: 100,
56
+ });
57
+ console.log(`Fetched ${page1.count} of ${page1.total} matching offers; next_offset=${page1.next_offset}`);
58
+
59
+ // 3. Size an LLM workload and rank live offers by full TCO
60
+ const sizing = estimateLlmVramRequirements({
61
+ parameterCountBillions: 70,
62
+ quantization: "bf16",
63
+ mode: "inference",
64
+ contextLength: 16384,
65
+ });
66
+
67
+ const ranked = rankOffersByTco(page1.offers, {
68
+ durationHours: 72,
69
+ minTotalVramGb: sizing.recommendedVramGb,
70
+ storageGb: 1000,
71
+ egressGb: 250,
72
+ confirmedOnly: true,
73
+ holderTier: "priority",
74
+ settlementAsset: "LTNS",
75
+ });
76
+
77
+ console.log(sizing.recommendedVramGb, ranked.ranked[0], ranked.spreadMultiplier);
78
+ ```
79
+
80
+ ## `totalOffers` vs `filteredOffers`
81
+
82
+ On `GET /api/v1/agent/status`:
83
+ - `summary.totalOffers` counts all normalized catalog offers across all 8 providers, including currently unavailable listings.
84
+ - `summary.filteredOffers` counts currently available offers (`availability_status != "unavailable"`), matching the exact total returned when paginating through `listOffers()` with default filters (`available_only: true`).
85
+
86
+ ## $LTNS Tier Thresholds (`0x6c29b040f7d139c93d22f8d6e29b1528e3ca4bf9`)
87
+
88
+ | Tier | Holding | OTC Desk Fee | AI Broker (15m) | Agent Read / Calc RPM |
89
+ | :- | :- | :- | :- | :- |
90
+ | **Open Access** (`open`) | `0 $LTNS` | `1.00%` (`100 bps`) | `30` | `60` / `90` |
91
+ | **Verified Holder** (`verified`) | `100,000 $LTNS` | `0.75%` (`75 bps`) | `75` | `150` / `225` |
92
+ | **Priority Desk** (`priority`) | `1,000,000 $LTNS` | `0.50%` (`50 bps`) | `150` | `300` / `450` |
93
+ | **Institutional** (`institutional`) | `5,000,000 $LTNS` | `0.00%` (`0 bps`) | `300` | `600` / `900` |
94
+
95
+ Settling a Private Compute Desk RFQ in `$LTNS` applies an extra `15 bps` (`0.15%`) fee reduction down to a `0 bps` floor.
96
+
97
+ ## Live Endpoints
98
+
99
+ - Base URL: `https://latens.trade`
100
+ - Price History Endpoint: `https://latens.trade/api/v1/agent/models/history?model=H100&window=24h`
101
+ - Utility & Wallet Inspector: `https://latens.trade/utility`
102
+ - OpenAPI 3.1 Specification: `https://latens.trade/api/v1/openapi.json`
103
+ - Changelog & Atom Feed: `https://latens.trade/changelog` · `https://latens.trade/feed.xml`
104
+ - Documentation: `https://latens.trade/docs`
105
+ - Ecosystem Chain: Robinhood Chain (`Chain ID 4663`)
106
+
107
+ ## License
108
+
109
+ MIT
@@ -0,0 +1,2 @@
1
+ import type { ComputeCostBreakdown, ComputeCostInput } from "./types.js";
2
+ export declare function calculateDeterministicComputeCost(input: ComputeCostInput): ComputeCostBreakdown;
@@ -0,0 +1,30 @@
1
+ import { roundUsd } from "./normalizer.js";
2
+ const HOURS_PER_MONTH = 730;
3
+ export function calculateDeterministicComputeCost(input) {
4
+ if (input.hourlyRatePerInstanceUsd < 0) {
5
+ throw new RangeError("hourlyRatePerInstanceUsd must be non-negative.");
6
+ }
7
+ if (input.durationHours <= 0) {
8
+ throw new RangeError("durationHours must be greater than zero.");
9
+ }
10
+ const instances = input.instanceCount ?? 1;
11
+ if (!Number.isInteger(instances) || instances < 1) {
12
+ throw new RangeError("instanceCount must be a positive integer.");
13
+ }
14
+ const computeSubtotal = input.hourlyRatePerInstanceUsd * instances * input.durationHours;
15
+ const storageGb = Math.max(0, input.storageGb ?? 0);
16
+ const storageMonthlyRate = Math.max(0, input.storageCostPerGbMonthUsd ?? 0);
17
+ const storageSubtotal = storageGb * (storageMonthlyRate / HOURS_PER_MONTH) * input.durationHours;
18
+ const egressGb = Math.max(0, input.egressGb ?? 0);
19
+ const egressRate = Math.max(0, input.egressCostPerGbUsd ?? 0);
20
+ const egressSubtotal = egressGb * egressRate;
21
+ const total = computeSubtotal + storageSubtotal + egressSubtotal;
22
+ return {
23
+ computeSubtotalUsd: roundUsd(computeSubtotal, 4),
24
+ storageSubtotalUsd: roundUsd(storageSubtotal, 4),
25
+ egressSubtotalUsd: roundUsd(egressSubtotal, 4),
26
+ totalEstimatedUsd: roundUsd(total, 4),
27
+ effectiveHourlyUsd: roundUsd(total / input.durationHours, 4),
28
+ currency: "USD",
29
+ };
30
+ }
@@ -0,0 +1,78 @@
1
+ import type { AgentCalculateInput, AgentOffersQuery, AgentOffersSort, GpuPriceHistoryQuery, GpuPriceHistoryResponse, HolderTierId, LlmSizingInput, LlmSizingResult, NormalizedGpuOffer, OfferTcoComparisonOptions, OfferTcoComparisonResult, TokenStandingResponse } from "./types.js";
2
+ export interface LatensClientOptions {
3
+ baseUrl?: string;
4
+ walletAddress?: string;
5
+ fetchImpl?: typeof fetch;
6
+ timeoutMs?: number;
7
+ }
8
+ export declare class LatensReadOnlyClient {
9
+ private readonly baseUrl;
10
+ private readonly walletAddress;
11
+ private readonly fetcher;
12
+ private readonly timeoutMs;
13
+ constructor(options?: LatensClientOptions);
14
+ listOffers(query?: AgentOffersQuery): Promise<{
15
+ count: number;
16
+ total: number;
17
+ offset: number;
18
+ limit: number;
19
+ sort: AgentOffersSort;
20
+ next_offset: number | null;
21
+ offers: NormalizedGpuOffer[];
22
+ data: NormalizedGpuOffer[];
23
+ last_synced_at?: string | null;
24
+ }>;
25
+ listModels(): Promise<{
26
+ count: number;
27
+ models: Array<{
28
+ gpu_model: string;
29
+ manufacturer: string;
30
+ available_offer_count: number;
31
+ min_price_per_gpu_usd: number;
32
+ median_price_per_gpu_usd: number;
33
+ vram_per_gpu_gb: number;
34
+ providers: string[];
35
+ }>;
36
+ }>;
37
+ getPriceHistory(query: GpuPriceHistoryQuery): Promise<GpuPriceHistoryResponse>;
38
+ calculateCost(input: AgentCalculateInput): Promise<{
39
+ read_only: boolean;
40
+ deterministic: boolean;
41
+ data: Record<string, unknown>;
42
+ }>;
43
+ getProviderStatus(): Promise<{
44
+ caller_holder_tier?: HolderTierId;
45
+ ecosystem_token?: {
46
+ ticker: string;
47
+ contract_address: string;
48
+ decimals: number;
49
+ total_supply: number;
50
+ wallet_header: string;
51
+ };
52
+ summary: {
53
+ totalOffers: number;
54
+ filteredOffers?: number;
55
+ connectedProviders: number;
56
+ totalProviders: number;
57
+ lastSyncedAt: string | null;
58
+ };
59
+ providers: Array<{
60
+ provider: string;
61
+ status: string;
62
+ offerCount?: number;
63
+ offer_count?: number;
64
+ }>;
65
+ }>;
66
+ getTokenStanding(address?: string, options?: {
67
+ refresh?: boolean;
68
+ }): Promise<TokenStandingResponse>;
69
+ compareLiveOffersForWorkload(params: {
70
+ workload: LlmSizingInput;
71
+ comparison: OfferTcoComparisonOptions;
72
+ query?: AgentOffersQuery;
73
+ }): Promise<{
74
+ sizing: LlmSizingResult;
75
+ comparison: OfferTcoComparisonResult;
76
+ }>;
77
+ private requestJson;
78
+ }
package/dist/client.js ADDED
@@ -0,0 +1,151 @@
1
+ import { estimateLlmVramRequirements, rankOffersByTco } from "./sizing.js";
2
+ import { isValidEvmAddress } from "./standing.js";
3
+ export class LatensReadOnlyClient {
4
+ baseUrl;
5
+ walletAddress;
6
+ fetcher;
7
+ timeoutMs;
8
+ constructor(options) {
9
+ this.baseUrl = (options?.baseUrl ?? "https://latens.trade").replace(/\/+$/, "");
10
+ const candidate = options?.walletAddress?.trim() ?? "";
11
+ this.walletAddress = isValidEvmAddress(candidate) ? candidate : null;
12
+ this.fetcher = options?.fetchImpl ?? fetch;
13
+ this.timeoutMs = options?.timeoutMs ?? 15_000;
14
+ }
15
+ async listOffers(query = {}) {
16
+ const params = new URLSearchParams();
17
+ const resolvedModel = query.model ?? query.gpu_model;
18
+ const resolvedMaxPrice = query.max_price_per_gpu_usd ?? query.max_hourly_usd;
19
+ if (resolvedModel)
20
+ params.set("model", resolvedModel);
21
+ if (query.provider)
22
+ params.set("provider", query.provider);
23
+ if (query.category)
24
+ params.set("category", query.category);
25
+ if (query.min_vram_gb !== undefined)
26
+ params.set("min_vram_gb", String(query.min_vram_gb));
27
+ if (resolvedMaxPrice !== undefined) {
28
+ params.set("max_price_per_gpu_usd", String(resolvedMaxPrice));
29
+ }
30
+ if (query.gpu_count !== undefined)
31
+ params.set("gpu_count", String(query.gpu_count));
32
+ if (query.region)
33
+ params.set("region", query.region);
34
+ if (query.available_only !== undefined) {
35
+ params.set("available_only", query.available_only ? "true" : "false");
36
+ }
37
+ if (query.sort)
38
+ params.set("sort", query.sort);
39
+ if (query.offset !== undefined)
40
+ params.set("offset", String(query.offset));
41
+ if (query.limit !== undefined)
42
+ params.set("limit", String(query.limit));
43
+ const qs = params.toString();
44
+ const raw = await this.requestJson(`/api/v1/agent/offers${qs ? `?${qs}` : ""}`);
45
+ const list = raw.data ?? raw.offers ?? [];
46
+ const offset = raw.offset ?? query.offset ?? 0;
47
+ const limit = raw.limit ?? query.limit ?? 50;
48
+ const total = raw.total ?? list.length;
49
+ const nextOffset = raw.next_offset !== undefined
50
+ ? raw.next_offset
51
+ : offset + list.length < total
52
+ ? offset + list.length
53
+ : null;
54
+ return {
55
+ count: raw.count ?? list.length,
56
+ total,
57
+ offset,
58
+ limit,
59
+ sort: raw.sort ?? query.sort ?? "price_asc",
60
+ next_offset: nextOffset,
61
+ offers: list,
62
+ data: list,
63
+ last_synced_at: raw.last_synced_at,
64
+ };
65
+ }
66
+ async listModels() {
67
+ const raw = await this.requestJson("/api/v1/agent/models");
68
+ const models = raw.data ?? raw.models ?? [];
69
+ return { count: raw.count ?? models.length, models };
70
+ }
71
+ async getPriceHistory(query) {
72
+ const model = query.model?.trim() ?? "";
73
+ if (!model) {
74
+ throw new TypeError("model is required for getPriceHistory()");
75
+ }
76
+ const params = new URLSearchParams();
77
+ params.set("model", model);
78
+ if (query.window)
79
+ params.set("window", query.window);
80
+ if (query.interval)
81
+ params.set("interval", query.interval);
82
+ if (query.category)
83
+ params.set("category", query.category);
84
+ return this.requestJson(`/api/v1/agent/models/history?${params.toString()}`);
85
+ }
86
+ async calculateCost(input) {
87
+ return this.requestJson("/api/v1/agent/calculate", {
88
+ method: "POST",
89
+ body: input,
90
+ });
91
+ }
92
+ async getProviderStatus() {
93
+ return this.requestJson("/api/v1/agent/status");
94
+ }
95
+ async getTokenStanding(address, options) {
96
+ const target = (address ?? this.walletAddress ?? "").trim();
97
+ const params = new URLSearchParams();
98
+ if (target) {
99
+ if (!isValidEvmAddress(target)) {
100
+ throw new TypeError("Invalid 42-character EVM wallet address.");
101
+ }
102
+ params.set("address", target);
103
+ }
104
+ if (options?.refresh) {
105
+ params.set("refresh", "1");
106
+ }
107
+ const qs = params.toString();
108
+ return this.requestJson(`/api/token/standing${qs ? `?${qs}` : ""}`);
109
+ }
110
+ async compareLiveOffersForWorkload(params) {
111
+ const sizing = estimateLlmVramRequirements(params.workload);
112
+ const { offers } = await this.listOffers({
113
+ available_only: params.comparison.availableOnly ?? true,
114
+ limit: params.query?.limit ?? 100,
115
+ ...params.query,
116
+ });
117
+ const comparison = rankOffersByTco(offers, {
118
+ ...params.comparison,
119
+ minTotalVramGb: params.comparison.minTotalVramGb ?? sizing.recommendedVramGb,
120
+ });
121
+ return { sizing, comparison };
122
+ }
123
+ async requestJson(pathname, init) {
124
+ const controller = new AbortController();
125
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
126
+ try {
127
+ const headers = {
128
+ Accept: "application/json",
129
+ };
130
+ if (this.walletAddress) {
131
+ headers["X-Latens-Wallet"] = this.walletAddress;
132
+ }
133
+ if (init?.body !== undefined) {
134
+ headers["Content-Type"] = "application/json";
135
+ }
136
+ const res = await this.fetcher(`${this.baseUrl}${pathname}`, {
137
+ method: init?.method ?? "GET",
138
+ headers,
139
+ body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,
140
+ signal: controller.signal,
141
+ });
142
+ if (!res.ok) {
143
+ throw new Error(`LATENS API HTTP ${res.status} on ${pathname}`);
144
+ }
145
+ return (await res.json());
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ }
150
+ }
151
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./types.js";
2
+ export * from "./normalizer.js";
3
+ export * from "./calculator.js";
4
+ export * from "./standing.js";
5
+ export * from "./sizing.js";
6
+ export * from "./client.js";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./types.js";
2
+ export * from "./normalizer.js";
3
+ export * from "./calculator.js";
4
+ export * from "./standing.js";
5
+ export * from "./sizing.js";
6
+ export * from "./client.js";
@@ -0,0 +1,2 @@
1
+ export declare function normalizeGpuModelName(rawName: string): string;
2
+ export declare function roundUsd(value: number, decimals?: number): number;
@@ -0,0 +1,40 @@
1
+ const MODEL_PATTERNS = [
2
+ [/\bb200\b/i, "B200"],
3
+ [/\bgh200\b/i, "GH200"],
4
+ [/\bh200\b/i, "H200"],
5
+ [/\bh100\b.*\bsxm\b/i, "H100 SXM"],
6
+ [/\bh100\b.*\bpcie\b/i, "H100 PCIe"],
7
+ [/\bh100\b.*\bnvl\b/i, "H100 NVL"],
8
+ [/\bh100\b/i, "H100 SXM"],
9
+ [/\ba100\b.*\bsxm\b/i, "A100 SXM"],
10
+ [/\ba100\b.*\bpcie\b/i, "A100 PCIe"],
11
+ [/\ba100\b/i, "A100 SXM"],
12
+ [/\bmi300x\b/i, "MI300X"],
13
+ [/\bl40s\b/i, "L40S"],
14
+ [/\bl40\b/i, "L40"],
15
+ [/\brtx\s*6000\s*ada\b/i, "RTX 6000 Ada"],
16
+ [/\brtx\s*a6000\b/i, "RTX A6000"],
17
+ [/\brtx\s*5090\b/i, "RTX 5090"],
18
+ [/\brtx\s*4090\b/i, "RTX 4090"],
19
+ [/\brtx\s*3090\b/i, "RTX 3090"],
20
+ [/\ba40\b/i, "A40"],
21
+ [/\bl4\b/i, "L4"],
22
+ ];
23
+ export function normalizeGpuModelName(rawName) {
24
+ const cleaned = rawName
25
+ .replace(/^NVIDIA[\s_-]+/i, "")
26
+ .replace(/^AMD[\s_-]+/i, "")
27
+ .replace(/_/g, " ")
28
+ .replace(/\s+/g, " ")
29
+ .trim();
30
+ for (const [pattern, canonical] of MODEL_PATTERNS) {
31
+ if (pattern.test(cleaned)) {
32
+ return canonical;
33
+ }
34
+ }
35
+ return cleaned || "Unknown GPU";
36
+ }
37
+ export function roundUsd(value, decimals = 4) {
38
+ const factor = 10 ** decimals;
39
+ return Math.round((value + Number.EPSILON) * factor) / factor;
40
+ }
@@ -0,0 +1,13 @@
1
+ import type { LlmSizingInput, LlmSizingResult, NormalizedGpuOffer, OfferTcoComparisonOptions, OfferTcoComparisonResult } from "./types.js";
2
+ /**
3
+ * Deterministically estimate GPU VRAM requirements for LLM inference,
4
+ * LoRA/QLoRA fine-tuning, or full-parameter fine-tuning, and return
5
+ * compatible multi-GPU hardware layouts.
6
+ */
7
+ export declare function estimateLlmVramRequirements(input: LlmSizingInput): LlmSizingResult;
8
+ /**
9
+ * Deterministically rank normalized GPU offers by total cost of ownership
10
+ * (compute + persistent storage + outbound egress), with optional $LTNS
11
+ * Private Compute Desk fee estimation.
12
+ */
13
+ export declare function rankOffersByTco(offers: readonly NormalizedGpuOffer[], options: OfferTcoComparisonOptions): OfferTcoComparisonResult;