@tokenbuddy/tb-admin 1.0.14 → 1.0.27

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