@tangle-network/tcloud 0.1.3 → 0.2.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,976 @@
1
+ // src/private-router.ts
2
+ function secureRandom() {
3
+ const arr = new Uint32Array(1);
4
+ crypto.getRandomValues(arr);
5
+ return arr[0] / (4294967295 + 1);
6
+ }
7
+ var PrivateRouter = class {
8
+ config;
9
+ operators = [];
10
+ usage = /* @__PURE__ */ new Map();
11
+ currentIndex = 0;
12
+ totalRequests = 0;
13
+ constructor(config = {}) {
14
+ this.config = {
15
+ strategy: config.strategy || "round-robin",
16
+ maxRequestsPerOperator: config.maxRequestsPerOperator || 5,
17
+ minOperators: config.minOperators || 3,
18
+ preferRegions: config.preferRegions,
19
+ excludeOperators: config.excludeOperators,
20
+ summarizeOnSwitch: config.summarizeOnSwitch ?? false
21
+ };
22
+ }
23
+ /** Set the available operator pool */
24
+ setOperators(operators) {
25
+ let filtered = operators.filter(
26
+ (o) => !this.config.excludeOperators?.includes(o.slug)
27
+ );
28
+ if (this.config.preferRegions?.length) {
29
+ filtered.sort((a, b) => {
30
+ const aPreferred = this.config.preferRegions.includes(a.region) ? 0 : 1;
31
+ const bPreferred = this.config.preferRegions.includes(b.region) ? 0 : 1;
32
+ return aPreferred - bPreferred;
33
+ });
34
+ }
35
+ this.operators = filtered;
36
+ }
37
+ /** Select the next operator for a request */
38
+ selectOperator(model) {
39
+ const eligible = this.operators.filter((o) => o.models.includes(model));
40
+ if (eligible.length === 0) return null;
41
+ if (eligible.length < this.config.minOperators) {
42
+ console.warn(
43
+ `[PrivateRouter] Only ${eligible.length} eligible operator(s) for model "${model}", but minOperators requires ${this.config.minOperators}. Refusing to route.`
44
+ );
45
+ return null;
46
+ }
47
+ this.totalRequests++;
48
+ switch (this.config.strategy) {
49
+ case "round-robin":
50
+ return this.roundRobin(eligible);
51
+ case "random":
52
+ return this.random(eligible);
53
+ case "geo-distributed":
54
+ return this.geoDistributed(eligible);
55
+ case "min-exposure":
56
+ return this.minExposure(eligible);
57
+ case "latency-aware":
58
+ return this.latencyAware(eligible);
59
+ default:
60
+ return this.roundRobin(eligible);
61
+ }
62
+ }
63
+ /** Should we summarize context before this request? (operator is changing) */
64
+ shouldSummarize(model) {
65
+ if (!this.config.summarizeOnSwitch) return false;
66
+ const next = this.peekNextOperator(model);
67
+ const last = this.getLastUsedOperator();
68
+ return next !== null && last !== null && next.slug !== last.slug;
69
+ }
70
+ /** Get privacy stats */
71
+ getStats() {
72
+ return {
73
+ totalRequests: this.totalRequests,
74
+ operatorsUsed: this.usage.size,
75
+ operatorBreakdown: Array.from(this.usage.values()).map((u) => ({
76
+ slug: u.slug,
77
+ requests: u.requestCount,
78
+ lastUsed: u.lastUsedAt
79
+ })),
80
+ strategy: this.config.strategy
81
+ };
82
+ }
83
+ // ─── Strategies ────────────────────────────────────────────
84
+ roundRobin(eligible) {
85
+ const op = eligible[this.currentIndex % eligible.length];
86
+ this.currentIndex++;
87
+ this.recordUsage(op);
88
+ return op;
89
+ }
90
+ random(eligible) {
91
+ const idx = Math.floor(secureRandom() * eligible.length);
92
+ const op = eligible[idx];
93
+ this.recordUsage(op);
94
+ return op;
95
+ }
96
+ geoDistributed(eligible) {
97
+ const regionUsage = /* @__PURE__ */ new Map();
98
+ for (const op2 of eligible) {
99
+ const usage = this.usage.get(op2.slug)?.requestCount || 0;
100
+ const current = regionUsage.get(op2.region) || 0;
101
+ regionUsage.set(op2.region, current + usage);
102
+ }
103
+ const sortedRegions = [...regionUsage.entries()].sort((a, b) => a[1] - b[1]);
104
+ const targetRegion = sortedRegions[0]?.[0];
105
+ const regionOps = eligible.filter((o) => o.region === targetRegion);
106
+ const op = regionOps[Math.floor(secureRandom() * regionOps.length)] || eligible[0];
107
+ this.recordUsage(op);
108
+ return op;
109
+ }
110
+ minExposure(eligible) {
111
+ const lastUsed = this.getLastUsedOperator();
112
+ if (lastUsed) {
113
+ const lastUsage = this.usage.get(lastUsed.slug);
114
+ const others = eligible.filter((o) => o.slug !== lastUsed.slug);
115
+ if (others.length > 0 && lastUsage && lastUsage.requestCount > 0) {
116
+ const sorted2 = others.sort(
117
+ (a, b) => (this.usage.get(a.slug)?.requestCount || 0) - (this.usage.get(b.slug)?.requestCount || 0)
118
+ );
119
+ const op2 = sorted2[0];
120
+ this.recordUsage(op2);
121
+ return op2;
122
+ }
123
+ }
124
+ const sorted = [...eligible].sort(
125
+ (a, b) => (this.usage.get(a.slug)?.requestCount || 0) - (this.usage.get(b.slug)?.requestCount || 0)
126
+ );
127
+ const op = sorted[0];
128
+ this.recordUsage(op);
129
+ return op;
130
+ }
131
+ latencyAware(eligible) {
132
+ const weights = eligible.map((o) => {
133
+ const latencyWeight = 1 / Math.max(o.avgLatencyMs, 10);
134
+ const usagePenalty = (this.usage.get(o.slug)?.requestCount || 0) * 0.1;
135
+ return Math.max(latencyWeight - usagePenalty, 0.01);
136
+ });
137
+ const totalWeight = weights.reduce((s, w) => s + w, 0);
138
+ let r = secureRandom() * totalWeight;
139
+ for (let i = 0; i < eligible.length; i++) {
140
+ r -= weights[i];
141
+ if (r <= 0) {
142
+ this.recordUsage(eligible[i]);
143
+ return eligible[i];
144
+ }
145
+ }
146
+ const op = eligible[eligible.length - 1];
147
+ this.recordUsage(op);
148
+ return op;
149
+ }
150
+ // ─── Helpers ───────────────────────────────────────────────
151
+ recordUsage(op) {
152
+ const existing = this.usage.get(op.slug);
153
+ this.usage.set(op.slug, {
154
+ slug: op.slug,
155
+ requestCount: (existing?.requestCount || 0) + 1,
156
+ lastUsedAt: Date.now()
157
+ });
158
+ }
159
+ getLastUsedOperator() {
160
+ let latest = null;
161
+ for (const u of this.usage.values()) {
162
+ if (!latest || u.lastUsedAt > latest.lastUsedAt) latest = u;
163
+ }
164
+ if (!latest) return null;
165
+ return this.operators.find((o) => o.slug === latest.slug) || null;
166
+ }
167
+ peekNextOperator(model) {
168
+ const eligible = this.operators.filter((o) => o.models.includes(model));
169
+ if (eligible.length === 0) return null;
170
+ if (eligible.length < this.config.minOperators) return null;
171
+ const last = this.getLastUsedOperator();
172
+ switch (this.config.strategy) {
173
+ case "round-robin":
174
+ return eligible[this.currentIndex % eligible.length];
175
+ case "min-exposure": {
176
+ if (last) {
177
+ const lastUsage = this.usage.get(last.slug);
178
+ const others = eligible.filter((o) => o.slug !== last.slug);
179
+ if (others.length > 0 && lastUsage && lastUsage.requestCount > 0) {
180
+ const sorted2 = others.sort(
181
+ (a, b) => (this.usage.get(a.slug)?.requestCount || 0) - (this.usage.get(b.slug)?.requestCount || 0)
182
+ );
183
+ return sorted2[0];
184
+ }
185
+ }
186
+ const sorted = [...eligible].sort(
187
+ (a, b) => (this.usage.get(a.slug)?.requestCount || 0) - (this.usage.get(b.slug)?.requestCount || 0)
188
+ );
189
+ return sorted[0];
190
+ }
191
+ case "geo-distributed": {
192
+ const regionUsage = /* @__PURE__ */ new Map();
193
+ for (const op of eligible) {
194
+ const usage = this.usage.get(op.slug)?.requestCount || 0;
195
+ const current = regionUsage.get(op.region) || 0;
196
+ regionUsage.set(op.region, current + usage);
197
+ }
198
+ const sortedRegions = [...regionUsage.entries()].sort((a, b) => a[1] - b[1]);
199
+ const targetRegion = sortedRegions[0]?.[0];
200
+ const regionOps = eligible.filter((o) => o.region === targetRegion);
201
+ return regionOps[0] || eligible[0];
202
+ }
203
+ case "random":
204
+ case "latency-aware":
205
+ default:
206
+ if (last && eligible.length > 1) {
207
+ return eligible.find((o) => o.slug !== last.slug) || eligible[0];
208
+ }
209
+ return eligible[0];
210
+ }
211
+ }
212
+ };
213
+
214
+ // src/client.ts
215
+ var DEFAULT_BASE_URL = "https://router.tangle.tools/v1";
216
+ async function proxiedFetch(privacy, url, init, streaming) {
217
+ if (!privacy || privacy.mode === "direct") {
218
+ return fetch(url, init);
219
+ }
220
+ if (privacy.mode === "relayer") {
221
+ if (!privacy.relayerUrl) {
222
+ throw new Error('relayerUrl is required when privacy mode is "relayer"');
223
+ }
224
+ const proxyPath = streaming ? "/relay/proxy-stream" : "/relay/proxy";
225
+ const hdrs = {};
226
+ if (init.headers) {
227
+ const entries = init.headers instanceof Headers ? Array.from(init.headers.entries()) : Object.entries(init.headers);
228
+ for (const [k, v] of entries) hdrs[k] = v;
229
+ }
230
+ return fetch(`${privacy.relayerUrl}${proxyPath}`, {
231
+ method: "POST",
232
+ headers: { "Content-Type": "application/json" },
233
+ body: JSON.stringify({
234
+ target: url,
235
+ body: typeof init.body === "string" ? JSON.parse(init.body) : init.body,
236
+ headers: hdrs
237
+ })
238
+ });
239
+ }
240
+ if (privacy.mode === "socks5") {
241
+ if (!privacy.socksProxy) {
242
+ throw new Error('socksProxy is required when privacy mode is "socks5"');
243
+ }
244
+ const { SocksProxyAgent } = await import("socks-proxy-agent");
245
+ const agent = new SocksProxyAgent(privacy.socksProxy);
246
+ return fetch(url, {
247
+ ...init,
248
+ // @ts-expect-error agent is supported by Node's undici but not in the standard RequestInit type
249
+ agent
250
+ });
251
+ }
252
+ return fetch(url, init);
253
+ }
254
+ var DEFAULT_RETRY = {
255
+ maxRetries: 3,
256
+ initialBackoffMs: 500,
257
+ maxBackoffMs: 3e4,
258
+ multiplier: 2,
259
+ retryableStatuses: [429, 500, 502, 503, 504]
260
+ };
261
+ var DEFAULT_TIMEOUT_MS = 6e4;
262
+ var TCloudClient = class _TCloudClient {
263
+ baseURL;
264
+ apiKey;
265
+ model;
266
+ headers;
267
+ spendAuthFn;
268
+ privacy;
269
+ limits;
270
+ retryConfig;
271
+ timeoutMs;
272
+ _totalSpent = 0;
273
+ _requestCount = 0;
274
+ privateRouter;
275
+ _cachedOperators = [];
276
+ _operatorsCachedAt = 0;
277
+ static OPERATORS_TTL_MS = 5 * 60 * 1e3;
278
+ constructor(config = {}) {
279
+ this.baseURL = (config.baseURL || DEFAULT_BASE_URL).replace(/\/$/, "");
280
+ this.apiKey = config.apiKey || process.env.TCLOUD_API_KEY;
281
+ this.model = config.model || "gpt-4o-mini";
282
+ this.privacy = config.privacy;
283
+ this.limits = config.limits;
284
+ this.retryConfig = config.retry === false ? null : { ...DEFAULT_RETRY, ...config.retry };
285
+ this.timeoutMs = config.timeout ?? DEFAULT_TIMEOUT_MS;
286
+ this.headers = {
287
+ "Content-Type": "application/json",
288
+ "X-Tangle-Client": "tcloud-sdk/0.2.0"
289
+ };
290
+ if (this.apiKey) {
291
+ this.headers["Authorization"] = `Bearer ${this.apiKey}`;
292
+ }
293
+ if (config.routing?.mode) {
294
+ this.headers["X-Tangle-Routing"] = config.routing.mode;
295
+ }
296
+ if (config.routing?.prefer) {
297
+ this.headers["X-Tangle-Operator"] = config.routing.prefer;
298
+ }
299
+ if (config.routing?.blueprintId) {
300
+ this.headers["X-Tangle-Blueprint"] = config.routing.blueprintId;
301
+ }
302
+ if (config.routing?.serviceId) {
303
+ this.headers["X-Tangle-Service"] = config.routing.serviceId;
304
+ }
305
+ if (config.routing?.region) {
306
+ this.headers["X-Tangle-Region"] = config.routing.region;
307
+ }
308
+ if (config.routing?.strategy) {
309
+ const strategyMap = {
310
+ "round-robin": "round-robin",
311
+ "lowest-latency": "latency-aware",
312
+ "lowest-price": "round-robin",
313
+ "highest-reputation": "round-robin"
314
+ };
315
+ this.privateRouter = new PrivateRouter({
316
+ strategy: strategyMap[config.routing.strategy] || "round-robin"
317
+ });
318
+ }
319
+ }
320
+ /** Set the SpendAuth signer for private mode */
321
+ setSpendAuthSigner(fn) {
322
+ this.spendAuthFn = fn;
323
+ }
324
+ /** Current metering stats */
325
+ get usage() {
326
+ return {
327
+ totalSpent: this._totalSpent,
328
+ requestCount: this._requestCount,
329
+ limits: this.limits ? { ...this.limits } : void 0
330
+ };
331
+ }
332
+ /** Check spending limits before a request. Throws TCloudError if blocked. */
333
+ checkLimits() {
334
+ if (!this.limits) return;
335
+ if (this.limits.maxRequests && this._requestCount >= this.limits.maxRequests) {
336
+ this.limits.onLimitReached?.({ type: "requests", current: this._requestCount, limit: this.limits.maxRequests });
337
+ throw new TCloudError(429, `Request limit reached (${this._requestCount}/${this.limits.maxRequests})`);
338
+ }
339
+ if (this.limits.maxTotalSpend && this._totalSpent >= this.limits.maxTotalSpend) {
340
+ this.limits.onLimitReached?.({ type: "total", current: this._totalSpent, limit: this.limits.maxTotalSpend });
341
+ throw new TCloudError(429, `Spending limit reached ($${this._totalSpent.toFixed(6)}/$${this.limits.maxTotalSpend})`);
342
+ }
343
+ if (this.limits.maxRequests && this.limits.onLimitWarning) {
344
+ const pct = this._requestCount / this.limits.maxRequests;
345
+ if (pct >= 0.8) this.limits.onLimitWarning({ type: "requests", current: this._requestCount, limit: this.limits.maxRequests });
346
+ }
347
+ if (this.limits.maxTotalSpend && this.limits.onLimitWarning) {
348
+ const pct = this._totalSpent / this.limits.maxTotalSpend;
349
+ if (pct >= 0.8) this.limits.onLimitWarning({ type: "total", current: this._totalSpent, limit: this.limits.maxTotalSpend });
350
+ }
351
+ }
352
+ /** Ensure the private router has operators loaded (with TTL-based caching) */
353
+ async ensureRouterOperators() {
354
+ if (!this.privateRouter) return;
355
+ const now = Date.now();
356
+ if (this._cachedOperators.length > 0 && now - this._operatorsCachedAt < _TCloudClient.OPERATORS_TTL_MS) {
357
+ return;
358
+ }
359
+ const data = await this.operators();
360
+ this._cachedOperators = (data.operators || []).map((op) => ({
361
+ slug: op.slug,
362
+ endpointUrl: op.endpointUrl,
363
+ region: "",
364
+ reputationScore: op.reputationScore,
365
+ avgLatencyMs: op.avgLatencyMs,
366
+ models: op.models.map((m) => m.modelId)
367
+ }));
368
+ this._operatorsCachedAt = now;
369
+ this.privateRouter.setOperators(this._cachedOperators);
370
+ }
371
+ /** Track cost after a response, using actual pricing from response headers when available */
372
+ trackCost(completion, res) {
373
+ this._requestCount++;
374
+ if (completion.usage) {
375
+ let estimatedCost;
376
+ const inputPrice = res ? parseFloat(res.headers.get("x-tangle-price-input") || "0") : 0;
377
+ const outputPrice = res ? parseFloat(res.headers.get("x-tangle-price-output") || "0") : 0;
378
+ if (inputPrice > 0 || outputPrice > 0) {
379
+ estimatedCost = (completion.usage.prompt_tokens || 0) * inputPrice + (completion.usage.completion_tokens || 0) * outputPrice;
380
+ } else {
381
+ const tokens = completion.usage.total_tokens || 0;
382
+ estimatedCost = tokens * 1e-6;
383
+ }
384
+ this._totalSpent += estimatedCost;
385
+ if (this.limits?.maxCostPerRequest && estimatedCost > this.limits.maxCostPerRequest) {
386
+ this.limits.onLimitReached?.({ type: "cost", current: estimatedCost, limit: this.limits.maxCostPerRequest });
387
+ }
388
+ }
389
+ }
390
+ /**
391
+ * Core fetch with retry + timeout. All helpers build on this.
392
+ * Retries on retryable status codes with exponential backoff + jitter.
393
+ */
394
+ async _doFetch(url, init, streaming) {
395
+ const retry = this.retryConfig;
396
+ const maxAttempts = retry ? retry.maxRetries + 1 : 1;
397
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
398
+ const controller = new AbortController();
399
+ let timer;
400
+ if (this.timeoutMs > 0 && !streaming) {
401
+ timer = setTimeout(() => controller.abort(), this.timeoutMs);
402
+ }
403
+ try {
404
+ const res = await proxiedFetch(this.privacy, url, {
405
+ ...init,
406
+ signal: controller.signal
407
+ }, streaming);
408
+ if (res.ok) return res;
409
+ if (retry && attempt < retry.maxRetries && retry.retryableStatuses.includes(res.status)) {
410
+ const backoff = Math.min(
411
+ retry.initialBackoffMs * Math.pow(retry.multiplier, attempt),
412
+ retry.maxBackoffMs
413
+ );
414
+ const jitter = backoff * 0.5 * Math.random();
415
+ await new Promise((r) => setTimeout(r, backoff + jitter));
416
+ continue;
417
+ }
418
+ const err = await res.json().catch(() => ({ error: res.statusText }));
419
+ throw new TCloudError(res.status, err.error?.message || err.error || err.message || res.statusText);
420
+ } catch (e) {
421
+ if (e instanceof TCloudError) throw e;
422
+ if (retry && attempt < retry.maxRetries) {
423
+ const backoff = Math.min(
424
+ retry.initialBackoffMs * Math.pow(retry.multiplier, attempt),
425
+ retry.maxBackoffMs
426
+ );
427
+ await new Promise((r) => setTimeout(r, backoff));
428
+ continue;
429
+ }
430
+ if (e?.name === "AbortError") {
431
+ throw new TCloudError(408, `Request timed out after ${this.timeoutMs}ms`);
432
+ }
433
+ throw new TCloudError(0, e?.message || "Network error");
434
+ } finally {
435
+ if (timer !== void 0) clearTimeout(timer);
436
+ }
437
+ }
438
+ throw new TCloudError(0, "Retry loop exhausted");
439
+ }
440
+ /**
441
+ * Shared request helper for billable JSON API calls.
442
+ * Enforces: checkLimits → fetch with retry/timeout → error parsing → requestCount.
443
+ */
444
+ async _request(url, init = {}) {
445
+ this.checkLimits();
446
+ const res = await this._doFetch(url, { headers: this.headers, ...init }, false);
447
+ this._requestCount++;
448
+ return res.json();
449
+ }
450
+ /**
451
+ * Shared request helper for read-only/non-billable JSON API calls.
452
+ * No limits check, no request counting.
453
+ */
454
+ async _fetch(url, init = {}) {
455
+ const res = await this._doFetch(url, { headers: this.headers, ...init }, false);
456
+ return res.json();
457
+ }
458
+ /**
459
+ * Shared request helper for billable calls that return non-JSON (e.g. ArrayBuffer).
460
+ */
461
+ async _requestRaw(url, init = {}) {
462
+ this.checkLimits();
463
+ const res = await this._doFetch(url, { headers: this.headers, ...init }, false);
464
+ this._requestCount++;
465
+ return res;
466
+ }
467
+ /**
468
+ * Prepare headers for chat requests — operator routing + SpendAuth.
469
+ * Shared between chat() and chatStream() to eliminate duplication.
470
+ */
471
+ async _prepareChatRequest(model) {
472
+ const headers = { ...this.headers };
473
+ if (this.spendAuthFn) {
474
+ const auth = await this.spendAuthFn();
475
+ headers["X-Payment-Signature"] = JSON.stringify(auth);
476
+ delete headers["Authorization"];
477
+ }
478
+ let baseURL = this.baseURL;
479
+ if (this.privateRouter) {
480
+ await this.ensureRouterOperators();
481
+ const operator = this.privateRouter.selectOperator(model);
482
+ if (operator) {
483
+ baseURL = operator.endpointUrl.replace(/\/$/, "");
484
+ headers["X-Tangle-Operator"] = operator.slug;
485
+ delete headers["Authorization"];
486
+ }
487
+ }
488
+ return { headers, baseURL };
489
+ }
490
+ /** Build the chat completions request body */
491
+ _chatBody(options, stream) {
492
+ return JSON.stringify({
493
+ model: options.model || this.model,
494
+ messages: options.messages,
495
+ temperature: options.temperature,
496
+ max_tokens: options.maxTokens,
497
+ stream,
498
+ stop: options.stop,
499
+ top_p: options.topP,
500
+ frequency_penalty: options.frequencyPenalty,
501
+ presence_penalty: options.presencePenalty,
502
+ response_format: options.responseFormat,
503
+ tools: options.tools,
504
+ tool_choice: options.toolChoice,
505
+ ...options.providerOptions
506
+ });
507
+ }
508
+ /** Chat completion (non-streaming) */
509
+ async chat(options) {
510
+ this.checkLimits();
511
+ const { headers, baseURL } = await this._prepareChatRequest(options.model || this.model);
512
+ const res = await this._doFetch(`${baseURL}/chat/completions`, {
513
+ method: "POST",
514
+ headers,
515
+ body: this._chatBody(options, false)
516
+ }, false);
517
+ const completion = await res.json();
518
+ this.trackCost(completion, res);
519
+ return completion;
520
+ }
521
+ /** Chat completion (streaming) — returns an async iterator of chunks */
522
+ async *chatStream(options) {
523
+ this.checkLimits();
524
+ this._requestCount++;
525
+ const { headers, baseURL } = await this._prepareChatRequest(options.model || this.model);
526
+ const res = await this._doFetch(`${baseURL}/chat/completions`, {
527
+ method: "POST",
528
+ headers,
529
+ body: this._chatBody(options, true)
530
+ }, true);
531
+ const reader = res.body.getReader();
532
+ const decoder = new TextDecoder();
533
+ let buf = "";
534
+ while (true) {
535
+ const { done, value } = await reader.read();
536
+ if (done) break;
537
+ buf += decoder.decode(value, { stream: true });
538
+ if (buf.length > 1048576) throw new TCloudError(502, "SSE buffer overflow \u2014 server sent >1MB without newline");
539
+ const lines = buf.split("\n");
540
+ buf = lines.pop() || "";
541
+ for (const line of lines) {
542
+ if (!line.startsWith("data: ")) continue;
543
+ const data = line.slice(6).trim();
544
+ if (data === "[DONE]") {
545
+ return;
546
+ }
547
+ try {
548
+ yield JSON.parse(data);
549
+ } catch {
550
+ }
551
+ }
552
+ }
553
+ }
554
+ /** Convenience: send a single message and get the text response */
555
+ async ask(message, modelOrOptions) {
556
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
557
+ const completion = await this.chat({
558
+ messages: [{ role: "user", content: message }],
559
+ ...options
560
+ });
561
+ return completion.choices[0]?.message?.content || "";
562
+ }
563
+ /** Convenience: send a single message and get the full completion (with usage) */
564
+ async askFull(message, modelOrOptions) {
565
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
566
+ return this.chat({
567
+ messages: [{ role: "user", content: message }],
568
+ ...options
569
+ });
570
+ }
571
+ /** Convenience: stream a single message and yield text chunks */
572
+ async *askStream(message, modelOrOptions) {
573
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
574
+ for await (const chunk of this.chatStream({
575
+ messages: [{ role: "user", content: message }],
576
+ ...options
577
+ })) {
578
+ const content = chunk.choices[0]?.delta?.content;
579
+ if (content) yield content;
580
+ }
581
+ }
582
+ /** List available models */
583
+ async models() {
584
+ const data = await this._fetch(`${this.baseURL}/models`);
585
+ return data.data || [];
586
+ }
587
+ /** List active operators */
588
+ async operators() {
589
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
590
+ return this._fetch(`${apiRoot}/api/operators`);
591
+ }
592
+ /** Get credit balance */
593
+ async credits() {
594
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
595
+ return this._fetch(`${apiRoot}/api/billing`);
596
+ }
597
+ /** Add credits */
598
+ async addCredits(amount) {
599
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
600
+ return this._fetch(`${apiRoot}/api/billing`, {
601
+ method: "POST",
602
+ body: JSON.stringify({ amount })
603
+ });
604
+ }
605
+ /** Create a new API key */
606
+ async createKey(name) {
607
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
608
+ return this._fetch(`${apiRoot}/api/keys`, {
609
+ method: "POST",
610
+ body: JSON.stringify({ name })
611
+ });
612
+ }
613
+ /** List API keys */
614
+ async keys() {
615
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
616
+ return this._fetch(`${apiRoot}/api/keys`);
617
+ }
618
+ /** Revoke an API key */
619
+ async revokeKey(id) {
620
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
621
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys/${id}`, {
622
+ method: "DELETE",
623
+ headers: this.headers
624
+ }, false);
625
+ if (!res.ok) {
626
+ const err = await res.json().catch(() => ({ error: res.statusText }));
627
+ throw new TCloudError(res.status, err.error?.message || err.error || err.message || res.statusText);
628
+ }
629
+ }
630
+ /** Generate embeddings */
631
+ async embeddings(options) {
632
+ return this._request(`${this.baseURL}/embeddings`, {
633
+ method: "POST",
634
+ body: JSON.stringify({
635
+ model: options.model || "text-embedding-3-small",
636
+ input: options.input
637
+ })
638
+ });
639
+ }
640
+ /** Generate images */
641
+ async imageGenerate(options) {
642
+ return this._request(`${this.baseURL}/images/generations`, {
643
+ method: "POST",
644
+ body: JSON.stringify({
645
+ model: options.model || "dall-e-3",
646
+ prompt: options.prompt,
647
+ n: options.n,
648
+ size: options.size,
649
+ quality: options.quality,
650
+ response_format: options.response_format
651
+ })
652
+ });
653
+ }
654
+ /** Rerank documents by relevance to a query */
655
+ async rerank(options) {
656
+ return this._request(`${this.baseURL}/rerank`, {
657
+ method: "POST",
658
+ body: JSON.stringify({
659
+ model: options.model || "rerank-english-v3.0",
660
+ query: options.query,
661
+ documents: options.documents,
662
+ top_n: options.top_n
663
+ })
664
+ });
665
+ }
666
+ /** Text-to-speech */
667
+ async speech(options) {
668
+ const res = await this._requestRaw(`${this.baseURL}/audio/speech`, {
669
+ method: "POST",
670
+ body: JSON.stringify({
671
+ model: options.model || "tts-1",
672
+ input: options.input,
673
+ voice: options.voice || "alloy"
674
+ })
675
+ });
676
+ return res.arrayBuffer();
677
+ }
678
+ /** Legacy completions endpoint */
679
+ async completions(options) {
680
+ return this._request(`${this.baseURL}/completions`, {
681
+ method: "POST",
682
+ body: JSON.stringify({
683
+ model: options.model || this.model,
684
+ prompt: options.prompt,
685
+ temperature: options.temperature,
686
+ max_tokens: options.maxTokens,
687
+ stop: options.stop,
688
+ top_p: options.topP
689
+ })
690
+ });
691
+ }
692
+ /** Audio transcription (speech-to-text) */
693
+ async transcribe(file, options) {
694
+ const formData = new FormData();
695
+ formData.append("file", file, "audio.webm");
696
+ formData.append("model", options?.model || "whisper-1");
697
+ if (options?.language) formData.append("language", options.language);
698
+ if (options?.prompt) formData.append("prompt", options.prompt);
699
+ const headers = { ...this.headers };
700
+ delete headers["Content-Type"];
701
+ this.checkLimits();
702
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/audio/transcriptions`, {
703
+ method: "POST",
704
+ headers,
705
+ body: formData
706
+ }, false);
707
+ if (!res.ok) {
708
+ const err = await res.json().catch(() => ({ error: res.statusText }));
709
+ throw new TCloudError(res.status, err.error?.message || err.error || err.message || res.statusText);
710
+ }
711
+ this._requestCount++;
712
+ return res.json();
713
+ }
714
+ /** Create a fine-tuning job */
715
+ async fineTuneCreate(options) {
716
+ return this._request(`${this.baseURL}/fine_tuning/jobs`, {
717
+ method: "POST",
718
+ body: JSON.stringify(options)
719
+ });
720
+ }
721
+ /** List fine-tuning jobs */
722
+ async fineTuneList() {
723
+ return this._fetch(`${this.baseURL}/fine_tuning/jobs`);
724
+ }
725
+ /** Submit a batch of chat requests */
726
+ async batch(requests) {
727
+ return this._request(`${this.baseURL}/batch`, {
728
+ method: "POST",
729
+ body: JSON.stringify({ requests })
730
+ });
731
+ }
732
+ /** Get batch job status */
733
+ async batchStatus(jobId) {
734
+ return this._fetch(`${this.baseURL}/batch?id=${jobId}`);
735
+ }
736
+ /** Generate video */
737
+ async videoGenerate(options) {
738
+ return this._request(`${this.baseURL}/video/generate`, {
739
+ method: "POST",
740
+ body: JSON.stringify(options)
741
+ });
742
+ }
743
+ /** Get video generation status */
744
+ async videoStatus(id) {
745
+ return this._fetch(`${this.baseURL}/video?id=${id}`);
746
+ }
747
+ /** Generate an avatar video (lip-synced talking head from audio + face image).
748
+ * Returns 202 with a job_id for async polling via avatarJobStatus(). */
749
+ async avatarGenerate(options) {
750
+ return this._request(`${this.baseURL}/avatar/generate`, {
751
+ method: "POST",
752
+ body: JSON.stringify(options)
753
+ });
754
+ }
755
+ /** Poll an avatar generation job by ID. */
756
+ async avatarJobStatus(jobId) {
757
+ return this._fetch(`${this.baseURL}/avatar/jobs/${jobId}`);
758
+ }
759
+ /** Poll an avatar job until it reaches a terminal state (completed/failed).
760
+ * Returns the final job status. Throws on failure. */
761
+ async pollAvatarJob(jobId, options) {
762
+ const interval = options?.intervalMs ?? 5e3;
763
+ const timeout = options?.timeoutMs ?? 3e5;
764
+ const deadline = Date.now() + timeout;
765
+ while (Date.now() < deadline) {
766
+ const job = await this.avatarJobStatus(jobId);
767
+ if (job.status === "completed") return job;
768
+ if (job.status === "failed") {
769
+ throw new TCloudError(500, job.error || `Avatar job ${jobId} failed`);
770
+ }
771
+ await new Promise((r) => setTimeout(r, interval));
772
+ }
773
+ throw new TCloudError(408, `Avatar job ${jobId} timed out after ${timeout}ms`);
774
+ }
775
+ /**
776
+ * Watch an async job via SSE until it reaches a terminal state.
777
+ * Works with avatar, video, and training blueprint operators.
778
+ *
779
+ * @param jobId - The job ID returned by the creation endpoint
780
+ * @param options - Optional: operatorUrl override, onEvent callback
781
+ * @returns The final JobEvent (completed/failed/cancelled)
782
+ */
783
+ async watchJob(jobId, options) {
784
+ const base = options?.operatorUrl?.replace(/\/$/, "") || this.baseURL;
785
+ const url = `${base}/v1/jobs/${encodeURIComponent(jobId)}/events`;
786
+ const timeout = options?.timeout ?? 3e5;
787
+ const controller = new AbortController();
788
+ const timer = setTimeout(() => controller.abort(), timeout);
789
+ try {
790
+ const watchHeaders = {
791
+ ...this.headers,
792
+ Accept: "text/event-stream"
793
+ };
794
+ if (options?.operatorUrl) {
795
+ delete watchHeaders["Authorization"];
796
+ }
797
+ if (options?.sseToken) {
798
+ watchHeaders["Authorization"] = `Bearer ${options.sseToken}`;
799
+ }
800
+ const res = await proxiedFetch(this.privacy, url, {
801
+ headers: watchHeaders,
802
+ signal: controller.signal
803
+ }, true);
804
+ if (!res.ok) {
805
+ const err = await res.json().catch(() => ({ error: res.statusText }));
806
+ throw new TCloudError(res.status, err.error?.message || err.error || res.statusText);
807
+ }
808
+ const reader = res.body.getReader();
809
+ const decoder = new TextDecoder();
810
+ let buf = "";
811
+ const terminalStatuses = /* @__PURE__ */ new Set(["completed", "failed", "cancelled"]);
812
+ while (true) {
813
+ const { done, value } = await reader.read();
814
+ if (done) {
815
+ throw new TCloudError(502, `SSE stream ended without terminal event for job ${jobId}`);
816
+ }
817
+ buf += decoder.decode(value, { stream: true });
818
+ if (buf.length > 1048576) throw new TCloudError(502, "SSE buffer overflow \u2014 server sent >1MB without newline");
819
+ const lines = buf.split("\n");
820
+ buf = lines.pop() || "";
821
+ for (const line of lines) {
822
+ if (!line.startsWith("data: ")) continue;
823
+ const data = line.slice(6).trim();
824
+ if (!data || data === "[DONE]") continue;
825
+ let event;
826
+ try {
827
+ event = JSON.parse(data);
828
+ } catch {
829
+ continue;
830
+ }
831
+ try {
832
+ options?.onEvent?.(event);
833
+ } catch (cbErr) {
834
+ console.error("watchJob onEvent callback error:", cbErr);
835
+ }
836
+ if (terminalStatuses.has(event.status)) {
837
+ return event;
838
+ }
839
+ }
840
+ }
841
+ } catch (err) {
842
+ if (err?.name === "AbortError") {
843
+ throw new TCloudError(408, `Job ${jobId} timed out after ${timeout}ms`);
844
+ }
845
+ throw err;
846
+ } finally {
847
+ clearTimeout(timer);
848
+ }
849
+ }
850
+ // ---------------------------------------------------------------------------
851
+ // Vector Store (requires operator routing — X-Tangle-Service/Blueprint/Operator)
852
+ // ---------------------------------------------------------------------------
853
+ /** Create a vector collection on the operator's vector store */
854
+ async createCollection(options) {
855
+ return this._request(`${this.baseURL}/collections`, {
856
+ method: "POST",
857
+ body: JSON.stringify(options)
858
+ });
859
+ }
860
+ /** List collections on the operator's vector store */
861
+ async listCollections() {
862
+ return this._fetch(`${this.baseURL}/collections`);
863
+ }
864
+ /** Upsert vectors into a collection */
865
+ async upsertVectors(collection, vectors) {
866
+ return this._request(`${this.baseURL}/collections/${encodeURIComponent(collection)}/upsert`, {
867
+ method: "POST",
868
+ body: JSON.stringify({ vectors })
869
+ });
870
+ }
871
+ /** Similarity search in a collection */
872
+ async queryVectors(collection, options) {
873
+ return this._request(`${this.baseURL}/collections/${encodeURIComponent(collection)}/query`, {
874
+ method: "POST",
875
+ body: JSON.stringify(options)
876
+ });
877
+ }
878
+ /** RAG query — embed text + search collection in one call */
879
+ async ragQuery(options) {
880
+ return this._request(`${this.baseURL}/rag`, {
881
+ method: "POST",
882
+ body: JSON.stringify(options)
883
+ });
884
+ }
885
+ /** Search models by name, provider, or capability */
886
+ async searchModels(query) {
887
+ const all = await this.models();
888
+ const q = query.toLowerCase();
889
+ return all.filter(
890
+ (m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q) || m._provider && m._provider.toLowerCase().includes(q)
891
+ );
892
+ }
893
+ /** Estimate cost for a request (without sending it) */
894
+ async estimateCost(options) {
895
+ const models = await this.models();
896
+ const model = models.find((m) => m.id === (options.model || this.model));
897
+ if (!model) return { inputCost: 0, outputCost: 0, total: 0 };
898
+ const inputCost = options.inputTokens * parseFloat(model.pricing.prompt);
899
+ const outputCost = options.outputTokens * parseFloat(model.pricing.completion);
900
+ return { inputCost, outputCost, total: inputCost + outputCost };
901
+ }
902
+ /**
903
+ * Get a pricing spectrum across resource tiers for a model.
904
+ *
905
+ * Uses REAL per-operator pricing from `operator.models[].inputPrice`.
906
+ * Each tier filters operators by GPU count and TEE capability, then
907
+ * reports the cheapest and most expensive operator for that config.
908
+ *
909
+ * @param options.model - Model ID to price (falls back to client default)
910
+ * @param options.tiers - Number of tiers (1-7, default 5)
911
+ */
912
+ async pricingSpectrum(options) {
913
+ const requestedTiers = Math.max(1, Math.min(options.tiers ?? 5, ALL_TIERS.length));
914
+ const modelId = options.model || this.model;
915
+ const selected = selectTiers(ALL_TIERS, requestedTiers);
916
+ const operatorData = await this.operators();
917
+ const allOperators = operatorData.operators || [];
918
+ return selected.map((tier) => {
919
+ const matching = allOperators.filter((op) => {
920
+ if (tier.gpu > 0 && (op.gpuCount ?? 0) < tier.gpu) return false;
921
+ if (tier.tee && !op.teeAttested) return false;
922
+ return true;
923
+ });
924
+ const prices = matching.map((op) => op.models.find((m) => m.modelId === modelId)?.inputPrice).filter((p) => p != null && p > 0).sort((a, b) => a - b);
925
+ const cheapestPrice = prices[0];
926
+ const priciestPrice = prices.length > 1 ? prices[prices.length - 1] : void 0;
927
+ return {
928
+ tier: tier.name,
929
+ config: tier,
930
+ cheapestPrice,
931
+ priciestPrice: priciestPrice !== cheapestPrice ? priciestPrice : void 0,
932
+ cheapest: cheapestPrice != null ? formatPrice(cheapestPrice) : "no operators for this config",
933
+ priciest: priciestPrice != null && priciestPrice !== cheapestPrice ? formatPrice(priciestPrice) : void 0,
934
+ availableOperators: matching.length,
935
+ operatorsWithModel: prices.length
936
+ };
937
+ });
938
+ }
939
+ };
940
+ var ALL_TIERS = [
941
+ { name: "cpu-only", cpu: 4, ramGb: 16, gpu: 0, tee: false },
942
+ { name: "gpu", cpu: 8, ramGb: 32, gpu: 1, tee: false },
943
+ { name: "gpu-tee", cpu: 8, ramGb: 32, gpu: 1, tee: true },
944
+ { name: "multi-gpu", cpu: 32, ramGb: 128, gpu: 2, tee: false },
945
+ { name: "multi-gpu-tee", cpu: 32, ramGb: 128, gpu: 2, tee: true },
946
+ { name: "max-gpu", cpu: 64, ramGb: 256, gpu: 4, tee: false },
947
+ { name: "max-gpu-tee", cpu: 64, ramGb: 256, gpu: 4, tee: true }
948
+ ];
949
+ function selectTiers(all, n) {
950
+ if (n >= all.length) return [...all];
951
+ if (n <= 1) return [all[0]];
952
+ if (n === 2) return [all[0], all[all.length - 1]];
953
+ const result = [all[0]];
954
+ const step = (all.length - 1) / (n - 1);
955
+ for (let i = 1; i < n - 1; i++) {
956
+ result.push(all[Math.round(i * step)]);
957
+ }
958
+ result.push(all[all.length - 1]);
959
+ return result;
960
+ }
961
+ function formatPrice(pricePerToken) {
962
+ return `$${(pricePerToken * 1e3).toFixed(6)}/1K tokens`;
963
+ }
964
+ var TCloudError = class extends Error {
965
+ constructor(status, message) {
966
+ super(message);
967
+ this.status = status;
968
+ this.name = "TCloudError";
969
+ }
970
+ };
971
+
972
+ export {
973
+ PrivateRouter,
974
+ TCloudClient,
975
+ TCloudError
976
+ };