@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.
package/dist/cli.cjs ADDED
@@ -0,0 +1,895 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/cli.ts
27
+ var import_commander = require("commander");
28
+
29
+ // src/client.ts
30
+ var DEFAULT_BASE_URL = "https://api.tangleai.cloud/v1";
31
+ async function proxiedFetch(privacy, url, init, streaming) {
32
+ if (!privacy || privacy.mode === "direct") {
33
+ return fetch(url, init);
34
+ }
35
+ if (privacy.mode === "relayer") {
36
+ if (!privacy.relayerUrl) {
37
+ throw new Error('relayerUrl is required when privacy mode is "relayer"');
38
+ }
39
+ const proxyPath = streaming ? "/relay/proxy-stream" : "/relay/proxy";
40
+ const hdrs = {};
41
+ if (init.headers) {
42
+ const entries = init.headers instanceof Headers ? Array.from(init.headers.entries()) : Object.entries(init.headers);
43
+ for (const [k, v] of entries) hdrs[k] = v;
44
+ }
45
+ return fetch(`${privacy.relayerUrl}${proxyPath}`, {
46
+ method: "POST",
47
+ headers: { "Content-Type": "application/json" },
48
+ body: JSON.stringify({
49
+ target: url,
50
+ body: typeof init.body === "string" ? JSON.parse(init.body) : init.body,
51
+ headers: hdrs
52
+ })
53
+ });
54
+ }
55
+ if (privacy.mode === "socks5") {
56
+ if (!privacy.socksProxy) {
57
+ throw new Error('socksProxy is required when privacy mode is "socks5"');
58
+ }
59
+ const { SocksProxyAgent } = await import("socks-proxy-agent");
60
+ const agent = new SocksProxyAgent(privacy.socksProxy);
61
+ return fetch(url, {
62
+ ...init,
63
+ // @ts-expect-error agent is supported by Node's undici but not in the standard RequestInit type
64
+ agent
65
+ });
66
+ }
67
+ return fetch(url, init);
68
+ }
69
+ var TCloudClient = class {
70
+ baseURL;
71
+ apiKey;
72
+ model;
73
+ headers;
74
+ spendAuthFn;
75
+ privacy;
76
+ limits;
77
+ _totalSpent = 0;
78
+ _requestCount = 0;
79
+ constructor(config = {}) {
80
+ this.baseURL = (config.baseURL || DEFAULT_BASE_URL).replace(/\/$/, "");
81
+ this.apiKey = config.apiKey || process.env.TCLOUD_API_KEY || process.env.OPENAI_API_KEY;
82
+ this.model = config.model || "gpt-4o-mini";
83
+ this.privacy = config.privacy;
84
+ this.limits = config.limits;
85
+ this.headers = {
86
+ "Content-Type": "application/json",
87
+ "X-Tangle-Client": "tcloud-sdk/0.1.0"
88
+ };
89
+ if (this.apiKey) {
90
+ this.headers["Authorization"] = `Bearer ${this.apiKey}`;
91
+ }
92
+ if (config.routing?.prefer) {
93
+ this.headers["X-Tangle-Operator"] = config.routing.prefer;
94
+ }
95
+ if (config.routing?.region) {
96
+ this.headers["X-Tangle-Region"] = config.routing.region;
97
+ }
98
+ }
99
+ /** Set the SpendAuth signer for private mode */
100
+ setSpendAuthSigner(fn) {
101
+ this.spendAuthFn = fn;
102
+ }
103
+ /** Current metering stats */
104
+ get usage() {
105
+ return {
106
+ totalSpent: this._totalSpent,
107
+ requestCount: this._requestCount,
108
+ limits: this.limits ? { ...this.limits } : void 0
109
+ };
110
+ }
111
+ /** Check spending limits before a request. Throws TCloudError if blocked. */
112
+ checkLimits() {
113
+ if (!this.limits) return;
114
+ if (this.limits.maxRequests && this._requestCount >= this.limits.maxRequests) {
115
+ this.limits.onLimitReached?.({ type: "requests", current: this._requestCount, limit: this.limits.maxRequests });
116
+ throw new TCloudError(429, `Request limit reached (${this._requestCount}/${this.limits.maxRequests})`);
117
+ }
118
+ if (this.limits.maxTotalSpend && this._totalSpent >= this.limits.maxTotalSpend) {
119
+ this.limits.onLimitReached?.({ type: "total", current: this._totalSpent, limit: this.limits.maxTotalSpend });
120
+ throw new TCloudError(429, `Spending limit reached ($${this._totalSpent.toFixed(6)}/$${this.limits.maxTotalSpend})`);
121
+ }
122
+ if (this.limits.maxRequests && this.limits.onLimitWarning) {
123
+ const pct = this._requestCount / this.limits.maxRequests;
124
+ if (pct >= 0.8) this.limits.onLimitWarning({ type: "requests", current: this._requestCount, limit: this.limits.maxRequests });
125
+ }
126
+ if (this.limits.maxTotalSpend && this.limits.onLimitWarning) {
127
+ const pct = this._totalSpent / this.limits.maxTotalSpend;
128
+ if (pct >= 0.8) this.limits.onLimitWarning({ type: "total", current: this._totalSpent, limit: this.limits.maxTotalSpend });
129
+ }
130
+ }
131
+ /** Track cost after a response */
132
+ trackCost(completion) {
133
+ this._requestCount++;
134
+ if (completion.usage) {
135
+ const tokens = completion.usage.total_tokens || 0;
136
+ const estimatedCost = tokens * 1e-6;
137
+ this._totalSpent += estimatedCost;
138
+ if (this.limits?.maxCostPerRequest && estimatedCost > this.limits.maxCostPerRequest) {
139
+ this.limits.onLimitReached?.({ type: "cost", current: estimatedCost, limit: this.limits.maxCostPerRequest });
140
+ }
141
+ }
142
+ }
143
+ /** Chat completion (non-streaming) */
144
+ async chat(options) {
145
+ this.checkLimits();
146
+ const headers = { ...this.headers };
147
+ if (this.spendAuthFn) {
148
+ const auth2 = await this.spendAuthFn();
149
+ headers["X-Payment-Signature"] = JSON.stringify(auth2);
150
+ delete headers["Authorization"];
151
+ }
152
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/chat/completions`, {
153
+ method: "POST",
154
+ headers,
155
+ body: JSON.stringify({
156
+ model: options.model || this.model,
157
+ messages: options.messages,
158
+ temperature: options.temperature,
159
+ max_tokens: options.maxTokens,
160
+ stream: false,
161
+ stop: options.stop,
162
+ top_p: options.topP,
163
+ frequency_penalty: options.frequencyPenalty,
164
+ presence_penalty: options.presencePenalty,
165
+ response_format: options.responseFormat,
166
+ tools: options.tools
167
+ })
168
+ }, false);
169
+ if (!res.ok) {
170
+ const err = await res.json().catch(() => ({ error: res.statusText }));
171
+ throw new TCloudError(res.status, err.error?.message || err.error || err.message || res.statusText);
172
+ }
173
+ const completion = await res.json();
174
+ this.trackCost(completion);
175
+ return completion;
176
+ }
177
+ /** Chat completion (streaming) — returns an async iterator of chunks */
178
+ async *chatStream(options) {
179
+ this.checkLimits();
180
+ const headers = { ...this.headers };
181
+ if (this.spendAuthFn) {
182
+ const auth2 = await this.spendAuthFn();
183
+ headers["X-Payment-Signature"] = JSON.stringify(auth2);
184
+ delete headers["Authorization"];
185
+ }
186
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/chat/completions`, {
187
+ method: "POST",
188
+ headers,
189
+ body: JSON.stringify({
190
+ model: options.model || this.model,
191
+ messages: options.messages,
192
+ temperature: options.temperature,
193
+ max_tokens: options.maxTokens,
194
+ stream: true,
195
+ stop: options.stop,
196
+ top_p: options.topP
197
+ })
198
+ }, true);
199
+ if (!res.ok) {
200
+ const err = await res.json().catch(() => ({ error: res.statusText }));
201
+ throw new TCloudError(res.status, err.error || err.message || res.statusText);
202
+ }
203
+ const reader = res.body.getReader();
204
+ const decoder = new TextDecoder();
205
+ let buf = "";
206
+ while (true) {
207
+ const { done, value } = await reader.read();
208
+ if (done) break;
209
+ buf += decoder.decode(value, { stream: true });
210
+ const lines = buf.split("\n");
211
+ buf = lines.pop() || "";
212
+ for (const line of lines) {
213
+ if (!line.startsWith("data: ")) continue;
214
+ const data = line.slice(6).trim();
215
+ if (data === "[DONE]") {
216
+ this._requestCount++;
217
+ return;
218
+ }
219
+ try {
220
+ yield JSON.parse(data);
221
+ } catch {
222
+ }
223
+ }
224
+ }
225
+ }
226
+ /** Convenience: send a single message and get the text response */
227
+ async ask(message, modelOrOptions) {
228
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
229
+ const completion = await this.chat({
230
+ messages: [{ role: "user", content: message }],
231
+ ...options
232
+ });
233
+ return completion.choices[0]?.message?.content || "";
234
+ }
235
+ /** Convenience: send a single message and get the full completion (with usage) */
236
+ async askFull(message, modelOrOptions) {
237
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
238
+ return this.chat({
239
+ messages: [{ role: "user", content: message }],
240
+ ...options
241
+ });
242
+ }
243
+ /** Convenience: stream a single message and yield text chunks */
244
+ async *askStream(message, modelOrOptions) {
245
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
246
+ for await (const chunk of this.chatStream({
247
+ messages: [{ role: "user", content: message }],
248
+ ...options
249
+ })) {
250
+ const content = chunk.choices[0]?.delta?.content;
251
+ if (content) yield content;
252
+ }
253
+ }
254
+ /** List available models */
255
+ async models() {
256
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/models`, { headers: this.headers }, false);
257
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch models");
258
+ const data = await res.json();
259
+ return data.data || [];
260
+ }
261
+ /** List active operators */
262
+ async operators() {
263
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
264
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/operators`, { headers: this.headers }, false);
265
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch operators");
266
+ return res.json();
267
+ }
268
+ /** Get credit balance */
269
+ async credits() {
270
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
271
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/billing`, { headers: this.headers }, false);
272
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch credits");
273
+ return res.json();
274
+ }
275
+ /** Add credits */
276
+ async addCredits(amount) {
277
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
278
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/billing`, {
279
+ method: "POST",
280
+ headers: this.headers,
281
+ body: JSON.stringify({ amount })
282
+ }, false);
283
+ if (!res.ok) throw new TCloudError(res.status, "Failed to add credits");
284
+ return res.json();
285
+ }
286
+ /** Create a new API key */
287
+ async createKey(name) {
288
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
289
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys`, {
290
+ method: "POST",
291
+ headers: this.headers,
292
+ body: JSON.stringify({ name })
293
+ }, false);
294
+ if (!res.ok) throw new TCloudError(res.status, "Failed to create API key");
295
+ return res.json();
296
+ }
297
+ /** List API keys */
298
+ async keys() {
299
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
300
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys`, { headers: this.headers }, false);
301
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch keys");
302
+ return res.json();
303
+ }
304
+ /** Revoke an API key */
305
+ async revokeKey(id) {
306
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
307
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys/${id}`, {
308
+ method: "DELETE",
309
+ headers: this.headers
310
+ }, false);
311
+ if (!res.ok) throw new TCloudError(res.status, "Failed to revoke key");
312
+ }
313
+ /** Search models by name, provider, or capability */
314
+ async searchModels(query) {
315
+ const all = await this.models();
316
+ const q = query.toLowerCase();
317
+ return all.filter(
318
+ (m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q) || m._provider && m._provider.toLowerCase().includes(q)
319
+ );
320
+ }
321
+ /** Estimate cost for a request (without sending it) */
322
+ async estimateCost(options) {
323
+ const models = await this.models();
324
+ const model = models.find((m) => m.id === (options.model || this.model));
325
+ if (!model) return { inputCost: 0, outputCost: 0, total: 0 };
326
+ const inputCost = options.inputTokens * parseFloat(model.pricing.prompt);
327
+ const outputCost = options.outputTokens * parseFloat(model.pricing.completion);
328
+ return { inputCost, outputCost, total: inputCost + outputCost };
329
+ }
330
+ };
331
+ var TCloudError = class extends Error {
332
+ constructor(status, message) {
333
+ super(message);
334
+ this.status = status;
335
+ this.name = "TCloudError";
336
+ }
337
+ };
338
+
339
+ // src/shielded.ts
340
+ var import_accounts = require("viem/accounts");
341
+ var import_viem = require("viem");
342
+ var SPEND_TYPEHASH = (0, import_viem.keccak256)(
343
+ (0, import_viem.toBytes)(
344
+ "SpendAuthorization(bytes32 commitment,uint64 serviceId,uint8 jobIndex,uint256 amount,address operator,uint256 nonce,uint64 expiry)"
345
+ )
346
+ );
347
+ var DEFAULT_DOMAIN = {
348
+ name: "ShieldedCredits",
349
+ version: "1"
350
+ };
351
+ function generateWallet() {
352
+ const privateKeyBytes = crypto.getRandomValues(new Uint8Array(32));
353
+ const privateKey = "0x" + Array.from(privateKeyBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
354
+ const saltBytes = crypto.getRandomValues(new Uint8Array(32));
355
+ const salt = "0x" + Array.from(saltBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
356
+ const account = (0, import_accounts.privateKeyToAccount)(privateKey);
357
+ const commitment = (0, import_viem.keccak256)(
358
+ (0, import_viem.encodeAbiParameters)(
359
+ (0, import_viem.parseAbiParameters)("address, bytes32"),
360
+ [account.address, salt]
361
+ )
362
+ );
363
+ return { privateKey, address: account.address, commitment, salt };
364
+ }
365
+ async function signSpendAuth(wallet2, params) {
366
+ const account = (0, import_accounts.privateKeyToAccount)(wallet2.privateKey);
367
+ const domainSeparator = (0, import_viem.keccak256)(
368
+ (0, import_viem.encodeAbiParameters)(
369
+ (0, import_viem.parseAbiParameters)("bytes32, bytes32, bytes32, uint256, address"),
370
+ [
371
+ (0, import_viem.keccak256)((0, import_viem.toBytes)("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),
372
+ (0, import_viem.keccak256)((0, import_viem.toBytes)(DEFAULT_DOMAIN.name)),
373
+ (0, import_viem.keccak256)((0, import_viem.toBytes)(DEFAULT_DOMAIN.version)),
374
+ BigInt(params.chainId),
375
+ params.creditsAddress
376
+ ]
377
+ )
378
+ );
379
+ const structHash = (0, import_viem.keccak256)(
380
+ (0, import_viem.encodeAbiParameters)(
381
+ (0, import_viem.parseAbiParameters)("bytes32, bytes32, uint64, uint8, uint256, address, uint256, uint64"),
382
+ [
383
+ SPEND_TYPEHASH,
384
+ wallet2.commitment,
385
+ params.serviceId,
386
+ params.jobIndex,
387
+ params.amount,
388
+ params.operator,
389
+ params.nonce,
390
+ params.expiry
391
+ ]
392
+ )
393
+ );
394
+ const digest = (0, import_viem.keccak256)(
395
+ (0, import_viem.concat)([(0, import_viem.toBytes)("0x1901"), (0, import_viem.toBytes)(domainSeparator), (0, import_viem.toBytes)(structHash)])
396
+ );
397
+ const signature = await account.sign({ hash: digest });
398
+ return {
399
+ commitment: wallet2.commitment,
400
+ serviceId: params.serviceId.toString(),
401
+ jobIndex: params.jobIndex,
402
+ amount: params.amount.toString(),
403
+ operator: params.operator,
404
+ nonce: params.nonce.toString(),
405
+ expiry: params.expiry.toString(),
406
+ signature
407
+ };
408
+ }
409
+ function estimateCost(inputTokens, maxOutputTokens, inputPricePerM = 0.15, outputPricePerM = 0.6) {
410
+ const cost = inputTokens / 1e6 * inputPricePerM + maxOutputTokens / 1e6 * outputPricePerM;
411
+ return BigInt(Math.ceil(cost * 1e6));
412
+ }
413
+ function createShieldedClient(config = {}) {
414
+ const wallet2 = config.wallet || generateWallet();
415
+ const chainId = config.chainId || 3799;
416
+ const creditsAddress = config.creditsAddress || "0x0000000000000000000000000000000000000000";
417
+ const operatorAddress = config.operatorAddress || "0x0000000000000000000000000000000000000000";
418
+ const serviceId = config.serviceId || 1n;
419
+ let nonce = 0n;
420
+ const client = new TCloudClient({
421
+ ...config,
422
+ apiKey: void 0
423
+ // no API key in private mode
424
+ });
425
+ client.setSpendAuthSigner(async () => {
426
+ const currentNonce = nonce++;
427
+ const amount = estimateCost(500, 4096);
428
+ const buffered = amount + amount / 5n;
429
+ return signSpendAuth(wallet2, {
430
+ serviceId,
431
+ jobIndex: 0,
432
+ amount: buffered,
433
+ operator: operatorAddress,
434
+ nonce: currentNonce,
435
+ expiry: BigInt(Math.floor(Date.now() / 1e3) + 300),
436
+ chainId,
437
+ creditsAddress
438
+ });
439
+ });
440
+ const monitor = { lastBalance: 0n, timer: null, replenishing: false };
441
+ if (config.autoReplenish) {
442
+ const ar = config.autoReplenish;
443
+ const intervalMs = ar.checkIntervalMs ?? 3e4;
444
+ const check = async () => {
445
+ try {
446
+ const balance = await fetchBalance(wallet2.commitment, creditsAddress, chainId);
447
+ monitor.lastBalance = balance;
448
+ if (balance < ar.minBalance && !monitor.replenishing) {
449
+ monitor.replenishing = true;
450
+ try {
451
+ if (ar.fundingSource === "relayer") {
452
+ await replenishViaRelayer(ar.relayerUrl, wallet2.commitment, wallet2.privateKey);
453
+ } else {
454
+ await replenishDirect(
455
+ ar.fundingWalletKey,
456
+ ar.tokenAddress,
457
+ ar.replenishAmount,
458
+ wallet2.commitment,
459
+ wallet2.address,
460
+ creditsAddress,
461
+ chainId
462
+ );
463
+ }
464
+ monitor.lastBalance = await fetchBalance(wallet2.commitment, creditsAddress, chainId);
465
+ console.log(`[tcloud/shielded] replenished. balance=${monitor.lastBalance}`);
466
+ } finally {
467
+ monitor.replenishing = false;
468
+ }
469
+ }
470
+ } catch (err) {
471
+ console.error("[tcloud/shielded] auto-replenish error:", err instanceof Error ? err.message : String(err));
472
+ }
473
+ };
474
+ void check();
475
+ monitor.timer = setInterval(() => void check(), intervalMs);
476
+ }
477
+ function stopAutoReplenish() {
478
+ if (monitor.timer) {
479
+ clearInterval(monitor.timer);
480
+ monitor.timer = null;
481
+ }
482
+ }
483
+ return Object.assign(client, { wallet: wallet2, stopAutoReplenish });
484
+ }
485
+ var GET_ACCOUNT_ABI = [{
486
+ type: "function",
487
+ name: "getAccount",
488
+ inputs: [{ name: "commitment", type: "bytes32" }],
489
+ outputs: [{
490
+ name: "",
491
+ type: "tuple",
492
+ components: [
493
+ { name: "spendingKey", type: "address" },
494
+ { name: "token", type: "address" },
495
+ { name: "balance", type: "uint256" },
496
+ { name: "totalFunded", type: "uint256" },
497
+ { name: "totalSpent", type: "uint256" },
498
+ { name: "nonce", type: "uint256" }
499
+ ]
500
+ }],
501
+ stateMutability: "view"
502
+ }];
503
+ var FUND_CREDITS_ABI = [{
504
+ type: "function",
505
+ name: "fundCredits",
506
+ inputs: [
507
+ { name: "token", type: "address" },
508
+ { name: "amount", type: "uint256" },
509
+ { name: "commitment", type: "bytes32" },
510
+ { name: "spendingKey", type: "address" }
511
+ ],
512
+ outputs: [],
513
+ stateMutability: "nonpayable"
514
+ }];
515
+ var ERC20_APPROVE_ABI = [{
516
+ type: "function",
517
+ name: "approve",
518
+ inputs: [
519
+ { name: "spender", type: "address" },
520
+ { name: "amount", type: "uint256" }
521
+ ],
522
+ outputs: [{ name: "", type: "bool" }],
523
+ stateMutability: "nonpayable"
524
+ }];
525
+ function makeChain(chainId, rpcUrl) {
526
+ return {
527
+ id: chainId,
528
+ name: `chain-${chainId}`,
529
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
530
+ rpcUrls: { default: { http: [rpcUrl] } }
531
+ };
532
+ }
533
+ function getRpcUrl(chainId) {
534
+ if (chainId === 3799) return "https://testnet-rpc.tangle.tools";
535
+ if (chainId === 5845) return "https://rpc.tangle.tools";
536
+ return "http://localhost:8545";
537
+ }
538
+ async function fetchBalance(commitment, creditsAddress, chainId) {
539
+ const { createPublicClient, http } = await import("viem");
540
+ const rpcUrl = getRpcUrl(chainId);
541
+ const client = createPublicClient({ chain: makeChain(chainId, rpcUrl), transport: http(rpcUrl) });
542
+ const result = await client.readContract({
543
+ address: creditsAddress,
544
+ abi: GET_ACCOUNT_ABI,
545
+ functionName: "getAccount",
546
+ args: [commitment]
547
+ });
548
+ return result.balance;
549
+ }
550
+ async function replenishViaRelayer(relayerUrl, commitment, spendingKey) {
551
+ const res = await fetch(`${relayerUrl.replace(/\/$/, "")}/relay/fund-credits`, {
552
+ method: "POST",
553
+ headers: { "Content-Type": "application/json" },
554
+ body: JSON.stringify({
555
+ anchorProof: { proof: "0x", auxPublicInputs: "0x", externalData: "0x", publicInputs: "0x", encryptions: "0x" },
556
+ commitment,
557
+ spendingKey
558
+ })
559
+ });
560
+ if (!res.ok) {
561
+ const body = await res.text();
562
+ throw new Error(`relayer fund-credits failed (${res.status}): ${body}`);
563
+ }
564
+ }
565
+ async function replenishDirect(fundingKey, tokenAddress, amount, commitment, spendingKeyAddress, creditsAddress, chainId) {
566
+ const { createPublicClient, createWalletClient, http } = await import("viem");
567
+ const { privateKeyToAccount: toAccount } = await import("viem/accounts");
568
+ const rpcUrl = getRpcUrl(chainId);
569
+ const chain = makeChain(chainId, rpcUrl);
570
+ const account = toAccount(fundingKey);
571
+ const pub = createPublicClient({ chain, transport: http(rpcUrl) });
572
+ const wal = createWalletClient({ account, chain, transport: http(rpcUrl) });
573
+ const approveHash = await wal.writeContract({
574
+ address: tokenAddress,
575
+ abi: ERC20_APPROVE_ABI,
576
+ functionName: "approve",
577
+ args: [creditsAddress, amount]
578
+ });
579
+ await pub.waitForTransactionReceipt({ hash: approveHash });
580
+ const fundHash = await wal.writeContract({
581
+ address: creditsAddress,
582
+ abi: FUND_CREDITS_ABI,
583
+ functionName: "fundCredits",
584
+ args: [tokenAddress, amount, commitment, spendingKeyAddress]
585
+ });
586
+ const receipt = await pub.waitForTransactionReceipt({ hash: fundHash });
587
+ if (receipt.status !== "success") {
588
+ throw new Error(`fundCredits reverted (tx: ${fundHash})`);
589
+ }
590
+ }
591
+
592
+ // src/index.ts
593
+ var TCloud = class _TCloud extends TCloudClient {
594
+ constructor(config) {
595
+ super(config);
596
+ }
597
+ /**
598
+ * Create a standard client with API key authentication.
599
+ *
600
+ * ```ts
601
+ * const client = TCloud.create({ apiKey: 'sk-tan-...' })
602
+ * ```
603
+ */
604
+ static create(config) {
605
+ return new _TCloud(config);
606
+ }
607
+ /**
608
+ * Create a shielded (private) client.
609
+ * Generates an ephemeral wallet and signs SpendAuth automatically.
610
+ * No API key needed. The operator never learns your identity.
611
+ *
612
+ * ```ts
613
+ * const client = TCloud.shielded()
614
+ * const response = await client.ask('Hello from the shadows')
615
+ * console.log(client.wallet.commitment) // anonymous credit account
616
+ * ```
617
+ */
618
+ static shielded(config) {
619
+ return createShieldedClient(config);
620
+ }
621
+ /**
622
+ * Generate a new ephemeral wallet (without creating a client).
623
+ *
624
+ * ```ts
625
+ * const wallet = TCloud.generateWallet()
626
+ * console.log(wallet.address, wallet.commitment)
627
+ * ```
628
+ */
629
+ static generateWallet = generateWallet;
630
+ };
631
+
632
+ // src/cli.ts
633
+ var fs = __toESM(require("fs"), 1);
634
+ var path = __toESM(require("path"), 1);
635
+ var readline = __toESM(require("readline"), 1);
636
+ var CONFIG_DIR = path.join(process.env.HOME || "~", ".tcloud");
637
+ var CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
638
+ var WALLETS_FILE = path.join(CONFIG_DIR, "wallets.json");
639
+ function ensureDir() {
640
+ if (!fs.existsSync(CONFIG_DIR)) fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
641
+ }
642
+ function loadConfig() {
643
+ ensureDir();
644
+ if (fs.existsSync(CONFIG_FILE)) return JSON.parse(fs.readFileSync(CONFIG_FILE, "utf-8"));
645
+ return { apiUrl: "https://api.tangleai.cloud", defaultModel: "gpt-4o-mini", chainId: 3799 };
646
+ }
647
+ function saveConfig(c) {
648
+ ensureDir();
649
+ fs.writeFileSync(CONFIG_FILE, JSON.stringify(c, null, 2), { mode: 384 });
650
+ }
651
+ function loadWallets() {
652
+ ensureDir();
653
+ if (fs.existsSync(WALLETS_FILE)) return JSON.parse(fs.readFileSync(WALLETS_FILE, "utf-8"));
654
+ return [];
655
+ }
656
+ function saveWallets(w) {
657
+ ensureDir();
658
+ fs.writeFileSync(WALLETS_FILE, JSON.stringify(w, null, 2), { mode: 384 });
659
+ }
660
+ function getClient(opts) {
661
+ const config = loadConfig();
662
+ if (opts?.private) {
663
+ const wallets = loadWallets();
664
+ if (wallets.length === 0) {
665
+ console.error("No shielded wallets. Run: tcloud wallet generate");
666
+ process.exit(1);
667
+ }
668
+ return TCloud.shielded({ baseURL: `${config.apiUrl}/v1`, wallet: wallets[0] });
669
+ }
670
+ return new TCloud({ baseURL: `${config.apiUrl}/v1`, apiKey: config.apiKey, model: config.defaultModel });
671
+ }
672
+ var program = new import_commander.Command();
673
+ program.name("tcloud").description("Tangle AI Cloud CLI").version("0.1.0");
674
+ program.command("config").description("View or update configuration").option("--api-url <url>", "API base URL").option("--api-key <key>", "API key").option("--model <model>", "Default model").option("--chain <id>", "Chain ID").action((opts) => {
675
+ const c = loadConfig();
676
+ if (opts.apiUrl) c.apiUrl = opts.apiUrl;
677
+ if (opts.apiKey) c.apiKey = opts.apiKey;
678
+ if (opts.model) c.defaultModel = opts.model;
679
+ if (opts.chain) c.chainId = parseInt(opts.chain);
680
+ saveConfig(c);
681
+ console.log(JSON.stringify(c, null, 2));
682
+ });
683
+ var auth = program.command("auth").description("Authentication");
684
+ auth.command("login").description("Log in via browser (device flow)").action(async () => {
685
+ const config = loadConfig();
686
+ try {
687
+ const res = await fetch(`${config.apiUrl}/api/auth/device`, { method: "POST" });
688
+ if (!res.ok) {
689
+ console.error("Auth server error");
690
+ process.exit(1);
691
+ }
692
+ const d = await res.json();
693
+ console.log(`
694
+ Open: ${d.verification_url}
695
+ Code: ${d.user_code}
696
+
697
+ Waiting...`);
698
+ const deadline = Date.now() + (d.expires_in || 600) * 1e3;
699
+ while (Date.now() < deadline) {
700
+ await new Promise((r2) => setTimeout(r2, (d.interval || 5) * 1e3));
701
+ const r = await fetch(`${config.apiUrl}/api/auth/device/token`, {
702
+ method: "POST",
703
+ headers: { "Content-Type": "application/json" },
704
+ body: JSON.stringify({ device_code: d.device_code })
705
+ });
706
+ const t = await r.json();
707
+ if (t.access_token) {
708
+ config.apiKey = t.access_token;
709
+ saveConfig(config);
710
+ console.log("\n Authenticated!");
711
+ return;
712
+ }
713
+ if (t.error === "expired_token") {
714
+ console.error("\n Code expired.");
715
+ process.exit(1);
716
+ }
717
+ process.stdout.write(".");
718
+ }
719
+ console.error("\n Timed out.");
720
+ } catch (e) {
721
+ console.error("Failed:", e.message);
722
+ }
723
+ });
724
+ auth.command("set-key").description("Set API key directly").argument("<key>").action((key) => {
725
+ const c = loadConfig();
726
+ c.apiKey = key;
727
+ saveConfig(c);
728
+ console.log("API key saved.");
729
+ });
730
+ auth.command("status").description("Show auth status").action(() => {
731
+ const c = loadConfig();
732
+ console.log(c.apiKey ? `Authenticated: ${c.apiKey.slice(0, 15)}...` : "Not authenticated");
733
+ const w = loadWallets();
734
+ if (w.length) console.log(`Shielded wallets: ${w.length}`);
735
+ });
736
+ var wallet = program.command("wallet").description("Shielded wallet management");
737
+ wallet.command("generate").description("Generate ephemeral wallet").option("-l, --label <name>").action((opts) => {
738
+ const w = generateWallet();
739
+ const wallets = loadWallets();
740
+ wallets.push({ ...w, label: opts.label, createdAt: (/* @__PURE__ */ new Date()).toISOString() });
741
+ saveWallets(wallets);
742
+ console.log(`Wallet generated:`);
743
+ console.log(` Address: ${w.address}`);
744
+ console.log(` Commitment: ${w.commitment}`);
745
+ console.log(` Saved to: ${WALLETS_FILE}`);
746
+ console.log(`
747
+ Fund with: tcloud credits fund`);
748
+ });
749
+ wallet.command("list").description("List wallets").action(() => {
750
+ const wallets = loadWallets();
751
+ if (!wallets.length) {
752
+ console.log("No wallets. Run: tcloud wallet generate");
753
+ return;
754
+ }
755
+ wallets.forEach((w, i) => console.log(` [${i}] ${(w.label || "default").padEnd(15)} ${w.commitment.slice(0, 20)}...`));
756
+ });
757
+ program.command("chat").description("Chat with a model").argument("[message]", "Message (or interactive if omitted)").option("-m, --model <model>", "Model").option("--private", "Use shielded credits (anonymous)").option("--stream", "Stream output", true).action(async (message, opts) => {
758
+ const client = getClient({ private: opts.private });
759
+ const model = opts.model || loadConfig().defaultModel;
760
+ if (!message) {
761
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
762
+ console.log(`tcloud chat \u2014 ${model}${opts.private ? " (private)" : ""}
763
+ Ctrl+C to exit.
764
+ `);
765
+ const ask = () => rl.question("> ", async (input) => {
766
+ if (!input.trim()) {
767
+ ask();
768
+ return;
769
+ }
770
+ try {
771
+ for await (const chunk of client.askStream(input.trim(), { model })) {
772
+ process.stdout.write(chunk);
773
+ }
774
+ process.stdout.write("\n\n");
775
+ } catch (e) {
776
+ console.error("Error:", e.message);
777
+ }
778
+ ask();
779
+ });
780
+ ask();
781
+ return;
782
+ }
783
+ try {
784
+ if (opts.stream) {
785
+ for await (const chunk of client.askStream(message, { model })) {
786
+ process.stdout.write(chunk);
787
+ }
788
+ process.stdout.write("\n");
789
+ } else {
790
+ const completion = await client.askFull(message, { model });
791
+ const text = completion.choices[0]?.message?.content || "";
792
+ const usedModel = completion.model || model;
793
+ const usage = completion.usage;
794
+ process.stdout.write(`[${usedModel}] ${text}
795
+ `);
796
+ if (usage) {
797
+ const cost = usage.total_tokens * 1e-6;
798
+ process.stdout.write(` \u21B3 ${usage.total_tokens} tokens \xB7 $${cost.toFixed(6)}
799
+ `);
800
+ }
801
+ }
802
+ } catch (e) {
803
+ console.error("Error:", e.message);
804
+ if (e.status === 402) console.error("Add credits: tcloud credits fund");
805
+ }
806
+ });
807
+ program.command("models").description("List available models").option("-s, --search <query>", "Search").action(async (opts) => {
808
+ const client = getClient();
809
+ try {
810
+ let models = await client.models();
811
+ if (opts.search) {
812
+ const q = opts.search.toLowerCase();
813
+ models = models.filter((m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q));
814
+ }
815
+ console.log(`${models.length} models:`);
816
+ models.slice(0, 30).forEach((m) => console.log(` ${m.id.padEnd(40)} ${m.name || ""}`));
817
+ if (models.length > 30) console.log(` ... +${models.length - 30} more`);
818
+ } catch (e) {
819
+ console.error("Error:", e.message);
820
+ }
821
+ });
822
+ program.command("operators").description("List active operators").action(async () => {
823
+ const client = getClient();
824
+ try {
825
+ const { operators, stats } = await client.operators();
826
+ console.log(`${stats.activeOperators} operators, ${stats.totalModels} models:
827
+ `);
828
+ operators.forEach(
829
+ (o) => console.log(` ${o.slug.padEnd(20)} ${o.status.padEnd(10)} ${String(o.models.length).padEnd(3)} models ${o.reputationScore}% rep ${o.avgLatencyMs}ms`)
830
+ );
831
+ } catch (e) {
832
+ console.error("Error:", e.message);
833
+ }
834
+ });
835
+ var credits = program.command("credits").description("Credit management");
836
+ credits.command("balance").description("Check balance").action(async () => {
837
+ const client = getClient();
838
+ try {
839
+ const data = await client.credits();
840
+ console.log(`Balance: $${data.balance.toFixed(4)}`);
841
+ if (data.transactions.length) {
842
+ console.log("\nRecent transactions:");
843
+ data.transactions.slice(0, 5).forEach(
844
+ (t) => console.log(` ${t.amount > 0 ? "+" : ""}$${Math.abs(t.amount).toFixed(4).padEnd(10)} ${t.description}`)
845
+ );
846
+ }
847
+ } catch (e) {
848
+ console.error("Error:", e.message);
849
+ }
850
+ });
851
+ credits.command("add").description("Add credits").argument("<amount>").action(async (amount) => {
852
+ const client = getClient();
853
+ try {
854
+ const data = await client.addCredits(parseFloat(amount));
855
+ console.log(`Credits added. New balance: $${data.balance.toFixed(4)}`);
856
+ } catch (e) {
857
+ console.error("Error:", e.message);
858
+ }
859
+ });
860
+ credits.command("fund").description("Fund shielded credits from pool").action(() => {
861
+ console.log("Shielded credit funding requires integration with the VAnchor pool.");
862
+ console.log("See: https://docs.tangleai.cloud/privacy/funding");
863
+ });
864
+ var keys = program.command("keys").description("API key management");
865
+ keys.command("create").description("Create API key").argument("<name>").action(async (name) => {
866
+ const config = loadConfig();
867
+ try {
868
+ const res = await fetch(`${config.apiUrl}/api/keys`, {
869
+ method: "POST",
870
+ headers: { "Content-Type": "application/json", ...config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {} },
871
+ body: JSON.stringify({ name })
872
+ });
873
+ const data = await res.json();
874
+ if (data.key) {
875
+ console.log(`Key created: ${data.key}
876
+ Save this \u2014 shown once only.`);
877
+ } else console.error("Error:", data.error);
878
+ } catch (e) {
879
+ console.error("Error:", e.message);
880
+ }
881
+ });
882
+ keys.command("list").description("List API keys").action(async () => {
883
+ const config = loadConfig();
884
+ try {
885
+ const res = await fetch(`${config.apiUrl}/api/keys`, {
886
+ headers: config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}
887
+ });
888
+ const data = await res.json();
889
+ if (data.keys?.length) data.keys.forEach((k) => console.log(` ${k.id.slice(0, 8)} ${k.name.padEnd(20)} ${k.keyPrefix}`));
890
+ else console.log("No keys.");
891
+ } catch (e) {
892
+ console.error("Error:", e.message);
893
+ }
894
+ });
895
+ program.parse();