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