@vibedev-si/dsh-vibedev 0.3.3 → 0.3.5

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/lib/index.js CHANGED
@@ -42,6 +42,25 @@ const SETTLE_READS_MS = [1500, 8e3];
42
42
  const MIN_READ_SPACING_MS = 5e3;
43
43
  const record$8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
44
44
  const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
45
+ /**
46
+ * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
47
+ * writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
48
+ * no amount at all.
49
+ */
50
+ function amountOf(value) {
51
+ let raw;
52
+ if (typeof value === "number") {
53
+ if (!Number.isFinite(value)) return void 0;
54
+ raw = String(value);
55
+ if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
56
+ } else raw = text$8(value);
57
+ return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
58
+ }
59
+ /** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
60
+ const seenOf = (read) => JSON.stringify({
61
+ balance: read.balance,
62
+ user: read.user
63
+ });
45
64
  /** The account state behind the pages. */
46
65
  var AccountService = class {
47
66
  options;
@@ -58,6 +77,10 @@ var AccountService = class {
58
77
  epoch = 0;
59
78
  /** When the last read after a charge started, to space them out. */
60
79
  lastSpendReadAt = Number.NEGATIVE_INFINITY;
80
+ /** The last read that succeeded, kept for the pages while a later read fails. */
81
+ lastGood;
82
+ /** The latest read failed, after the last one that succeeded. */
83
+ failure;
61
84
  /**
62
85
  * @param options - origin, credential chain, the plugin's sign-in and the route's model state.
63
86
  */
@@ -90,6 +113,8 @@ var AccountService = class {
90
113
  this.balanceCache = void 0;
91
114
  this.revalidating = void 0;
92
115
  this.lastSeen = void 0;
116
+ this.lastGood = void 0;
117
+ this.failure = void 0;
93
118
  this.changed();
94
119
  }
95
120
  /**
@@ -163,12 +188,17 @@ var AccountService = class {
163
188
  ...base,
164
189
  revision: this.revision
165
190
  };
166
- const [grantUser, me] = await Promise.all([credential.kind === "plugin" ? this.options.login.user().catch(() => void 0) : Promise.resolve(void 0), this.me(credential.token, fresh)]);
191
+ const [grantUser, read] = await Promise.all([credential.kind === "plugin" ? this.options.login.user().catch(() => void 0) : Promise.resolve(void 0), this.me(credential.token, fresh)]);
192
+ const good = this.lastGood?.token === credential.token ? this.lastGood.read : void 0;
193
+ const me = read.balance === void 0 && good !== void 0 ? good : read;
167
194
  const user = me.user ?? userOf(grantUser);
195
+ const failedAt = this.failure?.token === credential.token ? this.failure.at : void 0;
168
196
  return {
169
197
  ...base,
170
198
  ...user === void 0 ? {} : { user },
171
199
  ...me.balance === void 0 ? {} : { balance: me.balance },
200
+ ...me.readAt === void 0 ? {} : { readAt: me.readAt },
201
+ ...failedAt === void 0 ? {} : { readFailedAt: failedAt },
172
202
  revision: this.revision
173
203
  };
174
204
  }
@@ -206,8 +236,9 @@ var AccountService = class {
206
236
  if (!response.ok) return {};
207
237
  const body = record$8(await response.json().catch(() => void 0));
208
238
  const data = record$8(body?.data) ?? body;
209
- const balance = typeof data?.balance === "number" && Number.isFinite(data.balance) ? String(data.balance) : text$8(data?.balance);
239
+ const balance = amountOf(data?.balance);
210
240
  const currency = text$8(data?.currency) ?? "CNY";
241
+ const frozen = amountOf(data?.frozen_balance);
211
242
  const id = typeof data?.id === "number" ? String(data.id) : text$8(data?.id);
212
243
  const nickname = text$8(data?.nickname) ?? text$8(data?.username);
213
244
  const email = text$8(data?.email);
@@ -217,10 +248,14 @@ var AccountService = class {
217
248
  ...nickname === void 0 ? {} : { nickname }
218
249
  };
219
250
  return {
220
- ...balance === void 0 || !/^-?\d+(\.\d+)?$/.test(balance) ? {} : { balance: {
221
- amount: balance,
222
- currency
223
- } },
251
+ ...balance === void 0 ? {} : {
252
+ balance: {
253
+ amount: balance,
254
+ currency,
255
+ ...frozen === void 0 ? {} : { frozen }
256
+ },
257
+ readAt: this.now()
258
+ },
224
259
  ...user === void 0 ? {} : { user }
225
260
  };
226
261
  } catch {
@@ -237,6 +272,10 @@ var AccountService = class {
237
272
  if (epoch !== this.epoch) return;
238
273
  if (read.balance === void 0) {
239
274
  if (this.balanceCache?.value === value) this.balanceCache = void 0;
275
+ this.failure = {
276
+ token,
277
+ at: this.now()
278
+ };
240
279
  return;
241
280
  }
242
281
  this.balanceCache = {
@@ -244,7 +283,12 @@ var AccountService = class {
244
283
  at: this.now(),
245
284
  value
246
285
  };
247
- const seen = JSON.stringify(read);
286
+ this.lastGood = {
287
+ token,
288
+ read
289
+ };
290
+ this.failure = void 0;
291
+ const seen = seenOf(read);
248
292
  if (this.lastSeen !== void 0 && this.lastSeen !== seen) {
249
293
  this.lastSeen = seen;
250
294
  this.changed();
@@ -298,7 +342,7 @@ function userOf(user) {
298
342
  ...nickname === void 0 ? {} : { nickname }
299
343
  };
300
344
  }
301
- function json(status, body) {
345
+ function json$1(status, body) {
302
346
  return new Response(JSON.stringify(body), {
303
347
  status,
304
348
  headers: {
@@ -310,7 +354,7 @@ function json(status, body) {
310
354
  function failure(error) {
311
355
  const candidate = record$8(error)?.code;
312
356
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
313
- return json(500, { error: {
357
+ return json$1(500, { error: {
314
358
  code,
315
359
  message: code === "SIGN_IN_CANCELLED" ? "Sign-in was cancelled. 登录已取消。" : code === "SIGN_IN_TIMEOUT" ? "Sign-in expired. 登录已超时,请重新登录。" : "The account request could not be completed. 账号请求未完成,请查看登录诊断后重试。"
316
360
  } });
@@ -331,7 +375,7 @@ function accountRoutes(account) {
331
375
  const query = new URL(request.url, "http://host").searchParams;
332
376
  const since = query.get("since");
333
377
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
334
- return json(200, await account.view(query.get("fresh") === "1"));
378
+ return json$1(200, await account.view(query.get("fresh") === "1"));
335
379
  } catch (error) {
336
380
  return failure(error);
337
381
  }
@@ -344,7 +388,7 @@ function accountRoutes(account) {
344
388
  fetch: async (request) => {
345
389
  try {
346
390
  const body = record$8(await request.json().catch(() => void 0));
347
- return json(200, await account.signIn(body?.open !== false));
391
+ return json$1(200, await account.signIn(body?.open !== false));
348
392
  } catch (error) {
349
393
  return failure(error);
350
394
  }
@@ -356,7 +400,7 @@ function accountRoutes(account) {
356
400
  requestBody: "buffered",
357
401
  fetch: () => {
358
402
  account.cancel();
359
- return Promise.resolve(json(200, { ok: true }));
403
+ return Promise.resolve(json$1(200, { ok: true }));
360
404
  }
361
405
  },
362
406
  {
@@ -365,7 +409,7 @@ function accountRoutes(account) {
365
409
  requestBody: "buffered",
366
410
  fetch: async () => {
367
411
  try {
368
- return await account.signOut() ? json(200, { ok: true }) : json(409, { error: {
412
+ return await account.signOut() ? json$1(200, { ok: true }) : json$1(409, { error: {
369
413
  code: "SIGNED_IN_BY_APP",
370
414
  message: "The VibeDev account is the app's sign-in; sign out in the app."
371
415
  } });
@@ -377,6 +421,157 @@ function accountRoutes(account) {
377
421
  ];
378
422
  }
379
423
  //#endregion
424
+ //#region src/account/latency.ts
425
+ /** Path of the latency route. */
426
+ const LATENCY_ROUTE = "/api/dsh-vibedev/latency";
427
+ /** Timed requests after the first one. */
428
+ const TIMED_REQUESTS = 4;
429
+ /** Each request gets this long, its body included. */
430
+ const REQUEST_TIMEOUT_MS = 5e3;
431
+ /** A result is answered again for this long; `fresh` measures anyway. */
432
+ const RESULT_TTL_MS = 6e4;
433
+ /** One turn of the event loop, after which the previous request's connection is back in the pool. */
434
+ const pauseBriefly = () => new Promise((resolve) => {
435
+ setTimeout(resolve, 0);
436
+ });
437
+ var StatusError = class extends Error {
438
+ status;
439
+ constructor(status) {
440
+ super(`HTTP ${status}`);
441
+ this.status = status;
442
+ }
443
+ };
444
+ /**
445
+ * What stopped a request.
446
+ * @param error - what the request threw.
447
+ * @returns the error kind (and the status, for an HTTP answer).
448
+ */
449
+ function errorOf$1(error) {
450
+ if (error instanceof StatusError) return {
451
+ kind: "http",
452
+ status: error.status
453
+ };
454
+ const name = error?.name;
455
+ const code = error?.cause?.code;
456
+ if (name === "TimeoutError" || name === "AbortError" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "UND_ERR_HEADERS_TIMEOUT" || code === "UND_ERR_BODY_TIMEOUT" || code === "ETIMEDOUT") return { kind: "timeout" };
457
+ return { kind: "network" };
458
+ }
459
+ /** The middle value; for an even count, the mean of the two middle ones. */
460
+ function median(values) {
461
+ const sorted = [...values].sort((a, b) => a - b);
462
+ const upper = sorted[Math.floor(sorted.length / 2)] ?? 0;
463
+ return sorted.length % 2 === 1 ? upper : ((sorted[sorted.length / 2 - 1] ?? upper) + upper) / 2;
464
+ }
465
+ /** Measures the network latency to the gateway. */
466
+ var LatencyProbe = class {
467
+ options;
468
+ last;
469
+ running;
470
+ now;
471
+ clock;
472
+ /**
473
+ * @param options - the gateway origin, the plugin's user agent, and the fetch and clock seams.
474
+ */
475
+ constructor(options) {
476
+ this.options = options;
477
+ this.now = options.now ?? Date.now;
478
+ this.clock = options.clock ?? (() => performance.now());
479
+ }
480
+ /**
481
+ * The latency, measured now or within the last minute. One measurement runs at a time: a call while one runs
482
+ * shares it.
483
+ * @param fresh - measure again even when the last result is younger than a minute.
484
+ * @returns the result (a failure is a result too, with its error).
485
+ */
486
+ measure(fresh = false) {
487
+ if (this.running !== void 0) return this.running;
488
+ const last = this.last;
489
+ if (!fresh && last !== void 0 && this.now() - last.measuredAt < RESULT_TTL_MS) return Promise.resolve(last);
490
+ const running = this.run().then((result) => {
491
+ this.last = result;
492
+ return result;
493
+ }).finally(() => {
494
+ this.running = void 0;
495
+ });
496
+ this.running = running;
497
+ return running;
498
+ }
499
+ async run() {
500
+ const samples = [];
501
+ let warmup;
502
+ try {
503
+ warmup = await this.once();
504
+ for (let index = 0; index < TIMED_REQUESTS; index++) {
505
+ await (this.options.pause ?? pauseBriefly)();
506
+ samples.push(await this.once());
507
+ }
508
+ } catch (error) {
509
+ return {
510
+ samplesMs: samples,
511
+ ...warmup === void 0 ? {} : { warmupMs: warmup },
512
+ measuredAt: this.now(),
513
+ error: errorOf$1(error)
514
+ };
515
+ }
516
+ return {
517
+ medianMs: Math.round(median(samples)),
518
+ samplesMs: samples,
519
+ warmupMs: warmup,
520
+ measuredAt: this.now()
521
+ };
522
+ }
523
+ /** One `GET /health`, timed until its body has been read (which also lets the connection be reused). */
524
+ async once() {
525
+ const init = {
526
+ method: "GET",
527
+ headers: {
528
+ accept: "application/json",
529
+ "user-agent": this.options.userAgent
530
+ },
531
+ cache: "no-store",
532
+ redirect: "error",
533
+ signal: (this.options.timeout ?? ((ms) => AbortSignal.timeout(ms)))(REQUEST_TIMEOUT_MS)
534
+ };
535
+ const started = this.clock();
536
+ const response = await (this.options.fetch ?? globalThis.fetch)(`${this.options.origin}/health`, init);
537
+ await response.arrayBuffer();
538
+ const elapsed = Math.round(this.clock() - started);
539
+ if (!response.ok) throw new StatusError(response.status);
540
+ return elapsed;
541
+ }
542
+ };
543
+ function json(status, body) {
544
+ return new Response(JSON.stringify(body), {
545
+ status,
546
+ headers: {
547
+ "content-type": "application/json; charset=utf-8",
548
+ "cache-control": "no-store"
549
+ }
550
+ });
551
+ }
552
+ /**
553
+ * The latency route.
554
+ * @param probe - the probe.
555
+ * @returns routes for the client connection.
556
+ */
557
+ function latencyRoutes(probe) {
558
+ return [{
559
+ path: LATENCY_ROUTE,
560
+ methods: ["POST"],
561
+ requestBody: "buffered",
562
+ fetch: async (request) => {
563
+ try {
564
+ return json(200, await probe.measure(new URL(request.url, "http://host").searchParams.get("fresh") === "1"));
565
+ } catch {
566
+ return json(500, { error: {
567
+ code: "INTERNAL",
568
+ message: "The latency could not be measured. 网络延迟没有测成,请稍后重试。"
569
+ } });
570
+ }
571
+ }
572
+ }];
573
+ }
574
+ //#endregion
380
575
  //#region src/gateway/errors.ts
381
576
  /**
382
577
  * Failures the plugin reports to the model: a gateway refusal, or a request the
@@ -1571,7 +1766,7 @@ const ENDPOINT = {
1571
1766
  const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1572
1767
  const strings$1 = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
1573
1768
  const positive$1 = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
1574
- const price = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
1769
+ const price$1 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
1575
1770
  /**
1576
1771
  * The protocol a model family is called over best, before the catalog's endpoint list has a say:
1577
1772
  * Claude speaks Messages natively; GPT, the o-series, Codex, and Grok keep their reasoning state
@@ -1655,10 +1850,10 @@ function parseCatalog(body) {
1655
1850
  ...defaultReasoning === void 0 ? {} : { defaultReasoning },
1656
1851
  adaptiveThinking: capabilities.adaptive_thinking === true,
1657
1852
  cost: {
1658
- input: price(entry.input_price_per_mtok),
1659
- output: price(entry.output_price_per_mtok),
1660
- cacheRead: price(entry.cache_read_price_per_mtok),
1661
- cacheWrite: price(entry.cache_write_price_per_mtok)
1853
+ input: price$1(entry.input_price_per_mtok),
1854
+ output: price$1(entry.output_price_per_mtok),
1855
+ cacheRead: price$1(entry.cache_read_price_per_mtok),
1856
+ cacheWrite: price$1(entry.cache_write_price_per_mtok)
1662
1857
  }
1663
1858
  });
1664
1859
  }
@@ -4074,6 +4269,59 @@ function parsePricing(value, audioUnit) {
4074
4269
  } }
4075
4270
  };
4076
4271
  }
4272
+ const price = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
4273
+ /** A rule condition: `null` or absent is "any", a boolean is kept as it is (false included), anything else is unreadable. */
4274
+ function condition(raw, snake) {
4275
+ const value = field(raw, snake);
4276
+ if (value === void 0 || value === null) return {};
4277
+ return typeof value === "boolean" ? { value } : void 0;
4278
+ }
4279
+ /**
4280
+ * Parse `video_pricing`. Every rule is checked: one unreadable rule makes the
4281
+ * whole object unusable, since dropping it could make another rule look unique.
4282
+ * @param value - the entry's `video_pricing`.
4283
+ * @returns the pricing, the reason it cannot be used, or nothing when the entry has none.
4284
+ */
4285
+ function parseVideoPricing(value) {
4286
+ if (value === void 0 || value === null) return {};
4287
+ const raw = record$3(value);
4288
+ if (raw === void 0) return { videoPricingIssue: "invalid" };
4289
+ if (field(raw, "schema_version") !== 1) return { videoPricingIssue: "unknown-schema" };
4290
+ const invalid = { videoPricingIssue: "invalid" };
4291
+ const estimateOnly = field(raw, "estimate_only");
4292
+ if (field(raw, "currency") !== "CNY" || field(raw, "final_basis") !== "provider_tokens" || field(raw, "estimate_basis") !== "output_plus_reference_video_seconds" || typeof estimateOnly !== "boolean") return invalid;
4293
+ const rulesRaw = field(raw, "rules");
4294
+ if (!Array.isArray(rulesRaw) || rulesRaw.length === 0) return invalid;
4295
+ const rules = [];
4296
+ for (const item of rulesRaw) {
4297
+ const entry = record$3(item);
4298
+ if (entry === void 0) return invalid;
4299
+ const resolution = text$4(field(entry, "resolution"));
4300
+ const perMillion = price(field(entry, "price_per_million_tokens"));
4301
+ const estimateRaw = field(entry, "estimated_price_per_second");
4302
+ const perSecond = estimateRaw === void 0 || estimateRaw === null ? void 0 : price(estimateRaw);
4303
+ const video = condition(entry, "reference_video");
4304
+ const audio = condition(entry, "reference_audio");
4305
+ const image = condition(entry, "reference_image");
4306
+ if (resolution === void 0 || perMillion === void 0 || estimateRaw !== void 0 && estimateRaw !== null && perSecond === void 0 || video === void 0 || audio === void 0 || image === void 0) return invalid;
4307
+ rules.push({
4308
+ resolution,
4309
+ ...video.value === void 0 ? {} : { referenceVideo: video.value },
4310
+ ...audio.value === void 0 ? {} : { referenceAudio: audio.value },
4311
+ ...image.value === void 0 ? {} : { referenceImage: image.value },
4312
+ pricePerMillionTokensCny: perMillion,
4313
+ ...perSecond === void 0 ? {} : { estimatedPricePerSecondCny: perSecond }
4314
+ });
4315
+ }
4316
+ return { videoPricing: {
4317
+ schemaVersion: 1,
4318
+ currency: "CNY",
4319
+ finalBasis: "provider_tokens",
4320
+ estimateBasis: "output_plus_reference_video_seconds",
4321
+ estimateOnly,
4322
+ rules
4323
+ } };
4324
+ }
4077
4325
  /** Which kind of media model a catalog entry is, or undefined for a chat or internal model. */
4078
4326
  function kindOf(entry, capabilities, audio) {
4079
4327
  if (text$4(entry.internal_role) !== void 0) return void 0;
@@ -4115,6 +4363,7 @@ function parseMediaCatalog(body) {
4115
4363
  const name = text$4(entry.display_name) ?? id;
4116
4364
  const description = text$4(entry.description);
4117
4365
  const pricing = parsePricing(entry.media_pricing, audio?.billingUnit);
4366
+ const { videoPricing, videoPricingIssue } = parseVideoPricing(field(entry, "video_pricing"));
4118
4367
  const inputModalities = strings(capabilities.input_modalities) ?? strings(entry.input_modalities) ?? [];
4119
4368
  const endpoints = strings(capabilities.allowed_endpoints) ?? [];
4120
4369
  const aliases = (strings(entry.aliases) ?? []).map((alias) => alias.trim()).filter((alias) => alias !== "" && alias !== id);
@@ -4133,6 +4382,8 @@ function parseMediaCatalog(body) {
4133
4382
  ...aliases.length === 0 ? {} : { aliases },
4134
4383
  ...description === void 0 ? {} : { description },
4135
4384
  ...pricing === void 0 ? {} : { pricing },
4385
+ ...videoPricing === void 0 ? {} : { videoPricing },
4386
+ ...videoPricingIssue === void 0 ? {} : { videoPricingIssue },
4136
4387
  ...video === void 0 ? {} : { video },
4137
4388
  ...audio === void 0 ? {} : { audio },
4138
4389
  ...audioKind === void 0 ? {} : { audioKind }
@@ -4960,7 +5211,136 @@ var GatewaySearchProvider = class {
4960
5211
  }
4961
5212
  };
4962
5213
  //#endregion
5214
+ //#region src/util/decimal.ts
5215
+ const PATTERN = /^(-?)(\d+)(?:\.(\d*))?(?:e([+-]?\d+))?$/i;
5216
+ /**
5217
+ * The exact decimal of a finite number (as written by `String`) or a decimal string.
5218
+ * @param value - the number or text, such as `0.5819`, `1e-7` or `"3.98066354"`.
5219
+ * @returns the decimal.
5220
+ * @throws RangeError for anything that is not a finite decimal.
5221
+ */
5222
+ function decimal(value) {
5223
+ if (typeof value === "number" && !Number.isFinite(value)) throw new RangeError(`${value} is not a finite number`);
5224
+ const text = typeof value === "number" ? String(value) : value.trim();
5225
+ const match = PATTERN.exec(text);
5226
+ if (match === null) throw new RangeError(`"${text}" is not a decimal number`);
5227
+ const [, sign, whole = "0", fraction = "", exponent = "0"] = match;
5228
+ let digits = `${whole}${fraction}`;
5229
+ let scale = fraction.length - Number(exponent);
5230
+ if (scale < 0) {
5231
+ digits += "0".repeat(-scale);
5232
+ scale = 0;
5233
+ }
5234
+ const units = BigInt(digits);
5235
+ return {
5236
+ units: sign === "-" ? -units : units,
5237
+ scale
5238
+ };
5239
+ }
5240
+ /** Zero. */
5241
+ const ZERO = {
5242
+ units: 0n,
5243
+ scale: 0
5244
+ };
5245
+ function rescale(value, scale) {
5246
+ return value.units * 10n ** BigInt(scale - value.scale);
5247
+ }
5248
+ /**
5249
+ * The sum of two decimals.
5250
+ * @param a - the first.
5251
+ * @param b - the second.
5252
+ * @returns `a + b`, exactly.
5253
+ */
5254
+ function add(a, b) {
5255
+ const scale = Math.max(a.scale, b.scale);
5256
+ return {
5257
+ units: rescale(a, scale) + rescale(b, scale),
5258
+ scale
5259
+ };
5260
+ }
5261
+ /**
5262
+ * The product of two decimals.
5263
+ * @param a - the first.
5264
+ * @param b - the second.
5265
+ * @returns `a × b`, exactly.
5266
+ */
5267
+ function multiply(a, b) {
5268
+ return {
5269
+ units: a.units * b.units,
5270
+ scale: a.scale + b.scale
5271
+ };
5272
+ }
5273
+ /**
5274
+ * Round half up (away from zero) to a number of decimals.
5275
+ * @param value - the decimal.
5276
+ * @param places - decimals to keep.
5277
+ * @returns the rounded decimal.
5278
+ */
5279
+ function roundHalfUp(value, places) {
5280
+ if (value.scale <= places) return value;
5281
+ const factor = 10n ** BigInt(value.scale - places);
5282
+ const negative = value.units < 0n;
5283
+ const rounded = ((negative ? -value.units : value.units) + factor / 2n) / factor;
5284
+ return {
5285
+ units: negative ? -rounded : rounded,
5286
+ scale: places
5287
+ };
5288
+ }
5289
+ /**
5290
+ * Round up to a whole number (towards positive infinity).
5291
+ * @param value - the decimal.
5292
+ * @returns the smallest whole number not below it.
5293
+ */
5294
+ function ceil(value) {
5295
+ if (value.scale <= 0) return value;
5296
+ const factor = 10n ** BigInt(value.scale);
5297
+ return {
5298
+ units: value.units / factor + (value.units > 0n && value.units % factor !== 0n ? 1n : 0n),
5299
+ scale: 0
5300
+ };
5301
+ }
5302
+ /**
5303
+ * Exact text without trailing zeros (`2.9095`, `5`), padded to at least `minFraction` decimals.
5304
+ * @param value - the decimal.
5305
+ * @param minFraction - decimals always shown (`5.00` with 2).
5306
+ * @returns the text.
5307
+ */
5308
+ function format(value, minFraction = 0) {
5309
+ const negative = value.units < 0n;
5310
+ const digits = (negative ? -value.units : value.units).toString().padStart(value.scale + 1, "0");
5311
+ const whole = digits.slice(0, digits.length - value.scale);
5312
+ const fraction = digits.slice(digits.length - value.scale).replace(/0+$/, "").padEnd(minFraction, "0");
5313
+ const text = fraction === "" ? whole : `${whole}.${fraction}`;
5314
+ return negative && /[1-9]/.test(text) ? `-${text}` : text;
5315
+ }
5316
+ /**
5317
+ * The nearest number, for fields typed as numbers (never for money amounts).
5318
+ * @param value - the decimal.
5319
+ * @returns the number.
5320
+ */
5321
+ function toNumber(value) {
5322
+ return Number(format(value));
5323
+ }
5324
+ //#endregion
4963
5325
  //#region src/pricing.ts
5326
+ /**
5327
+ * Price estimates from the catalog's `media_pricing` (selling prices with the
5328
+ * account multiplier applied). The gateway estimates the same way at admission:
5329
+ * per-second video prices times billed seconds, where billed seconds are the
5330
+ * output length plus the summed reference video length, rounded up once.
5331
+ * Estimates are for the user's information; the gateway's receipt is the charge.
5332
+ *
5333
+ * Video models priced per video Token (`video_pricing`) are quoted by
5334
+ * {@link quoteVideo}: the matching rule's per-second estimate times the output
5335
+ * length plus every reference video's length, in exact decimals. The final
5336
+ * charge is the provider's billable Tokens times the rule's Token price, so a
5337
+ * Token price is never shown as an unconditional per-second price, never as
5338
+ * 未定价 and never as free — and what cannot be estimated says so.
5339
+ *
5340
+ * A model without a price is "not priced" (未定价), never free: only a price the
5341
+ * catalog states as zero is shown as ¥0.
5342
+ * @module dsh-vibedev/pricing
5343
+ */
4964
5344
  /** Shown wherever the catalog gives no price. */
4965
5345
  const UNPRICED = {
4966
5346
  en: "not priced",
@@ -5017,13 +5397,52 @@ function unitSuffix(unit, kind) {
5017
5397
  };
5018
5398
  }
5019
5399
  }
5400
+ /** Shown for a model whose `video_pricing` this plugin cannot use. */
5401
+ const VIDEO_PRICING_UNSUPPORTED = {
5402
+ en: "this plugin version does not support this video pricing mode: estimate unavailable; billed by actual video Token usage",
5403
+ zh: "当前插件版本暂不支持此视频计价方式的预估;按实际视频 Token 用量结算"
5404
+ };
5405
+ /** `480p 无参考视频、有参考音频` / `480p without reference video and with reference audio`. */
5406
+ function describeRuleConditions(rule, lang) {
5407
+ const parts = [
5408
+ [
5409
+ rule.referenceVideo,
5410
+ "reference video",
5411
+ "参考视频"
5412
+ ],
5413
+ [
5414
+ rule.referenceAudio,
5415
+ "reference audio",
5416
+ "参考音频"
5417
+ ],
5418
+ [
5419
+ rule.referenceImage,
5420
+ "reference image",
5421
+ "参考图"
5422
+ ]
5423
+ ].flatMap(([value, en, zh]) => value === void 0 ? [] : [lang === "zh" ? `${value ? "有" : "无"}${zh}` : `${value ? "with" : "without"} ${en}`]);
5424
+ return parts.length === 0 ? rule.resolution : `${rule.resolution} ${parts.join(lang === "zh" ? "、" : " and ")}`;
5425
+ }
5426
+ /** Every rule of a video Token pricing, each with its Token price and its per-second estimate (or that it has none). */
5427
+ function describeTokenPricing(pricing, lang) {
5428
+ const rules = pricing.rules.map((rule) => {
5429
+ const where = describeRuleConditions(rule, lang);
5430
+ const perMillion = exactYuan(rule.pricePerMillionTokensCny);
5431
+ const perSecond = rule.estimatedPricePerSecondCny === void 0 ? void 0 : exactYuan(rule.estimatedPricePerSecondCny);
5432
+ return lang === "zh" ? `${where} ${perMillion}/百万 Token(${perSecond === void 0 ? "暂无每秒预估" : `预计 ${perSecond}/秒`})` : `${where} ${perMillion} per million Tokens (${perSecond === void 0 ? "no per-second estimate" : `about ${perSecond}/s`})`;
5433
+ });
5434
+ return lang === "zh" ? `视频 Token 计价:${rules.join(";")}` : `video Token pricing (billed by actual video Tokens): ${rules.join(", ")}`;
5435
+ }
5020
5436
  /**
5021
5437
  * A one-line price for listings: `¥0.10 per image`, `¥0.99/s (720p)`; `not priced` without a price.
5438
+ * A video Token price lists its rules (`视频 Token 计价:480p 无参考视频 ¥60.06/百万 Token(预计 ¥0.5819/秒)…`).
5022
5439
  * @param model - the model.
5023
5440
  * @param lang - the language.
5024
5441
  * @returns the price line.
5025
5442
  */
5026
5443
  function describePrice(model, lang = "en") {
5444
+ if (model.videoPricingIssue !== void 0) return VIDEO_PRICING_UNSUPPORTED[lang];
5445
+ if (model.videoPricing !== void 0) return describeTokenPricing(model.videoPricing, lang);
5027
5446
  const pricing = model.pricing;
5028
5447
  if (pricing === void 0) return UNPRICED[lang];
5029
5448
  const per = (unit) => unitSuffix(unit, model.kind)[lang];
@@ -5045,31 +5464,11 @@ function estimateImages(model, count) {
5045
5464
  basis: count === 1 ? `${yuan(price.amount)} per image` : `${yuan(price.amount)} × ${count} images`
5046
5465
  };
5047
5466
  }
5048
- /**
5049
- * Estimate a video request.
5050
- * @param model - the video model.
5051
- * @param duration - the requested length in seconds, when given.
5052
- * @param resolution - the requested resolution, when given.
5053
- * @param referenceMs - the summed length of the reference videos.
5054
- * @returns the estimate, or undefined without a price.
5055
- */
5056
- function estimateVideo(model, duration, resolution, referenceMs = 0) {
5467
+ /** The legacy `media_pricing` price a video request pays: its resolution's tier, the only offered one, or the default. */
5468
+ function legacyVideoPrice(model, resolution) {
5057
5469
  if (model.pricing === void 0) return void 0;
5058
5470
  const only = model.video?.resolutions?.length === 1 ? model.video.resolutions[0] : void 0;
5059
- const price = tierFor(model.pricing, resolution ?? only);
5060
- if (price === void 0) return void 0;
5061
- if (price.unit === "generation") return {
5062
- amountCny: price.amount,
5063
- basis: `${yuan(price.amount)} per video`
5064
- };
5065
- if (price.unit !== "second") return void 0;
5066
- const output = duration ?? DEFAULT_BILLED_SECONDS;
5067
- const reference = Math.ceil(referenceMs / 1e3);
5068
- const seconds = output + reference;
5069
- return {
5070
- amountCny: price.amount * seconds,
5071
- basis: `${yuan(price.amount)}/s × ${reference === 0 ? `${output} s` : `(${output} s output + ${reference} s of reference video)`}`
5072
- };
5471
+ return tierFor(model.pricing, resolution ?? only);
5073
5472
  }
5074
5473
  /**
5075
5474
  * Quote an audio request: music, podcast and speech generation, or a transcription.
@@ -5134,6 +5533,316 @@ function quoteAudio(model, inputSeconds) {
5134
5533
  }
5135
5534
  };
5136
5535
  }
5536
+ /** Shown wherever video Token pricing gives no estimate. */
5537
+ const TOKEN_UNAVAILABLE = {
5538
+ en: "estimate unavailable; billed by actual video Token usage",
5539
+ zh: "无法预估;按实际视频 Token 用量结算"
5540
+ };
5541
+ const BILLED_BY_TOKENS = {
5542
+ en: "billed by actual video Token usage",
5543
+ zh: "按实际视频 Token 用量结算"
5544
+ };
5545
+ /** An exact price: `¥0.6952`, `¥36.036`, `¥60.00` (at least two decimals, never rounded). */
5546
+ function exactYuan(amount) {
5547
+ return `¥${format(decimal(amount), 2)}`;
5548
+ }
5549
+ /** A display amount: half up to two decimals (`2.9095` → `¥2.91`). */
5550
+ function roundedYuan(amount) {
5551
+ return `¥${format(roundHalfUp(amount, 2), 2)}`;
5552
+ }
5553
+ const positiveSeconds = (value) => typeof value === "number" && Number.isFinite(value) && value > 0;
5554
+ const wholeCount = (value) => value === void 0 || typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
5555
+ /** What is wrong with a request, in both languages, or undefined when it can be quoted. */
5556
+ function requestProblem(model, request) {
5557
+ if (model.kind !== "video") return {
5558
+ en: `${model.id} is not a video model.`,
5559
+ zh: `${model.id} 不是视频模型。`
5560
+ };
5561
+ if (request.durationSeconds !== void 0 && !positiveSeconds(request.durationSeconds)) return {
5562
+ en: "The output duration must be a positive number of seconds.",
5563
+ zh: "输出时长必须是正数秒。"
5564
+ };
5565
+ if (request.resolution !== void 0 && typeof request.resolution !== "string") return {
5566
+ en: "The resolution must be text.",
5567
+ zh: "分辨率必须是文本。"
5568
+ };
5569
+ const references = request.references;
5570
+ if (references === void 0) return void 0;
5571
+ if (typeof references !== "object" || references === null) return {
5572
+ en: "references must be an object.",
5573
+ zh: "references 必须是对象。"
5574
+ };
5575
+ if (!wholeCount(references.images) || !wholeCount(references.audios)) return {
5576
+ en: "Reference image and audio counts must be whole numbers of at least 0.",
5577
+ zh: "参考图和参考音频的数量必须是不小于 0 的整数。"
5578
+ };
5579
+ if (references.videos !== void 0) {
5580
+ if (!Array.isArray(references.videos)) return {
5581
+ en: "references.videos must be a list.",
5582
+ zh: "references.videos 必须是列表。"
5583
+ };
5584
+ for (const [index, video] of references.videos.entries()) if (typeof video !== "object" || video === null || video.durationSeconds !== void 0 && !positiveSeconds(video.durationSeconds)) return {
5585
+ en: `Reference video ${index + 1} must give its length as a positive number of seconds, or none when unknown.`,
5586
+ zh: `第 ${index + 1} 个参考视频的时长必须是正数秒(未知时不填)。`
5587
+ };
5588
+ }
5589
+ }
5590
+ /** The resolutions the catalog offers for a model, across its usable modes. */
5591
+ function offeredResolutions(model) {
5592
+ const video = model.video;
5593
+ if (video === void 0) return [];
5594
+ const modes = Object.values(effectiveVideoModes(video));
5595
+ const lists = modes.length === 0 ? [video.resolutions ?? []] : modes.map((mode) => mode?.resolutions ?? video.resolutions ?? []);
5596
+ const offered = /* @__PURE__ */ new Map();
5597
+ for (const list of lists) for (const item of list) if (!offered.has(item.toLowerCase())) offered.set(item.toLowerCase(), item);
5598
+ return [...offered.values()];
5599
+ }
5600
+ function describePresence(resolution, presence) {
5601
+ const has = (present, en, zh) => ({
5602
+ en: `${present ? "with" : "without"} ${en}`,
5603
+ zh: `${present ? "有" : "无"}${zh}`
5604
+ });
5605
+ const parts = [
5606
+ has(presence.video, "reference video", "参考视频"),
5607
+ has(presence.audio, "reference audio", "参考音频"),
5608
+ has(presence.image, "reference image", "参考图")
5609
+ ];
5610
+ return {
5611
+ en: `${resolution} ${parts.map((part) => part.en).join(", ")}`,
5612
+ zh: `${resolution}、${parts.map((part) => part.zh).join("、")}`
5613
+ };
5614
+ }
5615
+ const specificity = (rule) => [
5616
+ rule.referenceVideo,
5617
+ rule.referenceAudio,
5618
+ rule.referenceImage
5619
+ ].filter((item) => item !== void 0).length;
5620
+ const matches = (expected, present) => expected === void 0 || expected === present;
5621
+ function ruleOf(rule) {
5622
+ return {
5623
+ resolution: rule.resolution,
5624
+ ...rule.referenceVideo === void 0 ? {} : { referenceVideo: rule.referenceVideo },
5625
+ ...rule.referenceAudio === void 0 ? {} : { referenceAudio: rule.referenceAudio },
5626
+ ...rule.referenceImage === void 0 ? {} : { referenceImage: rule.referenceImage }
5627
+ };
5628
+ }
5629
+ /** Seconds as written: `7`, `7.5`. */
5630
+ const secondsText = (value) => format(value);
5631
+ function quoteTokens(model, pricing, request) {
5632
+ const unavailable = (reason, basis, pricePerMillion) => ({
5633
+ status: "unavailable",
5634
+ mode: "video_token",
5635
+ model: model.id,
5636
+ reason,
5637
+ ...pricePerMillion === void 0 ? {} : { pricePerMillionTokensCny: pricePerMillion },
5638
+ label: TOKEN_UNAVAILABLE,
5639
+ basis
5640
+ });
5641
+ let resolution = request.resolution?.trim();
5642
+ if (resolution === void 0 || resolution === "") {
5643
+ const offered = offeredResolutions(model);
5644
+ if (offered.length !== 1) return unavailable("missing-resolution", {
5645
+ en: `A resolution is needed to find the video Token price; ${BILLED_BY_TOKENS.en}.`,
5646
+ zh: `需要选择分辨率才能确定视频 Token 价格;${BILLED_BY_TOKENS.zh}。`
5647
+ });
5648
+ resolution = offered[0];
5649
+ }
5650
+ const videos = request.references?.videos ?? [];
5651
+ const presence = {
5652
+ video: videos.length > 0,
5653
+ audio: (request.references?.audios ?? 0) > 0,
5654
+ image: (request.references?.images ?? 0) > 0
5655
+ };
5656
+ const wanted = resolution.toLowerCase();
5657
+ const candidates = pricing.rules.filter((rule) => rule.resolution.trim().toLowerCase() === wanted && matches(rule.referenceVideo, presence.video) && matches(rule.referenceAudio, presence.audio) && matches(rule.referenceImage, presence.image));
5658
+ const asked = describePresence(resolution, presence);
5659
+ if (candidates.length === 0) return unavailable("no-matching-rule", {
5660
+ en: `The catalog has no video Token price for ${asked.en}; ${BILLED_BY_TOKENS.en}.`,
5661
+ zh: `目录中没有适用于 ${asked.zh} 的视频 Token 价格;${BILLED_BY_TOKENS.zh}。`
5662
+ });
5663
+ const top = Math.max(...candidates.map(specificity));
5664
+ const best = candidates.filter((rule) => specificity(rule) === top);
5665
+ if (best.length > 1) return unavailable("ambiguous-rules", {
5666
+ en: `Several video Token prices in the catalog apply equally to ${asked.en}, so the price cannot be determined; ${BILLED_BY_TOKENS.en}.`,
5667
+ zh: `目录中有多条视频 Token 价格同样适用于 ${asked.zh},无法确定价格;${BILLED_BY_TOKENS.zh}。`
5668
+ });
5669
+ const rule = best[0];
5670
+ const perMillion = rule.pricePerMillionTokensCny;
5671
+ const tokenPrice = {
5672
+ en: `${exactYuan(perMillion)} per million Tokens`,
5673
+ zh: `${exactYuan(perMillion)}/百万 Token`
5674
+ };
5675
+ const perSecond = rule.estimatedPricePerSecondCny;
5676
+ if (perSecond === void 0) return unavailable("no-estimated-price", {
5677
+ en: `The catalog gives no per-second estimate; ${tokenPrice.en}, ${BILLED_BY_TOKENS.en}.`,
5678
+ zh: `目录未给出每秒预估价;${tokenPrice.zh},${BILLED_BY_TOKENS.zh}。`
5679
+ }, perMillion);
5680
+ if (request.durationSeconds === void 0) return unavailable("missing-duration", {
5681
+ en: `An output duration is needed for an estimate; ${tokenPrice.en}, ${BILLED_BY_TOKENS.en}.`,
5682
+ zh: `需要输出时长才能预估;${tokenPrice.zh},${BILLED_BY_TOKENS.zh}。`
5683
+ }, perMillion);
5684
+ if (videos.some((video) => video.durationSeconds === void 0)) return unavailable("unknown-reference-duration", {
5685
+ en: `A reference video's length is unknown, so no estimate is possible; ${tokenPrice.en}, ${BILLED_BY_TOKENS.en}.`,
5686
+ zh: `参考视频时长未知,无法预估;${tokenPrice.zh},${BILLED_BY_TOKENS.zh}。`
5687
+ }, perMillion);
5688
+ const output = decimal(request.durationSeconds);
5689
+ const reference = videos.reduce((sum, video) => add(sum, decimal(video.durationSeconds)), ZERO);
5690
+ const billed = add(output, reference);
5691
+ const amount = multiply(decimal(perSecond), billed);
5692
+ const rate = exactYuan(perSecond);
5693
+ const seconds = presence.video ? {
5694
+ en: `(${secondsText(output)} s output + ${secondsText(reference)} s of reference video)`,
5695
+ zh: `(${secondsText(output)} 秒输出 + ${secondsText(reference)} 秒参考视频)`
5696
+ } : {
5697
+ en: `${secondsText(output)} s`,
5698
+ zh: `${secondsText(output)} 秒`
5699
+ };
5700
+ return {
5701
+ status: "estimate",
5702
+ mode: "video_token",
5703
+ model: model.id,
5704
+ currency: "CNY",
5705
+ amountCny: format(amount),
5706
+ estimatedPricePerSecondCny: perSecond,
5707
+ pricePerMillionTokensCny: perMillion,
5708
+ outputSeconds: request.durationSeconds,
5709
+ referenceVideoSeconds: toNumber(reference),
5710
+ billedSeconds: toNumber(billed),
5711
+ rule: ruleOf(rule),
5712
+ estimateOnly: true,
5713
+ finalBasis: "provider_tokens",
5714
+ label: {
5715
+ en: `about ${roundedYuan(amount)} · billed by actual video Tokens`,
5716
+ zh: `预计 ${roundedYuan(amount)} · 最终按实际视频 Token 结算`
5717
+ },
5718
+ basis: {
5719
+ en: `${rate}/s × ${seconds.en}, ${tokenPrice.en}`,
5720
+ zh: `${rate}/秒 × ${seconds.zh},${tokenPrice.zh}`
5721
+ }
5722
+ };
5723
+ }
5724
+ function quoteLegacy(model, request) {
5725
+ const resolution = request.resolution?.trim();
5726
+ const price = legacyVideoPrice(model, resolution === "" ? void 0 : resolution);
5727
+ if (price === void 0 || price.unit !== "generation" && price.unit !== "second") return {
5728
+ status: "unavailable",
5729
+ mode: "legacy",
5730
+ model: model.id,
5731
+ reason: "no-price",
5732
+ label: UNPRICED,
5733
+ basis: {
5734
+ en: "The catalog states no price for this request; the gateway receipt shows the charge.",
5735
+ zh: "目录未给出此请求的价格,以网关结算为准。"
5736
+ }
5737
+ };
5738
+ const estimate = (amount, basis) => {
5739
+ const shown = yuan(toNumber(amount));
5740
+ return {
5741
+ status: "estimate",
5742
+ mode: "legacy",
5743
+ model: model.id,
5744
+ currency: "CNY",
5745
+ amountCny: format(amount),
5746
+ label: {
5747
+ en: `about ${shown}`,
5748
+ zh: `约 ${shown}`
5749
+ },
5750
+ basis
5751
+ };
5752
+ };
5753
+ if (price.unit === "generation") return estimate(decimal(price.amount), {
5754
+ en: `${yuan(price.amount)} per video`,
5755
+ zh: `${yuan(price.amount)}/次`
5756
+ });
5757
+ const videos = request.references?.videos ?? [];
5758
+ if (videos.some((video) => video.durationSeconds === void 0)) return {
5759
+ status: "unavailable",
5760
+ mode: "legacy",
5761
+ model: model.id,
5762
+ reason: "unknown-reference-duration",
5763
+ label: {
5764
+ en: "estimate unavailable",
5765
+ zh: "无法预估"
5766
+ },
5767
+ basis: {
5768
+ en: `A reference video's length is unknown, so ${yuan(price.amount)}/s × (output + reference video seconds) cannot be estimated; the gateway receipt shows the charge.`,
5769
+ zh: `参考视频时长未知,无法按 ${yuan(price.amount)}/秒 × (输出 + 参考视频秒数) 预估,以网关结算为准。`
5770
+ }
5771
+ };
5772
+ const output = decimal(request.durationSeconds ?? DEFAULT_BILLED_SECONDS);
5773
+ const reference = ceil(videos.reduce((sum, video) => add(sum, decimal(video.durationSeconds)), ZERO));
5774
+ const amount = multiply(decimal(price.amount), add(output, reference));
5775
+ const plain = reference.units === 0n;
5776
+ return estimate(amount, {
5777
+ en: `${yuan(price.amount)}/s × ${plain ? `${format(output)} s` : `(${format(output)} s output + ${format(reference)} s of reference video)`}`,
5778
+ zh: `${yuan(price.amount)}/秒 × ${plain ? `${format(output)} 秒` : `(${format(output)} 秒输出 + ${format(reference)} 秒参考视频)`}`
5779
+ });
5780
+ }
5781
+ /**
5782
+ * Quote a video request from the catalog alone: no upload, no submission.
5783
+ *
5784
+ * Video Token pricing: the unique most specific rule for the resolution and
5785
+ * the presence of reference video, audio and images; its per-second estimate
5786
+ * times the output length plus every reference video's length. A model whose
5787
+ * `video_pricing` cannot be read gets no estimate and never falls back to its
5788
+ * legacy price. Legacy models are quoted as {@link estimateVideo} always did.
5789
+ * @param model - the resolved model.
5790
+ * @param request - the request.
5791
+ * @returns the quote.
5792
+ */
5793
+ function quoteVideo(model, request) {
5794
+ const mode = model.videoPricing !== void 0 || model.videoPricingIssue !== void 0 ? "video_token" : model.pricing !== void 0 ? "legacy" : "none";
5795
+ const problem = requestProblem(model, request);
5796
+ if (problem !== void 0) return {
5797
+ status: "unavailable",
5798
+ mode,
5799
+ model: model.id,
5800
+ reason: "invalid-request",
5801
+ label: mode === "video_token" ? TOKEN_UNAVAILABLE : {
5802
+ en: "estimate unavailable",
5803
+ zh: "无法预估"
5804
+ },
5805
+ basis: {
5806
+ en: `The request cannot be quoted: ${problem.en}`,
5807
+ zh: `无法预估此请求:${problem.zh}`
5808
+ }
5809
+ };
5810
+ if (model.videoPricingIssue !== void 0) return {
5811
+ status: "unavailable",
5812
+ mode,
5813
+ model: model.id,
5814
+ reason: model.videoPricingIssue === "unknown-schema" ? "unknown-schema" : "invalid-pricing",
5815
+ label: TOKEN_UNAVAILABLE,
5816
+ basis: model.videoPricingIssue === "unknown-schema" ? {
5817
+ en: `This plugin version does not support this video pricing mode, so no estimate is possible; ${BILLED_BY_TOKENS.en}.`,
5818
+ zh: `当前插件版本暂不支持此视频计价方式的预估;${BILLED_BY_TOKENS.zh}。`
5819
+ } : {
5820
+ en: `The catalog's video Token pricing cannot be read, so no estimate is possible; ${BILLED_BY_TOKENS.en}.`,
5821
+ zh: `目录中的视频 Token 价格无法读取,暂无法预估;${BILLED_BY_TOKENS.zh}。`
5822
+ }
5823
+ };
5824
+ if (model.videoPricing !== void 0) return quoteTokens(model, model.videoPricing, request);
5825
+ if (model.pricing !== void 0) return quoteLegacy(model, request);
5826
+ return {
5827
+ status: "unavailable",
5828
+ mode: "none",
5829
+ model: model.id,
5830
+ reason: "no-price",
5831
+ label: UNPRICED,
5832
+ basis: {
5833
+ en: "The catalog states no price for this model; the gateway receipt shows the charge.",
5834
+ zh: "目录未给出价格,以网关结算为准。"
5835
+ }
5836
+ };
5837
+ }
5838
+ /**
5839
+ * The estimate a task records: the quote amount half up to two decimals.
5840
+ * @param quote - the quote.
5841
+ * @returns `8.34`, or undefined without an estimate.
5842
+ */
5843
+ function quotedCny(quote) {
5844
+ return quote.status === "estimate" ? format(roundHalfUp(decimal(quote.amountCny), 2), 2) : void 0;
5845
+ }
5137
5846
  //#endregion
5138
5847
  //#region src/audio/request.ts
5139
5848
  /**
@@ -6380,27 +7089,44 @@ async function prepareVideoTask(runtime, call, request, save) {
6380
7089
  bytes: item.media.data.byteLength,
6381
7090
  ...assets[index]?.durationMs === void 0 ? {} : { durationMs: assets[index]?.durationMs }
6382
7091
  }] : []);
6383
- checkReferenceDurations(model, videos, loaded.flatMap((item, index) => item.input === "referenceAudios" ? [{
7092
+ const audios = loaded.flatMap((item, index) => item.input === "referenceAudios" ? [{
6384
7093
  source: item.media.source,
6385
7094
  mime: item.media.mime,
6386
7095
  bytes: item.media.data.byteLength,
6387
7096
  ...assets[index]?.durationMs === void 0 ? {} : { durationMs: assets[index]?.durationMs }
6388
- }] : []));
7097
+ }] : []);
7098
+ checkReferenceDurations(model, videos, audios);
6389
7099
  const urls = {};
6390
7100
  for (const [index, item] of loaded.entries()) {
6391
7101
  const asset = assets[index];
6392
7102
  (urls[item.input] ??= []).push(asset.referenceUrl);
6393
7103
  }
6394
- const referenceMs = videos.reduce((sum, clip) => sum + (clip.durationMs ?? 0), 0);
6395
- const estimate = estimateVideo(model, plan.duration, plan.resolution, referenceMs);
7104
+ const quote = quoteVideo(model, {
7105
+ model: model.id,
7106
+ ...plan.resolution === void 0 ? {} : { resolution: plan.resolution },
7107
+ ...plan.duration === void 0 ? {} : { durationSeconds: plan.duration },
7108
+ references: {
7109
+ videos: videos.map((clip) => clip.durationMs === void 0 ? {} : { durationSeconds: clip.durationMs / 1e3 }),
7110
+ images: loaded.filter((item) => INPUT_KIND[item.input] === "image").length,
7111
+ audios: audios.length
7112
+ }
7113
+ });
7114
+ const estimatedCny = quotedCny(quote);
6396
7115
  const shape = [
6397
7116
  plan.duration === void 0 ? void 0 : `${plan.duration} s`,
6398
7117
  plan.aspectRatio,
6399
7118
  plan.resolution
6400
7119
  ].filter(Boolean).join(", ");
7120
+ const price = quote.status === "estimate" && quote.mode === "legacy" ? {
7121
+ en: `, ${quote.label.en} (${quote.basis.en})`,
7122
+ zh: `,${quote.label.zh}`
7123
+ } : {
7124
+ en: `, ${quote.label.en} (${quote.basis.en})`,
7125
+ zh: `,${quote.label.zh}(${quote.basis.zh})`
7126
+ };
6401
7127
  await runtime.confirmSpending(call, "video_generate", {
6402
- en: `Generate a video with ${model.id} (${plan.mode}${shape === "" ? "" : `, ${shape}`})${estimate === void 0 ? "" : `, about ${yuan(estimate.amountCny)} (${estimate.basis})`}. Charged only if it succeeds.`,
6403
- zh: `用 ${model.id} 生成视频(${plan.mode}${shape === "" ? "" : `,${shape}`})${estimate === void 0 ? "" : `,约 ${yuan(estimate.amountCny)}`},成功才扣费。`
7128
+ en: `Generate a video with ${model.id} (${plan.mode}${shape === "" ? "" : `, ${shape}`})${price.en}. Charged only if it succeeds.`,
7129
+ zh: `用 ${model.id} 生成视频(${plan.mode}${shape === "" ? "" : `,${shape}`})${price.zh},成功才扣费。`
6404
7130
  });
6405
7131
  const now = runtime.now();
6406
7132
  return {
@@ -6419,10 +7145,11 @@ async function prepareVideoTask(runtime, call, request, save) {
6419
7145
  endpoint: "/v1/videos",
6420
7146
  body: videoRequestBody(model.id, request.prompt, plan, urls),
6421
7147
  status: "submitting",
6422
- ...estimate === void 0 ? {} : { estimatedCny: estimate.amountCny.toFixed(2) }
7148
+ ...estimatedCny === void 0 ? {} : { estimatedCny }
6423
7149
  },
6424
7150
  inputs: loaded.map((item) => item.input),
6425
- shape
7151
+ shape,
7152
+ quote
6426
7153
  };
6427
7154
  }
6428
7155
  /**
@@ -6433,7 +7160,7 @@ async function prepareVideoTask(runtime, call, request, save) {
6433
7160
  function videoGenerateTool(runtime) {
6434
7161
  return defineTool({
6435
7162
  name: "video_generate",
6436
- description: "Generate a video with a VibeDev video model. It runs as a background job (usually 1-10 minutes): this call returns once the gateway accepts the task, you are notified when it finishes, and the file is saved in the workspace (media/videos/). Modes: text_to_video (prompt only), first_frame (animate an image), first_last_frame (animate from one image to another), omni_reference (reference images, videos and audio guide characters, motion, style and sound). Each model supports different modes, reference counts, durations, aspect ratios and resolutions; media_models lists them, and requests a model cannot serve are refused before anything is uploaded or charged. Charged per second of video (plus reference video length) only when it succeeds; a running task cannot be cancelled.",
7163
+ description: "Generate a video with a VibeDev video model. It runs as a background job (usually 1-10 minutes): this call returns once the gateway accepts the task, you are notified when it finishes, and the file is saved in the workspace (media/videos/). Modes: text_to_video (prompt only), first_frame (animate an image), first_last_frame (animate from one image to another), omni_reference (reference images, videos and audio guide characters, motion, style and sound). Each model supports different modes, reference counts, durations, aspect ratios and resolutions; media_models lists them, and requests a model cannot serve are refused before anything is uploaded or charged. Charged at the model's catalog price (per second of video plus reference video length, per generation, or by actual video Tokens; media_models lists it) only when it succeeds; a running task cannot be cancelled.",
6437
7164
  parameters: {
6438
7165
  prompt: {
6439
7166
  type: "string",
@@ -6621,8 +7348,9 @@ const view = (record) => ({
6621
7348
  ...record.outputs === void 0 ? {} : { outputs: record.outputs.map(({ index: _index, bytes: _bytes, ...output }) => ({ ...output })) },
6622
7349
  ...record.error === void 0 ? {} : { error: { ...record.error } },
6623
7350
  ...record.estimatedCny === void 0 ? {} : { estimatedCny: record.estimatedCny },
6624
- ...record.chargedCny === void 0 ? {} : { chargedCny: record.chargedCny },
7351
+ ...record.chargedCny === void 0 || record.settlement === "pending" ? {} : { chargedCny: record.chargedCny },
6625
7352
  ...record.settlement === void 0 ? {} : { settlement: record.settlement },
7353
+ ...record.settlement !== "pending" || record.settlementPendingReason === void 0 ? {} : { settlementPendingReason: record.settlementPendingReason },
6626
7354
  ...record.billing === void 0 ? {} : { billing: { ...record.billing } },
6627
7355
  createdAt: record.createdAt,
6628
7356
  updatedAt: record.updatedAt
@@ -6678,6 +7406,41 @@ var MediaHostService = class {
6678
7406
  return quoteAudio(await this.runtime.findModel(model, signal));
6679
7407
  }
6680
7408
  /**
7409
+ * What a video request is expected to cost, from the (cached) catalog alone:
7410
+ * nothing is uploaded, submitted or recorded. Video Token pricing gives the
7411
+ * matching rule's estimate (`预计 ¥8.34 · 最终按实际视频 Token 结算`) or says why there
7412
+ * is none; legacy prices are quoted as before. A model the account does not
7413
+ * have is an `invalid-request`; a catalog failure (no sign-in, no network) is thrown.
7414
+ * @param request - the model (id or alias), resolution, duration and references.
7415
+ * @param signal - cancels the catalog request.
7416
+ * @returns the quote, under the model's canonical id.
7417
+ */
7418
+ async videoQuote(request, signal) {
7419
+ const wanted = typeof request?.model === "string" ? request.model.trim() : "";
7420
+ let model;
7421
+ try {
7422
+ if (wanted === "") throw new MediaError("A video quote needs a model.", "MODEL_NOT_FOUND", { field: "model" });
7423
+ model = await this.runtime.findModel(wanted, signal);
7424
+ } catch (error) {
7425
+ if (!(error instanceof MediaError) || error.code !== "MODEL_NOT_FOUND") throw error;
7426
+ return {
7427
+ status: "unavailable",
7428
+ mode: "none",
7429
+ model: wanted,
7430
+ reason: "invalid-request",
7431
+ label: {
7432
+ en: "estimate unavailable",
7433
+ zh: "无法预估"
7434
+ },
7435
+ basis: {
7436
+ en: `There is no model "${wanted}" on this VibeDev account.`,
7437
+ zh: `当前 VibeDev 账号没有模型“${wanted}”。`
7438
+ }
7439
+ };
7440
+ }
7441
+ return quoteVideo(model, request);
7442
+ }
7443
+ /**
6681
7444
  * Generate images now and save them.
6682
7445
  * @param request - what to generate.
6683
7446
  * @param target - the workspace and where the files go.
@@ -7026,23 +7789,59 @@ const seconds = (value) => {
7026
7789
  const number = typeof value === "string" ? Number(value) : value;
7027
7790
  return typeof number === "number" && Number.isFinite(number) && number > 0 ? number : void 0;
7028
7791
  };
7029
- /** The billing facts of a task: whether the charge settled, and the billed length. */
7030
- function billing(raw, status) {
7031
- const blocks = [
7792
+ /** The blocks billing facts are read from, in order: `billing`, `usage`, `effective`, then the answer itself. */
7793
+ function billingBlocks(raw) {
7794
+ return [
7032
7795
  record$1(raw.billing),
7033
7796
  record$1(raw.usage),
7034
7797
  record$1(raw.effective),
7035
7798
  raw
7036
7799
  ].filter((block) => block !== void 0);
7037
- const pick = (...names) => {
7038
- for (const block of blocks) for (const name of names) if (block[name] !== void 0) return block[name];
7039
- };
7040
- const originalSeconds = seconds(pick("original_seconds", "billed_original_seconds", "original_duration_seconds"));
7041
- const minutes = seconds(pick("billed_minutes", "minutes"));
7042
- const stateRaw = text$1(pick("settlement_state", "settlement_status"))?.toLowerCase();
7043
- const settlement = status.toLowerCase() === SETTLEMENT_PENDING || stateRaw === "pending" ? "pending" : stateRaw === "settled" || stateRaw === "completed" ? "settled" : void 0;
7800
+ }
7801
+ function pickFrom(blocks, ...names) {
7802
+ for (const block of blocks) for (const name of names) if (block[name] !== void 0 && block[name] !== null) return block[name];
7803
+ }
7804
+ const SETTLEMENT_FIELDS = [
7805
+ "billing_status",
7806
+ "settlement_state",
7807
+ "settlement_status"
7808
+ ];
7809
+ const tokens = (value) => {
7810
+ const number = typeof value === "string" && /^\d+$/.test(value.trim()) ? Number(value) : value;
7811
+ return typeof number === "number" && Number.isSafeInteger(number) && number >= 0 ? number : void 0;
7812
+ };
7813
+ /**
7814
+ * Whether a task's charge settled, for video and audio alike. An explicit
7815
+ * pending (anywhere in the answer) wins; settled needs an explicit word. Whether
7816
+ * any status was given at all is reported apart, so the tracker can tell an older
7817
+ * gateway (no status: a charge then implies settled) from a word it does not know.
7818
+ */
7819
+ function settlementOf(raw, status) {
7820
+ const blocks = billingBlocks(raw);
7821
+ const words = [];
7822
+ let reported = status.toLowerCase() === SETTLEMENT_PENDING;
7823
+ for (const block of blocks) for (const name of SETTLEMENT_FIELDS) {
7824
+ if (block[name] === void 0 || block[name] === null) continue;
7825
+ reported = true;
7826
+ const word = text$1(block[name])?.toLowerCase();
7827
+ if (word !== void 0) words.push(word);
7828
+ }
7829
+ const settlement = status.toLowerCase() === SETTLEMENT_PENDING || words.includes("pending") ? "pending" : words.includes("settled") || words.includes("completed") ? "settled" : void 0;
7830
+ const reason = settlement === "pending" ? text$1(pickFrom(blocks, "billing_pending_reason", "settlement_pending_reason")) : void 0;
7831
+ const billedTokens = tokens(pickFrom(blocks, "billed_tokens"));
7044
7832
  return {
7833
+ billingStatusReported: reported,
7045
7834
  ...settlement === void 0 ? {} : { settlement },
7835
+ ...reason === void 0 ? {} : { settlementPendingReason: reason },
7836
+ ...billedTokens === void 0 ? {} : { billedTokens }
7837
+ };
7838
+ }
7839
+ /** The billed lengths of an audio task: original seconds (speech) and minutes (transcription). */
7840
+ function billedLengths(raw) {
7841
+ const blocks = billingBlocks(raw);
7842
+ const originalSeconds = seconds(pickFrom(blocks, "original_seconds", "billed_original_seconds", "original_duration_seconds"));
7843
+ const minutes = seconds(pickFrom(blocks, "billed_minutes", "minutes"));
7844
+ return {
7046
7845
  ...originalSeconds === void 0 ? {} : { billedOriginalSeconds: originalSeconds },
7047
7846
  ...minutes === void 0 ? {} : { billedMinutes: minutes }
7048
7847
  };
@@ -7100,6 +7899,7 @@ function parseVideoTask(body) {
7100
7899
  ...progress === void 0 ? {} : { progress },
7101
7900
  ...error === void 0 ? {} : { error },
7102
7901
  ...receipt(raw),
7902
+ ...settlementOf(raw, status),
7103
7903
  outputs: state === "completed" ? [{
7104
7904
  index: 0,
7105
7905
  ...url === void 0 ? {} : { url },
@@ -7153,7 +7953,8 @@ function parseAudioTask(body) {
7153
7953
  ...progress === void 0 ? {} : { progress },
7154
7954
  ...error === void 0 ? {} : { error },
7155
7955
  ...receipt(raw),
7156
- ...billing(raw, status),
7956
+ ...settlementOf(raw, status),
7957
+ ...billedLengths(raw),
7157
7958
  outputs: state === "completed" ? outputs : []
7158
7959
  };
7159
7960
  }
@@ -7663,19 +8464,36 @@ var TaskTracker = class {
7663
8464
  }
7664
8465
  return Math.min(6e4, 5e3 * 2 ** Math.min(failures - 1, 4));
7665
8466
  }
7666
- /** The money and billing facts of a gateway answer, merged into what the record already knows. */
8467
+ /**
8468
+ * The money and billing facts of a gateway answer, merged into what the record already knows.
8469
+ *
8470
+ * An explicit status decides: `pending` records no charge (a charge reported
8471
+ * alongside it is not final, and the task is not free either) and drops one
8472
+ * recorded earlier; `settled` records the charge exactly as given. Only an
8473
+ * answer that carries no billing or settlement status at all — older gateways —
8474
+ * lets a charge imply `settled`. An answer that says nothing leaves what the
8475
+ * record holds, so a settled task is never downgraded by it.
8476
+ */
7667
8477
  moneyOf(record, task) {
7668
- const charged = task.settlement === "pending" ? void 0 : task.chargedCny;
7669
- const settlement = task.settlement ?? (charged !== void 0 ? "settled" : void 0);
7670
- const billing = task.billedOriginalSeconds !== void 0 || task.billedMinutes !== void 0 ? { billing: {
8478
+ const settlement = task.settlement ?? (!task.billingStatusReported && task.chargedCny !== void 0 ? "settled" : void 0);
8479
+ const billing = task.billedOriginalSeconds !== void 0 || task.billedMinutes !== void 0 || task.billedTokens !== void 0 ? { billing: {
7671
8480
  ...record.billing,
7672
8481
  ...task.billedOriginalSeconds === void 0 ? {} : { originalSeconds: task.billedOriginalSeconds },
7673
- ...task.billedMinutes === void 0 ? {} : { minutes: task.billedMinutes }
8482
+ ...task.billedMinutes === void 0 ? {} : { minutes: task.billedMinutes },
8483
+ ...task.billedTokens === void 0 ? {} : { tokens: task.billedTokens }
7674
8484
  } } : {};
7675
8485
  return {
7676
8486
  ...task.estimatedCny === void 0 ? {} : { estimatedCny: task.estimatedCny },
7677
- ...charged === void 0 ? {} : { chargedCny: charged },
7678
- ...settlement === void 0 ? {} : { settlement },
8487
+ ...settlement === "pending" ? {
8488
+ settlement,
8489
+ chargedCny: void 0,
8490
+ settlementPendingReason: task.settlementPendingReason
8491
+ } : {},
8492
+ ...settlement === "settled" ? {
8493
+ settlement,
8494
+ settlementPendingReason: void 0,
8495
+ ...task.chargedCny === void 0 ? {} : { chargedCny: task.chargedCny }
8496
+ } : {},
7679
8497
  ...billing
7680
8498
  };
7681
8499
  }
@@ -8774,8 +9592,12 @@ function apply(ctx, config) {
8774
9592
  })
8775
9593
  });
8776
9594
  account = accountService;
9595
+ const latency = new LatencyProbe({
9596
+ origin,
9597
+ userAgent
9598
+ });
8777
9599
  ctx.inject(["connection"], (scoped) => {
8778
- for (const accountRoute of accountRoutes(accountService)) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
9600
+ for (const accountRoute of [...accountRoutes(accountService), ...latencyRoutes(latency)]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
8779
9601
  });
8780
9602
  ctx.effect(() => {
8781
9603
  tracker.resume().catch((error) => {
@@ -8810,6 +9632,6 @@ function apply(ctx, config) {
8810
9632
  });
8811
9633
  }
8812
9634
  //#endregion
8813
- export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, INSUFFICIENT_BALANCE_CODE, MediaError, MediaHostService, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, version };
9635
+ export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, version };
8814
9636
 
8815
9637
  //# sourceMappingURL=index.js.map