@vibedev-si/dsh-vibedev 0.11.2 → 0.11.3

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
@@ -50,8 +50,8 @@ const MIN_READ_SPACING_MS = 5e3;
50
50
  * current when nobody opens anything.
51
51
  */
52
52
  const CATALOG_REFRESH_GAP_MS = 6e4;
53
- const record$15 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
54
- const text$9 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
53
+ const record$17 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
54
+ const text$10 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
55
55
  /**
56
56
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
57
57
  * writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
@@ -63,7 +63,7 @@ function amountOf(value) {
63
63
  if (!Number.isFinite(value)) return void 0;
64
64
  raw = String(value);
65
65
  if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
66
- } else raw = text$9(value);
66
+ } else raw = text$10(value);
67
67
  return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
68
68
  }
69
69
  /** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
@@ -305,14 +305,14 @@ var AccountService = class {
305
305
  redirect: "error"
306
306
  });
307
307
  if (!response.ok) return {};
308
- const body = record$15(await response.json().catch(() => void 0));
309
- const data = record$15(body?.data) ?? body;
308
+ const body = record$17(await response.json().catch(() => void 0));
309
+ const data = record$17(body?.data) ?? body;
310
310
  const balance = amountOf(data?.balance);
311
- const currency = text$9(data?.currency) ?? "CNY";
311
+ const currency = text$10(data?.currency) ?? "CNY";
312
312
  const frozen = amountOf(data?.frozen_balance);
313
- const id = typeof data?.id === "number" ? String(data.id) : text$9(data?.id);
314
- const nickname = text$9(data?.nickname) ?? text$9(data?.username);
315
- const email = text$9(data?.email);
313
+ const id = typeof data?.id === "number" ? String(data.id) : text$10(data?.id);
314
+ const nickname = text$10(data?.nickname) ?? text$10(data?.username);
315
+ const email = text$10(data?.email);
316
316
  const user = id === void 0 && nickname === void 0 && email === void 0 ? void 0 : {
317
317
  ...id === void 0 ? {} : { id },
318
318
  ...email === void 0 ? {} : { email },
@@ -426,8 +426,8 @@ function json$3(status, body) {
426
426
  }
427
427
  });
428
428
  }
429
- function failure$1(error) {
430
- const candidate = record$15(error)?.code;
429
+ function failure$2(error) {
430
+ const candidate = record$17(error)?.code;
431
431
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
432
432
  return json$3(500, { error: {
433
433
  code,
@@ -446,7 +446,7 @@ function accountRoutes(account) {
446
446
  methods: ["POST"],
447
447
  requestBody: "buffered",
448
448
  fetch: async (request) => {
449
- const body = record$15(await request.json().catch(() => void 0));
449
+ const body = record$17(await request.json().catch(() => void 0));
450
450
  return json$3(200, { consumed: typeof body?.id === "string" && account.consumeNavigation(body.id) });
451
451
  }
452
452
  },
@@ -461,7 +461,7 @@ function accountRoutes(account) {
461
461
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
462
462
  return json$3(200, await account.view(query.get("fresh") === "1"));
463
463
  } catch (error) {
464
- return failure$1(error);
464
+ return failure$2(error);
465
465
  }
466
466
  }
467
467
  },
@@ -471,10 +471,10 @@ function accountRoutes(account) {
471
471
  requestBody: "buffered",
472
472
  fetch: async (request) => {
473
473
  try {
474
- const body = record$15(await request.json().catch(() => void 0));
474
+ const body = record$17(await request.json().catch(() => void 0));
475
475
  return json$3(200, await account.signIn(body?.open !== false));
476
476
  } catch (error) {
477
- return failure$1(error);
477
+ return failure$2(error);
478
478
  }
479
479
  }
480
480
  },
@@ -498,7 +498,7 @@ function accountRoutes(account) {
498
498
  message: "The VibeDev account is the app's sign-in; sign out in the app."
499
499
  } });
500
500
  } catch (error) {
501
- return failure$1(error);
501
+ return failure$2(error);
502
502
  }
503
503
  }
504
504
  }
@@ -606,10 +606,10 @@ function normalizeErrorStage(value) {
606
606
  request: "submit"
607
607
  }[word];
608
608
  }
609
- function record$14(value) {
609
+ function record$16(value) {
610
610
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
611
611
  }
612
- function text$8(value) {
612
+ function text$9(value) {
613
613
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
614
614
  }
615
615
  function count$1(value) {
@@ -618,7 +618,7 @@ function count$1(value) {
618
618
  /** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
619
619
  function amount$2(value) {
620
620
  if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
621
- const raw = text$8(value);
621
+ const raw = text$9(value);
622
622
  return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
623
623
  }
624
624
  /**
@@ -632,16 +632,16 @@ function amount$2(value) {
632
632
  * @returns the fields found.
633
633
  */
634
634
  function parseGatewayFailure(body) {
635
- const root = record$14(body);
635
+ const root = record$16(body);
636
636
  if (root === void 0) return {};
637
- const source = record$14(root.error) ?? root;
638
- const metadata = record$14(source.metadata) ?? record$14(root.metadata);
639
- const gatewayCode = text$8(source.gateway_code) ?? text$8(root.gateway_code);
640
- const code = gatewayCode ?? text$8(source.code) ?? text$8(source.type) ?? text$8(root.reason);
641
- const message = text$8(source.message) ?? (typeof root.error === "string" ? text$8(root.error) : void 0);
642
- const field = text$8(source.field) ?? text$8(metadata?.field);
643
- const rule = text$8(source.rule) ?? text$8(metadata?.rule);
644
- const rechargeUrl = text$8(source.recharge_url) ?? text$8(root.recharge_url);
637
+ const source = record$16(root.error) ?? root;
638
+ const metadata = record$16(source.metadata) ?? record$16(root.metadata);
639
+ const gatewayCode = text$9(source.gateway_code) ?? text$9(root.gateway_code);
640
+ const code = gatewayCode ?? text$9(source.code) ?? text$9(source.type) ?? text$9(root.reason);
641
+ const message = text$9(source.message) ?? (typeof root.error === "string" ? text$9(root.error) : void 0);
642
+ const field = text$9(source.field) ?? text$9(metadata?.field);
643
+ const rule = text$9(source.rule) ?? text$9(metadata?.rule);
644
+ const rechargeUrl = text$9(source.recharge_url) ?? text$9(root.recharge_url);
645
645
  const numbers = {
646
646
  active: count$1(source.active),
647
647
  limit: count$1(source.limit)
@@ -651,19 +651,19 @@ function parseGatewayFailure(body) {
651
651
  availableCny: amount$2(source.available_cny),
652
652
  pendingCny: amount$2(source.pending_cny)
653
653
  };
654
- const submissionState = text$8(source.submission_state) ?? text$8(root.submission_state);
655
- const retryAction = text$8(source.retry_action) ?? text$8(root.retry_action);
656
- const assetId = text$8(source.asset_id) ?? text$8(root.asset_id);
654
+ const submissionState = text$9(source.submission_state) ?? text$9(root.submission_state);
655
+ const retryAction = text$9(source.retry_action) ?? text$9(root.retry_action);
656
+ const assetId = text$9(source.asset_id) ?? text$9(root.asset_id);
657
657
  return {
658
658
  ...gatewayCode === void 0 ? {} : { gatewayCode },
659
659
  ...Object.fromEntries(Object.entries({
660
- category: normalizeErrorCategory(text$8(source.category) ?? text$8(root.category), code),
661
- stage: normalizeErrorStage(text$8(source.stage) ?? text$8(root.stage)),
662
- requestId: text$8(source.request_id) ?? text$8(root.request_id),
663
- taskId: text$8(source.task_id) ?? text$8(root.task_id),
664
- operationId: text$8(source.operation_id) ?? text$8(root.operation_id),
665
- billingState: text$8(source.billing_state) ?? text$8(root.billing_state),
666
- retryAt: text$8(source.retry_at) ?? text$8(root.retry_at),
660
+ category: normalizeErrorCategory(text$9(source.category) ?? text$9(root.category), code),
661
+ stage: normalizeErrorStage(text$9(source.stage) ?? text$9(root.stage)),
662
+ requestId: text$9(source.request_id) ?? text$9(root.request_id),
663
+ taskId: text$9(source.task_id) ?? text$9(root.task_id),
664
+ operationId: text$9(source.operation_id) ?? text$9(root.operation_id),
665
+ billingState: text$9(source.billing_state) ?? text$9(root.billing_state),
666
+ retryAt: text$9(source.retry_at) ?? text$9(root.retry_at),
667
667
  retryAfterSeconds: count$1(source.retry_after_seconds) ?? count$1(root.retry_after_seconds)
668
668
  }).filter(([, value]) => value !== void 0)),
669
669
  ...code === void 0 ? {} : { code },
@@ -730,11 +730,11 @@ function gatewayFailureWithHeaders(body, headers) {
730
730
  const failure = parseGatewayFailure(body);
731
731
  return {
732
732
  ...failure,
733
- code: failure.gatewayCode ?? text$8(headers.get("x-vibedev-error-code")) ?? failure.code,
734
- category: normalizeErrorCategory(failure.category ?? text$8(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$8(headers.get("x-vibedev-error-code")) ?? failure.code),
735
- requestId: failure.requestId ?? text$8(headers.get("x-request-id")),
736
- retryAction: failure.retryAction ?? text$8(headers.get("x-vibedev-retry-action")),
737
- retryAt: failure.retryAt ?? text$8(headers.get("x-vibedev-retry-at"))
733
+ code: failure.gatewayCode ?? text$9(headers.get("x-vibedev-error-code")) ?? failure.code,
734
+ category: normalizeErrorCategory(failure.category ?? text$9(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$9(headers.get("x-vibedev-error-code")) ?? failure.code),
735
+ requestId: failure.requestId ?? text$9(headers.get("x-request-id")),
736
+ retryAction: failure.retryAction ?? text$9(headers.get("x-vibedev-retry-action")),
737
+ retryAt: failure.retryAt ?? text$9(headers.get("x-vibedev-retry-at"))
738
738
  };
739
739
  }
740
740
  function isUserAuthenticationFailure(failure) {
@@ -743,19 +743,19 @@ function isUserAuthenticationFailure(failure) {
743
743
  function sdkGatewayFailure(message, headers = {}) {
744
744
  const prefix = /\bvibedev:([A-Z][A-Z0-9_]{1,100}):/.exec(message)?.[1];
745
745
  const legacy = /["'](?:gateway_code|code)["']\s*:\s*["'](APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)["']/.exec(message)?.[1];
746
- const code = text$8(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
747
- const category = text$8(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
746
+ const code = text$9(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
747
+ const category = text$9(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
748
748
  if (code === void 0 && category === void 0) return void 0;
749
749
  return {
750
750
  code,
751
751
  category: normalizeErrorCategory(category, code),
752
- requestId: text$8(headers["x-request-id"]),
753
- retryAction: text$8(headers["x-vibedev-retry-action"])
752
+ requestId: text$9(headers["x-request-id"]),
753
+ retryAction: text$9(headers["x-vibedev-retry-action"])
754
754
  };
755
755
  }
756
756
  //#endregion
757
757
  //#region src/account/center-price-contract.ts
758
- const record$13 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
758
+ const record$15 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
759
759
  const keys = (value = "") => value.split(" ").filter(Boolean);
760
760
  const scalar$1 = (value) => value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && value.length <= 1e3 && !/\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
761
761
  /** Only public DNS HTTPS references become navigable links. No credentials, IPs or local hosts. */
@@ -773,7 +773,7 @@ function publicReferenceUrl(value) {
773
773
  }
774
774
  function project$1(value, shape) {
775
775
  if (value === null) return null;
776
- const source = record$13(value);
776
+ const source = record$15(value);
777
777
  if (!source) return void 0;
778
778
  const out = {};
779
779
  for (const key of keys(shape.fields)) {
@@ -801,7 +801,7 @@ function project$1(value, shape) {
801
801
  out[key] = source[key].slice(0, key === "models" ? 48 : 1e3).map((item) => child === "scalar" ? scalar$1(item) : child === "matrix" ? Array.isArray(item) ? item.slice(0, 64).map(scalar$1).filter((v) => v !== void 0) : void 0 : project$1(item, child)).filter((item) => item !== void 0);
802
802
  }
803
803
  for (const [key, child] of Object.entries(shape.maps ?? {})) {
804
- const map = record$13(source[key]);
804
+ const map = record$15(source[key]);
805
805
  if (!map) continue;
806
806
  out[key] = Object.fromEntries(Object.entries(map).slice(0, 64).filter(([name, value]) => /^[a-z][a-z0-9_]{0,63}$/i.test(name) && !/secret|password|credential|api_key/i.test(name) && (key !== "reasoning_effort_multipliers" || [
807
807
  "none",
@@ -1629,11 +1629,11 @@ function projectBusinessReceipt(value) {
1629
1629
  //#endregion
1630
1630
  //#region src/account/center-contract.ts
1631
1631
  /** Exact, read-only account-page schemas. No caller-selected URL or object shape. */
1632
- const record$12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1632
+ const record$14 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1633
1633
  const fields = (text) => text.split(" ");
1634
1634
  const scalar = (value) => value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && value.length <= 1e3 && !/\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
1635
1635
  function project(value, shape) {
1636
- const source = record$12(value);
1636
+ const source = record$14(value);
1637
1637
  if (source === void 0) return void 0;
1638
1638
  if (shape === imageSizes) return Object.fromEntries(Object.entries(source).filter(([key, item]) => {
1639
1639
  const kilo = /^(\d{1,2}(?:\.\d{1,3})?)K$/.exec(key), dimensions = /^(\d{1,5})x(\d{1,5})$/.exec(key);
@@ -1646,7 +1646,7 @@ function project(value, shape) {
1646
1646
  "inbound_endpoint",
1647
1647
  "upstream_endpoint",
1648
1648
  "endpoint"
1649
- ].includes(key) && (typeof item !== "string" || !SAFE_ENDPOINTS.has(item))) continue;
1649
+ ].includes(key) && (typeof item !== "string" || !safeEndpoint(item))) continue;
1650
1650
  if (item !== void 0) result[key] = item;
1651
1651
  }
1652
1652
  for (const [key, child] of Object.entries(shape.objects ?? {})) {
@@ -1656,7 +1656,13 @@ function project(value, shape) {
1656
1656
  for (const [key, child] of Object.entries(shape.arrays ?? {})) if (Array.isArray(source[key])) result[key] = source[key].slice(0, 1e3).map((item) => child === "scalar" ? scalar(item) : project(item, child)).filter((item) => item !== void 0);
1657
1657
  return result;
1658
1658
  }
1659
- const SAFE_ENDPOINTS = new Set(fields("/v1/systemone /v1/completions /v1/alpha/search /v1/responses/compact /v1/responses/input_tokens /v1/images/tasks /v1/videos/generations /v1/videos/edits /v1/videos/extensions /v1beta/models /v1beta/cachedContents /v1internal:streamGenerateContent /v1/messages /v1/messages/count_tokens /v1/chat/completions /v1/responses /v1/embeddings /v1/images/generations /v1/images/edits /v1/videos /v1/audio/speech /v1/audio/transcriptions /v1/audio/translations /v1/realtime /messages /messages/count_tokens /chat/completions /responses /embeddings /images/generations /images/edits /videos /tts /stt /realtime /alpha/search /v3/contents/generations/tasks /api/v3/contents/generations/tasks /v1/contents/generations/tasks"));
1659
+ const SAFE_ENDPOINTS = new Set(fields("/v1/systemone /v1/completions /v1/alpha/search /v1/responses/compact /v1/responses/input_tokens /v1/images/tasks /v1/videos/generations /v1/videos/edits /v1/videos/extensions /v1beta/models /v1beta/cachedContents /v1internal:streamGenerateContent /v1/messages /v1/messages/count_tokens /v1/chat/completions /v1/responses /v1/embeddings /v1/images/generations /v1/images/edits /v1/videos /v1/audio/speech /v1/audio/transcriptions /v1/audio/translations /v1/realtime /messages /messages/count_tokens /chat/completions /responses /embeddings /images/generations /images/edits /videos /tts /stt /realtime /alpha/search /v3/contents/generations/tasks /api/v3/contents/generations/tasks /v1/contents/generations/tasks /v1/audio/voice-profiles /v1/audio/voice-profiles/:id /v1/audio/voice-profiles/{id}"));
1660
+ /** Voice profiles (`GET`/`POST /v1/audio/voice-profiles`, `DELETE /v1/audio/voice-profiles/{id}`): the route template above, or a concrete `vp_…` id. */
1661
+ const VOICE_PROFILE_ENDPOINT = /^\/v1\/audio\/voice-profiles\/vp_[A-Za-z0-9_-]{1,120}$/;
1662
+ /** An endpoint a usage or error row may show. */
1663
+ function safeEndpoint(value) {
1664
+ return SAFE_ENDPOINTS.has(value) || VOICE_PROFILE_ENDPOINT.test(value);
1665
+ }
1660
1666
  const imageSizes = { fields: [] };
1661
1667
  const group = { fields: fields("id name platform description status subscription_type rate_multiplier peak_rate_enabled peak_start peak_end peak_rate_multiplier") };
1662
1668
  const window = { fields: fields("state remaining_percent resets_at") };
@@ -1888,7 +1894,7 @@ function centerQuery(path, params) {
1888
1894
  /** Legacy summary only: monetary weekly fields become a percentage, never a five-hour window. */
1889
1895
  function projectAccountData(value) {
1890
1896
  const convert = (item) => {
1891
- const output = project(item, subscription), source = record$12(item);
1897
+ const output = project(item, subscription), source = record$14(item);
1892
1898
  if (output === void 0 || source === void 0) return void 0;
1893
1899
  const number = (n) => typeof n === "number" && Number.isFinite(n) ? n : typeof n === "string" && /^\d+(?:\.\d+)?$/.test(n) ? Number(n) : void 0;
1894
1900
  const used = number(source.weekly_used_usd), limit = number(source.weekly_limit_usd);
@@ -1900,7 +1906,7 @@ function projectAccountData(value) {
1900
1906
  return output;
1901
1907
  };
1902
1908
  if (Array.isArray(value)) return value.slice(0, 1e3).map(convert).filter((item) => item !== void 0);
1903
- const source = record$12(value);
1909
+ const source = record$14(value);
1904
1910
  return source === void 0 ? {} : {
1905
1911
  ...project(source, { fields: ["active_count"] }),
1906
1912
  ...Array.isArray(source.subscriptions) ? { subscriptions: source.subscriptions.slice(0, 1e3).map(convert).filter((item) => item !== void 0) } : {}
@@ -1936,14 +1942,14 @@ function projectCenterRoute(path, value) {
1936
1942
  //#endregion
1937
1943
  //#region src/account/center-business.ts
1938
1944
  const object$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1939
- const answer$2 = (status, body) => new Response(JSON.stringify(body), {
1945
+ const answer$3 = (status, body) => new Response(JSON.stringify(body), {
1940
1946
  status,
1941
1947
  headers: {
1942
1948
  "content-type": "application/json; charset=utf-8",
1943
1949
  "cache-control": "private, no-store"
1944
1950
  }
1945
1951
  });
1946
- const failure = (status, code, notSubmitted, extra = {}) => answer$2(status, {
1952
+ const failure$1 = (status, code, notSubmitted, extra = {}) => answer$3(status, {
1947
1953
  ...extra,
1948
1954
  ...notSubmitted ? { not_submitted: true } : {},
1949
1955
  error: {
@@ -1951,7 +1957,7 @@ const failure = (status, code, notSubmitted, extra = {}) => answer$2(status, {
1951
1957
  category: code === "INVALID_INPUT" ? "invalid_input" : code === "ACCOUNT_CHANGED" ? "access_restricted" : "service_unavailable"
1952
1958
  }
1953
1959
  });
1954
- const sameAccount$1 = (a, b) => a.signedIn && b.signedIn && a.userId !== void 0 && a.userId === b.userId;
1960
+ const sameAccount$2 = (a, b) => a.signedIn && b.signedIn && a.userId !== void 0 && a.userId === b.userId;
1955
1961
  /** The buffered wire body must be unambiguous before it is canonicalized and fingerprinted. */
1956
1962
  function uniqueBusinessJson(raw) {
1957
1963
  if (Buffer.byteLength(raw, "utf8") > 1 << 20) throw new Error("body too large");
@@ -1986,29 +1992,29 @@ function accountBusinessActionsRoutes(http, account) {
1986
1992
  let before, dispatched = false;
1987
1993
  const stillCurrent = async () => {
1988
1994
  try {
1989
- return before !== void 0 && sameAccount$1(before, await account.identity());
1995
+ return before !== void 0 && sameAccount$2(before, await account.identity());
1990
1996
  } catch {
1991
1997
  return false;
1992
1998
  }
1993
1999
  };
1994
2000
  try {
1995
- if (new URL(request.url, "http://host").search !== "") return failure(400, "INVALID_INPUT", true);
2001
+ if (new URL(request.url, "http://host").search !== "") return failure$1(400, "INVALID_INPUT", true);
1996
2002
  let body;
1997
2003
  try {
1998
2004
  body = object$2(uniqueBusinessJson(await request.text()));
1999
2005
  } catch {
2000
- return failure(400, "INVALID_INPUT", true);
2006
+ return failure$1(400, "INVALID_INPUT", true);
2001
2007
  }
2002
2008
  if (body === void 0 || Object.keys(body).some((key) => ![
2003
2009
  "operation_id",
2004
2010
  "expected_user_id",
2005
2011
  "payload"
2006
- ].includes(key)) || !validOperationId(body.operation_id) || typeof body.expected_user_id !== "string") return failure(400, "INVALID_INPUT", true);
2012
+ ].includes(key)) || !validOperationId(body.operation_id) || typeof body.expected_user_id !== "string") return failure$1(400, "INVALID_INPUT", true);
2007
2013
  const parsed = validateBusinessAction(kind, body.payload);
2008
- if (parsed === void 0) return failure(400, "INVALID_INPUT", true);
2014
+ if (parsed === void 0) return failure$1(400, "INVALID_INPUT", true);
2009
2015
  before = await account.identity();
2010
- if (!before.signedIn || before.userId === void 0) return failure(401, "ACCOUNT_UNAVAILABLE", true);
2011
- if (before.userId !== body.expected_user_id) return failure(409, "ACCOUNT_CHANGED", true);
2016
+ if (!before.signedIn || before.userId === void 0) return failure$1(401, "ACCOUNT_UNAVAILABLE", true);
2017
+ if (before.userId !== body.expected_user_id) return failure$1(409, "ACCOUNT_CHANGED", true);
2012
2018
  dispatched = true;
2013
2019
  const raw = await http.json(`/v1/account/${parsed.wire}`, {
2014
2020
  method: parsed.method,
@@ -2021,24 +2027,24 @@ function accountBusinessActionsRoutes(http, account) {
2021
2027
  });
2022
2028
  if (!await stillCurrent()) {
2023
2029
  http.invalidateAccountSnapshots();
2024
- return failure(409, "ACCOUNT_CHANGED", false);
2030
+ return failure$1(409, "ACCOUNT_CHANGED", false);
2025
2031
  }
2026
2032
  const receipt = object$2(projectBusinessReceipt(object$2(raw)?.data));
2027
2033
  const expectedAction = kind === "redeem/apply" ? "redeem" : kind.replace("/", ".");
2028
- if (receipt === void 0 || receipt.operation_id !== body.operation_id || receipt.action !== expectedAction) return failure(502, "ACCOUNT_ACTION_UNKNOWN", false);
2034
+ if (receipt === void 0 || receipt.operation_id !== body.operation_id || receipt.action !== expectedAction) return failure$1(502, "ACCOUNT_ACTION_UNKNOWN", false);
2029
2035
  if (receipt.state === "succeeded") http.invalidateAccountSnapshots();
2030
- return answer$2(200, {
2036
+ return answer$3(200, {
2031
2037
  code: 0,
2032
2038
  data: receipt
2033
2039
  });
2034
2040
  } catch (error) {
2035
2041
  if (before !== void 0 && !await stillCurrent()) {
2036
2042
  http.invalidateAccountSnapshots();
2037
- return failure(409, "ACCOUNT_CHANGED", !dispatched);
2043
+ return failure$1(409, "ACCOUNT_CHANGED", !dispatched);
2038
2044
  }
2039
2045
  if (error instanceof MediaError) {
2040
2046
  const status = error.details.status ?? 502;
2041
- if (status === 404 || status === 405) return failure(200, "ACCOUNT_ACTION_UNSUPPORTED", true, { unsupported: true });
2047
+ if (status === 404 || status === 405) return failure$1(200, "ACCOUNT_ACTION_UNSUPPORTED", true, { unsupported: true });
2042
2048
  const refused = [
2043
2049
  400,
2044
2050
  401,
@@ -2046,9 +2052,9 @@ function accountBusinessActionsRoutes(http, account) {
2046
2052
  413,
2047
2053
  422
2048
2054
  ].includes(status);
2049
- return failure(status, refused ? error.code : "ACCOUNT_ACTION_UNKNOWN", refused);
2055
+ return failure$1(status, refused ? error.code : "ACCOUNT_ACTION_UNKNOWN", refused);
2050
2056
  }
2051
- return failure(502, "ACCOUNT_ACTION_UNKNOWN", !dispatched);
2057
+ return failure$1(502, "ACCOUNT_ACTION_UNKNOWN", !dispatched);
2052
2058
  }
2053
2059
  }
2054
2060
  }));
@@ -2057,7 +2063,7 @@ function accountBusinessActionsRoutes(http, account) {
2057
2063
  //#region src/account/center.ts
2058
2064
  const CENTER_PREFIX = "/api/dsh-vibedev/account-center";
2059
2065
  const obj = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2060
- function answer$1(status, body) {
2066
+ function answer$2(status, body) {
2061
2067
  return new Response(JSON.stringify(body), {
2062
2068
  status,
2063
2069
  headers: {
@@ -2066,7 +2072,7 @@ function answer$1(status, body) {
2066
2072
  }
2067
2073
  });
2068
2074
  }
2069
- function sameAccount(before, after) {
2075
+ function sameAccount$1(before, after) {
2070
2076
  return before.signedIn && after.signedIn && before.userId === after.userId && (before.userId !== void 0 || before.credential.token === after.credential.token);
2071
2077
  }
2072
2078
  function accountCenterRoutes(http, account) {
@@ -2078,7 +2084,7 @@ function accountCenterRoutes(http, account) {
2078
2084
  let before;
2079
2085
  const changed = () => {
2080
2086
  http.invalidateAccountSnapshots();
2081
- return answer$1(409, { error: {
2087
+ return answer$2(409, { error: {
2082
2088
  code: "ACCOUNT_CHANGED",
2083
2089
  message: "账号已切换,请刷新页面。"
2084
2090
  } });
@@ -2086,14 +2092,14 @@ function accountCenterRoutes(http, account) {
2086
2092
  try {
2087
2093
  const params = new URL(request.url, "http://host").searchParams;
2088
2094
  const parsed = centerQuery(path, params);
2089
- if (parsed === void 0) return answer$1(400, { error: {
2095
+ if (parsed === void 0) return answer$2(400, { error: {
2090
2096
  code: "INVALID_INPUT",
2091
2097
  category: "invalid_input",
2092
2098
  message: "筛选参数不符合要求。"
2093
2099
  } });
2094
2100
  const { query, wire, fresh } = parsed;
2095
2101
  before = await account.identity();
2096
- if (!before.signedIn) return answer$1(401, { error: {
2102
+ if (!before.signedIn) return answer$2(401, { error: {
2097
2103
  code: "AUTHENTICATION_REQUIRED",
2098
2104
  category: "authentication",
2099
2105
  message: "请先登录 VibeDev。"
@@ -2104,30 +2110,30 @@ function accountCenterRoutes(http, account) {
2104
2110
  timeoutMs: 3e4,
2105
2111
  signal: request.signal,
2106
2112
  busyRetries: 0,
2107
- isCurrentAccount: async () => sameAccount(before, await account.identity())
2113
+ isCurrentAccount: async () => sameAccount$1(before, await account.identity())
2108
2114
  };
2109
2115
  const data = path === "entitlements" && before.userId !== void 0 && query.size === 0 ? await http.entitlements(`${http.origin}\nuser:${before.userId}`, options, fresh) : await http.json(`/v1/account/${wire}${query.size === 0 ? "" : `?${query}`}`, options);
2110
2116
  const after = await account.identity();
2111
- if (!sameAccount(before, after)) return changed();
2117
+ if (!sameAccount$1(before, after)) return changed();
2112
2118
  const projected = projectCenterRoute(path, obj(data)?.data ?? data);
2113
- if (projected === void 0) return answer$1(502, { error: {
2119
+ if (projected === void 0) return answer$2(502, { error: {
2114
2120
  code: "ACCOUNT_READ_UNAVAILABLE",
2115
2121
  category: "service_unavailable"
2116
2122
  } });
2117
- return answer$1(200, {
2123
+ return answer$2(200, {
2118
2124
  code: 0,
2119
2125
  data: projected
2120
2126
  });
2121
2127
  } catch (error) {
2122
- if (error instanceof MediaError && error.code === "ACCOUNT_CHANGED" || before !== void 0 && !sameAccount(before, await account.identity())) return changed();
2123
- if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405)) return answer$1(200, { unsupported: true });
2124
- if (error instanceof MediaError) return answer$1(error.details.status ?? 502, { error: {
2128
+ if (error instanceof MediaError && error.code === "ACCOUNT_CHANGED" || before !== void 0 && !sameAccount$1(before, await account.identity())) return changed();
2129
+ if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405)) return answer$2(200, { unsupported: true });
2130
+ if (error instanceof MediaError) return answer$2(error.details.status ?? 502, { error: {
2125
2131
  code: error.code,
2126
2132
  category: error.details.category,
2127
2133
  message: error.message,
2128
2134
  request_id: error.details.requestId
2129
2135
  } });
2130
- return answer$1(502, { error: {
2136
+ return answer$2(502, { error: {
2131
2137
  code: "ACCOUNT_READ_UNAVAILABLE",
2132
2138
  category: "service_unavailable",
2133
2139
  message: "账户信息暂时无法获取,请稍后刷新。"
@@ -2797,8 +2803,8 @@ const unavailable = () => json$2(200, {
2797
2803
  items: [],
2798
2804
  unread: 0
2799
2805
  });
2800
- const record$11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2801
- const text$7 = (value) => typeof value === "string" ? value : void 0;
2806
+ const record$13 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2807
+ const text$8 = (value) => typeof value === "string" ? value : void 0;
2802
2808
  const identifier = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
2803
2809
  /**
2804
2810
  * One announcement from the wire, with every field it needs and nothing else.
@@ -2806,12 +2812,12 @@ const identifier = (value) => typeof value === "number" && Number.isSafeInteger(
2806
2812
  * @returns the announcement, or undefined when the entry cannot be rendered.
2807
2813
  */
2808
2814
  function parseAnnouncement(value) {
2809
- const item = record$11(value);
2815
+ const item = record$13(value);
2810
2816
  if (item === void 0) return void 0;
2811
2817
  const id = identifier(item.id);
2812
- const title = text$7(item.title);
2813
- const content = text$7(item.content);
2814
- const createdAt = text$7(item.created_at);
2818
+ const title = text$8(item.title);
2819
+ const content = text$8(item.content);
2820
+ const createdAt = text$8(item.created_at);
2815
2821
  if (id === void 0 || title === void 0 || content === void 0 || createdAt === void 0) return void 0;
2816
2822
  return {
2817
2823
  id,
@@ -2821,7 +2827,7 @@ function parseAnnouncement(value) {
2821
2827
  notifyMode: item.notify_mode === "popup" ? "popup" : "silent",
2822
2828
  ...typeof item.starts_at === "string" ? { startsAt: item.starts_at } : {},
2823
2829
  ...typeof item.ends_at === "string" ? { endsAt: item.ends_at } : {},
2824
- readAt: text$7(item.read_at) ?? null
2830
+ readAt: text$8(item.read_at) ?? null
2825
2831
  };
2826
2832
  }
2827
2833
  /**
@@ -2831,7 +2837,7 @@ function parseAnnouncement(value) {
2831
2837
  */
2832
2838
  function entriesOf(payload) {
2833
2839
  if (Array.isArray(payload)) return payload;
2834
- const data = record$11(payload)?.data;
2840
+ const data = record$13(payload)?.data;
2835
2841
  return Array.isArray(data) ? data : void 0;
2836
2842
  }
2837
2843
  /**
@@ -2915,7 +2921,7 @@ function announcementRoutes({ http, account }) {
2915
2921
  fetch: async (incoming) => {
2916
2922
  const entered = await enter(incoming);
2917
2923
  if (entered instanceof Response) return entered;
2918
- const body = record$11(await incoming.json().catch(() => void 0));
2924
+ const body = record$13(await incoming.json().catch(() => void 0));
2919
2925
  const id = identifier(body?.id);
2920
2926
  if (id === void 0) return json$2(400, { error: {
2921
2927
  code: "ANNOUNCEMENT_INVALID_ID",
@@ -3887,7 +3893,7 @@ const invalid = (field) => json(400, { error: {
3887
3893
  code: "FEEDBACK_INVALID",
3888
3894
  field
3889
3895
  } });
3890
- const record$10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3896
+ const record$12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3891
3897
  /**
3892
3898
  * The feedback routes.
3893
3899
  * @param options - the uploader's submit, the recent errors and the credential check.
@@ -3905,7 +3911,7 @@ function feedbackRoutes(options) {
3905
3911
  requestBody: "buffered",
3906
3912
  fetch: async (request) => {
3907
3913
  try {
3908
- const body = record$10(await request.json().catch(() => void 0));
3914
+ const body = record$12(await request.json().catch(() => void 0));
3909
3915
  if (body === void 0) return invalid("body");
3910
3916
  if (body.category !== void 0 && body.category !== null && !isCategory(body.category)) return invalid("category");
3911
3917
  if (body.text !== void 0 && typeof body.text !== "string") return invalid("text");
@@ -3915,7 +3921,7 @@ function feedbackRoutes(options) {
3915
3921
  if (text === void 0 && category === void 0) return invalid("text");
3916
3922
  let content;
3917
3923
  if (body.attachment !== void 0 && body.attachment !== null) {
3918
- const given = record$10(body.attachment)?.content;
3924
+ const given = record$12(body.attachment)?.content;
3919
3925
  if (typeof given !== "string" || given === "" || Buffer$1.byteLength(given, "utf8") > 262144) return invalid("attachment");
3920
3926
  content = given;
3921
3927
  }
@@ -4000,7 +4006,8 @@ const ACCOUNT_PAGES = [
4000
4006
  "redeem",
4001
4007
  "affiliate",
4002
4008
  "profile",
4003
- "messages"
4009
+ "messages",
4010
+ "voice_profiles"
4004
4011
  ];
4005
4012
  //#endregion
4006
4013
  //#region src/gateway/http.ts
@@ -5122,8 +5129,8 @@ const CALLBACK_PATH = "/dsh-media/callback";
5122
5129
  function base64url(data) {
5123
5130
  return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5124
5131
  }
5125
- const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5126
- const text$6 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5132
+ const record$11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5133
+ const text$7 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5127
5134
  /**
5128
5135
  * Read a token answer (`redeem` or `refresh`).
5129
5136
  * @param body - the parsed envelope `{code, data}` or a bare data object.
@@ -5132,18 +5139,18 @@ const text$6 = (value) => typeof value === "string" && value.trim() !== "" ? val
5132
5139
  * @returns the grant, or undefined when the answer lacks tokens.
5133
5140
  */
5134
5141
  function parseGrant(body, now, previous) {
5135
- const envelope = record$9(body);
5136
- const data = record$9(envelope?.data) ?? envelope;
5137
- const accessToken = text$6(data?.access_token);
5138
- const refreshToken = text$6(data?.refresh_token);
5142
+ const envelope = record$11(body);
5143
+ const data = record$11(envelope?.data) ?? envelope;
5144
+ const accessToken = text$7(data?.access_token);
5145
+ const refreshToken = text$7(data?.refresh_token);
5139
5146
  if (data === void 0 || accessToken === void 0 || refreshToken === void 0) return void 0;
5140
5147
  const seconds = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
5141
- const user = record$9(data.user);
5142
- const sessionId = text$6(data.session_id) ?? previous?.sessionId;
5148
+ const user = record$11(data.user);
5149
+ const sessionId = text$7(data.session_id) ?? previous?.sessionId;
5143
5150
  const parsedUser = user === void 0 ? previous?.user : {
5144
- ...text$6(user.id) === void 0 && typeof user.id !== "number" ? {} : { id: String(user.id) },
5145
- ...text$6(user.email) === void 0 ? {} : { email: text$6(user.email) },
5146
- ...text$6(user.nickname) === void 0 ? {} : { nickname: text$6(user.nickname) }
5151
+ ...text$7(user.id) === void 0 && typeof user.id !== "number" ? {} : { id: String(user.id) },
5152
+ ...text$7(user.email) === void 0 ? {} : { email: text$7(user.email) },
5153
+ ...text$7(user.nickname) === void 0 ? {} : { nickname: text$7(user.nickname) }
5147
5154
  };
5148
5155
  return {
5149
5156
  accessToken,
@@ -5563,8 +5570,8 @@ var PluginLogin = class {
5563
5570
  return;
5564
5571
  }
5565
5572
  if (!live()) return;
5566
- const envelope = record$9(body);
5567
- const parsed = envelope !== void 0 && (envelope.code === void 0 || envelope.code === 0) && (envelope.data === void 0 || record$9(envelope.data) !== void 0) ? parseGrant(body, this.now()) : void 0;
5573
+ const envelope = record$11(body);
5574
+ const parsed = envelope !== void 0 && (envelope.code === void 0 || envelope.code === 0) && (envelope.data === void 0 || record$11(envelope.data) !== void 0) ? parseGrant(body, this.now()) : void 0;
5568
5575
  if (parsed === void 0) {
5569
5576
  answer(502, "VibeDev", failurePage({
5570
5577
  ...this.attempt,
@@ -5756,7 +5763,7 @@ const ENDPOINT = {
5756
5763
  "openai-responses": "/v1/responses",
5757
5764
  "openai-completions": "/v1/chat/completions"
5758
5765
  };
5759
- const record$8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5766
+ const record$10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5760
5767
  const strings$1 = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
5761
5768
  const positive$2 = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
5762
5769
  const price$1 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
@@ -5810,15 +5817,15 @@ function reasoningLevelsOf(value) {
5810
5817
  * @returns the chat models, in catalog order; entries that are not chat models or cannot be called are left out.
5811
5818
  */
5812
5819
  function parseCatalog(body) {
5813
- const list = Array.isArray(body) ? body : record$8(body)?.data;
5820
+ const list = Array.isArray(body) ? body : record$10(body)?.data;
5814
5821
  if (!Array.isArray(list)) return [];
5815
5822
  const models = [];
5816
5823
  const seen = /* @__PURE__ */ new Set();
5817
5824
  for (const raw of list) {
5818
- const entry = record$8(raw);
5825
+ const entry = record$10(raw);
5819
5826
  const id = typeof entry?.id === "string" ? entry.id.trim() : "";
5820
5827
  if (entry === void 0 || id === "" || seen.has(id)) continue;
5821
- const capabilities = record$8(entry.capabilities);
5828
+ const capabilities = record$10(entry.capabilities);
5822
5829
  if (capabilities === void 0) continue;
5823
5830
  if (typeof entry.media_type === "string" && entry.media_type !== "") continue;
5824
5831
  if (typeof entry.internal_role === "string" && entry.internal_role !== "") continue;
@@ -5833,7 +5840,7 @@ function parseCatalog(body) {
5833
5840
  const inputs = strings$1(capabilities.input_modalities) ?? [];
5834
5841
  const nativeMedia = api === "openai-completions" ? NATIVE_MEDIA.filter((kind) => inputs.includes(kind)) : [];
5835
5842
  const maxInputTokens = positive$2(capabilities.max_input_tokens);
5836
- const rawFamily = record$8(entry.model_family);
5843
+ const rawFamily = record$10(entry.model_family);
5837
5844
  const familyId = typeof rawFamily?.id === "string" ? rawFamily.id.trim() : "";
5838
5845
  const familyLabel = typeof rawFamily?.label === "string" ? rawFamily.label.trim() : "";
5839
5846
  seen.add(id);
@@ -7340,7 +7347,7 @@ const PRICE_CONTEXT_QUERY = "scope=platform&period=7d&sort=recommended&page=1&pa
7340
7347
  const DEFAULT_TIMEOUT_MS = 1e4;
7341
7348
  /** The same label for an English surface. */
7342
7349
  const DEFAULT_PROMOTION_BADGE_EN = "Limited-time offer";
7343
- const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7350
+ const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
7344
7351
  const string = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
7345
7352
  const amount$1 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
7346
7353
  const groupId = (value) => {
@@ -7355,7 +7362,7 @@ function instant$1(value) {
7355
7362
  return Number.isFinite(parsed) ? parsed : void 0;
7356
7363
  }
7357
7364
  function tier(value) {
7358
- const source = record$7(value);
7365
+ const source = record$9(value);
7359
7366
  if (source === void 0) return void 0;
7360
7367
  const prevSpendMin = amount$1(source.prev_spend_min);
7361
7368
  const discountRate = amount$1(source.discount_rate);
@@ -7371,7 +7378,7 @@ function tier(value) {
7371
7378
  * @returns the promotion with its window resolved, or undefined.
7372
7379
  */
7373
7380
  function parsePromotion(value) {
7374
- const source = record$7(value);
7381
+ const source = record$9(value);
7375
7382
  if (source === void 0) return void 0;
7376
7383
  const model = string(source.model);
7377
7384
  const startsAt = string(source.starts_at);
@@ -7521,16 +7528,16 @@ var PromotionService = class {
7521
7528
  }
7522
7529
  /** The pricing group the account center already prices this account with. */
7523
7530
  async priceGroup() {
7524
- const answer = record$7(await this.options.http.json(`${PRICE_CONTEXT_PATH}?${PRICE_CONTEXT_QUERY}`, {
7531
+ const answer = record$9(await this.options.http.json(`${PRICE_CONTEXT_PATH}?${PRICE_CONTEXT_QUERY}`, {
7525
7532
  timeoutMs: this.timeoutMs,
7526
7533
  busyRetries: 0
7527
7534
  }));
7528
- const data = record$7(answer?.data) ?? answer;
7529
- return groupId(record$7(data?.price_context)?.group_id);
7535
+ const data = record$9(answer?.data) ?? answer;
7536
+ return groupId(record$9(data?.price_context)?.group_id);
7530
7537
  }
7531
7538
  /** The public list. `anonymous` keeps a signed-out or broken sign-in from changing the answer. */
7532
7539
  async list() {
7533
- const data = record$7(await this.options.http.json(PROMOTIONS_PATH, {
7540
+ const data = record$9(await this.options.http.json(PROMOTIONS_PATH, {
7534
7541
  anonymous: true,
7535
7542
  timeoutMs: this.timeoutMs,
7536
7543
  busyRetries: 0
@@ -8373,7 +8380,7 @@ function installGatewayModels(ctx, options) {
8373
8380
  const PROMOTIONS_ROUTE = "/api/dsh-vibedev/promotions";
8374
8381
  /** How long the page waits for a promotion answer before showing prices without labels. */
8375
8382
  const ROUTE_WAIT_MS = 2e3;
8376
- const answer = (body) => new Response(JSON.stringify(body), {
8383
+ const answer$1 = (body) => new Response(JSON.stringify(body), {
8377
8384
  status: 200,
8378
8385
  headers: {
8379
8386
  "content-type": "application/json",
@@ -8398,7 +8405,7 @@ function promotionRoutes(promotions) {
8398
8405
  items = [];
8399
8406
  }
8400
8407
  const group = promotions.snapshotGroup();
8401
- return answer({
8408
+ return answer$1({
8402
8409
  code: 0,
8403
8410
  data: {
8404
8411
  items,
@@ -8445,10 +8452,10 @@ const FIRST_LOOK_MS = 1e3;
8445
8452
  const LOOK_STEP_MAX_MS = 1e4;
8446
8453
  /** Uploads this library starts for one file: its own, and one more after another upload of the file ended without it. */
8447
8454
  const OWN_UPLOADS = 2;
8448
- const record$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8449
- const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
8455
+ const record$8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8456
+ const text$6 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
8450
8457
  const httpUrl$1 = (value) => {
8451
- const url = text$5(value);
8458
+ const url = text$6(value);
8452
8459
  return url !== void 0 && /^https?:\/\//i.test(url) ? url : void 0;
8453
8460
  };
8454
8461
  /**
@@ -8458,17 +8465,17 @@ const httpUrl$1 = (value) => {
8458
8465
  * @returns the asset facts, or undefined when the answer names no usable URL.
8459
8466
  */
8460
8467
  function parseAsset(body, fallbackType) {
8461
- const raw = record$6(body);
8462
- const assetId = text$5(raw?.asset_id);
8468
+ const raw = record$8(body);
8469
+ const assetId = text$6(raw?.asset_id);
8463
8470
  const referenceUrl = httpUrl$1(raw?.reference_url);
8464
8471
  if (raw === void 0 || assetId === void 0 || referenceUrl === void 0) return void 0;
8465
8472
  const contentUrl = httpUrl$1(raw.content_url);
8466
- const expiresAt = text$5(raw.expires_at);
8473
+ const expiresAt = text$6(raw.expires_at);
8467
8474
  const duration = raw.duration_ms;
8468
8475
  return {
8469
8476
  assetId,
8470
8477
  referenceUrl,
8471
- contentType: text$5(raw.content_type) ?? fallbackType,
8478
+ contentType: text$6(raw.content_type) ?? fallbackType,
8472
8479
  ...contentUrl === void 0 ? {} : { contentUrl },
8473
8480
  ...expiresAt === void 0 ? {} : { expiresAt },
8474
8481
  ...typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? { durationMs: duration } : {}
@@ -8608,7 +8615,7 @@ var MediaLibrary = class {
8608
8615
  }
8609
8616
  /** `POST /uploads`: the asset when the library already holds the file, else the upload it hands out. */
8610
8617
  async declare(media, purpose, sha256, signal) {
8611
- const created = record$6(await this.http.json("/v1/media-assets/uploads", {
8618
+ const created = record$8(await this.http.json("/v1/media-assets/uploads", {
8612
8619
  method: "POST",
8613
8620
  json: {
8614
8621
  filename: media.name,
@@ -8619,7 +8626,7 @@ var MediaLibrary = class {
8619
8626
  },
8620
8627
  signal
8621
8628
  }));
8622
- const assetId = text$5(created?.asset_id);
8629
+ const assetId = text$6(created?.asset_id);
8623
8630
  if (created === void 0 || assetId === void 0) throw new MediaError(`The VibeDev gateway did not accept the upload of "${media.source}".`, "ASSET_UPLOAD_REFUSED");
8624
8631
  if (created.upload_required !== false) return {
8625
8632
  kind: "upload",
@@ -8642,10 +8649,10 @@ var MediaLibrary = class {
8642
8649
  }
8643
8650
  /** PUT the bytes where `uploads` said, then `complete`. */
8644
8651
  async put(media, sha256, assetId, created, signal) {
8645
- const uploadUrl = httpUrl$1(created.upload_url) ?? (text$5(created.upload_url)?.startsWith("/") === true ? this.http.url(text$5(created.upload_url)) : void 0);
8652
+ const uploadUrl = httpUrl$1(created.upload_url) ?? (text$6(created.upload_url)?.startsWith("/") === true ? this.http.url(text$6(created.upload_url)) : void 0);
8646
8653
  if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
8647
8654
  const headers = { "content-type": media.mime };
8648
- for (const [name, value] of Object.entries(record$6(created.upload_headers) ?? {})) if (typeof value === "string") headers[name.toLowerCase()] = value;
8655
+ for (const [name, value] of Object.entries(record$8(created.upload_headers) ?? {})) if (typeof value === "string") headers[name.toLowerCase()] = value;
8649
8656
  await this.http.send(uploadUrl, {
8650
8657
  method: "PUT",
8651
8658
  body: media.data,
@@ -8707,8 +8714,8 @@ const AUDIO_GENERATION_KINDS = [
8707
8714
  "speech",
8708
8715
  "transcription"
8709
8716
  ];
8710
- const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8711
- const text$4 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
8717
+ const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8718
+ const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
8712
8719
  const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
8713
8720
  const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
8714
8721
  const positive$1 = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
@@ -8755,15 +8762,15 @@ function parseModes(raw) {
8755
8762
  const version = field(raw, "modes_schema_version");
8756
8763
  const modesRaw = raw.modes;
8757
8764
  if (version === void 0 && modesRaw === void 0) return {};
8758
- if (version !== 1 || record$5(modesRaw) === void 0) return { unreadableModesVersion: typeof version === "number" ? version : 0 };
8765
+ if (version !== 1 || record$7(modesRaw) === void 0) return { unreadableModesVersion: typeof version === "number" ? version : 0 };
8759
8766
  const modes = {};
8760
8767
  for (const mode of VIDEO_MODES) {
8761
- const entry = record$5(modesRaw[mode]);
8768
+ const entry = record$7(modesRaw[mode]);
8762
8769
  if (entry === void 0) continue;
8763
- const inputsRaw = record$5(entry.inputs) ?? {};
8770
+ const inputsRaw = record$7(entry.inputs) ?? {};
8764
8771
  const inputs = {};
8765
8772
  for (const [key, limitRaw] of Object.entries(inputsRaw)) {
8766
- const limit = record$5(limitRaw);
8773
+ const limit = record$7(limitRaw);
8767
8774
  const min = count(limit?.min);
8768
8775
  const max = count(limit?.max);
8769
8776
  if (!VIDEO_INPUTS.includes(key) || limit === void 0 || min === void 0 || max === void 0 || min > max) return { unreadableModesVersion: 1 };
@@ -8872,11 +8879,11 @@ function parseVideoCapabilities(raw) {
8872
8879
  if (Array.isArray(combinationsRaw)) {
8873
8880
  const combinations = [];
8874
8881
  for (const item of combinationsRaw) {
8875
- const entry = record$5(item);
8882
+ const entry = record$7(item);
8876
8883
  if (entry === void 0) continue;
8877
8884
  const duration = positive$1(field(entry, "duration_seconds"));
8878
- const ratio = text$4(entry.ratio);
8879
- const resolution = text$4(entry.resolution);
8885
+ const ratio = text$5(entry.ratio);
8886
+ const resolution = text$5(entry.resolution);
8880
8887
  combinations.push({
8881
8888
  ...duration === void 0 ? {} : { duration },
8882
8889
  ...ratio === void 0 ? {} : { ratio },
@@ -8966,12 +8973,12 @@ const PRICE_UNITS = [
8966
8973
  ];
8967
8974
  /** The audio block: `entry.audio`, else `capabilities.audio`, else the fields flattened into `capabilities`. */
8968
8975
  function audioBlock(entry, capabilities) {
8969
- const own = record$5(entry.audio) ?? record$5(capabilities.audio);
8976
+ const own = record$7(entry.audio) ?? record$7(capabilities.audio);
8970
8977
  if (own !== void 0) return own;
8971
8978
  return field(capabilities, "generation_kind") !== void 0 ? capabilities : void 0;
8972
8979
  }
8973
8980
  function stringChoices(raw) {
8974
- const choices = record$5(raw);
8981
+ const choices = record$7(raw);
8975
8982
  if (choices === void 0) return void 0;
8976
8983
  const out = {};
8977
8984
  for (const [name, values] of Object.entries(choices)) {
@@ -9015,7 +9022,7 @@ function parseReferenceLimits(raw, form) {
9015
9022
  if (mimes !== void 0 && mimes.length > 0) limits.mimes = mimes;
9016
9023
  const exclusive = list(raw, "mutually_exclusive_with") ?? list(raw, "exclusive_with");
9017
9024
  if (exclusive !== void 0 && exclusive.length > 0) limits.exclusiveWith = exclusive;
9018
- const purpose = text$4(field(raw, "asset_purpose")) ?? text$4(raw.purpose);
9025
+ const purpose = text$5(field(raw, "asset_purpose")) ?? text$5(raw.purpose);
9019
9026
  if (purpose !== void 0) limits.purpose = purpose;
9020
9027
  return limits;
9021
9028
  }
@@ -9044,11 +9051,11 @@ function seedReferenceLimits(raw) {
9044
9051
  function parseOutputFormats(raw) {
9045
9052
  const declared = field(raw, "output_formats");
9046
9053
  if (!Array.isArray(declared)) return void 0;
9047
- const rates = record$5(field(raw, "sample_rates")) ?? record$5(field(raw, "output_sample_rates"));
9054
+ const rates = record$7(field(raw, "sample_rates")) ?? record$7(field(raw, "output_sample_rates"));
9048
9055
  const formats = [];
9049
9056
  for (const item of declared) {
9050
- const entry = record$5(item);
9051
- const format = (entry === void 0 ? text$4(item) : text$4(entry.format))?.toLowerCase();
9057
+ const entry = record$7(item);
9058
+ const format = (entry === void 0 ? text$5(item) : text$5(entry.format))?.toLowerCase();
9052
9059
  if (format === void 0 || formats.some((known) => known.format === format)) continue;
9053
9060
  const sampleRates = (entry === void 0 ? void 0 : field(entry, "sample_rates")) ?? rates?.[format];
9054
9061
  const valid = Array.isArray(sampleRates) ? sampleRates.filter((rate) => positive$1(rate) !== void 0 && Number.isInteger(rate)) : [];
@@ -9067,20 +9074,20 @@ function parseOutputFormats(raw) {
9067
9074
  * @returns the declared capabilities; `generationKind` is absent unless declared.
9068
9075
  */
9069
9076
  function parseAudioCapabilities(raw) {
9070
- const kindRaw = text$4(field(raw, "generation_kind"))?.toLowerCase();
9077
+ const kindRaw = text$5(field(raw, "generation_kind"))?.toLowerCase();
9071
9078
  const generationKind = AUDIO_GENERATION_KINDS.includes(kindRaw ?? "") ? kindRaw : void 0;
9072
- const billingRaw = text$4(field(raw, "billing_unit"))?.toLowerCase();
9079
+ const billingRaw = text$5(field(raw, "billing_unit"))?.toLowerCase();
9073
9080
  const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
9074
- const promptField = text$4(field(raw, "prompt_field"));
9081
+ const promptField = text$5(field(raw, "prompt_field"));
9075
9082
  const requestFields = list(raw, "request_fields") ?? [];
9076
9083
  const union = [
9077
9084
  "reference_audio_input",
9078
9085
  "reference_image_input",
9079
9086
  "speaker_input"
9080
9087
  ].some((name) => bool(raw, name) !== void 0);
9081
- const references = parseReferenceLimits(record$5(field(raw, "references")) ?? record$5(field(raw, "reference_audio")), union ? "object" : "url") ?? seedReferenceLimits(raw);
9088
+ const references = parseReferenceLimits(record$7(field(raw, "references")) ?? record$7(field(raw, "reference_audio")), union ? "object" : "url") ?? seedReferenceLimits(raw);
9082
9089
  const outputFormats = parseOutputFormats(raw);
9083
- const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
9090
+ const defaultFormat = text$5(field(raw, "default_format"))?.toLowerCase();
9084
9091
  const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
9085
9092
  const watermarkFields = list(raw, "watermark_fields");
9086
9093
  const result = { requestFields };
@@ -9092,6 +9099,7 @@ function parseAudioCapabilities(raw) {
9092
9099
  if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
9093
9100
  if (choices !== void 0) result.choices = choices;
9094
9101
  if (watermarkFields !== void 0 && watermarkFields.length > 0) result.watermarkFields = watermarkFields;
9102
+ if (bool(raw, "supports_voice_cover") === true) result.supportsVoiceCover = true;
9095
9103
  for (const [key, ...names] of [
9096
9104
  [
9097
9105
  "maxPromptChars",
@@ -9120,13 +9128,13 @@ function parseAudioCapabilities(raw) {
9120
9128
  return result;
9121
9129
  }
9122
9130
  function parsePricing(value, audioUnit) {
9123
- const raw = record$5(value);
9131
+ const raw = record$7(value);
9124
9132
  if (raw === void 0) return void 0;
9125
9133
  const unit = (item) => PRICE_UNITS.includes(item) ? item : item === void 0 && audioUnit !== void 0 ? audioUnit : void 0;
9126
9134
  const tiers = [];
9127
9135
  if (Array.isArray(raw.tiers)) for (const entry of raw.tiers) {
9128
- const tier = record$5(entry);
9129
- const name = text$4(tier?.tier);
9136
+ const tier = record$7(entry);
9137
+ const name = text$5(tier?.tier);
9130
9138
  const tierUnit = unit(tier?.unit);
9131
9139
  const amount = typeof tier?.amount === "number" && Number.isFinite(tier.amount) && tier.amount >= 0 ? tier.amount : void 0;
9132
9140
  if (name !== void 0 && tierUnit !== void 0 && amount !== void 0) tiers.push({
@@ -9135,12 +9143,12 @@ function parsePricing(value, audioUnit) {
9135
9143
  amount
9136
9144
  });
9137
9145
  }
9138
- const fallback = record$5(raw.default);
9146
+ const fallback = record$7(raw.default);
9139
9147
  const fallbackUnit = unit(fallback?.unit);
9140
9148
  const fallbackAmount = typeof fallback?.amount === "number" && Number.isFinite(fallback.amount) && fallback.amount >= 0 ? fallback.amount : void 0;
9141
9149
  if (tiers.length === 0 && (fallbackUnit === void 0 || fallbackAmount === void 0)) return void 0;
9142
9150
  return {
9143
- currency: text$4(raw.currency) ?? "CNY",
9151
+ currency: text$5(raw.currency) ?? "CNY",
9144
9152
  tiers,
9145
9153
  ...fallbackUnit === void 0 || fallbackAmount === void 0 ? {} : { default: {
9146
9154
  unit: fallbackUnit,
@@ -9163,7 +9171,7 @@ function condition(raw, snake) {
9163
9171
  */
9164
9172
  function parseVideoPricing(value) {
9165
9173
  if (value === void 0 || value === null) return {};
9166
- const raw = record$5(value);
9174
+ const raw = record$7(value);
9167
9175
  if (raw === void 0) return { videoPricingIssue: "invalid" };
9168
9176
  if (field(raw, "schema_version") !== 1) return { videoPricingIssue: "unknown-schema" };
9169
9177
  const invalid = { videoPricingIssue: "invalid" };
@@ -9173,9 +9181,9 @@ function parseVideoPricing(value) {
9173
9181
  if (!Array.isArray(rulesRaw) || rulesRaw.length === 0) return invalid;
9174
9182
  const rules = [];
9175
9183
  for (const item of rulesRaw) {
9176
- const entry = record$5(item);
9184
+ const entry = record$7(item);
9177
9185
  if (entry === void 0) return invalid;
9178
- const resolution = text$4(field(entry, "resolution"));
9186
+ const resolution = text$5(field(entry, "resolution"));
9179
9187
  const perMillion = price(field(entry, "price_per_million_tokens"));
9180
9188
  const estimateRaw = field(entry, "estimated_price_per_second");
9181
9189
  const perSecond = estimateRaw === void 0 || estimateRaw === null ? void 0 : price(estimateRaw);
@@ -9203,10 +9211,10 @@ function parseVideoPricing(value) {
9203
9211
  }
9204
9212
  /** Which kind of media model a catalog entry is, or undefined for a chat or internal model. */
9205
9213
  function kindOf(entry, capabilities, audio) {
9206
- if (text$4(entry.internal_role) !== void 0) return void 0;
9214
+ if (text$5(entry.internal_role) !== void 0) return void 0;
9207
9215
  if (audio?.generationKind === "transcription") return "transcription";
9208
9216
  if (audio?.generationKind !== void 0) return "audio";
9209
- const mediaType = text$4(entry.media_type);
9217
+ const mediaType = text$5(entry.media_type);
9210
9218
  if (mediaType === "video" || mediaType === "image" || mediaType === "audio" || mediaType === "transcription") return mediaType;
9211
9219
  if (capabilities.transcription === true || capabilities.realtime_transcription === true) return "transcription";
9212
9220
  const outputs = strings(capabilities.output_modalities) ?? strings(entry.output_modalities) ?? [];
@@ -9225,22 +9233,22 @@ function kindOf(entry, capabilities, audio) {
9225
9233
  * @returns the media models, in catalog order.
9226
9234
  */
9227
9235
  function parseMediaCatalog(body) {
9228
- const entries = Array.isArray(body) ? body : record$5(body)?.data;
9236
+ const entries = Array.isArray(body) ? body : record$7(body)?.data;
9229
9237
  if (!Array.isArray(entries)) return [];
9230
9238
  const models = [];
9231
9239
  const seen = /* @__PURE__ */ new Set();
9232
9240
  for (const item of entries) {
9233
- const entry = record$5(item);
9234
- const id = text$4(entry?.id);
9241
+ const entry = record$7(item);
9242
+ const id = text$5(entry?.id);
9235
9243
  if (entry === void 0 || id === void 0 || seen.has(id)) continue;
9236
- const capabilities = record$5(entry.capabilities) ?? {};
9244
+ const capabilities = record$7(entry.capabilities) ?? {};
9237
9245
  const audioRaw = audioBlock(entry, capabilities);
9238
9246
  const audio = audioRaw === void 0 ? void 0 : parseAudioCapabilities(audioRaw);
9239
9247
  const kind = kindOf(entry, capabilities, audio);
9240
9248
  if (kind === void 0) continue;
9241
9249
  seen.add(id);
9242
- const name = text$4(entry.display_name) ?? id;
9243
- const description = text$4(entry.description);
9250
+ const name = text$5(entry.display_name) ?? id;
9251
+ const description = text$5(entry.description);
9244
9252
  const pricing = parsePricing(entry.media_pricing, audio?.billingUnit);
9245
9253
  const { videoPricing, videoPricingIssue } = parseVideoPricing(field(entry, "video_pricing"));
9246
9254
  const inputModalities = strings(capabilities.input_modalities) ?? strings(entry.input_modalities) ?? [];
@@ -9249,7 +9257,7 @@ function parseMediaCatalog(body) {
9249
9257
  let video;
9250
9258
  if (kind === "video") video = {
9251
9259
  ...parseVideoCapabilities(capabilities),
9252
- ...parseVideoCapabilities(record$5(entry.video) ?? {})
9260
+ ...parseVideoCapabilities(record$7(entry.video) ?? {})
9253
9261
  };
9254
9262
  const imageSizes = kind === "image" ? optionList(field(capabilities, "image_sizes")) : void 0;
9255
9263
  const imageRatios = kind === "image" ? optionList(field(capabilities, "image_ratios")) : void 0;
@@ -9872,7 +9880,7 @@ var GatewayFetchError = class extends WebError {
9872
9880
  this.name = "GatewayFetchError";
9873
9881
  }
9874
9882
  };
9875
- function record$4(value) {
9883
+ function record$6(value) {
9876
9884
  return typeof value === "object" && value !== null && !Array.isArray(value);
9877
9885
  }
9878
9886
  function positive(value) {
@@ -9912,14 +9920,14 @@ function invalidCapability() {
9912
9920
  }
9913
9921
  /** Decode only the fixed advertised Fetch V1 lane; absence is not a request to probe an endpoint. */
9914
9922
  function readGatewayFetchCapability(payload) {
9915
- if (record$4(payload) && (payload.error !== void 0 || typeof payload.code === "number" && payload.code !== 0)) throw invalidCapability();
9916
- if (!record$4(payload) || !record$4(payload.data)) return void 0;
9923
+ if (record$6(payload) && (payload.error !== void 0 || typeof payload.code === "number" && payload.code !== 0)) throw invalidCapability();
9924
+ if (!record$6(payload) || !record$6(payload.data)) return void 0;
9917
9925
  const capabilities = payload.data.capabilities;
9918
9926
  if (capabilities === void 0) return void 0;
9919
9927
  if (!Array.isArray(capabilities)) throw invalidCapability();
9920
9928
  if (!capabilities.includes("web-fetch-v1")) return void 0;
9921
9929
  const value = payload.data.web_fetch;
9922
- if (!record$4(value) || value.path !== FETCH_PATH || value.mode !== "extracted_content" || value.content_format !== "markdown" || value.character_unit !== "unicode_code_point" || value.security_scope !== SECURITY_SCOPE || !positive(value.max_url_characters) || !positive(value.max_body_characters) || !positive(value.max_provider_response_bytes) || !positive(value.timeout_ms) || !Array.isArray(value.allowed_ports) || value.allowed_ports.length === 0 || !value.allowed_ports.every((port) => port === 80 || port === 443)) throw invalidCapability();
9930
+ if (!record$6(value) || value.path !== FETCH_PATH || value.mode !== "extracted_content" || value.content_format !== "markdown" || value.character_unit !== "unicode_code_point" || value.security_scope !== SECURITY_SCOPE || !positive(value.max_url_characters) || !positive(value.max_body_characters) || !positive(value.max_provider_response_bytes) || !positive(value.timeout_ms) || !Array.isArray(value.allowed_ports) || value.allowed_ports.length === 0 || !value.allowed_ports.every((port) => port === 80 || port === 443)) throw invalidCapability();
9923
9931
  return {
9924
9932
  path: FETCH_PATH,
9925
9933
  mode: "extracted_content",
@@ -9940,7 +9948,7 @@ function normalizedRequest(value) {
9940
9948
  }
9941
9949
  /** Decode extraction facts without claiming an observed target status, final address or completeness. */
9942
9950
  function decodeGatewayFetchResponse(payload, requestedUrl, maxBodyCharacters) {
9943
- if (!record$4(payload) || typeof payload.requested_url !== "string" || payload.final_url !== null || payload.target_status_code !== null || payload.source_completeness !== "unknown" || typeof payload.truncated !== "boolean" || typeof payload.cached !== "boolean" || !record$4(payload.body) || payload.body.kind !== "text" || payload.body.format !== "markdown" || typeof payload.body.content !== "string" || payload.body.content.trim() === "" || payload.title !== void 0 && (typeof payload.title !== "string" || exceeds(payload.title, 4096))) throw invalidResponse();
9951
+ if (!record$6(payload) || typeof payload.requested_url !== "string" || payload.final_url !== null || payload.target_status_code !== null || payload.source_completeness !== "unknown" || typeof payload.truncated !== "boolean" || typeof payload.cached !== "boolean" || !record$6(payload.body) || payload.body.kind !== "text" || payload.body.format !== "markdown" || typeof payload.body.content !== "string" || payload.body.content.trim() === "" || payload.title !== void 0 && (typeof payload.title !== "string" || exceeds(payload.title, 4096))) throw invalidResponse();
9944
9952
  try {
9945
9953
  if (normalizedRequest(payload.requested_url) !== normalizedRequest(requestedUrl)) throw invalidResponse();
9946
9954
  } catch {
@@ -9969,8 +9977,8 @@ function decodeGatewayFetchResponse(payload, requestedUrl, maxBodyCharacters) {
9969
9977
  }
9970
9978
  function dependencyFailure(error, stage) {
9971
9979
  if (error instanceof GatewayFetchError) return error;
9972
- const source = record$4(error) ? error : void 0;
9973
- const details = record$4(source?.details) ? source.details : void 0;
9980
+ const source = record$6(error) ? error : void 0;
9981
+ const details = record$6(source?.details) ? source.details : void 0;
9974
9982
  const failure = gatewayFailureWithHeaders({ error: {
9975
9983
  code: safeId(source?.code),
9976
9984
  message: typeof source?.message === "string" ? source.message : void 0,
@@ -10053,7 +10061,7 @@ async function readJson(response, maxBytes, signal) {
10053
10061
  }
10054
10062
  function gatewayError(response, payload) {
10055
10063
  const parsed = gatewayFailureWithHeaders(payload, response.headers);
10056
- const source = record$4(payload) && record$4(payload.error) ? payload.error : void 0;
10064
+ const source = record$6(payload) && record$6(payload.error) ? payload.error : void 0;
10057
10065
  const code = safeId(parsed.code) ?? "WEB_FETCH_FAILED";
10058
10066
  const requestId = safeRequestId(parsed.requestId) ?? safeRequestId(response.headers.get("x-request-id"));
10059
10067
  const wait = retryAfterMs(response.headers.get("retry-after")) ?? (positive(source?.retry_after_seconds) ? source.retry_after_seconds * 1e3 : void 0);
@@ -10481,7 +10489,7 @@ var GatewaySearchError = class extends WebError {
10481
10489
  function isRecord(value) {
10482
10490
  return typeof value === "object" && value !== null && !Array.isArray(value);
10483
10491
  }
10484
- function text$3(value) {
10492
+ function text$4(value) {
10485
10493
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10486
10494
  }
10487
10495
  /** The gateway's own words for a failure, for error messages: ` (CODE: message)`. */
@@ -10563,9 +10571,9 @@ function mapSearchResponse(payload) {
10563
10571
  const sources = [];
10564
10572
  for (const item of payload.results) {
10565
10573
  if (!isRecord(item) || typeof item.url !== "string" || !URL.canParse(item.url)) continue;
10566
- const title = text$3(item.title);
10567
- const snippet = text$3(item.snippet);
10568
- const publishedAt = text$3(item.published_at);
10574
+ const title = text$4(item.title);
10575
+ const snippet = text$4(item.snippet);
10576
+ const publishedAt = text$4(item.published_at);
10569
10577
  sources.push({
10570
10578
  url: item.url,
10571
10579
  ...title === void 0 ? {} : { title },
@@ -10573,7 +10581,7 @@ function mapSearchResponse(payload) {
10573
10581
  ...publishedAt === void 0 ? {} : { publishedAt }
10574
10582
  });
10575
10583
  }
10576
- const answers = (Array.isArray(payload.answers) ? payload.answers : []).map((answer) => text$3(answer) ?? (isRecord(answer) ? text$3(answer.answer) : void 0)).filter((answer) => answer !== void 0);
10584
+ const answers = (Array.isArray(payload.answers) ? payload.answers : []).map((answer) => text$4(answer) ?? (isRecord(answer) ? text$4(answer.answer) : void 0)).filter((answer) => answer !== void 0);
10577
10585
  return {
10578
10586
  ...answers.length === 0 ? {} : { content: answers.join("\n\n") },
10579
10587
  sources,
@@ -11754,6 +11762,452 @@ function quotedCny(quote) {
11754
11762
  return quote.status === "estimate" ? format(roundHalfUp(decimal(quote.amountCny), 2), 2) : void 0;
11755
11763
  }
11756
11764
  //#endregion
11765
+ //#region src/audio/voice-profiles.ts
11766
+ /**
11767
+ * Voice profiles (音色): a user's own singing voice, kept by the gateway under a
11768
+ * `vp_…` id that `audio_generate` passes as `voice_id` to a model declaring it
11769
+ * (Suno V6 音色翻唱). The gateway's OpenAI-style endpoints:
11770
+ *
11771
+ * | call | what |
11772
+ * | -------------------------------------- | -------------------------------------- |
11773
+ * | `POST /v1/audio/voice-profiles` | `{ model, file_url, title }` → profile |
11774
+ * | `GET /v1/audio/voice-profiles` | the account's profiles |
11775
+ * | `DELETE /v1/audio/voice-profiles/{id}` | close one for good |
11776
+ *
11777
+ * Creating a profile is free and makes no song. The audio is checked here first
11778
+ * (type, ≤ 10 MiB, 6–60 s), uploaded to the media library under the
11779
+ * `audio_reference` purpose like speech references, and its public HTTPS link
11780
+ * goes in `file_url`. A profile is usable only once its status is `ready`.
11781
+ *
11782
+ * Only `vp_…` ids ever cross this module: a provider's own voice id is never
11783
+ * read out of an answer, never accepted as input, and is scrubbed from the
11784
+ * failure reasons shown to the user.
11785
+ * @module dsh-vibedev/audio/voice-profiles
11786
+ */
11787
+ /** The gateway endpoint. */
11788
+ const VOICE_PROFILES_PATH = "/v1/audio/voice-profiles";
11789
+ /** The model a profile is created for. */
11790
+ const VOICE_PROFILE_MODEL = "suno-v6-vibedev";
11791
+ /** The only id form accepted or shown. */
11792
+ const VOICE_PROFILE_ID = /^vp_[A-Za-z0-9_-]{1,120}$/;
11793
+ /** The media-library purpose the voice sample is uploaded under. */
11794
+ const VOICE_PROFILE_PURPOSE = "audio_reference";
11795
+ /** What the gateway takes as a voice sample. */
11796
+ const VOICE_SAMPLE_LIMITS = {
11797
+ maxBytes: 10485760,
11798
+ minSeconds: 6,
11799
+ maxSeconds: 60,
11800
+ /** Below this the voice is usually less faithful; the interfaces recommend it. */
11801
+ recommendedMinSeconds: 10,
11802
+ extensions: [
11803
+ "mp3",
11804
+ "wav",
11805
+ "m4a",
11806
+ "aac",
11807
+ "flac",
11808
+ "ogg"
11809
+ ],
11810
+ mimes: [
11811
+ "audio/mpeg",
11812
+ "audio/mp3",
11813
+ "audio/wav",
11814
+ "audio/x-wav",
11815
+ "audio/wave",
11816
+ "audio/vnd.wave",
11817
+ "audio/mp4",
11818
+ "audio/x-m4a",
11819
+ "audio/m4a",
11820
+ "audio/aac",
11821
+ "audio/x-aac",
11822
+ "audio/flac",
11823
+ "audio/x-flac",
11824
+ "audio/ogg"
11825
+ ]
11826
+ };
11827
+ /**
11828
+ * Provider refusals and what they mean, checked in order against the reason and the code (Suno refuses a sample that
11829
+ * "matches an existing recording", for one). A reason none of them matches is shown as it came, scrubbed.
11830
+ */
11831
+ const VOICE_REJECTIONS = [
11832
+ {
11833
+ kind: "similar_recording",
11834
+ pattern: /match(?:es|ed)? (?:an? )?existing recording|similar to (?:an? )?(?:existing|known) (?:recording|song|track)|existing (?:recording|track) match|copyright|copyrighted|already exists in (?:the )?(?:catalog|library)|duplicate recording/i,
11835
+ en: "This sample is too similar to an existing recording. Use a different clean, original vocal.",
11836
+ zh: "这段样本和已有录音太像,请换一段干净、独特的人声。"
11837
+ },
11838
+ {
11839
+ kind: "too_short",
11840
+ pattern: /too short|shorter than|at least \d+(?:\.\d+)? ?s(?:ec(?:ond)?s?)?\b|minimum (?:duration|length)|duration (?:is )?below/i,
11841
+ en: "This sample is too short: at least 6 seconds are needed (10–60 s works best).",
11842
+ zh: "样本太短:至少需要 6 秒(建议 10–60 秒)。"
11843
+ },
11844
+ {
11845
+ kind: "too_long",
11846
+ pattern: /too long|longer than|at most \d+(?:\.\d+)? ?s(?:ec(?:ond)?s?)?\b|maximum (?:duration|length)|duration (?:is )?(?:above|exceeds?)|exceeds? (?:the )?(?:max(?:imum)? )?duration/i,
11847
+ en: "This sample is too long: at most 60 seconds. Trim it to 10–60 s of clean vocals.",
11848
+ zh: "样本太长:最多 60 秒,请剪到 10–60 秒的干净人声。"
11849
+ },
11850
+ {
11851
+ kind: "format",
11852
+ pattern: /unsupported (?:audio |file )?(?:format|type|codec)|invalid (?:audio |file )?(?:format|type)|format (?:is )?not supported|could not (?:decode|read|parse) (?:the )?(?:audio|file)|corrupt(?:ed)? (?:audio|file)/i,
11853
+ en: "This audio format is not supported, or the file could not be read. Use mp3, wav, m4a, aac, flac or ogg.",
11854
+ zh: "音频格式不支持或文件无法读取,请使用 mp3、wav、m4a、aac、flac 或 ogg。"
11855
+ },
11856
+ {
11857
+ kind: "not_clean_vocal",
11858
+ pattern: /no (?:clear |detectable |audible )?(?:vocals?|voice|singing)|not (?:a )?clean vocal|vocals? not (?:detected|found|clear)|background (?:music|noise)|accompaniment|instrumental|multiple (?:voices|singers|speakers)|too (?:much )?noisy|noise level/i,
11859
+ en: "This is not a clean solo vocal. Use a recording of one voice without accompaniment or background noise.",
11860
+ zh: "这不是干净的人声:请换一段只有一个人声、不带伴奏和杂音的录音。"
11861
+ }
11862
+ ];
11863
+ /**
11864
+ * The plain meaning of a provider refusal.
11865
+ * @param reason - the provider's reason, and/or its code.
11866
+ * @returns the rejection, or undefined when none matches.
11867
+ */
11868
+ function voiceRejectionOf(...texts) {
11869
+ const text = texts.filter((item) => item !== void 0).join(" ").replace(/[_-]+/g, " ");
11870
+ return text === "" ? void 0 : VOICE_REJECTIONS.find((rule) => rule.pattern.test(text));
11871
+ }
11872
+ const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
11873
+ const text$3 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
11874
+ const READY = /* @__PURE__ */ new Set([
11875
+ "ready",
11876
+ "active",
11877
+ "available",
11878
+ "succeeded",
11879
+ "success",
11880
+ "completed"
11881
+ ]);
11882
+ const FAILED$1 = /* @__PURE__ */ new Set([
11883
+ "failed",
11884
+ "failure",
11885
+ "error",
11886
+ "rejected",
11887
+ "invalid",
11888
+ "cancelled",
11889
+ "canceled",
11890
+ "expired"
11891
+ ]);
11892
+ const DELETED = /* @__PURE__ */ new Set([
11893
+ "deleted",
11894
+ "closed",
11895
+ "removed",
11896
+ "disabled"
11897
+ ]);
11898
+ /** Map the gateway's status word; anything not settled counts as still being made. */
11899
+ function voiceStatusOf(raw) {
11900
+ const value = raw?.toLowerCase();
11901
+ if (value === void 0) return "processing";
11902
+ if (READY.has(value)) return "ready";
11903
+ if (FAILED$1.has(value)) return "failed";
11904
+ if (DELETED.has(value)) return "deleted";
11905
+ return "processing";
11906
+ }
11907
+ /**
11908
+ * A failure reason safe to show: no links, bearer tokens or long opaque ids (a provider's voice id would be one),
11909
+ * at most 300 characters. `vp_…` ids stay.
11910
+ */
11911
+ function scrubReason(value) {
11912
+ const clean = value.replace(/https?:\/\/[^\s)\]}>"']+/gi, "[link]").replace(/\b(?:Bearer\s+\S+|vdat_\S+|sk-\S+|eyJ[\w-]+\.[\w.-]+)/gi, "[redacted]").replace(/\b(?!vp_)[A-Za-z0-9][A-Za-z0-9_-]{23,}\b/g, "[id]").replace(/[\r\n\t]+/g, " ").trim();
11913
+ const chars = [...clean];
11914
+ return chars.length <= 300 ? clean : `${chars.slice(0, 299).join("")}…`;
11915
+ }
11916
+ function isoOf(value) {
11917
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
11918
+ const ms = value < 0xe8d4a51000 ? value * 1e3 : value;
11919
+ const date = new Date(ms);
11920
+ return Number.isFinite(date.getTime()) ? date.toISOString() : void 0;
11921
+ }
11922
+ const raw = text$3(value);
11923
+ if (raw === void 0) return void 0;
11924
+ const parsed = Date.parse(raw);
11925
+ return Number.isFinite(parsed) ? new Date(parsed).toISOString() : void 0;
11926
+ }
11927
+ function secondsOf(raw) {
11928
+ for (const key of [
11929
+ "duration_seconds",
11930
+ "duration",
11931
+ "audio_duration_seconds",
11932
+ "audio_duration"
11933
+ ]) {
11934
+ const value = raw[key];
11935
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
11936
+ }
11937
+ const ms = raw.duration_ms;
11938
+ return typeof ms === "number" && Number.isFinite(ms) && ms > 0 ? ms / 1e3 : void 0;
11939
+ }
11940
+ /**
11941
+ * Read one profile from a gateway answer. Only the allow-listed fields are kept, and an entry whose id is not a
11942
+ * `vp_…` id is dropped whole, so a provider id can never reach a caller.
11943
+ * @param value - one entry, or `{ data: entry }`.
11944
+ * @returns the profile, or undefined.
11945
+ */
11946
+ function parseVoiceProfile(value) {
11947
+ const outer = record$5(value);
11948
+ const raw = record$5(outer?.data) !== void 0 && outer?.id === void 0 ? record$5(outer?.data) : outer;
11949
+ if (raw === void 0) return void 0;
11950
+ const id = text$3(raw.id) ?? text$3(raw.voice_profile_id);
11951
+ if (id === void 0 || !VOICE_PROFILE_ID.test(id)) return void 0;
11952
+ const rawStatus = text$3(raw.status) ?? text$3(raw.state);
11953
+ const status = voiceStatusOf(rawStatus);
11954
+ const error = record$5(raw.error);
11955
+ const reason = text$3(error?.message) ?? text$3(raw.failure_reason) ?? text$3(raw.error_message) ?? text$3(raw.reason) ?? text$3(raw.error);
11956
+ const code = text$3(error?.code) ?? text$3(raw.failure_code) ?? text$3(raw.error_code);
11957
+ const title = text$3(raw.title) ?? text$3(raw.name);
11958
+ const seconds = secondsOf(raw);
11959
+ const createdAt = isoOf(raw.created_at) ?? isoOf(raw.created);
11960
+ const model = text$3(raw.model);
11961
+ const rejection = status === "failed" ? voiceRejectionOf(reason, code) : void 0;
11962
+ return {
11963
+ id,
11964
+ status,
11965
+ ...title === void 0 ? {} : { title: [...title].slice(0, 160).join("") },
11966
+ ...rawStatus === void 0 ? {} : { rawStatus: rawStatus.slice(0, 40) },
11967
+ ...status === "failed" && reason !== void 0 ? { failureReason: scrubReason(reason) } : {},
11968
+ ...rejection === void 0 ? {} : { failureKind: rejection.kind },
11969
+ ...status === "failed" && code !== void 0 && /^[\w.-]{1,80}$/.test(code) ? { failureCode: code } : {},
11970
+ ...seconds === void 0 ? {} : { durationSeconds: Math.round(seconds * 10) / 10 },
11971
+ ...createdAt === void 0 ? {} : { createdAt },
11972
+ ...model === void 0 || !/^[\w.-]{1,80}$/.test(model) ? {} : { model }
11973
+ };
11974
+ }
11975
+ /**
11976
+ * Read a list answer: `{ data: [...] }`, `{ items: [...] }`, `{ data: { items: [...] } }` or a bare array.
11977
+ * @param value - the answer.
11978
+ * @returns the profiles, newest first when the gateway dates them.
11979
+ */
11980
+ function parseVoiceProfiles(value) {
11981
+ const outer = record$5(value);
11982
+ const inner = record$5(outer?.data);
11983
+ return (Array.isArray(value) ? value : Array.isArray(outer?.data) ? outer.data : Array.isArray(outer?.items) ? outer.items : Array.isArray(inner?.items) ? inner.items : Array.isArray(inner?.data) ? inner.data : []).slice(0, 500).map(parseVoiceProfile).filter((item) => item !== void 0 && item.status !== "deleted").sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""));
11984
+ }
11985
+ /**
11986
+ * Check a profile id before it is sent: only `vp_…` ids.
11987
+ * @param id - what the caller passed.
11988
+ * @returns the trimmed id.
11989
+ * @throws {@link MediaError} `VOICE_PROFILE_ID_INVALID` for anything else (a provider's own id included).
11990
+ */
11991
+ function checkVoiceProfileId(id, field = "id") {
11992
+ const value = typeof id === "string" ? id.trim() : "";
11993
+ if (!VOICE_PROFILE_ID.test(value)) throw localInputError("A voice profile is named by its vp_… id (voice_profile_list shows them); no other voice id is accepted.", "VOICE_PROFILE_ID_INVALID", { field });
11994
+ return value;
11995
+ }
11996
+ /** Check a title: required, trimmed, at most {@link VOICE_TITLE_MAX} characters, no control characters. */
11997
+ function checkVoiceTitle(title) {
11998
+ const value = typeof title === "string" ? title.replace(/\s+/g, " ").trim() : "";
11999
+ if (value === "") throw localInputError("A voice profile needs a name (title).", "VOICE_TITLE_REQUIRED", { field: "title" });
12000
+ if (/[\u0000-\u001f\u007f]/.test(value)) throw localInputError("The voice profile name may not hold control characters.", "VOICE_TITLE_INVALID", { field: "title" });
12001
+ if ([...value].length > 80) throw localInputError(`The voice profile name is ${[...value].length} characters; at most 80.`, "VOICE_TITLE_TOO_LONG", { field: "title" });
12002
+ return value;
12003
+ }
12004
+ /** The file extension of a name, lower-case, without the dot. */
12005
+ function extensionOf(name) {
12006
+ return /\.([a-z0-9]{2,5})$/i.exec(name.trim())?.[1]?.toLowerCase();
12007
+ }
12008
+ /**
12009
+ * The length of a PCM WAV or a FLAC file from its header, when it can be read without decoding.
12010
+ * Other formats are measured by the media library after the upload.
12011
+ * @param data - the file bytes.
12012
+ * @returns seconds, or undefined.
12013
+ */
12014
+ function headerSeconds(data) {
12015
+ const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
12016
+ const ascii = (at, length) => at + length <= data.length ? String.fromCharCode(...data.subarray(at, at + length)) : "";
12017
+ if (ascii(0, 4) === "RIFF" && ascii(8, 4) === "WAVE") {
12018
+ let byteRate;
12019
+ for (let at = 12; at + 8 <= data.length;) {
12020
+ const id = ascii(at, 4), size = view.getUint32(at + 4, true);
12021
+ if (id === "fmt " && at + 16 <= data.length) byteRate = view.getUint32(at + 16, true);
12022
+ if (id === "data") {
12023
+ if (byteRate === void 0 || byteRate === 0) return void 0;
12024
+ const bytes = size === 0 || size === 4294967295 ? data.length - at - 8 : Math.min(size, data.length - at - 8);
12025
+ return bytes > 0 ? bytes / byteRate : void 0;
12026
+ }
12027
+ at += 8 + size + size % 2;
12028
+ }
12029
+ return;
12030
+ }
12031
+ if (ascii(0, 4) === "fLaC" && data.length >= 42 && (data[4] & 127) === 0) {
12032
+ const b = data.subarray(8, 42);
12033
+ const rate = b[10] << 12 | b[11] << 4 | b[12] >> 4;
12034
+ const total = (b[13] & 15) * 2 ** 32 + (b[14] << 24 >>> 0) + (b[15] << 16) + (b[16] << 8) + b[17];
12035
+ return rate > 0 && total > 0 ? total / rate : void 0;
12036
+ }
12037
+ }
12038
+ /**
12039
+ * Check a voice sample before anything is uploaded: type (extension or sniffed MIME on the allow-list), size, and —
12040
+ * when its header tells — its length.
12041
+ * @param media - the loaded file.
12042
+ * @returns the length read from the header, when there was one.
12043
+ * @throws {@link MediaError} with `rule` naming the broken limit.
12044
+ */
12045
+ function checkVoiceSample(media) {
12046
+ const limits = VOICE_SAMPLE_LIMITS;
12047
+ const extension = extensionOf(media.name);
12048
+ const mime = media.mime.toLowerCase().split(";")[0]?.trim() ?? "";
12049
+ if (!(limits.mimes.includes(mime) || mime === "application/octet-stream" && extension !== void 0 && limits.extensions.includes(extension))) throw voiceRule(`"${media.source}" is ${mime || "of an unknown type"}; a voice sample must be ${limits.extensions.join(", ")}.`, "VOICE_SAMPLE_FORMAT", "format");
12050
+ if (media.data.byteLength === 0) throw voiceRule(`"${media.source}" is empty.`, "VOICE_SAMPLE_EMPTY", "empty");
12051
+ if (media.data.byteLength > limits.maxBytes) throw voiceRule(`"${media.source}" is ${(media.data.byteLength / 1048576).toFixed(1)} MiB; a voice sample may be at most 10 MiB.`, "VOICE_SAMPLE_TOO_LARGE", "too_large");
12052
+ const seconds = headerSeconds(media.data);
12053
+ if (seconds !== void 0) checkVoiceSeconds(seconds, media.source);
12054
+ return seconds === void 0 ? {} : { seconds };
12055
+ }
12056
+ /** Check a measured length against 6–60 s. */
12057
+ function checkVoiceSeconds(seconds, source) {
12058
+ const limits = VOICE_SAMPLE_LIMITS;
12059
+ if (seconds < limits.minSeconds) throw voiceRule(`"${source}" is ${seconds.toFixed(1)} s; a voice sample needs at least ${limits.minSeconds} s (10–60 s of clean vocals works best).`, "VOICE_SAMPLE_TOO_SHORT", "too_short");
12060
+ if (seconds > limits.maxSeconds) throw voiceRule(`"${source}" is ${seconds.toFixed(1)} s; a voice sample may be at most ${limits.maxSeconds} s. Trim it to 10–60 s of clean vocals.`, "VOICE_SAMPLE_TOO_LONG", "too_long");
12061
+ }
12062
+ function voiceRule(message, code, rule) {
12063
+ return localInputError(message, code, {
12064
+ field: "source",
12065
+ rule
12066
+ });
12067
+ }
12068
+ /** The voice-profile endpoints, with the local checks and the upload in front of a creation. */
12069
+ var VoiceProfiles = class {
12070
+ options;
12071
+ sleep;
12072
+ now;
12073
+ constructor(options) {
12074
+ this.options = options;
12075
+ this.sleep = options.sleep ?? delay$1;
12076
+ this.now = options.now ?? Date.now;
12077
+ }
12078
+ request(options) {
12079
+ return {
12080
+ timeoutMs: 3e4,
12081
+ ...options.signal === void 0 ? {} : { signal: options.signal },
12082
+ ...options.isCurrentAccount === void 0 ? {} : { isCurrentAccount: options.isCurrentAccount }
12083
+ };
12084
+ }
12085
+ /** The account's profiles (closed ones left out). */
12086
+ async list(options = {}) {
12087
+ return parseVoiceProfiles(await this.options.http.json(VOICE_PROFILES_PATH, this.request(options)));
12088
+ }
12089
+ /** One profile, read from the list (the gateway offers no single read). */
12090
+ async get(id, options = {}) {
12091
+ const wanted = checkVoiceProfileId(id);
12092
+ return (await this.list(options)).find((profile) => profile.id === wanted);
12093
+ }
12094
+ /**
12095
+ * Check, upload and create one profile. Nothing is created when a check fails, the upload fails, the media library
12096
+ * hands back no public HTTPS link, or the measured length is outside 6–60 s.
12097
+ * @param media - the loaded voice sample.
12098
+ * @param title - the profile's name.
12099
+ * @param options - cancellation and the account guard.
12100
+ * @returns the profile as the gateway answered (often still being made).
12101
+ */
12102
+ async create(media, title, options = {}) {
12103
+ const name = checkVoiceTitle(title);
12104
+ const local = checkVoiceSample(media);
12105
+ let asset;
12106
+ try {
12107
+ asset = await this.options.upload(media, VOICE_PROFILE_PURPOSE, options.signal);
12108
+ } catch (error) {
12109
+ if (error instanceof MediaError && (error.code === "ABORTED" || error.code === "ACCOUNT_CHANGED" || error.code === "NOT_SIGNED_IN")) throw error;
12110
+ throw new MediaError(`The voice sample "${media.source}" could not be uploaded to the VibeDev media library${error instanceof Error ? ` (${error.message})` : ""}. No voice profile was created.`, "VOICE_SAMPLE_UPLOAD_FAILED", {
12111
+ stage: "upload",
12112
+ retryable: true,
12113
+ submissionState: "not_submitted",
12114
+ billingState: "not_charged"
12115
+ }, { cause: error });
12116
+ }
12117
+ const measured = asset.durationMs === void 0 ? local.seconds : asset.durationMs / 1e3;
12118
+ if (measured === void 0) throw localInputError(`The length of "${media.source}" could not be measured, so the 6–60 s limit cannot be checked. Export it as a standard WAV or MP3 and try again.`, "VOICE_SAMPLE_DURATION_UNKNOWN", {
12119
+ field: "source",
12120
+ rule: "duration_unknown"
12121
+ });
12122
+ checkVoiceSeconds(measured, media.source);
12123
+ if (!/^https:\/\//i.test(asset.referenceUrl)) throw new MediaError("The VibeDev media library returned no public HTTPS link for the voice sample, so no voice profile was created. Try again later.", "VOICE_SAMPLE_URL_UNAVAILABLE", {
12124
+ stage: "upload",
12125
+ retryable: true,
12126
+ submissionState: "not_submitted",
12127
+ billingState: "not_charged"
12128
+ });
12129
+ let answer;
12130
+ try {
12131
+ answer = await this.options.http.json(VOICE_PROFILES_PATH, {
12132
+ ...this.request(options),
12133
+ method: "POST",
12134
+ idempotencyKey: `vp-${randomUUID()}`,
12135
+ busyRetries: 0,
12136
+ json: {
12137
+ model: VOICE_PROFILE_MODEL,
12138
+ file_url: asset.referenceUrl,
12139
+ title: name
12140
+ }
12141
+ });
12142
+ } catch (error) {
12143
+ const rejection = error instanceof MediaError && (error.details.status ?? 0) >= 400 && (error.details.status ?? 0) < 500 ? voiceRejectionOf(error.message, error.code) : void 0;
12144
+ if (rejection === void 0) throw error;
12145
+ throw new MediaError(`${rejection.en} ${rejection.zh} (${scrubReason(error.message)}) No voice profile was created and nothing was charged.`, "VOICE_SAMPLE_REJECTED", {
12146
+ ...error.details,
12147
+ category: "invalid_input",
12148
+ rule: rejection.kind,
12149
+ field: "source",
12150
+ submissionState: "rejected",
12151
+ billingState: "not_charged"
12152
+ }, { cause: error });
12153
+ }
12154
+ const profile = parseVoiceProfile(answer);
12155
+ if (profile === void 0) throw new MediaError("The VibeDev gateway accepted the voice sample but answered without a vp_… profile id. Check voice_profile_list before trying again.", "VOICE_PROFILE_BAD_RESPONSE", {
12156
+ stage: "submit",
12157
+ retryable: false
12158
+ });
12159
+ return {
12160
+ ...profile,
12161
+ ...profile.durationSeconds === void 0 ? { durationSeconds: Math.round(measured * 10) / 10 } : {},
12162
+ ...profile.title === void 0 ? { title: name } : {}
12163
+ };
12164
+ }
12165
+ /**
12166
+ * Close one profile for good. Songs already made with it are not affected.
12167
+ * @param id - a `vp_…` id.
12168
+ */
12169
+ async remove(id, options = {}) {
12170
+ const wanted = checkVoiceProfileId(id);
12171
+ await this.options.http.send(`${VOICE_PROFILES_PATH}/${encodeURIComponent(wanted)}`, {
12172
+ ...this.request(options),
12173
+ method: "DELETE",
12174
+ busyRetries: 0
12175
+ });
12176
+ }
12177
+ /**
12178
+ * Read the profile until it is ready or failed, or the wait runs out: 2 s, then 3 s, 5 s and every 8 s.
12179
+ * @param id - the profile.
12180
+ * @param options - cancellation, the time limit and a progress callback.
12181
+ * @returns the last state read; `processing` when the wait ran out.
12182
+ */
12183
+ async waitUntilSettled(id, options = {}) {
12184
+ const started = this.now();
12185
+ const limit = options.timeoutMs ?? 18e4;
12186
+ const steps = [
12187
+ 2e3,
12188
+ 3e3,
12189
+ 5e3
12190
+ ];
12191
+ let last = {
12192
+ id: checkVoiceProfileId(id),
12193
+ status: "processing"
12194
+ };
12195
+ for (let round = 0;; round++) {
12196
+ const left = started + limit - this.now();
12197
+ if (left <= 0) return last;
12198
+ await this.sleep(Math.min(steps[round] ?? 8e3, left), options.signal);
12199
+ const found = await this.get(id, options);
12200
+ if (found === void 0) throw new MediaError(`Voice profile ${id} is no longer on this account (it may have been deleted).`, "VOICE_PROFILE_NOT_FOUND", {
12201
+ status: 404,
12202
+ retryable: false
12203
+ });
12204
+ last = found;
12205
+ options.onProgress?.(found, this.now() - started);
12206
+ if (found.status !== "processing") return found;
12207
+ }
12208
+ }
12209
+ };
12210
+ //#endregion
11757
12211
  //#region src/audio/request.ts
11758
12212
  /**
11759
12213
  * Audio generation requests — music, podcasts and speech — checked against what
@@ -11764,7 +12218,7 @@ function quotedCny(quote) {
11764
12218
  *
11765
12219
  * | kind | wire fields |
11766
12220
  * | ------- | --------------------------------------------------------------- |
11767
- * | music | model, prompt, lyrics, genre, mood, gender |
12221
+ * | music | model, prompt, lyrics, genre, mood, gender; as declared: style, title, instrumental, voice_id, source_audio_url, audio_weight, mode |
11768
12222
  * | podcast | model, prompt, source_url |
11769
12223
  * | speech | as declared; Seed: model, text_prompt, references, audio_config, watermark |
11770
12224
  *
@@ -11810,6 +12264,38 @@ const SPEECH_ONLY = [
11810
12264
  "sampleRate",
11811
12265
  "duration"
11812
12266
  ];
12267
+ /** Fields that belong to music only: a voice profile and the song to cover. */
12268
+ const MUSIC_ONLY = ["voiceId", "sourceAudio"];
12269
+ /**
12270
+ * The mode a music request derives (see {@link MusicMode}).
12271
+ * @param request - the request.
12272
+ * @returns the mode.
12273
+ */
12274
+ function musicModeOf(request) {
12275
+ if (has(request.voiceId)) return "voice_cover";
12276
+ if (has(request.sourceAudio)) return "cover";
12277
+ return "generate";
12278
+ }
12279
+ /** The song to cover: audio, or a video whose sound is used. */
12280
+ const SOURCE_AUDIO_MIMES = [
12281
+ "audio/mpeg",
12282
+ "audio/mp3",
12283
+ "audio/wav",
12284
+ "audio/x-wav",
12285
+ "audio/wave",
12286
+ "audio/mp4",
12287
+ "audio/x-m4a",
12288
+ "audio/aac",
12289
+ "audio/x-aac",
12290
+ "audio/flac",
12291
+ "audio/x-flac",
12292
+ "audio/ogg",
12293
+ "video/mp4",
12294
+ "video/quicktime",
12295
+ "video/webm"
12296
+ ];
12297
+ /** The largest song to cover: the provider recommends 8–10 MB, so 10 MiB is held here before anything is uploaded. */
12298
+ const SOURCE_AUDIO_MAX_BYTES = 10485760;
11813
12299
  /** Default limit on one reference file when the catalog states none. */
11814
12300
  const DEFAULT_REFERENCE_BYTES = 20971520;
11815
12301
  const OPERATION_ID = /^[\w-]{8,80}$/;
@@ -11841,26 +12327,26 @@ function promptFieldOf(model) {
11841
12327
  "input"
11842
12328
  ].find((name) => fields.includes(name));
11843
12329
  }
11844
- function refuse(message, field) {
12330
+ function refuse$1(message, field) {
11845
12331
  throw localInputError(message, "AUDIO_OPTION_INVALID", field === void 0 ? {} : { field });
11846
12332
  }
11847
12333
  /** Check one value against the model's declared choices for a field. */
11848
12334
  function checkChoice(audio, wire, value) {
11849
12335
  const choices = audio?.choices?.[wire];
11850
- if (choices !== void 0 && !choices.some((choice) => choice.toLowerCase() === value.toLowerCase())) refuse(`${wire} "${value}" is not offered by this model; it takes ${choices.join(", ")}.`, wire);
12336
+ if (choices !== void 0 && !choices.some((choice) => choice.toLowerCase() === value.toLowerCase())) refuse$1(`${wire} "${value}" is not offered by this model; it takes ${choices.join(", ")}.`, wire);
11851
12337
  }
11852
12338
  /** The output format and sample rate a speech request uses, from the declared formats only. */
11853
12339
  function audioConfigOf(model, format, sampleRate) {
11854
12340
  const formats = model.audio?.outputFormats ?? [];
11855
12341
  if (formats.length === 0) {
11856
- if (format !== void 0 || sampleRate !== void 0) refuse(`${model.id} declares no output formats, so format and sample_rate cannot be chosen.`, "format");
12342
+ if (format !== void 0 || sampleRate !== void 0) refuse$1(`${model.id} declares no output formats, so format and sample_rate cannot be chosen.`, "format");
11857
12343
  return;
11858
12344
  }
11859
12345
  const wanted = format?.trim().toLowerCase();
11860
12346
  const chosen = wanted === void 0 || wanted === "" ? formats.find((item) => item.format === model.audio?.defaultFormat) ?? formats[0] : formats.find((item) => item.format === wanted);
11861
- if (chosen === void 0) refuse(`${model.id} writes ${formats.map((item) => item.format).join(", ")}, not "${format}".`, "format");
12347
+ if (chosen === void 0) refuse$1(`${model.id} writes ${formats.map((item) => item.format).join(", ")}, not "${format}".`, "format");
11862
12348
  if (sampleRate !== void 0) {
11863
- if (chosen.sampleRates.length > 0 && !chosen.sampleRates.includes(sampleRate)) refuse(`${chosen.format.toUpperCase()} from ${model.id} takes a sample rate of ${chosen.sampleRates.join(", ")} Hz, not ${sampleRate}.`, "sample_rate");
12349
+ if (chosen.sampleRates.length > 0 && !chosen.sampleRates.includes(sampleRate)) refuse$1(`${chosen.format.toUpperCase()} from ${model.id} takes a sample rate of ${chosen.sampleRates.join(", ")} Hz, not ${sampleRate}.`, "sample_rate");
11864
12350
  return {
11865
12351
  format: chosen.format,
11866
12352
  sample_rate: sampleRate
@@ -11888,19 +12374,24 @@ function audioRequestBody(model, request) {
11888
12374
  if (fields.length === 0) throw localInputError(`${model.id} declares no request fields, so no request can be built for it.`, "AUDIO_FIELDS_UNDECLARED", { field: "model" });
11889
12375
  if (kind !== "speech") for (const name of SPEECH_ONLY) {
11890
12376
  const value = request[name];
11891
- if (value !== void 0 && !(Array.isArray(value) && value.length === 0)) refuse(`${name === "sampleRate" ? "sample_rate" : name} is for speech; ${kind === "music" ? "music" : "a podcast"} does not take it.`, name);
12377
+ if (value !== void 0 && !(Array.isArray(value) && value.length === 0)) refuse$1(`${name === "sampleRate" ? "sample_rate" : name} is for speech; ${kind === "music" ? "music" : "a podcast"} does not take it.`, name);
12378
+ }
12379
+ if (kind !== "music") {
12380
+ for (const name of MUSIC_ONLY) if (has(request[name])) refuse$1(`${name === "voiceId" ? "voice_id" : "source_audio"} is for music; ${kind === "speech" ? "speech" : "a podcast"} does not take it.`, name);
11892
12381
  }
11893
12382
  const takes = (wire) => fields.includes(wire);
11894
12383
  const body = { model: model.id };
11895
12384
  const promptField = promptFieldOf(model);
11896
12385
  const prompt = request.prompt?.trim();
11897
12386
  if (has(prompt)) {
11898
- if (promptField === void 0) refuse(`${model.id} takes no text prompt.`, "prompt");
11899
- if (audio?.maxPromptChars !== void 0 && [...prompt].length > audio.maxPromptChars) refuse(`The text is ${[...prompt].length} characters; ${model.id} takes at most ${audio.maxPromptChars}.`, promptField);
12387
+ if (promptField === void 0) refuse$1(`${model.id} takes no text prompt.`, "prompt");
12388
+ if (audio?.maxPromptChars !== void 0 && [...prompt].length > audio.maxPromptChars) refuse$1(`The text is ${[...prompt].length} characters; ${model.id} takes at most ${audio.maxPromptChars}.`, promptField);
11900
12389
  body[promptField] = prompt;
11901
12390
  }
11902
12391
  for (const [key, wire] of [
11903
12392
  ["lyrics", "lyrics"],
12393
+ ["style", "style"],
12394
+ ["title", "title"],
11904
12395
  ["genre", "genre"],
11905
12396
  ["mood", "mood"],
11906
12397
  ["gender", "gender"],
@@ -11908,28 +12399,53 @@ function audioRequestBody(model, request) {
11908
12399
  ]) {
11909
12400
  const value = request[key]?.trim();
11910
12401
  if (!has(value)) continue;
11911
- if (!takes(wire)) refuse(`${model.id} does not take ${wire}; it takes ${fields.filter((name) => name !== "model").join(", ")}.`, wire);
12402
+ if (!takes(wire)) refuse$1(`${model.id} does not take ${wire}; it takes ${fields.filter((name) => name !== "model").join(", ")}.`, wire);
11912
12403
  checkChoice(audio, wire, value);
11913
- if (wire === "source_url" && !/^https?:\/\//i.test(value)) refuse("source_url must be an http(s) link.", wire);
12404
+ if (wire === "source_url" && !/^https?:\/\//i.test(value)) refuse$1("source_url must be an http(s) link.", wire);
11914
12405
  body[wire] = value;
11915
12406
  }
12407
+ if (request.instrumental !== void 0) {
12408
+ if (!takes("instrumental")) refuse$1(`${model.id} does not take instrumental.`, "instrumental");
12409
+ body.instrumental = request.instrumental;
12410
+ }
12411
+ if (kind === "music") {
12412
+ if (has(request.voiceId)) {
12413
+ const voiceId = checkVoiceProfileId(request.voiceId, "voice_id");
12414
+ if (!takes("voice_id")) refuse$1(`${model.id} does not take voice_id; a voice cover needs a music model that declares it (media_models lists the fields).`, "voice_id");
12415
+ if (!supportsVoiceCover(model)) refuse$1(`${model.id} does not support voice covers (it declares no supports_voice_cover), so voice_id would be ignored; leave model out to use one that does.`, "voice_id");
12416
+ body.voice_id = voiceId;
12417
+ }
12418
+ if (has(request.sourceAudio) && !takes("source_audio_url")) refuse$1(`${model.id} does not take source_audio_url; covering a song needs a music model that declares it (media_models lists the fields).`, "source_audio");
12419
+ const mode = musicModeOf(request);
12420
+ if (request.audioWeight !== void 0) {
12421
+ const weight = request.audioWeight;
12422
+ if (typeof weight !== "number" || !Number.isFinite(weight) || weight < 0 || weight > 1) refuse$1(`audio_weight must be a number from 0 to 1 (inclusive); ${String(weight)} was given.`, "audio_weight");
12423
+ if (mode === "generate") refuse$1("audio_weight (how closely the song follows the reference audio) only applies to a cover: give source_audio (上传翻唱) or voice_id (音色翻唱), or leave audio_weight out.", "audio_weight");
12424
+ if (!takes("audio_weight")) refuse$1(`${model.id} does not take audio_weight.`, "audio_weight");
12425
+ body.audio_weight = weight;
12426
+ }
12427
+ if (takes("mode")) {
12428
+ checkChoice(audio, "mode", mode);
12429
+ body.mode = mode;
12430
+ }
12431
+ } else if (request.audioWeight !== void 0) refuse$1(`audio_weight is for music covers; ${kind === "speech" ? "speech" : "a podcast"} does not take it.`, "audio_weight");
11916
12432
  if (request.duration !== void 0) {
11917
- if (!takes("duration")) refuse(`${model.id} does not take a duration.`, "duration");
12433
+ if (!takes("duration")) refuse$1(`${model.id} does not take a duration.`, "duration");
11918
12434
  body.duration = request.duration;
11919
12435
  }
11920
12436
  if (request.watermark !== void 0) {
11921
- if (!takes("watermark")) refuse(`${model.id} does not take watermark.`, "watermark");
12437
+ if (!takes("watermark")) refuse$1(`${model.id} does not take watermark.`, "watermark");
11922
12438
  const fields = audio?.watermarkFields;
11923
12439
  if (fields === void 0) body.watermark = request.watermark;
11924
12440
  else if (fields.includes("aigc_watermark")) body.watermark = { aigc_watermark: request.watermark };
11925
- else refuse(`${model.id} declares its watermark as ${fields.join(", ")}, without a switch to turn it on or off.`, "watermark");
12441
+ else refuse$1(`${model.id} declares its watermark as ${fields.join(", ")}, without a switch to turn it on or off.`, "watermark");
11926
12442
  }
11927
12443
  if (request.format !== void 0 || request.sampleRate !== void 0 || takes("audio_config")) {
11928
- if (!takes("audio_config")) refuse(`${model.id} does not take an output format or sample rate.`, "format");
12444
+ if (!takes("audio_config")) refuse$1(`${model.id} does not take an output format or sample rate.`, "format");
11929
12445
  const config = audioConfigOf(model, request.format, request.sampleRate);
11930
12446
  if (config !== void 0) body.audio_config = config;
11931
12447
  }
11932
- if ((request.references?.length ?? 0) > 0 && !takes("references")) refuse(`${model.id} does not take reference audio.`, "references");
12448
+ if ((request.references?.length ?? 0) > 0 && !takes("references")) refuse$1(`${model.id} does not take reference audio.`, "references");
11933
12449
  if (kind === "music" && !has(prompt)) throw localInputError("Music needs a prompt describing the song.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
11934
12450
  if (kind === "podcast" && !has(prompt) && body.source_url === void 0) throw localInputError("A podcast needs a prompt (the topic), a source_url, or both.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
11935
12451
  if (kind === "speech" && !has(prompt)) throw localInputError("Speech needs the text to speak.", "AUDIO_PROMPT_REQUIRED", { field: promptField ?? "prompt" });
@@ -11938,10 +12454,10 @@ function audioRequestBody(model, request) {
11938
12454
  /** Load, check and upload the reference audio of a speech request; their measured lengths are checked too. */
11939
12455
  async function uploadReferences(runtime, call, model, sources, body) {
11940
12456
  const limits = model.audio?.references;
11941
- if (limits === void 0) refuse(`${model.id} does not take reference audio.`, "references");
11942
- if (sources.length < limits.min || sources.length > limits.max) refuse(limits.min === limits.max ? `${model.id} takes exactly ${limits.max} reference audio file(s); ${sources.length} were given.` : `${model.id} takes ${limits.min}–${limits.max} reference audio file(s); ${sources.length} were given.`, "references");
12457
+ if (limits === void 0) refuse$1(`${model.id} does not take reference audio.`, "references");
12458
+ if (sources.length < limits.min || sources.length > limits.max) refuse$1(limits.min === limits.max ? `${model.id} takes exactly ${limits.max} reference audio file(s); ${sources.length} were given.` : `${model.id} takes ${limits.min}–${limits.max} reference audio file(s); ${sources.length} were given.`, "references");
11943
12459
  const clash = (limits.exclusiveWith ?? []).filter((name) => body[name] !== void 0);
11944
- if (clash.length > 0) refuse(`Reference audio cannot be combined with ${clash.join(", ")} on ${model.id}.`, "references");
12460
+ if (clash.length > 0) refuse$1(`Reference audio cannot be combined with ${clash.join(", ")} on ${model.id}.`, "references");
11945
12461
  const maxBytes = limits.maxBytes ?? DEFAULT_REFERENCE_BYTES;
11946
12462
  const loaded = [];
11947
12463
  for (const source of sources) {
@@ -11969,12 +12485,85 @@ async function uploadReferences(runtime, call, model, sources, body) {
11969
12485
  return checked;
11970
12486
  }
11971
12487
  /**
12488
+ * Load, check and upload the song a cover is made from, and hand back its public HTTPS link. Every failure is an
12489
+ * explicit error: a cover never quietly becomes a plain generation.
12490
+ * @param runtime - the media runtime.
12491
+ * @param call - the tool call or host call.
12492
+ * @param source - a workspace path, `chat:N` (audio), `chat:video:N`, or an https link.
12493
+ * @returns the media library's public HTTPS link.
12494
+ */
12495
+ async function uploadSourceAudio(runtime, call, source) {
12496
+ if (/^http:\/\//i.test(source)) refuse$1("source_audio must be an https link, a workspace file or a chat attachment; plain http links are not taken.", "source_audio");
12497
+ if (/^data:/i.test(source)) refuse$1("source_audio must be a workspace file, a chat attachment or an https link.", "source_audio");
12498
+ const chat = parseChatReference(source);
12499
+ const media = await runtime.load(call, source, chat?.kind === "video" ? "video" : "audio", SOURCE_AUDIO_MAX_BYTES).catch((error) => {
12500
+ if (error instanceof MediaError && error.code === "MEDIA_TOO_LARGE") throw localInputError(`The song to cover is larger than 10 MiB (${error.message}). Keep the source audio for a cover under 10 MB; trim or compress a larger file first. 翻唱源音频建议控制在 10 MB 以内,超大的请先剪辑或压缩。`, "SOURCE_AUDIO_TOO_LARGE", {
12501
+ field: "source_audio",
12502
+ rule: "too_large"
12503
+ });
12504
+ throw error;
12505
+ });
12506
+ const mime = media.mime.toLowerCase().split(";")[0]?.trim() ?? "";
12507
+ if (!SOURCE_AUDIO_MIMES.includes(mime)) throw localInputError(`"${media.source}" is ${mime || "of an unknown type"}; the song to cover must be audio (mp3, wav, m4a, aac, flac, ogg) or video (mp4, mov, webm).`, "SOURCE_AUDIO_MEDIA_TYPE_UNSUPPORTED", { field: "source_audio" });
12508
+ let asset;
12509
+ try {
12510
+ asset = await runtime.library.upload(media, "audio_reference", call.signal);
12511
+ } catch (error) {
12512
+ if (error instanceof MediaError && (error.code === "ABORTED" || error.code === "ACCOUNT_CHANGED" || error.code === "NOT_SIGNED_IN")) throw error;
12513
+ throw new MediaError(`The song to cover ("${media.source}") could not be uploaded to the VibeDev media library${error instanceof Error ? ` (${error.message})` : ""}. Nothing was submitted or charged.`, "SOURCE_AUDIO_UPLOAD_FAILED", {
12514
+ stage: "upload",
12515
+ retryable: true,
12516
+ submissionState: "not_submitted",
12517
+ billingState: "not_charged"
12518
+ }, { cause: error });
12519
+ }
12520
+ if (!/^https:\/\//i.test(asset.referenceUrl)) throw new MediaError(`The VibeDev media library returned no public HTTPS link for "${media.source}", so the cover was not submitted (nothing was charged). Try again later.`, "SOURCE_AUDIO_URL_UNAVAILABLE", {
12521
+ stage: "upload",
12522
+ retryable: true,
12523
+ submissionState: "not_submitted",
12524
+ billingState: "not_charged"
12525
+ });
12526
+ return asset.referenceUrl;
12527
+ }
12528
+ /** Whether a model sings in a voice profile, as the catalog declares it (`audio.supports_voice_cover`). */
12529
+ function supportsVoiceCover(model) {
12530
+ return model.audio?.supportsVoiceCover === true;
12531
+ }
12532
+ /**
12533
+ * The model of a voice cover nobody named: the first music model that declares `supports_voice_cover: true`, by
12534
+ * declaration only. None is an error: a model without it would ignore `voice_id` and still charge.
12535
+ */
12536
+ async function chooseVoiceCoverModel(runtime, signal) {
12537
+ const found = (await runtime.models(signal)).find((candidate) => servesSlot(candidate, "music") && supportsVoiceCover(candidate));
12538
+ if (found !== void 0) return found;
12539
+ throw new MediaError("No model on this VibeDev account supports voice covers right now (none declares supports_voice_cover), so nothing was submitted or charged. 当前没有支持音色翻唱的模型。", "VOICE_COVER_MODEL_UNAVAILABLE", {
12540
+ category: "model_unavailable",
12541
+ stage: "catalog",
12542
+ submissionState: "not_submitted",
12543
+ billingState: "not_charged",
12544
+ retryable: false,
12545
+ field: "voice_id"
12546
+ });
12547
+ }
12548
+ /**
11972
12549
  * Choose the model for a request: the one named (an id or an alias), else the
11973
12550
  * pinned or first model of the kind. A named model must make the kind asked for.
12551
+ *
12552
+ * Music without a named model: a voice cover (`voice_cover`) takes the first model that declares
12553
+ * `supports_voice_cover: true` (see {@link chooseVoiceCoverModel}); a cover or a plain song follows `musicModel` as
12554
+ * before, preferring a model that declares the fields the request uses and not a voice-cover model unless
12555
+ * `musicModel` itself names it.
11974
12556
  */
11975
12557
  async function chooseAudioModel(runtime, request, signal) {
11976
12558
  if (request.kind === void 0 && !has(request.model)) throw localInputError("Say what to make (music, podcast or speech), or name a model.", "AUDIO_KIND_REQUIRED", { field: "type" });
11977
- if (request.kind !== void 0) return runtime.pickModel("audio", request.kind, request.model, void 0, signal);
12559
+ if (request.kind !== void 0) {
12560
+ if (request.kind !== "music" || has(request.model)) return runtime.pickModel("audio", request.kind, request.model, void 0, signal);
12561
+ if (musicModeOf(request) === "voice_cover") return chooseVoiceCoverModel(runtime, signal);
12562
+ const needed = [...has(request.sourceAudio) ? ["source_audio_url"] : [], ...request.audioWeight !== void 0 ? ["audio_weight"] : []];
12563
+ const pinned = runtime.settings.defaultModel("music").trim().toLowerCase();
12564
+ const accept = (candidate) => (candidate.id.toLowerCase() === pinned || !supportsVoiceCover(candidate)) && needed.every((name) => requestFieldsOf(candidate).includes(name));
12565
+ return runtime.pickModel("audio", "music", void 0, accept, signal);
12566
+ }
11978
12567
  const model = await runtime.findModel(request.model, signal);
11979
12568
  if (model.kind !== "audio") throw localInputError(`${model.id} is not an audio generation model.`, "MODEL_KIND_MISMATCH", { field: "model" });
11980
12569
  if (audioKindOf(model) === void 0) throw localInputError(`${model.id} does not declare what kind of audio it makes, so it cannot be used for generation.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
@@ -11998,10 +12587,18 @@ async function prepareAudioTask(runtime, call, request, save) {
11998
12587
  const body = audioRequestBody(model, request);
11999
12588
  const references = request.references ?? [];
12000
12589
  if (references.length > 0) body.references = (await uploadReferences(runtime, call, model, references, body)).map((item) => model.audio?.references?.form === "object" ? { audio_url: item.asset.referenceUrl } : item.asset.referenceUrl);
12001
- else if ((model.audio?.references?.min ?? 0) > 0) refuse(`${model.id} needs at least ${model.audio?.references?.min} reference audio file(s).`, "references");
12590
+ else if ((model.audio?.references?.min ?? 0) > 0) refuse$1(`${model.id} needs at least ${model.audio?.references?.min} reference audio file(s).`, "references");
12591
+ if (kind === "music" && has(request.sourceAudio)) body.source_audio_url = await uploadSourceAudio(runtime, call, request.sourceAudio.trim());
12002
12592
  const quote = quoteAudio(model);
12593
+ const mode = kind === "music" ? musicModeOf(request) : "generate";
12003
12594
  const what = {
12004
- music: {
12595
+ music: mode === "voice_cover" ? {
12596
+ en: "a voice cover",
12597
+ zh: "一首音色翻唱"
12598
+ } : mode === "cover" ? {
12599
+ en: "a cover",
12600
+ zh: "一首翻唱"
12601
+ } : {
12005
12602
  en: "a song",
12006
12603
  zh: "一首音乐"
12007
12604
  },
@@ -12074,6 +12671,8 @@ function audioFormOf(model) {
12074
12671
  });
12075
12672
  for (const [key, wire] of [
12076
12673
  ["lyrics", "lyrics"],
12674
+ ["style", "style"],
12675
+ ["title", "title"],
12077
12676
  ["genre", "genre"],
12078
12677
  ["mood", "mood"],
12079
12678
  ["gender", "gender"],
@@ -12088,6 +12687,22 @@ function audioFormOf(model) {
12088
12687
  ...choices === void 0 ? {} : { choices }
12089
12688
  });
12090
12689
  }
12690
+ if (kind === "music") {
12691
+ for (const [key, wire] of [
12692
+ ["instrumental", "instrumental"],
12693
+ ["voiceId", "voice_id"],
12694
+ ["sourceAudio", "source_audio_url"],
12695
+ ["audioWeight", "audio_weight"]
12696
+ ]) if (fields.includes(wire)) out.push({
12697
+ key,
12698
+ wire,
12699
+ required: false
12700
+ });
12701
+ } else if (fields.includes("instrumental")) out.push({
12702
+ key: "instrumental",
12703
+ wire: "instrumental",
12704
+ required: false
12705
+ });
12091
12706
  if (kind === "speech") {
12092
12707
  if (fields.includes("references") && audio?.references !== void 0) out.push({
12093
12708
  key: "references",
@@ -12128,7 +12743,7 @@ function audioFormOf(model) {
12128
12743
  }
12129
12744
  //#endregion
12130
12745
  //#region src/tasks/progress.ts
12131
- const record$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
12746
+ const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
12132
12747
  const nonNegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
12133
12748
  const position = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
12134
12749
  const instant = (value) => {
@@ -12171,7 +12786,7 @@ function progressOf$1(value) {
12171
12786
  return number > 1 ? number / 100 : number;
12172
12787
  }
12173
12788
  function timingOf(value, receivedAt) {
12174
- const raw = record$3(value);
12789
+ const raw = record$4(value);
12175
12790
  if (raw === void 0) return void 0;
12176
12791
  const serverTime = instant(raw.server_time);
12177
12792
  const skew = serverTime === void 0 ? 0 : receivedAt - serverTime;
@@ -12200,7 +12815,7 @@ function timingOf(value, receivedAt) {
12200
12815
  };
12201
12816
  }
12202
12817
  function queueOf(value) {
12203
- const raw = record$3(value);
12818
+ const raw = record$4(value);
12204
12819
  if (raw === void 0) return void 0;
12205
12820
  const facts = {
12206
12821
  position: position(raw.position),
@@ -12876,7 +13491,7 @@ const REFERENCE_TYPES = [
12876
13491
  "image/webp"
12877
13492
  ];
12878
13493
  const SIZE = /^\d{2,5}x\d{2,5}$/;
12879
- const record$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
13494
+ const record$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
12880
13495
  const text$2 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
12881
13496
  const noPaths = { readPath: () => Promise.reject(new MediaError("The gateway returned an unexpected image reference.", "GATEWAY_BAD_RESPONSE")) };
12882
13497
  /**
@@ -12887,11 +13502,11 @@ const noPaths = { readPath: () => Promise.reject(new MediaError("The gateway ret
12887
13502
  * @returns the images and the revised prompt, when the model returned one.
12888
13503
  */
12889
13504
  async function decodeImages(runtime, body, signal) {
12890
- const items = record$2(body)?.data;
13505
+ const items = record$3(body)?.data;
12891
13506
  const images = [];
12892
13507
  let revisedPrompt;
12893
13508
  for (const item of Array.isArray(items) ? items : []) {
12894
- const entry = record$2(item);
13509
+ const entry = record$3(item);
12895
13510
  if (entry === void 0) continue;
12896
13511
  revisedPrompt ??= text$2(entry.revised_prompt);
12897
13512
  const b64 = text$2(entry.b64_json);
@@ -14330,7 +14945,7 @@ var MediaHostService = class {
14330
14945
  * the answer arrived.
14331
14946
  * @module dsh-vibedev/tasks/remote
14332
14947
  */
14333
- const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
14948
+ const record$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
14334
14949
  const text$1 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
14335
14950
  const httpUrl = (value) => {
14336
14951
  const url = text$1(value);
@@ -14374,9 +14989,9 @@ const seconds = (value) => {
14374
14989
  /** The blocks billing facts are read from, in order: `billing`, `usage`, `effective`, then the answer itself. */
14375
14990
  function billingBlocks(raw) {
14376
14991
  return [
14377
- record$1(raw.billing),
14378
- record$1(raw.usage),
14379
- record$1(raw.effective),
14992
+ record$2(raw.billing),
14993
+ record$2(raw.usage),
14994
+ record$2(raw.effective),
14380
14995
  raw
14381
14996
  ].filter((block) => block !== void 0);
14382
14997
  }
@@ -14429,7 +15044,7 @@ function billedLengths(raw) {
14429
15044
  };
14430
15045
  }
14431
15046
  function errorOf(raw) {
14432
- const nested = record$1(raw.error);
15047
+ const nested = record$2(raw.error);
14433
15048
  const message = text$1(nested?.message) ?? text$1(raw.error) ?? text$1(raw.failure_reason) ?? text$1(raw.error_message) ?? text$1(raw.fail_reason);
14434
15049
  const code = text$1(nested?.code) ?? text$1(nested?.type) ?? text$1(raw.error_code);
14435
15050
  if (message === void 0 && code === void 0) return void 0;
@@ -14448,7 +15063,7 @@ function errorOf(raw) {
14448
15063
  };
14449
15064
  }
14450
15065
  function receiptFacts(raw) {
14451
- const effective = record$1(raw.effective) ?? {};
15066
+ const effective = record$2(raw.effective) ?? {};
14452
15067
  const source = effective.billing_source;
14453
15068
  return {
14454
15069
  ...Object.fromEntries(Object.entries({
@@ -14469,7 +15084,7 @@ function progressOf(value) {
14469
15084
  return Math.min(100, Math.round(value <= 1 && value !== 0 ? value * 100 : value));
14470
15085
  }
14471
15086
  function receipt(raw) {
14472
- const effective = record$1(raw.effective) ?? {};
15087
+ const effective = record$2(raw.effective) ?? {};
14473
15088
  const estimatedCny = amount(effective.estimated_cny);
14474
15089
  const chargedCny = amount(effective.charged_cny) ?? amount(raw.charged_cny);
14475
15090
  return {
@@ -14485,12 +15100,12 @@ function receipt(raw) {
14485
15100
  * @returns the task, or undefined when the answer names no task id.
14486
15101
  */
14487
15102
  function parseVideoTask(body, receivedAt = Date.now()) {
14488
- const raw = record$1(body);
15103
+ const raw = record$2(body);
14489
15104
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
14490
15105
  if (raw === void 0 || id === void 0) return void 0;
14491
15106
  const status = text$1(raw.status) ?? "queued";
14492
- const video = record$1(raw.video) ?? {};
14493
- const asset = record$1(raw.asset) ?? record$1(video.asset) ?? {};
15107
+ const video = record$2(raw.video) ?? {};
15108
+ const asset = record$2(raw.asset) ?? record$2(video.asset) ?? {};
14494
15109
  const url = httpUrl(video.url) ?? httpUrl(asset.content_url) ?? httpUrl(raw.url) ?? httpUrl(asset.reference_url);
14495
15110
  const durationMs = typeof asset.duration_ms === "number" && asset.duration_ms > 0 ? asset.duration_ms : void 0;
14496
15111
  const seconds = typeof raw.seconds === "number" ? raw.seconds : typeof raw.seconds === "string" ? Number(raw.seconds) : void 0;
@@ -14526,14 +15141,14 @@ function parseVideoTask(body, receivedAt = Date.now()) {
14526
15141
  * @returns the task, or undefined when the answer names no task id.
14527
15142
  */
14528
15143
  function parseAudioTask(body, receivedAt = Date.now()) {
14529
- const raw = record$1(body);
15144
+ const raw = record$2(body);
14530
15145
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
14531
15146
  if (raw === void 0 || id === void 0) return void 0;
14532
15147
  const status = text$1(raw.status) ?? "queued";
14533
15148
  const state = stateOf(status);
14534
15149
  const outputs = [];
14535
15150
  if (Array.isArray(raw.outputs)) for (const [index, item] of raw.outputs.entries()) {
14536
- const output = record$1(item);
15151
+ const output = record$2(item);
14537
15152
  if (output === void 0) continue;
14538
15153
  const url = httpUrl(output.content_url) ?? httpUrl(output.url);
14539
15154
  const contentType = text$1(output.content_type);
@@ -15705,7 +16320,7 @@ function mediaAccountTool(runtime, chain, login) {
15705
16320
  function audioGenerateTool(runtime) {
15706
16321
  return defineTool({
15707
16322
  name: "audio_generate",
15708
- description: "Generate music (a song with vocals or an instrumental), a podcast episode (a spoken conversation about a topic or a web page) or speech (text read aloud, optionally in the voice of reference audio) with a VibeDev audio model. It runs as a background job: this call returns once the gateway accepts the task, you are notified when it finishes, and the files are saved in the workspace (media/audio/). Each model takes only the fields it declares; media_models lists them with prices (music and podcasts per request, speech per second of original audio). Final billing follows the gateway receipt.",
16323
+ description: "Generate music (a song with vocals or an instrumental), a podcast episode (a spoken conversation about a topic or a web page) or speech (text read aloud, optionally in the voice of reference audio) with a VibeDev audio model. It runs as a background job: this call returns once the gateway accepts the task, you are notified when it finishes, and the files are saved in the workspace (media/audio/). Each model takes only the fields it declares; media_models lists them with prices (music and podcasts per request, speech per second of original audio). Final billing follows the gateway receipt. Music covers, on a model that declares the fields: voice_id (a vp_… voice profile from voice_profile_list, for 音色翻唱) and/or source_audio (a song to cover, 上传翻唱). The mode is chosen automatically and sent as mode when the model declares it: voice_id given → voice_cover; only source_audio → cover; neither → generate. voice_id together with source_audio means covering that audio in the chosen voice (voice_cover, both sent). Without a named model a voice cover uses the first model that supports voice covers (media_models), while covers and plain songs use the music model. audio_weight (0–1) applies only to a cover or voice cover.",
15709
16324
  parameters: {
15710
16325
  type: {
15711
16326
  type: "string",
@@ -15733,6 +16348,30 @@ function audioGenerateTool(runtime) {
15733
16348
  type: "string",
15734
16349
  description: "Music only: the singer's voice, such as male or female."
15735
16350
  },
16351
+ style: {
16352
+ type: "string",
16353
+ description: "Music only, when the model declares it: the style, such as \"lo-fi hip hop, warm piano\"."
16354
+ },
16355
+ title: {
16356
+ type: "string",
16357
+ description: "Music only, when the model declares it: the song title."
16358
+ },
16359
+ instrumental: {
16360
+ type: "boolean",
16361
+ description: "Music only, when the model declares it: true for no vocals."
16362
+ },
16363
+ voice_id: {
16364
+ type: "string",
16365
+ description: "Music only (音色翻唱): a voice profile id of the form vp_… from voice_profile_list whose status is ready. No other kind of voice id is accepted. Sends mode voice_cover; with source_audio as well, that audio is covered in this voice."
16366
+ },
16367
+ source_audio: {
16368
+ type: "string",
16369
+ description: "Music only (上传翻唱): the song to cover — a workspace file path, chat:1 for the most recent audio the user attached (chat:video:1 for an attached video), or an https link; audio (mp3, wav, m4a, aac, flac, ogg) or video (mp4, mov, webm), at most 10 MB (trim or compress a larger file first). It is uploaded to the VibeDev media library first. Sends mode cover (voice_cover with voice_id)."
16370
+ },
16371
+ audio_weight: {
16372
+ type: "number",
16373
+ description: "Music covers only (needs voice_id or source_audio): how closely the song follows the reference audio, from 0 to 1 inclusive."
16374
+ },
15736
16375
  source_url: {
15737
16376
  type: "string",
15738
16377
  description: "Podcast only: an http(s) page for the hosts to discuss."
@@ -15819,6 +16458,12 @@ function audioGenerateTool(runtime) {
15819
16458
  ...args.genre === void 0 ? {} : { genre: args.genre },
15820
16459
  ...args.mood === void 0 ? {} : { mood: args.mood },
15821
16460
  ...args.gender === void 0 ? {} : { gender: args.gender },
16461
+ ...args.style === void 0 ? {} : { style: args.style },
16462
+ ...args.title === void 0 ? {} : { title: args.title },
16463
+ ...args.instrumental === void 0 ? {} : { instrumental: args.instrumental },
16464
+ ...args.voice_id === void 0 ? {} : { voiceId: args.voice_id },
16465
+ ...args.source_audio === void 0 ? {} : { sourceAudio: args.source_audio },
16466
+ ...args.audio_weight === void 0 ? {} : { audioWeight: args.audio_weight },
15822
16467
  ...args.source_url === void 0 ? {} : { sourceUrl: args.source_url },
15823
16468
  ...args.references === void 0 ? {} : { references: args.references },
15824
16469
  ...args.format === void 0 ? {} : { format: args.format },
@@ -15898,6 +16543,7 @@ function describeAudioModel(model) {
15898
16543
  if (model.audioKind === void 0) return "does not declare what kind of audio it makes; it cannot be used for generation";
15899
16544
  const fields = requestFieldsOf(model).filter((name) => name !== "model");
15900
16545
  const parts = [`fields: ${fields.join(", ") || "none declared"}`];
16546
+ if (audio?.supportsVoiceCover === true) parts.push("supports voice covers (voice_id)");
15901
16547
  const prompt = promptFieldOf(model);
15902
16548
  if (prompt !== void 0 && prompt !== "prompt") parts.push(`the text goes in ${prompt}`);
15903
16549
  const references = audio?.references;
@@ -16136,7 +16782,7 @@ const ACCEPTED = [
16136
16782
  "video/mp4",
16137
16783
  "video/webm"
16138
16784
  ];
16139
- const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
16785
+ const record$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
16140
16786
  const text = (value) => typeof value === "string" ? value : void 0;
16141
16787
  /**
16142
16788
  * The length of a PCM WAV file from its header.
@@ -16261,19 +16907,19 @@ function audioTranscribeTool(runtime) {
16261
16907
  busyRetries: BUSY_RETRIES,
16262
16908
  maxBusyWaitMs: 3e4
16263
16909
  });
16264
- let answer = record(await response.json().catch(() => void 0));
16910
+ let answer = record$1(await response.json().catch(() => void 0));
16265
16911
  const started = runtime.now();
16266
16912
  while (text(answer?.text) === void 0) {
16267
16913
  const id = text(answer?.id) ?? text(answer?.task_id);
16268
16914
  const status = text(answer?.status)?.toLowerCase();
16269
16915
  if (status === "failed" || status === "error" || status === "cancelled") {
16270
- const error = record(answer?.error);
16916
+ const error = record$1(answer?.error);
16271
16917
  throw new MediaError(`The transcription failed${error === void 0 ? "" : ` (${text(error.code) ?? ""}: ${text(error.message) ?? ""})`}; failed transcriptions are not charged.`, "TRANSCRIPTION_FAILED");
16272
16918
  }
16273
16919
  if (id === void 0) throw new MediaError("The VibeDev gateway returned neither a transcript nor a task.", "GATEWAY_BAD_RESPONSE");
16274
16920
  if (runtime.now() - started > POLL_LIMIT_MS) throw new MediaError(`The transcription task ${id} did not finish within 15 minutes.`, "TRANSCRIPTION_TIMEOUT");
16275
16921
  await sleep(POLL_MS, exec.signal);
16276
- answer = record(await runtime.http.json(`/v1/audio/transcriptions/${encodeURIComponent(id)}`, {
16922
+ answer = record$1(await runtime.http.json(`/v1/audio/transcriptions/${encodeURIComponent(id)}`, {
16277
16923
  timeoutMs: 3e4,
16278
16924
  signal: exec.signal
16279
16925
  }));
@@ -16295,6 +16941,388 @@ function audioTranscribeTool(runtime) {
16295
16941
  });
16296
16942
  }
16297
16943
  //#endregion
16944
+ //#region src/gateway/paid-path.ts
16945
+ /**
16946
+ * Which accepted gateway requests may have spent money, so the balance is read again after them.
16947
+ * @module dsh-vibedev/gateway/paid-path
16948
+ */
16949
+ /** Generations and transcriptions (uploads and reads are free). */
16950
+ const PAID_PATH = /^\/v1\/(?:images|videos|audio)(?:\/|$)/;
16951
+ /** Free paths under a paid prefix: voice profiles are created, listed and deleted without a charge. */
16952
+ const FREE_PATH = /^\/v1\/audio\/voice-profiles(?:\/|$)/;
16953
+ /**
16954
+ * Whether an accepted request may have been charged.
16955
+ * @param method - the HTTP method.
16956
+ * @param path - the request path, without the query.
16957
+ * @returns true for a POST to a generation or transcription endpoint.
16958
+ */
16959
+ function isPaidRequest(method, path) {
16960
+ return method === "POST" && PAID_PATH.test(path) && !FREE_PATH.test(path);
16961
+ }
16962
+ //#endregion
16963
+ //#region src/account/voice-profile-routes.ts
16964
+ /**
16965
+ * The account center's 「我的音色」 routes (answers are never cached; credentials and provider ids never leave):
16966
+ *
16967
+ * - `GET /api/dsh-vibedev/voice-profiles` — `{ code: 0, data: { items, limits } }`, or `{ unsupported: true }` when
16968
+ * the gateway has no voice profiles;
16969
+ * - `POST /api/dsh-vibedev/voice-profiles` — `{ title, filename, data (base64), expected_user_id }`: checked, uploaded
16970
+ * and created; answers the profile, usually still `processing` (the page then reads the list until it settles);
16971
+ * - `POST /api/dsh-vibedev/voice-profiles/delete` — `{ id, expected_user_id }`: closes a `vp_…` profile for good.
16972
+ *
16973
+ * Every call is held to the account the page shows (`X-VibeDev-Expected-User` or `expected_user_id`): a different
16974
+ * signed-in account answers 409 `ACCOUNT_CHANGED` and nothing is sent.
16975
+ * @module dsh-vibedev/account/voice-profile-routes
16976
+ */
16977
+ const VOICE_PROFILE_ROUTE = "/api/dsh-vibedev/voice-profiles";
16978
+ const VOICE_PROFILE_DELETE_ROUTE = "/api/dsh-vibedev/voice-profiles/delete";
16979
+ /** The limits the page checks before it uploads. */
16980
+ const VOICE_PAGE_LIMITS = {
16981
+ maxBytes: VOICE_SAMPLE_LIMITS.maxBytes,
16982
+ minSeconds: VOICE_SAMPLE_LIMITS.minSeconds,
16983
+ maxSeconds: VOICE_SAMPLE_LIMITS.maxSeconds,
16984
+ recommendedMinSeconds: VOICE_SAMPLE_LIMITS.recommendedMinSeconds,
16985
+ extensions: VOICE_SAMPLE_LIMITS.extensions
16986
+ };
16987
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
16988
+ const answer = (status, body) => new Response(JSON.stringify(body), {
16989
+ status,
16990
+ headers: {
16991
+ "content-type": "application/json; charset=utf-8",
16992
+ "cache-control": "private, no-store"
16993
+ }
16994
+ });
16995
+ const refuse = (status, code, category, extra = {}) => answer(status, { error: {
16996
+ code,
16997
+ category,
16998
+ ...extra
16999
+ } });
17000
+ const sameAccount = (a, b) => a.signedIn && b.signedIn && a.userId !== void 0 && a.userId === b.userId;
17001
+ /** A failure as the page shows it: code, category, the rule a local check broke, and a message safe to display. */
17002
+ function failure(error) {
17003
+ if (error instanceof MediaError) {
17004
+ const category = error.details.category ?? "internal_error";
17005
+ const status = error.details.status ?? (category === "invalid_input" ? 400 : category === "authentication" ? 401 : 502);
17006
+ return refuse(status, error.code, category, {
17007
+ message: error.message,
17008
+ ...error.details.rule === void 0 ? {} : { rule: error.details.rule },
17009
+ ...error.details.requestId === void 0 ? {} : { request_id: error.details.requestId }
17010
+ });
17011
+ }
17012
+ return refuse(502, "VOICE_PROFILE_UNAVAILABLE", "service_unavailable");
17013
+ }
17014
+ /**
17015
+ * The routes.
17016
+ * @param voices - the voice-profile service.
17017
+ * @param account - the signed-in account, for the account guard.
17018
+ * @returns routes for the client connection.
17019
+ */
17020
+ function voiceProfileRoutes(voices, account) {
17021
+ /** The signed-in account the request expects, or the refusal to answer with. */
17022
+ const guard = async (expected) => {
17023
+ const before = await account.identity();
17024
+ if (!before.signedIn || before.userId === void 0) return refuse(401, "AUTHENTICATION_REQUIRED", "authentication");
17025
+ if (typeof expected !== "string" || expected !== before.userId) return refuse(409, "ACCOUNT_CHANGED", "access_restricted");
17026
+ return {
17027
+ before,
17028
+ isCurrentAccount: async () => {
17029
+ try {
17030
+ return sameAccount(before, await account.identity());
17031
+ } catch {
17032
+ return false;
17033
+ }
17034
+ }
17035
+ };
17036
+ };
17037
+ const json = async (request) => {
17038
+ try {
17039
+ return record(JSON.parse(await request.text()));
17040
+ } catch {
17041
+ return;
17042
+ }
17043
+ };
17044
+ return [{
17045
+ path: VOICE_PROFILE_ROUTE,
17046
+ methods: ["GET", "POST"],
17047
+ requestBody: "buffered",
17048
+ fetch: async (request) => {
17049
+ try {
17050
+ if (request.method === "GET") {
17051
+ const checked = await guard(request.headers.get("X-VibeDev-Expected-User"));
17052
+ if (checked instanceof Response) return checked;
17053
+ const items = await voices.list({
17054
+ signal: request.signal,
17055
+ isCurrentAccount: checked.isCurrentAccount
17056
+ });
17057
+ if (!await checked.isCurrentAccount()) return refuse(409, "ACCOUNT_CHANGED", "access_restricted");
17058
+ return answer(200, {
17059
+ code: 0,
17060
+ data: {
17061
+ items,
17062
+ limits: VOICE_PAGE_LIMITS
17063
+ }
17064
+ });
17065
+ }
17066
+ const body = await json(request);
17067
+ if (body === void 0) return refuse(400, "INVALID_INPUT", "invalid_input");
17068
+ const checked = await guard(typeof body.expected_user_id === "string" ? body.expected_user_id : void 0);
17069
+ if (checked instanceof Response) return checked;
17070
+ const { title, filename, data } = body;
17071
+ if (typeof title !== "string" || typeof filename !== "string" || filename.length > 255 || typeof data !== "string" || data === "") return refuse(400, "INVALID_INPUT", "invalid_input");
17072
+ if (data.length > Math.ceil(VOICE_SAMPLE_LIMITS.maxBytes / 3) * 4 + 8) return refuse(413, "VOICE_SAMPLE_TOO_LARGE", "invalid_input", { rule: "too_large" });
17073
+ const bytes = new Uint8Array(Buffer$1.from(data, "base64"));
17074
+ const name = filename.replace(/[\\/]/g, "_").trim() || "voice";
17075
+ const profile = await voices.create({
17076
+ source: name,
17077
+ name,
17078
+ mime: sniffMime(bytes, name),
17079
+ data: bytes
17080
+ }, title, {
17081
+ signal: request.signal,
17082
+ isCurrentAccount: checked.isCurrentAccount
17083
+ });
17084
+ return answer(200, {
17085
+ code: 0,
17086
+ data: profile
17087
+ });
17088
+ } catch (error) {
17089
+ if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405) && request.method === "GET") return answer(200, { unsupported: true });
17090
+ return failure(error);
17091
+ }
17092
+ }
17093
+ }, {
17094
+ path: VOICE_PROFILE_DELETE_ROUTE,
17095
+ methods: ["POST"],
17096
+ requestBody: "buffered",
17097
+ fetch: async (request) => {
17098
+ try {
17099
+ const body = await json(request);
17100
+ if (body === void 0) return refuse(400, "INVALID_INPUT", "invalid_input");
17101
+ const id = checkVoiceProfileId(body.id);
17102
+ const checked = await guard(typeof body.expected_user_id === "string" ? body.expected_user_id : void 0);
17103
+ if (checked instanceof Response) return checked;
17104
+ await voices.remove(id, {
17105
+ signal: request.signal,
17106
+ isCurrentAccount: checked.isCurrentAccount
17107
+ });
17108
+ return answer(200, {
17109
+ code: 0,
17110
+ data: { id }
17111
+ });
17112
+ } catch (error) {
17113
+ return failure(error);
17114
+ }
17115
+ }
17116
+ }];
17117
+ }
17118
+ //#endregion
17119
+ //#region src/tools/voice-profiles.ts
17120
+ /**
17121
+ * `voice_profile_create`, `voice_profile_list`, `voice_profile_delete`: the user's voice profiles (音色) for Suno
17122
+ * voice covers. Creating one is free and makes no song; only `vp_…` ids are shown or accepted.
17123
+ * @module dsh-vibedev/tools/voice-profiles
17124
+ */
17125
+ const PROFILE_SCHEMA = {
17126
+ type: "object",
17127
+ additionalProperties: false,
17128
+ properties: {
17129
+ id: {
17130
+ type: "string",
17131
+ required: true
17132
+ },
17133
+ status: {
17134
+ type: "string",
17135
+ required: true
17136
+ },
17137
+ title: { type: "string" },
17138
+ failureReason: { type: "string" },
17139
+ failureKind: { type: "string" },
17140
+ durationSeconds: { type: "number" },
17141
+ createdAt: { type: "string" }
17142
+ }
17143
+ };
17144
+ /** The model-facing projection of one profile. */
17145
+ function shown(profile) {
17146
+ return {
17147
+ id: profile.id,
17148
+ status: profile.status,
17149
+ ...profile.title === void 0 ? {} : { title: profile.title },
17150
+ ...profile.failureReason === void 0 ? {} : { failureReason: profile.failureReason },
17151
+ ...profile.failureKind === void 0 ? {} : { failureKind: profile.failureKind },
17152
+ ...profile.durationSeconds === void 0 ? {} : { durationSeconds: profile.durationSeconds },
17153
+ ...profile.createdAt === void 0 ? {} : { createdAt: profile.createdAt }
17154
+ };
17155
+ }
17156
+ /** A failure in plain words when the refusal is recognised (with the provider's reason after it), else the reason as it came. */
17157
+ function failureWords(profile) {
17158
+ const known = VOICE_REJECTIONS.find((rule) => rule.kind === profile.failureKind);
17159
+ if (known === void 0) return profile.failureReason;
17160
+ return `${known.en} ${known.zh}${profile.failureReason === void 0 ? "" : ` (${profile.failureReason})`}`;
17161
+ }
17162
+ /** One line per profile, for messages. */
17163
+ function describeVoiceProfile(profile) {
17164
+ const state = profile.status === "ready" ? "ready — usable as audio_generate voice_id" : profile.status === "failed" ? `failed: ${failureWords(profile) ?? "the gateway gave no reason"}` : "still being created";
17165
+ const facts = [profile.durationSeconds === void 0 ? void 0 : `${profile.durationSeconds.toFixed(1)} s`, profile.createdAt].filter(Boolean);
17166
+ return `${profile.id}${profile.title === void 0 ? "" : ` "${profile.title}"`} — ${state}${facts.length === 0 ? "" : ` (${facts.join(", ")})`}`;
17167
+ }
17168
+ const LIMITS = `${VOICE_SAMPLE_LIMITS.minSeconds}–${VOICE_SAMPLE_LIMITS.maxSeconds} s (10–60 s works best), at most 10 MiB, ${VOICE_SAMPLE_LIMITS.extensions.join("/")}, ideally clean solo vocals without accompaniment`;
17169
+ /**
17170
+ * `voice_profile_create`.
17171
+ * @param runtime - loads the sample (workspace paths, links, chat attachments).
17172
+ * @param profiles - the voice-profile service.
17173
+ * @returns the tool.
17174
+ */
17175
+ function voiceProfileCreateTool(runtime, profiles) {
17176
+ return defineTool({
17177
+ name: "voice_profile_create",
17178
+ description: "Create a VibeDev voice profile (音色) from a recording of the user's own singing voice, for Suno voice covers (audio_generate voice_id). Free: it makes no song and charges nothing. The sample must be " + LIMITS + "; it is checked, uploaded to the VibeDev media library and submitted, and the call waits until the profile is ready or failed. The result is a vp_… id — the only form of voice id that exists for the user; never ask for or pass any other voice id. Only create one when the user asks, from audio they have the right to use. Do not promise that a profile is kept forever.",
17179
+ parameters: {
17180
+ source: {
17181
+ type: "string",
17182
+ required: true,
17183
+ description: `The voice sample: ${SOURCE_HELP}.`
17184
+ },
17185
+ title: {
17186
+ type: "string",
17187
+ required: true,
17188
+ description: "A name for the profile, at most 80 characters."
17189
+ }
17190
+ },
17191
+ output: {
17192
+ schema: {
17193
+ type: "object",
17194
+ additionalProperties: false,
17195
+ properties: {
17196
+ profile: PROFILE_SCHEMA,
17197
+ message: {
17198
+ type: "string",
17199
+ required: true
17200
+ }
17201
+ }
17202
+ },
17203
+ render: (_args, value) => [{
17204
+ type: "text",
17205
+ text: value.message
17206
+ }]
17207
+ },
17208
+ timeoutMs: 36e4,
17209
+ async execute(args, exec) {
17210
+ const title = checkVoiceTitle(args.title);
17211
+ const media = await runtime.load(exec, args.source, "audio", VOICE_SAMPLE_LIMITS.maxBytes);
17212
+ const created = await profiles.create(media, title, { signal: exec.signal });
17213
+ const final = created.status === "processing" ? await profiles.waitUntilSettled(created.id, { signal: exec.signal }) : created;
17214
+ const message = final.status === "ready" ? `Voice profile created and ready: ${describeVoiceProfile(final)}. Pass voice_id "${final.id}" to audio_generate (music) for a voice cover. Creating it charged nothing.` : final.status === "failed" ? `The voice profile could not be created: ${describeVoiceProfile(final)}. Nothing was charged. A clean solo vocal of 10–60 s usually works.` : `Voice profile ${final.id} is still being created. voice_profile_list shows when it is ready; do not use it before then. Nothing was charged.`;
17215
+ return {
17216
+ profile: shown(final),
17217
+ message
17218
+ };
17219
+ }
17220
+ });
17221
+ }
17222
+ /**
17223
+ * `voice_profile_list`.
17224
+ * @param profiles - the voice-profile service.
17225
+ * @returns the tool.
17226
+ */
17227
+ function voiceProfileListTool(profiles) {
17228
+ return defineTool({
17229
+ name: "voice_profile_list",
17230
+ description: "List the user's VibeDev voice profiles (音色): vp_… id, name, status (ready, processing or failed with the reason), length and creation time. Only a ready profile can be passed to audio_generate as voice_id.",
17231
+ parameters: {},
17232
+ output: {
17233
+ schema: {
17234
+ type: "object",
17235
+ additionalProperties: false,
17236
+ properties: {
17237
+ profiles: {
17238
+ type: "array",
17239
+ items: PROFILE_SCHEMA
17240
+ },
17241
+ message: {
17242
+ type: "string",
17243
+ required: true
17244
+ }
17245
+ }
17246
+ },
17247
+ render: (_args, value) => [{
17248
+ type: "text",
17249
+ text: value.message
17250
+ }]
17251
+ },
17252
+ isConcurrencySafe: () => true,
17253
+ async execute(_args, exec) {
17254
+ const list = await profiles.list({ signal: exec.signal });
17255
+ return {
17256
+ profiles: list.map(shown),
17257
+ message: list.length === 0 ? "This VibeDev account has no voice profiles. voice_profile_create makes one from a 10–60 s recording of the user's voice (free)." : `Voice profiles:\n${list.map((profile) => `- ${describeVoiceProfile(profile)}`).join("\n")}`
17258
+ };
17259
+ }
17260
+ });
17261
+ }
17262
+ /**
17263
+ * `voice_profile_delete`.
17264
+ * @param runtime - for the user's confirmation, when the host can ask.
17265
+ * @param profiles - the voice-profile service.
17266
+ * @returns the tool.
17267
+ */
17268
+ function voiceProfileDeleteTool(runtime, profiles) {
17269
+ return defineTool({
17270
+ name: "voice_profile_delete",
17271
+ description: "Permanently delete one of the user's VibeDev voice profiles by its vp_… id. This cannot be undone: the profile cannot be used for new voice covers again; songs already made with it are not affected. Only delete when the user explicitly asks for that profile.",
17272
+ parameters: { id: {
17273
+ type: "string",
17274
+ required: true,
17275
+ description: "The vp_… id from voice_profile_list."
17276
+ } },
17277
+ output: {
17278
+ schema: {
17279
+ type: "object",
17280
+ additionalProperties: false,
17281
+ properties: {
17282
+ id: {
17283
+ type: "string",
17284
+ required: true
17285
+ },
17286
+ message: {
17287
+ type: "string",
17288
+ required: true
17289
+ }
17290
+ }
17291
+ },
17292
+ render: (_args, value) => [{
17293
+ type: "text",
17294
+ text: value.message
17295
+ }]
17296
+ },
17297
+ async execute(args, exec) {
17298
+ const id = checkVoiceProfileId(args.id);
17299
+ const approval = runtime.options.approval?.();
17300
+ if (approval !== void 0 && exec.agent !== void 0) {
17301
+ const en = `Permanently delete voice profile ${id}? It cannot be restored; songs already made with it are not affected.`;
17302
+ const zh = `永久删除音色 ${id}?删除后不可恢复;已生成的歌曲不受影响。`;
17303
+ const outcome = await approval.request({
17304
+ agent: exec.agent,
17305
+ toolName: "voice_profile_delete",
17306
+ callId: exec.callId,
17307
+ signal: exec.signal,
17308
+ reason: en,
17309
+ displayReason: {
17310
+ en,
17311
+ zh,
17312
+ "zh-CN": zh
17313
+ }
17314
+ });
17315
+ if (outcome !== "allowed-once") throw new MediaError(outcome === "cancelled" ? "The deletion was cancelled; the voice profile is kept." : "The user did not confirm the deletion; the voice profile is kept.", "VOICE_PROFILE_DELETE_DECLINED");
17316
+ }
17317
+ await profiles.remove(id, { signal: exec.signal });
17318
+ return {
17319
+ id,
17320
+ message: `Voice profile ${id} was deleted for good. Songs already made with it are not affected.`
17321
+ };
17322
+ }
17323
+ });
17324
+ }
17325
+ //#endregion
16298
17326
  //#region src/index.ts
16299
17327
  /**
16300
17328
  * dsh-vibedev (formerly dsh-media): the VibeDev account and the VibeDev
@@ -16318,8 +17346,6 @@ function audioTranscribeTool(runtime) {
16318
17346
  * ```
16319
17347
  * @module dsh-vibedev
16320
17348
  */
16321
- /** Requests that are charged: generations and transcriptions (uploads and reads are free). */
16322
- const PAID_PATH = /^\/v1\/(?:images|videos|audio)(?:\/|$)/;
16323
17349
  /**
16324
17350
  * How long a model listing waits for promotion labels before it answers without
16325
17351
  * them. A picker must never wait on decoration.
@@ -16422,7 +17448,7 @@ const Config = Schema.object({
16422
17448
  stateDir: "Plugin data folder (empty for the default)"
16423
17449
  }
16424
17450
  });
16425
- const GUIDANCE = "VibeDev media tools: image_generate, video_generate, audio_generate (music, a podcast or speech) and audio_transcribe create and transcribe media with the user's VibeDev account; media_models lists models and prices. Use them on your own judgment whenever generated media serves the request (illustrations, product shots, storyboard frames, short clips, background music, a podcast episode, a voice-over), not only when a tool is named. They spend the user's balance, so make what the request needs rather than speculative variations. Results are saved in the workspace under media/. An image result is the saved file, not the picture: read it with read_image when you need to look, and read each file once — every read is another image in the context. Pass files the user attached in this chat as chat:1 (the most recent), chat:2, and so on. Video and audio run as background jobs: carry on and let the job notification report the result.";
17451
+ const GUIDANCE = "VibeDev media tools: image_generate, video_generate, audio_generate (music, a podcast or speech) and audio_transcribe create and transcribe media with the user's VibeDev account; media_models lists models and prices. Use them on your own judgment whenever generated media serves the request (illustrations, product shots, storyboard frames, short clips, background music, a podcast episode, a voice-over), not only when a tool is named. They spend the user's balance, so make what the request needs rather than speculative variations. Results are saved in the workspace under media/. An image result is the saved file, not the picture: read it with read_image when you need to look, and read each file once — every read is another image in the context. Pass files the user attached in this chat as chat:1 (the most recent), chat:2, and so on. Video and audio run as background jobs: carry on and let the job notification report the result. Voice covers (音色翻唱) use the user's own voice profile: voice_profile_create makes one for free from a 6–60 s vocal recording (voice_profile_list, voice_profile_delete), and audio_generate takes its vp_… id as voice_id; source_audio covers an uploaded song.";
16426
17452
  function apply(ctx, config) {
16427
17453
  const origin = normalizeGatewayOrigin(config.gatewayOrigin);
16428
17454
  const stateDir = stateDirectory(config.stateDir);
@@ -16464,7 +17490,7 @@ function apply(ctx, config) {
16464
17490
  resolveCredential: () => chain.resolve(),
16465
17491
  rejectToken: (credential) => chain.reject(credential),
16466
17492
  onAccepted: ({ method, path }) => {
16467
- if (method === "POST" && PAID_PATH.test(path)) spent();
17493
+ if (isPaidRequest(method, path)) spent();
16468
17494
  }
16469
17495
  });
16470
17496
  const promotions = new PromotionService({ http });
@@ -16508,6 +17534,10 @@ function apply(ctx, config) {
16508
17534
  jobs: () => ctx.get("jobs"),
16509
17535
  log: warn
16510
17536
  });
17537
+ const voices = new VoiceProfiles({
17538
+ http,
17539
+ upload: (media, purpose, signal) => runtime.library.upload(media, purpose, signal)
17540
+ });
16511
17541
  for (const tool of [
16512
17542
  mediaModelsTool(runtime),
16513
17543
  imageGenerateTool(runtime),
@@ -16515,7 +17545,10 @@ function apply(ctx, config) {
16515
17545
  audioGenerateTool(runtime),
16516
17546
  audioTranscribeTool(runtime),
16517
17547
  mediaTasksTool(runtime),
16518
- mediaAccountTool(runtime, chain, login)
17548
+ mediaAccountTool(runtime, chain, login),
17549
+ voiceProfileCreateTool(runtime, voices),
17550
+ voiceProfileListTool(voices),
17551
+ voiceProfileDeleteTool(runtime, voices)
16519
17552
  ]) ctx.tools.register(tool);
16520
17553
  const accountContext = async () => {
16521
17554
  const identity = await account?.identity();
@@ -16636,6 +17669,7 @@ function apply(ctx, config) {
16636
17669
  for (const accountRoute of [
16637
17670
  ...accountRoutes(accountService),
16638
17671
  ...accountCenterRoutes(http, accountService),
17672
+ ...voiceProfileRoutes(voices, accountService),
16639
17673
  ...announcementRoutes({
16640
17674
  http,
16641
17675
  account: accountService