@tangle-network/tcloud 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,343 @@
1
+ import { Hex } from 'viem';
2
+
3
+ /** Core types for the tcloud SDK */
4
+ interface TCloudConfig {
5
+ /** API base URL (default: https://api.tangleai.cloud/v1) */
6
+ baseURL?: string;
7
+ /** API key for standard (non-private) mode */
8
+ apiKey?: string;
9
+ /** Default model */
10
+ model?: string;
11
+ /** Operator routing preferences */
12
+ routing?: RoutingConfig;
13
+ /** Enable shielded (private) mode */
14
+ shielded?: ShieldedConfig | boolean;
15
+ /** Privacy proxy configuration for IP hiding */
16
+ privacy?: PrivacyConfig;
17
+ /** Spending limits and metering */
18
+ limits?: SpendingLimits;
19
+ }
20
+ interface SpendingLimits {
21
+ /** Max USD to spend per request. Rejects if estimated cost exceeds this. */
22
+ maxCostPerRequest?: number;
23
+ /** Max USD to spend across all requests in this client's lifetime. Stops at limit. */
24
+ maxTotalSpend?: number;
25
+ /** Max requests allowed. Stops at limit. */
26
+ maxRequests?: number;
27
+ /** Callback when a limit is approached (80% threshold) */
28
+ onLimitWarning?: (info: {
29
+ type: 'cost' | 'total' | 'requests';
30
+ current: number;
31
+ limit: number;
32
+ }) => void;
33
+ /** Callback when a limit is hit (request blocked) */
34
+ onLimitReached?: (info: {
35
+ type: 'cost' | 'total' | 'requests';
36
+ current: number;
37
+ limit: number;
38
+ }) => void;
39
+ }
40
+ interface RoutingConfig {
41
+ /** Preferred operator slug */
42
+ prefer?: string;
43
+ /** Routing strategy */
44
+ strategy?: 'lowest-latency' | 'lowest-price' | 'highest-reputation' | 'round-robin';
45
+ /** Region filter */
46
+ region?: string;
47
+ /** Fallback operator slugs (tried in order) */
48
+ fallback?: string[];
49
+ }
50
+ interface PrivacyConfig {
51
+ /** 'direct' — no proxy (default). 'relayer' — route through tcloud-relayer. 'socks5' — route through SOCKS5 proxy (e.g. Tor). */
52
+ mode: 'direct' | 'relayer' | 'socks5';
53
+ /** Relayer URL for 'relayer' mode (e.g. 'http://localhost:3030') */
54
+ relayerUrl?: string;
55
+ /**
56
+ * SOCKS5 proxy URL for 'socks5' mode (e.g. 'socks5://127.0.0.1:9050' for Tor).
57
+ * Requires `socks-proxy-agent` as an optional peer dependency.
58
+ */
59
+ socksProxy?: string;
60
+ }
61
+ interface ShieldedConfig {
62
+ /** Pre-existing spending private key (hex). If not set, generates ephemeral. */
63
+ spendingKey?: string;
64
+ /** Pre-existing commitment. If not set, derives from key. */
65
+ commitment?: string;
66
+ /** Chain ID (default: 3799 for Tangle testnet) */
67
+ chainId?: number;
68
+ /** ShieldedCredits contract address */
69
+ creditsAddress?: string;
70
+ /** Service ID for the blueprint */
71
+ serviceId?: bigint;
72
+ /** Privacy proxy configuration for IP hiding */
73
+ privacy?: PrivacyConfig;
74
+ }
75
+ interface ChatMessage {
76
+ role: 'system' | 'user' | 'assistant' | 'tool';
77
+ content: string;
78
+ name?: string;
79
+ }
80
+ interface ChatOptions {
81
+ /** Model to use */
82
+ model?: string;
83
+ /** Messages */
84
+ messages: ChatMessage[];
85
+ /** Temperature (0-2) */
86
+ temperature?: number;
87
+ /** Max tokens to generate */
88
+ maxTokens?: number;
89
+ /** Stream response */
90
+ stream?: boolean;
91
+ /** Stop sequences */
92
+ stop?: string | string[];
93
+ /** Top-p sampling */
94
+ topP?: number;
95
+ /** Frequency penalty */
96
+ frequencyPenalty?: number;
97
+ /** Presence penalty */
98
+ presencePenalty?: number;
99
+ /** JSON mode */
100
+ responseFormat?: {
101
+ type: 'text' | 'json_object';
102
+ };
103
+ /** Tools / function calling */
104
+ tools?: any[];
105
+ }
106
+ interface ChatCompletion {
107
+ id: string;
108
+ object: string;
109
+ created: number;
110
+ model: string;
111
+ choices: {
112
+ index: number;
113
+ message: ChatMessage;
114
+ finish_reason: string;
115
+ }[];
116
+ usage?: {
117
+ prompt_tokens: number;
118
+ completion_tokens: number;
119
+ total_tokens: number;
120
+ };
121
+ }
122
+ interface ChatCompletionChunk {
123
+ id: string;
124
+ object: string;
125
+ created: number;
126
+ model: string;
127
+ choices: {
128
+ index: number;
129
+ delta: Partial<ChatMessage>;
130
+ finish_reason: string | null;
131
+ }[];
132
+ }
133
+ interface Model {
134
+ id: string;
135
+ name: string;
136
+ description?: string;
137
+ context_length: number;
138
+ pricing: {
139
+ prompt: string;
140
+ completion: string;
141
+ };
142
+ _provider?: string;
143
+ architecture?: {
144
+ input_modalities?: string[];
145
+ output_modalities?: string[];
146
+ };
147
+ }
148
+ interface Operator {
149
+ id: string;
150
+ slug: string;
151
+ name: string;
152
+ description?: string;
153
+ status: string;
154
+ endpointUrl: string;
155
+ blueprintType: string;
156
+ reputationScore: number;
157
+ uptimePercent: number;
158
+ avgLatencyMs: number;
159
+ totalRequests: number;
160
+ stakeTnt: number;
161
+ models: {
162
+ modelId: string;
163
+ inputPrice: number;
164
+ outputPrice: number;
165
+ }[];
166
+ }
167
+ interface CreditBalance {
168
+ balance: number;
169
+ transactions: {
170
+ id: string;
171
+ amount: number;
172
+ type: string;
173
+ description: string;
174
+ createdAt: string;
175
+ }[];
176
+ }
177
+ interface SpendAuth {
178
+ commitment: string;
179
+ serviceId: string;
180
+ jobIndex: number;
181
+ amount: string;
182
+ operator: string;
183
+ nonce: string;
184
+ expiry: string;
185
+ signature: string;
186
+ }
187
+
188
+ /**
189
+ * Core HTTP client for Tangle AI Cloud.
190
+ * Shared between CLI and SDK.
191
+ */
192
+
193
+ declare class TCloudClient {
194
+ readonly baseURL: string;
195
+ readonly apiKey?: string;
196
+ readonly model: string;
197
+ private headers;
198
+ private spendAuthFn?;
199
+ private privacy?;
200
+ private limits?;
201
+ private _totalSpent;
202
+ private _requestCount;
203
+ constructor(config?: TCloudConfig);
204
+ /** Set the SpendAuth signer for private mode */
205
+ setSpendAuthSigner(fn: () => Promise<SpendAuth>): void;
206
+ /** Current metering stats */
207
+ get usage(): {
208
+ totalSpent: number;
209
+ requestCount: number;
210
+ limits: {
211
+ maxCostPerRequest?: number;
212
+ maxTotalSpend?: number;
213
+ maxRequests?: number;
214
+ onLimitWarning?: (info: {
215
+ type: "cost" | "total" | "requests";
216
+ current: number;
217
+ limit: number;
218
+ }) => void;
219
+ onLimitReached?: (info: {
220
+ type: "cost" | "total" | "requests";
221
+ current: number;
222
+ limit: number;
223
+ }) => void;
224
+ } | undefined;
225
+ };
226
+ /** Check spending limits before a request. Throws TCloudError if blocked. */
227
+ private checkLimits;
228
+ /** Track cost after a response */
229
+ private trackCost;
230
+ /** Chat completion (non-streaming) */
231
+ chat(options: ChatOptions): Promise<ChatCompletion>;
232
+ /** Chat completion (streaming) — returns an async iterator of chunks */
233
+ chatStream(options: ChatOptions): AsyncGenerator<ChatCompletionChunk>;
234
+ /** Convenience: send a single message and get the text response */
235
+ ask(message: string, modelOrOptions?: string | Partial<ChatOptions>): Promise<string>;
236
+ /** Convenience: send a single message and get the full completion (with usage) */
237
+ askFull(message: string, modelOrOptions?: string | Partial<ChatOptions>): Promise<ChatCompletion>;
238
+ /** Convenience: stream a single message and yield text chunks */
239
+ askStream(message: string, modelOrOptions?: string | Partial<ChatOptions>): AsyncGenerator<string>;
240
+ /** List available models */
241
+ models(): Promise<Model[]>;
242
+ /** List active operators */
243
+ operators(): Promise<{
244
+ operators: Operator[];
245
+ stats: any;
246
+ }>;
247
+ /** Get credit balance */
248
+ credits(): Promise<CreditBalance>;
249
+ /** Add credits */
250
+ addCredits(amount: number): Promise<{
251
+ balance: number;
252
+ }>;
253
+ /** Create a new API key */
254
+ createKey(name: string): Promise<{
255
+ key: string;
256
+ id: string;
257
+ }>;
258
+ /** List API keys */
259
+ keys(): Promise<{
260
+ id: string;
261
+ name: string;
262
+ prefix: string;
263
+ createdAt: string;
264
+ lastUsedAt: string | null;
265
+ }[]>;
266
+ /** Revoke an API key */
267
+ revokeKey(id: string): Promise<void>;
268
+ /** Search models by name, provider, or capability */
269
+ searchModels(query: string): Promise<Model[]>;
270
+ /** Estimate cost for a request (without sending it) */
271
+ estimateCost(options: {
272
+ model?: string;
273
+ inputTokens: number;
274
+ outputTokens: number;
275
+ }): Promise<{
276
+ inputCost: number;
277
+ outputCost: number;
278
+ total: number;
279
+ }>;
280
+ }
281
+ declare class TCloudError extends Error {
282
+ status: number;
283
+ constructor(status: number, message: string);
284
+ }
285
+
286
+ /**
287
+ * tcloud/shielded — Ephemeral wallet generation, SpendAuth signing, private inference.
288
+ *
289
+ * import { TCloud } from 'tcloud'
290
+ * const client = TCloud.shielded() // anonymous, no API key
291
+ */
292
+
293
+ interface ShieldedWallet {
294
+ /** Ephemeral spending private key (hex) */
295
+ privateKey: Hex;
296
+ /** Derived address */
297
+ address: string;
298
+ /** Credit account commitment */
299
+ commitment: Hex;
300
+ /** Random salt */
301
+ salt: Hex;
302
+ }
303
+ /** Generate a new ephemeral shielded wallet */
304
+ declare function generateWallet(): ShieldedWallet;
305
+ /** Sign a SpendAuth for a request */
306
+ declare function signSpendAuth(wallet: ShieldedWallet, params: {
307
+ serviceId: bigint;
308
+ jobIndex: number;
309
+ amount: bigint;
310
+ operator: Hex;
311
+ nonce: bigint;
312
+ expiry: bigint;
313
+ chainId: number;
314
+ creditsAddress: Hex;
315
+ }): Promise<SpendAuth>;
316
+ /** Estimate cost in tsUSD base units (6 decimals) */
317
+ declare function estimateCost(inputTokens: number, maxOutputTokens: number, inputPricePerM?: number, outputPricePerM?: number): bigint;
318
+ interface AutoReplenishOptions {
319
+ minBalance: bigint;
320
+ replenishAmount: bigint;
321
+ checkIntervalMs?: number;
322
+ fundingSource: 'relayer' | 'direct';
323
+ relayerUrl?: string;
324
+ fundingWalletKey?: Hex;
325
+ tokenAddress?: Hex;
326
+ }
327
+ /**
328
+ * Create a shielded TCloudClient that signs SpendAuth automatically.
329
+ * Every request is anonymous — no API key, no identity.
330
+ */
331
+ declare function createShieldedClient(config?: TCloudConfig & {
332
+ wallet?: ShieldedWallet;
333
+ operatorAddress?: Hex;
334
+ chainId?: number;
335
+ creditsAddress?: Hex;
336
+ serviceId?: bigint;
337
+ autoReplenish?: AutoReplenishOptions;
338
+ }): TCloudClient & {
339
+ wallet: ShieldedWallet;
340
+ stopAutoReplenish: () => void;
341
+ };
342
+
343
+ export { type AutoReplenishOptions as A, type ChatCompletion as C, type Model as M, type Operator as O, type PrivacyConfig as P, type RoutingConfig as R, type ShieldedWallet as S, TCloudClient as T, type TCloudConfig as a, type ChatCompletionChunk as b, type ChatMessage as c, type ChatOptions as d, type CreditBalance as e, type ShieldedConfig as f, generateWallet as g, type SpendAuth as h, type SpendingLimits as i, TCloudError as j, createShieldedClient as k, estimateCost as l, signSpendAuth as s };