@tokenbuddy/tb-admin 1.0.13 → 1.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/src/bootstrap-registry.d.ts +1 -0
  2. package/dist/src/bootstrap-registry.d.ts.map +1 -1
  3. package/dist/src/bootstrap-registry.js.map +1 -1
  4. package/dist/src/cli.d.ts.map +1 -1
  5. package/dist/src/cli.js +30 -16
  6. package/dist/src/cli.js.map +1 -1
  7. package/dist/src/server-cmd.d.ts +27 -2
  8. package/dist/src/server-cmd.d.ts.map +1 -1
  9. package/dist/src/server-cmd.js +131 -26
  10. package/dist/src/server-cmd.js.map +1 -1
  11. package/dist/src/ui-actions.d.ts +88 -0
  12. package/dist/src/ui-actions.d.ts.map +1 -0
  13. package/dist/src/ui-actions.js +763 -0
  14. package/dist/src/ui-actions.js.map +1 -0
  15. package/dist/src/ui-command.d.ts +4 -0
  16. package/dist/src/ui-command.d.ts.map +1 -0
  17. package/dist/src/ui-command.js +37 -0
  18. package/dist/src/ui-command.js.map +1 -0
  19. package/dist/src/ui-server.d.ts +23 -0
  20. package/dist/src/ui-server.d.ts.map +1 -0
  21. package/dist/src/ui-server.js +245 -0
  22. package/dist/src/ui-server.js.map +1 -0
  23. package/dist/src/ui-state.d.ts +134 -0
  24. package/dist/src/ui-state.d.ts.map +1 -0
  25. package/dist/src/ui-state.js +407 -0
  26. package/dist/src/ui-state.js.map +1 -0
  27. package/dist/src/ui-static.d.ts +2 -0
  28. package/dist/src/ui-static.d.ts.map +1 -0
  29. package/dist/src/ui-static.js +144 -0
  30. package/dist/src/ui-static.js.map +1 -0
  31. package/dist/src/upstream-balance-probe.d.ts +41 -0
  32. package/dist/src/upstream-balance-probe.d.ts.map +1 -0
  33. package/dist/src/upstream-balance-probe.js +379 -0
  34. package/dist/src/upstream-balance-probe.js.map +1 -0
  35. package/package.json +1 -1
  36. package/src/bootstrap-registry.ts +1 -0
  37. package/src/cli.ts +32 -16
  38. package/src/server-cmd.ts +163 -29
  39. package/src/ui-actions.ts +901 -0
  40. package/src/ui-command.ts +39 -0
  41. package/src/ui-server.ts +308 -0
  42. package/src/ui-state.ts +575 -0
  43. package/src/ui-static.ts +144 -0
  44. package/src/upstream-balance-probe.ts +505 -0
  45. package/tests/admin.test.ts +893 -4
@@ -0,0 +1,901 @@
1
+ import { spawn } from "child_process";
2
+ import * as fs from "fs";
3
+ import * as os from "os";
4
+ import * as path from "path";
5
+ import YAML from "js-yaml";
6
+ import type { SellerRegistryDocument, SellerRegistryEntry } from "./bootstrap-registry.js";
7
+ import { ConfigManager } from "./config.js";
8
+ import { AdminUiState } from "./ui-state.js";
9
+
10
+ export interface UiActionResult {
11
+ ok: boolean;
12
+ stdout: string;
13
+ stderr: string;
14
+ command: string[];
15
+ }
16
+
17
+ export interface CreateSellerRequest {
18
+ sellerName: string;
19
+ region: string;
20
+ image: string;
21
+ upstreamWebsite: string;
22
+ upstreamUrl: string;
23
+ upstreamApiKey: string;
24
+ upstreamBalanceProbeTemplate?: string;
25
+ upstreamBalanceProbeUrl?: string;
26
+ upstreamBalanceProbeUserId?: string;
27
+ upstreamBalanceProbeRechargeUrl?: string;
28
+ upstreamBalanceUrl?: string;
29
+ upstreamUserId?: string;
30
+ upstreamRechargeUrl?: string;
31
+ maxConnections: number;
32
+ maxQueueDepth: number;
33
+ markupRatio: number;
34
+ discountRatio: number;
35
+ paymentMethods?: string[] | string;
36
+ paymentMethod?: string;
37
+ clawtipPayTo?: string;
38
+ clawtipSm4KeyBase64?: string;
39
+ clawtipSkillSlug?: string;
40
+ clawtipSkillId?: string;
41
+ clawtipDescription?: string;
42
+ clawtipResourceUrl?: string;
43
+ clawtipActivationFeeFen?: number;
44
+ clawtipMicrosPerFen?: number;
45
+ flyConfig?: string;
46
+ operatorSecret?: string;
47
+ app?: string;
48
+ dryRun?: boolean;
49
+ }
50
+
51
+ export interface UiActionsOptions {
52
+ configManager: ConfigManager;
53
+ configPath?: string;
54
+ profile?: string;
55
+ url?: string;
56
+ token?: string;
57
+ fetchJson?: (url: string, init?: RequestInit) => Promise<unknown>;
58
+ commandRunner?: (args: string[], timeoutMs: number) => Promise<UiActionResult>;
59
+ }
60
+
61
+ type ConfigPatch = Record<string, unknown>;
62
+ export type UiActionProgressStatus = "pending" | "running" | "succeeded" | "failed" | "skipped";
63
+ export type UiActionProgressStepId = "check_registry" | "validate_config" | "create_deployment" | "wait_seller" | "apply_config" | "refresh_models" | "publish_registry";
64
+
65
+ export interface UiActionProgressEvent {
66
+ stepId: UiActionProgressStepId;
67
+ status: UiActionProgressStatus;
68
+ title: string;
69
+ message?: string;
70
+ result?: UiActionResult;
71
+ }
72
+
73
+ type UiActionProgressReporter = (event: UiActionProgressEvent) => void;
74
+
75
+ export class UiActions {
76
+ private readonly state: AdminUiState;
77
+ private readonly options: UiActionsOptions;
78
+ private readonly commandRunner?: (args: string[], timeoutMs: number) => Promise<UiActionResult>;
79
+
80
+ constructor(options: UiActionsOptions) {
81
+ this.options = options;
82
+ this.commandRunner = options.commandRunner;
83
+ this.state = new AdminUiState(options);
84
+ }
85
+
86
+ public async updateSellerConfig(id: string, patch: ConfigPatch): Promise<UiActionResult> {
87
+ const { profileName, config } = await this.state.rawSellerConfig(id);
88
+ if (!profileName) {
89
+ throw new Error(`seller \`${id}\` has no local profile for seller-config put`);
90
+ }
91
+ const next = mergeSellerConfigPatch(config, patch);
92
+ return this.withTempYaml(next, async (filePath) => {
93
+ const validate = await this.runAdmin(profileArgs(this.options, profileName, ["seller-config", "validate", "--file", filePath]), 30000);
94
+ if (!validate.ok) {
95
+ return validate;
96
+ }
97
+ return this.runAdmin(profileArgs(this.options, profileName, ["seller-config", "put", "--file", filePath]), 30000);
98
+ });
99
+ }
100
+
101
+ public async createSeller(request: CreateSellerRequest, progress?: UiActionProgressReporter): Promise<{ result: UiActionResult; configValidation: UiActionResult; readiness?: UiActionResult; configPut?: UiActionResult; modelsRefresh?: UiActionResult; registryPublish?: UiActionResult; configPreview: Record<string, unknown>; publishRegistry: "completed" | "failed" | "skipped" }> {
102
+ const normalizedRequest = normalizeCreateSellerRequest(request);
103
+ const report = progress || (() => undefined);
104
+ validateCreateSellerRequest(normalizedRequest);
105
+ report({ stepId: "check_registry", status: "running", title: "Check bootstrap registry", message: "Checking seller name conflicts before creating Fly resources." });
106
+ const registry = await this.state.fetchRegistry();
107
+ const appName = normalizedRequest.app || normalizedRequest.sellerName;
108
+ const conflict = registry.sellers.find((seller) => {
109
+ return seller.id === normalizedRequest.sellerName || seller.name === normalizedRequest.sellerName || seller.app === appName;
110
+ });
111
+ if (conflict) {
112
+ throw new Error(`seller \`${normalizedRequest.sellerName}\` already exists in bootstrap registry`);
113
+ }
114
+ report({ stepId: "check_registry", status: "succeeded", title: "Check bootstrap registry", message: "No registry conflict found." });
115
+ const provider = this.options.configManager.getSellerProvider("fly");
116
+ const operatorSecret = normalizedRequest.operatorSecret || provider?.operator_secret;
117
+ const flyConfig = normalizedRequest.flyConfig;
118
+ if (!operatorSecret) {
119
+ throw new Error("operatorSecret is required in local admin config seller_providers.fly.operator_secret or request body");
120
+ }
121
+ if (!flyConfig) {
122
+ throw new Error("flyConfig is required before creating a seller deployment");
123
+ }
124
+ const configRequest = {
125
+ ...normalizedRequest,
126
+ operatorSecret
127
+ };
128
+
129
+ return this.withTempYaml(initialSellerConfig(configRequest, false), async (filePath) => {
130
+ const normalizedUpstreamMessage = normalizedRequest.upstreamUrl !== request.upstreamUrl
131
+ ? `Normalized upstreamUrl to ${normalizedRequest.upstreamUrl} before validation.`
132
+ : "";
133
+ report({ stepId: "validate_config", status: "running", title: "Validate seller config", message: normalizedUpstreamMessage || "Validating generated seller config." });
134
+ const configValidation = await this.runAdmin(globalArgs(this.options, ["seller-config", "validate", "--file", filePath]), 30000);
135
+ report({
136
+ stepId: "validate_config",
137
+ status: configValidation.ok ? "succeeded" : "failed",
138
+ title: "Validate seller config",
139
+ message: configValidation.ok ? `${normalizedUpstreamMessage} Seller config is valid.`.trim() : "Seller config validation failed.",
140
+ result: configValidation
141
+ });
142
+ if (!configValidation.ok) {
143
+ return {
144
+ result: configValidation,
145
+ configValidation,
146
+ configPreview: initialSellerConfig(configRequest, true),
147
+ publishRegistry: "skipped"
148
+ };
149
+ }
150
+ const args = [
151
+ "seller",
152
+ "create",
153
+ normalizedRequest.sellerName,
154
+ "--region",
155
+ normalizedRequest.region,
156
+ "--image",
157
+ normalizedRequest.image,
158
+ "--fly-config",
159
+ flyConfig,
160
+ "--initial-config",
161
+ filePath,
162
+ "--operator-secret",
163
+ operatorSecret
164
+ ];
165
+ if (normalizedRequest.app) {
166
+ args.push("--app", normalizedRequest.app);
167
+ }
168
+ if (normalizedRequest.dryRun) {
169
+ args.push("--dry-run");
170
+ }
171
+ report({ stepId: "create_deployment", status: "running", title: "Create Fly deployment", message: `Creating ${appName} in ${normalizedRequest.region}.` });
172
+ const result = await this.runAdmin(globalArgs(this.options, args), 10 * 60 * 1000);
173
+ report({
174
+ stepId: "create_deployment",
175
+ status: result.ok ? "succeeded" : "failed",
176
+ title: "Create Fly deployment",
177
+ message: result.ok ? "Fly deployment command completed." : "Fly deployment command failed.",
178
+ result
179
+ });
180
+ let configPut: UiActionResult | undefined;
181
+ let modelsRefresh: UiActionResult | undefined;
182
+ let readiness: UiActionResult | undefined;
183
+ if (result.ok && !normalizedRequest.dryRun) {
184
+ readiness = await this.waitForSellerReady(appName, operatorSecret, report);
185
+ if (!readiness.ok) {
186
+ return {
187
+ result,
188
+ configValidation,
189
+ readiness,
190
+ configPreview: initialSellerConfig(configRequest, true),
191
+ publishRegistry: "skipped"
192
+ };
193
+ }
194
+ report({ stepId: "apply_config", status: "running", title: "Apply seller config", message: `Writing config to ${sellerOperatorUrl(appName)}.` });
195
+ configPut = await this.runAdmin(globalArgs(
196
+ {
197
+ ...this.options,
198
+ profile: undefined,
199
+ url: sellerOperatorUrl(appName),
200
+ token: operatorSecret
201
+ },
202
+ ["seller-config", "put", "--file", filePath]
203
+ ), 30000);
204
+ report({
205
+ stepId: "apply_config",
206
+ status: configPut.ok ? "succeeded" : "failed",
207
+ title: "Apply seller config",
208
+ message: configPut.ok ? "Seller config was written to the deployment." : "Seller config write failed.",
209
+ result: configPut
210
+ });
211
+ if (configPut.ok) {
212
+ report({ stepId: "refresh_models", status: "running", title: "Refresh upstream models", message: `Refreshing model catalog from ${sellerOperatorUrl(appName)}.` });
213
+ modelsRefresh = await this.runAdmin(globalArgs(
214
+ {
215
+ ...this.options,
216
+ profile: undefined,
217
+ url: sellerOperatorUrl(appName),
218
+ token: operatorSecret
219
+ },
220
+ ["upstreams", "refresh", "--auto-models"]
221
+ ), 30000);
222
+ report({
223
+ stepId: "refresh_models",
224
+ status: modelsRefresh.ok ? "succeeded" : "failed",
225
+ title: "Refresh upstream models",
226
+ message: modelsRefresh.ok ? "Upstream model catalog was refreshed." : "Upstream model refresh failed.",
227
+ result: modelsRefresh
228
+ });
229
+ }
230
+ } else if (normalizedRequest.dryRun) {
231
+ report({ stepId: "apply_config", status: "skipped", title: "Apply seller config", message: "Skipped because this is a dry run." });
232
+ report({ stepId: "refresh_models", status: "skipped", title: "Refresh upstream models", message: "Skipped because this is a dry run." });
233
+ }
234
+ const registryPublish = await this.publishCreatedSellerRegistryEntry({
235
+ registry,
236
+ request: normalizedRequest,
237
+ appName,
238
+ operatorSecret,
239
+ enabled: Boolean(result.ok && !normalizedRequest.dryRun && readiness?.ok && configPut?.ok && modelsRefresh?.ok),
240
+ report
241
+ });
242
+ return {
243
+ result,
244
+ configValidation,
245
+ readiness,
246
+ configPut,
247
+ modelsRefresh,
248
+ registryPublish,
249
+ configPreview: initialSellerConfig(configRequest, true),
250
+ publishRegistry: registryPublish ? (registryPublish.ok ? "completed" : "failed") : "skipped"
251
+ };
252
+ });
253
+ }
254
+
255
+ public async setRegistryStatus(id: string, status: "active" | "draining" | "offline"): Promise<UiActionResult> {
256
+ const registry = await this.state.fetchRegistry();
257
+ const target = registry.sellers.find((seller) => seller.id === id || seller.name === id || seller.app === id);
258
+ if (!target) {
259
+ throw new Error(`seller \`${id}\` not found in bootstrap registry`);
260
+ }
261
+ const next = {
262
+ ...registry,
263
+ updatedAt: new Date().toISOString(),
264
+ sellers: registry.sellers.map((seller) => seller === target ? { ...seller, status } : seller)
265
+ };
266
+ return this.withTempJson(next, async (filePath) => {
267
+ const validate = await this.runAdmin(globalArgs(this.options, ["bootstrap", "sellers", "validate", "--file", filePath]), 30000);
268
+ if (!validate.ok) {
269
+ return validate;
270
+ }
271
+ return this.runAdmin(globalArgs(this.options, ["bootstrap", "sellers", "put", "--file", filePath]), 30000);
272
+ });
273
+ }
274
+
275
+ public async deleteDeployment(id: string, confirm: boolean): Promise<UiActionResult> {
276
+ const registry = await this.state.fetchRegistry();
277
+ const target = registry.sellers.find((seller) => seller.id === id || seller.name === id || seller.app === id);
278
+ if (!target) {
279
+ throw new Error(`seller \`${id}\` not found in bootstrap registry`);
280
+ }
281
+ const app = target.app || target.id || target.name;
282
+ const args = ["seller", "remove", app, "--app", app];
283
+ if (!confirm) {
284
+ args.push("--dry-run");
285
+ }
286
+ return this.runAdmin(globalArgs(this.options, args), confirm ? 10 * 60 * 1000 : 30000);
287
+ }
288
+
289
+ private async withTempYaml<T>(document: unknown, callback: (filePath: string) => Promise<T>): Promise<T> {
290
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "tb-admin-ui-"));
291
+ const filePath = path.join(dir, "seller-config.yaml");
292
+ try {
293
+ fs.writeFileSync(filePath, YAML.dump(document, { lineWidth: 120, noRefs: true, sortKeys: false }), "utf8");
294
+ return await callback(filePath);
295
+ } finally {
296
+ fs.rmSync(dir, { recursive: true, force: true });
297
+ }
298
+ }
299
+
300
+ private async withTempJson<T>(document: unknown, callback: (filePath: string) => Promise<T>): Promise<T> {
301
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "tb-admin-ui-"));
302
+ const filePath = path.join(dir, "registry.json");
303
+ try {
304
+ fs.writeFileSync(filePath, JSON.stringify(document, null, 2), "utf8");
305
+ return await callback(filePath);
306
+ } finally {
307
+ fs.rmSync(dir, { recursive: true, force: true });
308
+ }
309
+ }
310
+
311
+ private runAdmin(args: string[], timeoutMs: number): Promise<UiActionResult> {
312
+ if (this.commandRunner) {
313
+ return this.commandRunner(args, timeoutMs);
314
+ }
315
+ return runTbAdmin(args, timeoutMs);
316
+ }
317
+
318
+ private async waitForSellerReady(appName: string, operatorSecret: string, report: UiActionProgressReporter): Promise<UiActionResult> {
319
+ const maxAttempts = 18;
320
+ const delayMs = 5000;
321
+ let last: UiActionResult | undefined;
322
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
323
+ report({
324
+ stepId: "wait_seller",
325
+ status: "running",
326
+ title: "Wait for seller service",
327
+ message: `Waiting for operator API to become ready (${attempt}/${maxAttempts}).`
328
+ });
329
+ last = await this.runAdmin(globalArgs(
330
+ {
331
+ ...this.options,
332
+ profile: undefined,
333
+ url: sellerOperatorUrl(appName),
334
+ token: operatorSecret
335
+ },
336
+ ["status"]
337
+ ), 30000);
338
+ if (last.ok) {
339
+ report({
340
+ stepId: "wait_seller",
341
+ status: "succeeded",
342
+ title: "Wait for seller service",
343
+ message: "Seller operator API is ready.",
344
+ result: last
345
+ });
346
+ return last;
347
+ }
348
+ if (attempt < maxAttempts) {
349
+ await sleep(delayMs);
350
+ }
351
+ }
352
+ const failed = last || {
353
+ ok: false,
354
+ stdout: "",
355
+ stderr: "seller service did not become ready",
356
+ command: []
357
+ };
358
+ report({
359
+ stepId: "wait_seller",
360
+ status: "failed",
361
+ title: "Wait for seller service",
362
+ message: "Seller operator API did not become ready before config write.",
363
+ result: failed
364
+ });
365
+ return failed;
366
+ }
367
+
368
+ private async publishCreatedSellerRegistryEntry(options: {
369
+ registry: SellerRegistryDocument;
370
+ request: CreateSellerRequest;
371
+ appName: string;
372
+ operatorSecret: string;
373
+ enabled: boolean;
374
+ report: UiActionProgressReporter;
375
+ }): Promise<UiActionResult | undefined> {
376
+ const { registry, request, appName, operatorSecret, enabled, report } = options;
377
+ if (!enabled) {
378
+ report({
379
+ stepId: "publish_registry",
380
+ status: "skipped",
381
+ title: "Publish bootstrap registry",
382
+ message: "Skipped because the deployment workflow did not complete successfully."
383
+ });
384
+ return undefined;
385
+ }
386
+
387
+ report({
388
+ stepId: "publish_registry",
389
+ status: "running",
390
+ title: "Publish bootstrap registry",
391
+ message: `Publishing ${request.sellerName} to bootstrap registry.`
392
+ });
393
+
394
+ let next: SellerRegistryDocument;
395
+ try {
396
+ const upstreams = await this.fetchSellerOperatorJson(appName, operatorSecret, "/operator/admin/upstreams");
397
+ const service = await this.fetchSellerOperatorJson(appName, operatorSecret, "/operator/admin/service");
398
+ next = nextRegistryDocument(registry, request, appName, upstreams, service);
399
+ } catch (err: any) {
400
+ const failed = {
401
+ ok: false,
402
+ stdout: "",
403
+ stderr: redactSensitive(err.message || "failed to build bootstrap registry entry"),
404
+ command: ["fetch", `${sellerOperatorUrl(appName)}/operator/admin/upstreams`]
405
+ };
406
+ report({
407
+ stepId: "publish_registry",
408
+ status: "failed",
409
+ title: "Publish bootstrap registry",
410
+ message: "Failed to read seller metadata for bootstrap registry.",
411
+ result: failed
412
+ });
413
+ return failed;
414
+ }
415
+ return this.withTempJson(next, async (filePath) => {
416
+ const validate = await this.runAdmin(globalArgs(this.options, ["bootstrap", "sellers", "validate", "--file", filePath]), 30000);
417
+ if (!validate.ok) {
418
+ report({
419
+ stepId: "publish_registry",
420
+ status: "failed",
421
+ title: "Publish bootstrap registry",
422
+ message: "Generated bootstrap registry entry failed validation.",
423
+ result: validate
424
+ });
425
+ return validate;
426
+ }
427
+ const put = await this.runAdmin(globalArgs(this.options, ["bootstrap", "sellers", "put", "--file", filePath]), 30000);
428
+ report({
429
+ stepId: "publish_registry",
430
+ status: put.ok ? "succeeded" : "failed",
431
+ title: "Publish bootstrap registry",
432
+ message: put.ok ? "Bootstrap registry was published with the new seller." : "Bootstrap registry publish failed.",
433
+ result: put
434
+ });
435
+ return put;
436
+ });
437
+ }
438
+
439
+ private async fetchSellerOperatorJson(appName: string, operatorSecret: string, pathName: string): Promise<Record<string, unknown>> {
440
+ const fetchJson = this.options.fetchJson || defaultFetchJson;
441
+ const response = await fetchJson(`${sellerOperatorUrl(appName)}${pathName}`, {
442
+ headers: { Authorization: `Bearer ${operatorSecret}` }
443
+ });
444
+ if (response && typeof response === "object" && !Array.isArray(response)) {
445
+ return response as Record<string, unknown>;
446
+ }
447
+ return {};
448
+ }
449
+ }
450
+
451
+ function nextRegistryDocument(
452
+ registry: SellerRegistryDocument,
453
+ request: CreateSellerRequest,
454
+ appName: string,
455
+ upstreams: Record<string, unknown>,
456
+ service: Record<string, unknown>
457
+ ): SellerRegistryDocument {
458
+ const entry = registryEntryFromCreatedSeller(request, appName, upstreams, service);
459
+ const sellers = registry.sellers.filter((seller) => {
460
+ return seller.id !== entry.id && seller.name !== entry.name && seller.app !== entry.app;
461
+ });
462
+ return {
463
+ ...registry,
464
+ version: Number(registry.version || 0) + 1,
465
+ updatedAt: new Date().toISOString(),
466
+ sellers: [...sellers, entry]
467
+ };
468
+ }
469
+
470
+ function registryEntryFromCreatedSeller(
471
+ request: CreateSellerRequest,
472
+ appName: string,
473
+ upstreams: Record<string, unknown>,
474
+ service: Record<string, unknown>
475
+ ): SellerRegistryEntry {
476
+ const models = modelIdsFrom(upstreams.models) || modelIdsFrom(service.models);
477
+ if (!models || models.length === 0) {
478
+ throw new Error("seller operator upstreams did not return models for bootstrap registry");
479
+ }
480
+ const supportedProtocols = supportedProtocolsFrom(service.supportedProtocols)
481
+ || supportedProtocolsFrom(upstreams.supportedProtocols)
482
+ || ["chat_completions"];
483
+ const paymentMethods = paymentMethodsFromRequest(request);
484
+ return {
485
+ id: request.sellerName,
486
+ name: request.sellerName,
487
+ app: appName,
488
+ url: sellerOperatorUrl(appName),
489
+ status: "pending",
490
+ region: stringValue(request.region),
491
+ modelsCount: models.length || undefined,
492
+ sampleModels: models.slice(0, 5),
493
+ models,
494
+ supportedProtocols,
495
+ paymentMethods,
496
+ recommendedFor: models.slice(0, 5)
497
+ };
498
+ }
499
+
500
+ function modelIdsFrom(value: unknown): string[] | undefined {
501
+ if (!Array.isArray(value)) {
502
+ return undefined;
503
+ }
504
+ return Array.from(new Set(value.map((entry) => {
505
+ if (typeof entry === "string") {
506
+ return entry;
507
+ }
508
+ if (entry && typeof entry === "object" && "id" in entry) {
509
+ const id = (entry as { id?: unknown }).id;
510
+ return typeof id === "string" && id.trim() ? id.trim() : undefined;
511
+ }
512
+ return undefined;
513
+ }).filter((entry): entry is string => Boolean(entry))));
514
+ }
515
+
516
+ function supportedProtocolsFrom(value: unknown): string[] | undefined {
517
+ if (!Array.isArray(value)) {
518
+ return undefined;
519
+ }
520
+ const protocols = value.map((entry) => stringValue(entry)).filter((entry): entry is string => Boolean(entry));
521
+ return protocols.length > 0 ? Array.from(new Set(protocols)) : undefined;
522
+ }
523
+
524
+ export function runTbAdmin(args: string[], timeoutMs: number): Promise<UiActionResult> {
525
+ const entry = adminEntryPath();
526
+ const command = [process.execPath, entry, ...args];
527
+ return new Promise((resolve) => {
528
+ const child = spawn(process.execPath, [entry, ...args], {
529
+ shell: false,
530
+ stdio: ["ignore", "pipe", "pipe"]
531
+ });
532
+ const timer = setTimeout(() => {
533
+ child.kill("SIGTERM");
534
+ }, timeoutMs);
535
+ let stdout = "";
536
+ let stderr = "";
537
+ child.stdout.on("data", (chunk) => {
538
+ stdout += chunk.toString();
539
+ });
540
+ child.stderr.on("data", (chunk) => {
541
+ stderr += chunk.toString();
542
+ });
543
+ child.on("close", (code) => {
544
+ clearTimeout(timer);
545
+ resolve({
546
+ ok: code === 0,
547
+ stdout: redactSensitive(stdout),
548
+ stderr: redactSensitive(stderr),
549
+ command: redactCommand(command)
550
+ });
551
+ });
552
+ });
553
+ }
554
+
555
+ async function defaultFetchJson(url: string, init?: RequestInit): Promise<unknown> {
556
+ const response = await fetch(url, init);
557
+ if (!response.ok) {
558
+ const text = await response.text();
559
+ throw new Error(`HTTP Error ${response.status}: ${redactSensitive(text || response.statusText)}`);
560
+ }
561
+ const text = await response.text();
562
+ return text ? JSON.parse(text) : {};
563
+ }
564
+
565
+ function adminEntryPath(): string {
566
+ const current = process.argv[1] || "";
567
+ if (current.endsWith("tb-admin.js")) {
568
+ return current;
569
+ }
570
+ return path.resolve(process.cwd(), "packages/admin-cli/bin/tb-admin.js");
571
+ }
572
+
573
+ function globalArgs(options: UiActionsOptions, args: string[]): string[] {
574
+ const output: string[] = [];
575
+ if (options.configPath) {
576
+ output.push("--config", options.configPath);
577
+ }
578
+ if (options.profile) {
579
+ output.push("--profile", options.profile);
580
+ }
581
+ if (options.url) {
582
+ output.push("--url", options.url);
583
+ }
584
+ if (options.token) {
585
+ output.push("--token", options.token);
586
+ }
587
+ output.push(...args);
588
+ return output;
589
+ }
590
+
591
+ function profileArgs(options: UiActionsOptions, profileName: string, args: string[]): string[] {
592
+ return globalArgs({ ...options, profile: profileName, url: undefined, token: undefined }, args);
593
+ }
594
+
595
+ function mergeSellerConfigPatch(config: Record<string, unknown>, patch: ConfigPatch): Record<string, unknown> {
596
+ const next = { ...config };
597
+ copyIfPresent(next, patch, "upstreamUrl");
598
+ copyIfPresent(next, patch, "upstreamApiKey");
599
+ applyBalanceProbePatch(next, patch);
600
+ copyIfPresent(next, patch, "upstreamBalanceUrl");
601
+ copyIfPresent(next, patch, "upstreamUserId");
602
+ copyIfPresent(next, patch, "upstreamRechargeUrl");
603
+ copyIfPresent(next, patch, "markupRatio");
604
+ copyIfPresent(next, patch, "discountRatio");
605
+ copyIfPresent(next, patch, "maxConnections");
606
+ copyIfPresent(next, patch, "maxQueueDepth");
607
+ if (Array.isArray(patch.models)) {
608
+ next.models = patch.models;
609
+ }
610
+ if (patch.modelAliases && typeof patch.modelAliases === "object" && !Array.isArray(patch.modelAliases)) {
611
+ next.modelAliases = patch.modelAliases;
612
+ }
613
+ return next;
614
+ }
615
+
616
+ function copyIfPresent(target: Record<string, unknown>, source: ConfigPatch, key: string): void {
617
+ if (source[key] !== undefined) {
618
+ target[key] = source[key];
619
+ }
620
+ }
621
+
622
+ function validateCreateSellerRequest(request: CreateSellerRequest): void {
623
+ requireString(request.sellerName, "sellerName");
624
+ requireString(request.region, "region");
625
+ requireString(request.image, "image");
626
+ requireString(request.upstreamWebsite, "upstreamWebsite");
627
+ requireString(request.upstreamUrl, "upstreamUrl");
628
+ requireString(request.upstreamApiKey, "upstreamApiKey");
629
+ if (stringValue(request.upstreamBalanceProbeTemplate) !== "none") {
630
+ requireString(balanceProbeUrl(request), "upstreamBalanceProbeUrl");
631
+ }
632
+ requirePositiveInteger(request.maxConnections, "maxConnections");
633
+ requirePositiveInteger(request.maxQueueDepth, "maxQueueDepth");
634
+ requireFiniteNumber(request.markupRatio, "markupRatio");
635
+ requireFiniteNumber(request.discountRatio, "discountRatio");
636
+ const paymentMethods = paymentMethodsFromRequest(request);
637
+ const invalidPaymentMethod = paymentMethods.find((method) => !["clawtip", "mock"].includes(method));
638
+ if (invalidPaymentMethod) {
639
+ throw new Error("paymentMethods must contain only clawtip or mock");
640
+ }
641
+ if (paymentMethods.includes("clawtip")) {
642
+ requireString(request.clawtipPayTo, "clawtipPayTo");
643
+ requireString(request.clawtipSm4KeyBase64, "clawtipSm4KeyBase64");
644
+ }
645
+ }
646
+
647
+ function normalizeCreateSellerRequest(request: CreateSellerRequest): CreateSellerRequest {
648
+ const upstreamUrl = stripTrailingV1(request.upstreamUrl);
649
+ const app = stringValue(request.app) || request.sellerName;
650
+ const normalized = {
651
+ ...request,
652
+ app,
653
+ image: stringValue(request.image) || "registry.fly.io/tb-seller:latest",
654
+ flyConfig: stringValue(request.flyConfig) || "deploy/fly.io/fly.tb-seller.toml",
655
+ upstreamUrl
656
+ };
657
+ if (paymentMethodsFromRequest(normalized).includes("clawtip")) {
658
+ normalized.clawtipSkillSlug = stringValue(normalized.clawtipSkillSlug) || app;
659
+ normalized.clawtipSkillId = stringValue(normalized.clawtipSkillId) || `si-${app}`;
660
+ normalized.clawtipDescription = stringValue(normalized.clawtipDescription) || `TokenBuddy Seller ${request.sellerName}`;
661
+ normalized.clawtipResourceUrl = stringValue(normalized.clawtipResourceUrl) || sellerOperatorUrl(app);
662
+ normalized.clawtipActivationFeeFen = Number(normalized.clawtipActivationFeeFen || 1);
663
+ normalized.clawtipMicrosPerFen = Number(normalized.clawtipMicrosPerFen || 10000);
664
+ }
665
+ return normalized;
666
+ }
667
+
668
+ function initialSellerConfig(request: CreateSellerRequest, masked: boolean): Record<string, unknown> {
669
+ const upstreamBalanceProbe = balanceProbeConfigFromRequest(request);
670
+ const upstreamBalanceUrl = balanceProbeUrl(request);
671
+ const upstreamUserId = balanceProbeUserId(request);
672
+ const upstreamRechargeUrl = balanceProbeRechargeUrl(request);
673
+ const paymentConfig = paymentConfigFromRequest(request, masked);
674
+ return {
675
+ upstreamUrl: request.upstreamUrl,
676
+ upstreamApiKey: masked ? "********" : request.upstreamApiKey,
677
+ upstreamWebsite: request.upstreamWebsite,
678
+ upstreamBalanceUrl,
679
+ upstreamUserId,
680
+ upstreamRechargeUrl,
681
+ upstreamBalanceProbe,
682
+ maxConnections: request.maxConnections,
683
+ maxQueueDepth: request.maxQueueDepth,
684
+ markupRatio: request.markupRatio,
685
+ discountRatio: request.discountRatio,
686
+ operatorSecret: masked ? "********" : stringValue(request.operatorSecret),
687
+ ...paymentConfig
688
+ };
689
+ }
690
+
691
+ function paymentConfigFromRequest(request: CreateSellerRequest, masked: boolean): Record<string, unknown> {
692
+ const paymentMethods = paymentMethodsFromRequest(request);
693
+ const config: Record<string, unknown> = {
694
+ allowMock: paymentMethods.includes("mock")
695
+ };
696
+ if (!paymentMethods.includes("clawtip")) {
697
+ return config;
698
+ }
699
+ return {
700
+ ...config,
701
+ clawtip: {
702
+ payTo: stringValue(request.clawtipPayTo),
703
+ sm4KeyBase64: masked ? "********" : stringValue(request.clawtipSm4KeyBase64),
704
+ skillSlug: stringValue(request.clawtipSkillSlug),
705
+ skillId: stringValue(request.clawtipSkillId),
706
+ description: stringValue(request.clawtipDescription),
707
+ resourceUrl: stringValue(request.clawtipResourceUrl),
708
+ activationFeeFen: Number(request.clawtipActivationFeeFen),
709
+ microsPerFen: Number(request.clawtipMicrosPerFen)
710
+ }
711
+ };
712
+ }
713
+
714
+ function paymentMethodsFromRequest(request: CreateSellerRequest): string[] {
715
+ const values = request.paymentMethods !== undefined
716
+ ? arrayStringValues(request.paymentMethods)
717
+ : legacyPaymentMethodsFromRequest(request);
718
+ return Array.from(new Set(values));
719
+ }
720
+
721
+ function legacyPaymentMethodsFromRequest(request: CreateSellerRequest): string[] {
722
+ const paymentMethod = stringValue(request.paymentMethod);
723
+ if (paymentMethod === "none") {
724
+ return [];
725
+ }
726
+ return [paymentMethod || "clawtip"];
727
+ }
728
+
729
+ function arrayStringValues(value: unknown): string[] {
730
+ if (Array.isArray(value)) {
731
+ return value.map((entry) => stringValue(entry)).filter((entry): entry is string => Boolean(entry));
732
+ }
733
+ const single = stringValue(value);
734
+ return single ? single.split(",").map((entry) => entry.trim()).filter(Boolean) : [];
735
+ }
736
+
737
+ function applyBalanceProbePatch(target: Record<string, unknown>, patch: ConfigPatch): void {
738
+ const template = stringValue(patch.upstreamBalanceProbeTemplate);
739
+ const url = stringValue(patch.upstreamBalanceProbeUrl) || stringValue(patch.upstreamBalanceUrl);
740
+ const userId = stringValue(patch.upstreamBalanceProbeUserId) || stringValue(patch.upstreamUserId);
741
+ const rechargeUrl = stringValue(patch.upstreamBalanceProbeRechargeUrl) || stringValue(patch.upstreamRechargeUrl);
742
+ if (template === undefined && url === undefined && userId === undefined && rechargeUrl === undefined) {
743
+ return;
744
+ }
745
+ const current = objectValue(target.upstreamBalanceProbe) || {};
746
+ target.upstreamBalanceProbe = {
747
+ ...current,
748
+ ...(template !== undefined ? { template } : {}),
749
+ ...(url !== undefined ? { url } : {}),
750
+ ...(userId !== undefined ? { userId } : {}),
751
+ ...(rechargeUrl !== undefined ? { rechargeUrl } : {})
752
+ };
753
+ if (url !== undefined) {
754
+ target.upstreamBalanceUrl = url;
755
+ }
756
+ if (userId !== undefined) {
757
+ target.upstreamUserId = userId;
758
+ }
759
+ if (rechargeUrl !== undefined) {
760
+ target.upstreamRechargeUrl = rechargeUrl;
761
+ }
762
+ }
763
+
764
+ function balanceProbeConfigFromRequest(request: CreateSellerRequest): Record<string, unknown> {
765
+ return {
766
+ template: stringValue(request.upstreamBalanceProbeTemplate) || "auto",
767
+ url: balanceProbeUrl(request),
768
+ userId: balanceProbeUserId(request),
769
+ rechargeUrl: balanceProbeRechargeUrl(request)
770
+ };
771
+ }
772
+
773
+ function balanceProbeUrl(request: CreateSellerRequest): string | undefined {
774
+ const explicit = stringValue(request.upstreamBalanceProbeUrl) || stringValue(request.upstreamBalanceUrl);
775
+ if (explicit) {
776
+ return explicit;
777
+ }
778
+ const template = stringValue(request.upstreamBalanceProbeTemplate) || "auto";
779
+ const upstreamUrl = stringValue(request.upstreamUrl);
780
+ const host = hostName(upstreamUrl);
781
+ if (template === "none") {
782
+ return undefined;
783
+ }
784
+ if (template === "openrouter") {
785
+ return "https://openrouter.ai/api/v1/credits";
786
+ }
787
+ if (template === "deepseek") {
788
+ return "https://api.deepseek.com/user/balance";
789
+ }
790
+ if (template === "stepfun") {
791
+ return "https://api.stepfun.com/v1/accounts";
792
+ }
793
+ if (template === "novita") {
794
+ return "https://api.novita.ai/v3/user/balance";
795
+ }
796
+ if (template === "siliconflow") {
797
+ return host.endsWith(".com") ? "https://api.siliconflow.com/v1/user/info" : "https://api.siliconflow.cn/v1/user/info";
798
+ }
799
+ if (template === "usage_generic") {
800
+ return upstreamUrl ? usageUrl(upstreamUrl) : undefined;
801
+ }
802
+ if (template === "auto") {
803
+ if (host === "api.deepseek.com") {
804
+ return "https://api.deepseek.com/user/balance";
805
+ }
806
+ if (host === "api.stepfun.ai" || host === "api.stepfun.com") {
807
+ return "https://api.stepfun.com/v1/accounts";
808
+ }
809
+ if (host === "api.siliconflow.cn") {
810
+ return "https://api.siliconflow.cn/v1/user/info";
811
+ }
812
+ if (host === "api.siliconflow.com") {
813
+ return "https://api.siliconflow.com/v1/user/info";
814
+ }
815
+ if (host === "openrouter.ai") {
816
+ return "https://openrouter.ai/api/v1/credits";
817
+ }
818
+ if (host === "api.novita.ai") {
819
+ return "https://api.novita.ai/v3/user/balance";
820
+ }
821
+ return upstreamUrl ? usageUrl(upstreamUrl) : undefined;
822
+ }
823
+ return undefined;
824
+ }
825
+
826
+ function balanceProbeUserId(request: CreateSellerRequest): string | undefined {
827
+ return stringValue(request.upstreamBalanceProbeUserId) || stringValue(request.upstreamUserId);
828
+ }
829
+
830
+ function balanceProbeRechargeUrl(request: CreateSellerRequest): string | undefined {
831
+ return stringValue(request.upstreamBalanceProbeRechargeUrl) || stringValue(request.upstreamRechargeUrl);
832
+ }
833
+
834
+ function stringValue(value: unknown): string | undefined {
835
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
836
+ }
837
+
838
+ function objectValue(value: unknown): Record<string, unknown> | undefined {
839
+ return value && typeof value === "object" && !Array.isArray(value)
840
+ ? value as Record<string, unknown>
841
+ : undefined;
842
+ }
843
+
844
+ function stripTrailingV1(value: string): string {
845
+ return String(value || "").trim().replace(/\/v1\/?$/i, "");
846
+ }
847
+
848
+ function usageUrl(value: string): string {
849
+ const base = String(value || "").trim().replace(/\/+$/, "");
850
+ return /\/v1$/i.test(base) ? `${base}/usage` : `${base}/v1/usage`;
851
+ }
852
+
853
+ function hostName(value: unknown): string {
854
+ try {
855
+ return new URL(String(value || "")).hostname.toLowerCase();
856
+ } catch {
857
+ return "";
858
+ }
859
+ }
860
+
861
+ function sellerOperatorUrl(appName: string): string {
862
+ return `https://${appName}.fly.dev`;
863
+ }
864
+
865
+ function sleep(ms: number): Promise<void> {
866
+ return new Promise((resolve) => setTimeout(resolve, ms));
867
+ }
868
+
869
+ function requireString(value: unknown, field: string): void {
870
+ if (typeof value !== "string" || !value.trim()) {
871
+ throw new Error(`${field} is required`);
872
+ }
873
+ }
874
+
875
+ function requirePositiveInteger(value: unknown, field: string): void {
876
+ const parsed = Number(value);
877
+ if (!Number.isInteger(parsed) || parsed < 1) {
878
+ throw new Error(`${field} must be >= 1`);
879
+ }
880
+ }
881
+
882
+ function requireFiniteNumber(value: unknown, field: string): void {
883
+ if (!Number.isFinite(Number(value))) {
884
+ throw new Error(`${field} must be a number`);
885
+ }
886
+ }
887
+
888
+ function redactCommand(command: string[]): string[] {
889
+ return command.map((part, index) => {
890
+ const prev = command[index - 1];
891
+ if (prev === "--operator-secret" || prev === "--token" || prev === "--api-key") {
892
+ return "********";
893
+ }
894
+ return redactSensitive(part);
895
+ });
896
+ }
897
+
898
+ function redactSensitive(value: string): string {
899
+ return value.replace(/(sk-[A-Za-z0-9_-]+)/g, "********")
900
+ .replace(/(operatorSecret|upstreamApiKey|token|apiKey|sm4KeyBase64|clawtipSm4KeyBase64)["'=:\s]+([^"',\s]+)/gi, "$1=********");
901
+ }