@vibedev-si/dsh-vibedev 0.11.1 → 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
@@ -2,6 +2,7 @@ import { p as lazyApi, r as createModels$1 } from "./models-CAcLevEN.js";
2
2
  import { createWriteStream, readFileSync } from "node:fs";
3
3
  import Schema from "@deepseek-ai/schemastery";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
+ import * as dshLlm from "@deepseek-ai/dsh-llm";
5
6
  import { APP_IDENTITY, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, HarnessError, IMAGE_OFFLOAD_REQUIRED_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload, resolveImageAttachmentAccess } from "@deepseek-ai/dsh-llm";
6
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
8
  import { arch, homedir, platform, release } from "node:os";
@@ -49,8 +50,8 @@ const MIN_READ_SPACING_MS = 5e3;
49
50
  * current when nobody opens anything.
50
51
  */
51
52
  const CATALOG_REFRESH_GAP_MS = 6e4;
52
- const record$15 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
53
- 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;
54
55
  /**
55
56
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
56
57
  * writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
@@ -62,7 +63,7 @@ function amountOf(value) {
62
63
  if (!Number.isFinite(value)) return void 0;
63
64
  raw = String(value);
64
65
  if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
65
- } else raw = text$9(value);
66
+ } else raw = text$10(value);
66
67
  return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
67
68
  }
68
69
  /** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
@@ -304,14 +305,14 @@ var AccountService = class {
304
305
  redirect: "error"
305
306
  });
306
307
  if (!response.ok) return {};
307
- const body = record$15(await response.json().catch(() => void 0));
308
- 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;
309
310
  const balance = amountOf(data?.balance);
310
- const currency = text$9(data?.currency) ?? "CNY";
311
+ const currency = text$10(data?.currency) ?? "CNY";
311
312
  const frozen = amountOf(data?.frozen_balance);
312
- const id = typeof data?.id === "number" ? String(data.id) : text$9(data?.id);
313
- const nickname = text$9(data?.nickname) ?? text$9(data?.username);
314
- 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);
315
316
  const user = id === void 0 && nickname === void 0 && email === void 0 ? void 0 : {
316
317
  ...id === void 0 ? {} : { id },
317
318
  ...email === void 0 ? {} : { email },
@@ -425,8 +426,8 @@ function json$3(status, body) {
425
426
  }
426
427
  });
427
428
  }
428
- function failure$1(error) {
429
- const candidate = record$15(error)?.code;
429
+ function failure$2(error) {
430
+ const candidate = record$17(error)?.code;
430
431
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
431
432
  return json$3(500, { error: {
432
433
  code,
@@ -445,7 +446,7 @@ function accountRoutes(account) {
445
446
  methods: ["POST"],
446
447
  requestBody: "buffered",
447
448
  fetch: async (request) => {
448
- const body = record$15(await request.json().catch(() => void 0));
449
+ const body = record$17(await request.json().catch(() => void 0));
449
450
  return json$3(200, { consumed: typeof body?.id === "string" && account.consumeNavigation(body.id) });
450
451
  }
451
452
  },
@@ -460,7 +461,7 @@ function accountRoutes(account) {
460
461
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
461
462
  return json$3(200, await account.view(query.get("fresh") === "1"));
462
463
  } catch (error) {
463
- return failure$1(error);
464
+ return failure$2(error);
464
465
  }
465
466
  }
466
467
  },
@@ -470,10 +471,10 @@ function accountRoutes(account) {
470
471
  requestBody: "buffered",
471
472
  fetch: async (request) => {
472
473
  try {
473
- const body = record$15(await request.json().catch(() => void 0));
474
+ const body = record$17(await request.json().catch(() => void 0));
474
475
  return json$3(200, await account.signIn(body?.open !== false));
475
476
  } catch (error) {
476
- return failure$1(error);
477
+ return failure$2(error);
477
478
  }
478
479
  }
479
480
  },
@@ -497,7 +498,7 @@ function accountRoutes(account) {
497
498
  message: "The VibeDev account is the app's sign-in; sign out in the app."
498
499
  } });
499
500
  } catch (error) {
500
- return failure$1(error);
501
+ return failure$2(error);
501
502
  }
502
503
  }
503
504
  }
@@ -605,10 +606,10 @@ function normalizeErrorStage(value) {
605
606
  request: "submit"
606
607
  }[word];
607
608
  }
608
- function record$14(value) {
609
+ function record$16(value) {
609
610
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
610
611
  }
611
- function text$8(value) {
612
+ function text$9(value) {
612
613
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
613
614
  }
614
615
  function count$1(value) {
@@ -617,7 +618,7 @@ function count$1(value) {
617
618
  /** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
618
619
  function amount$2(value) {
619
620
  if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
620
- const raw = text$8(value);
621
+ const raw = text$9(value);
621
622
  return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
622
623
  }
623
624
  /**
@@ -631,16 +632,16 @@ function amount$2(value) {
631
632
  * @returns the fields found.
632
633
  */
633
634
  function parseGatewayFailure(body) {
634
- const root = record$14(body);
635
+ const root = record$16(body);
635
636
  if (root === void 0) return {};
636
- const source = record$14(root.error) ?? root;
637
- const metadata = record$14(source.metadata) ?? record$14(root.metadata);
638
- const gatewayCode = text$8(source.gateway_code) ?? text$8(root.gateway_code);
639
- const code = gatewayCode ?? text$8(source.code) ?? text$8(source.type) ?? text$8(root.reason);
640
- const message = text$8(source.message) ?? (typeof root.error === "string" ? text$8(root.error) : void 0);
641
- const field = text$8(source.field) ?? text$8(metadata?.field);
642
- const rule = text$8(source.rule) ?? text$8(metadata?.rule);
643
- 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);
644
645
  const numbers = {
645
646
  active: count$1(source.active),
646
647
  limit: count$1(source.limit)
@@ -650,19 +651,19 @@ function parseGatewayFailure(body) {
650
651
  availableCny: amount$2(source.available_cny),
651
652
  pendingCny: amount$2(source.pending_cny)
652
653
  };
653
- const submissionState = text$8(source.submission_state) ?? text$8(root.submission_state);
654
- const retryAction = text$8(source.retry_action) ?? text$8(root.retry_action);
655
- 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);
656
657
  return {
657
658
  ...gatewayCode === void 0 ? {} : { gatewayCode },
658
659
  ...Object.fromEntries(Object.entries({
659
- category: normalizeErrorCategory(text$8(source.category) ?? text$8(root.category), code),
660
- stage: normalizeErrorStage(text$8(source.stage) ?? text$8(root.stage)),
661
- requestId: text$8(source.request_id) ?? text$8(root.request_id),
662
- taskId: text$8(source.task_id) ?? text$8(root.task_id),
663
- operationId: text$8(source.operation_id) ?? text$8(root.operation_id),
664
- billingState: text$8(source.billing_state) ?? text$8(root.billing_state),
665
- 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),
666
667
  retryAfterSeconds: count$1(source.retry_after_seconds) ?? count$1(root.retry_after_seconds)
667
668
  }).filter(([, value]) => value !== void 0)),
668
669
  ...code === void 0 ? {} : { code },
@@ -729,11 +730,11 @@ function gatewayFailureWithHeaders(body, headers) {
729
730
  const failure = parseGatewayFailure(body);
730
731
  return {
731
732
  ...failure,
732
- code: failure.gatewayCode ?? text$8(headers.get("x-vibedev-error-code")) ?? failure.code,
733
- category: normalizeErrorCategory(failure.category ?? text$8(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$8(headers.get("x-vibedev-error-code")) ?? failure.code),
734
- requestId: failure.requestId ?? text$8(headers.get("x-request-id")),
735
- retryAction: failure.retryAction ?? text$8(headers.get("x-vibedev-retry-action")),
736
- 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"))
737
738
  };
738
739
  }
739
740
  function isUserAuthenticationFailure(failure) {
@@ -742,19 +743,19 @@ function isUserAuthenticationFailure(failure) {
742
743
  function sdkGatewayFailure(message, headers = {}) {
743
744
  const prefix = /\bvibedev:([A-Z][A-Z0-9_]{1,100}):/.exec(message)?.[1];
744
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];
745
- const code = text$8(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
746
- 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");
747
748
  if (code === void 0 && category === void 0) return void 0;
748
749
  return {
749
750
  code,
750
751
  category: normalizeErrorCategory(category, code),
751
- requestId: text$8(headers["x-request-id"]),
752
- 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"])
753
754
  };
754
755
  }
755
756
  //#endregion
756
757
  //#region src/account/center-price-contract.ts
757
- 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;
758
759
  const keys = (value = "") => value.split(" ").filter(Boolean);
759
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;
760
761
  /** Only public DNS HTTPS references become navigable links. No credentials, IPs or local hosts. */
@@ -772,7 +773,7 @@ function publicReferenceUrl(value) {
772
773
  }
773
774
  function project$1(value, shape) {
774
775
  if (value === null) return null;
775
- const source = record$13(value);
776
+ const source = record$15(value);
776
777
  if (!source) return void 0;
777
778
  const out = {};
778
779
  for (const key of keys(shape.fields)) {
@@ -800,7 +801,7 @@ function project$1(value, shape) {
800
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);
801
802
  }
802
803
  for (const [key, child] of Object.entries(shape.maps ?? {})) {
803
- const map = record$13(source[key]);
804
+ const map = record$15(source[key]);
804
805
  if (!map) continue;
805
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" || [
806
807
  "none",
@@ -1628,11 +1629,11 @@ function projectBusinessReceipt(value) {
1628
1629
  //#endregion
1629
1630
  //#region src/account/center-contract.ts
1630
1631
  /** Exact, read-only account-page schemas. No caller-selected URL or object shape. */
1631
- 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;
1632
1633
  const fields = (text) => text.split(" ");
1633
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;
1634
1635
  function project(value, shape) {
1635
- const source = record$12(value);
1636
+ const source = record$14(value);
1636
1637
  if (source === void 0) return void 0;
1637
1638
  if (shape === imageSizes) return Object.fromEntries(Object.entries(source).filter(([key, item]) => {
1638
1639
  const kilo = /^(\d{1,2}(?:\.\d{1,3})?)K$/.exec(key), dimensions = /^(\d{1,5})x(\d{1,5})$/.exec(key);
@@ -1645,7 +1646,7 @@ function project(value, shape) {
1645
1646
  "inbound_endpoint",
1646
1647
  "upstream_endpoint",
1647
1648
  "endpoint"
1648
- ].includes(key) && (typeof item !== "string" || !SAFE_ENDPOINTS.has(item))) continue;
1649
+ ].includes(key) && (typeof item !== "string" || !safeEndpoint(item))) continue;
1649
1650
  if (item !== void 0) result[key] = item;
1650
1651
  }
1651
1652
  for (const [key, child] of Object.entries(shape.objects ?? {})) {
@@ -1655,7 +1656,13 @@ function project(value, shape) {
1655
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);
1656
1657
  return result;
1657
1658
  }
1658
- 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
+ }
1659
1666
  const imageSizes = { fields: [] };
1660
1667
  const group = { fields: fields("id name platform description status subscription_type rate_multiplier peak_rate_enabled peak_start peak_end peak_rate_multiplier") };
1661
1668
  const window = { fields: fields("state remaining_percent resets_at") };
@@ -1887,7 +1894,7 @@ function centerQuery(path, params) {
1887
1894
  /** Legacy summary only: monetary weekly fields become a percentage, never a five-hour window. */
1888
1895
  function projectAccountData(value) {
1889
1896
  const convert = (item) => {
1890
- const output = project(item, subscription), source = record$12(item);
1897
+ const output = project(item, subscription), source = record$14(item);
1891
1898
  if (output === void 0 || source === void 0) return void 0;
1892
1899
  const number = (n) => typeof n === "number" && Number.isFinite(n) ? n : typeof n === "string" && /^\d+(?:\.\d+)?$/.test(n) ? Number(n) : void 0;
1893
1900
  const used = number(source.weekly_used_usd), limit = number(source.weekly_limit_usd);
@@ -1899,7 +1906,7 @@ function projectAccountData(value) {
1899
1906
  return output;
1900
1907
  };
1901
1908
  if (Array.isArray(value)) return value.slice(0, 1e3).map(convert).filter((item) => item !== void 0);
1902
- const source = record$12(value);
1909
+ const source = record$14(value);
1903
1910
  return source === void 0 ? {} : {
1904
1911
  ...project(source, { fields: ["active_count"] }),
1905
1912
  ...Array.isArray(source.subscriptions) ? { subscriptions: source.subscriptions.slice(0, 1e3).map(convert).filter((item) => item !== void 0) } : {}
@@ -1935,14 +1942,14 @@ function projectCenterRoute(path, value) {
1935
1942
  //#endregion
1936
1943
  //#region src/account/center-business.ts
1937
1944
  const object$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1938
- const answer$2 = (status, body) => new Response(JSON.stringify(body), {
1945
+ const answer$3 = (status, body) => new Response(JSON.stringify(body), {
1939
1946
  status,
1940
1947
  headers: {
1941
1948
  "content-type": "application/json; charset=utf-8",
1942
1949
  "cache-control": "private, no-store"
1943
1950
  }
1944
1951
  });
1945
- const failure = (status, code, notSubmitted, extra = {}) => answer$2(status, {
1952
+ const failure$1 = (status, code, notSubmitted, extra = {}) => answer$3(status, {
1946
1953
  ...extra,
1947
1954
  ...notSubmitted ? { not_submitted: true } : {},
1948
1955
  error: {
@@ -1950,7 +1957,7 @@ const failure = (status, code, notSubmitted, extra = {}) => answer$2(status, {
1950
1957
  category: code === "INVALID_INPUT" ? "invalid_input" : code === "ACCOUNT_CHANGED" ? "access_restricted" : "service_unavailable"
1951
1958
  }
1952
1959
  });
1953
- 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;
1954
1961
  /** The buffered wire body must be unambiguous before it is canonicalized and fingerprinted. */
1955
1962
  function uniqueBusinessJson(raw) {
1956
1963
  if (Buffer.byteLength(raw, "utf8") > 1 << 20) throw new Error("body too large");
@@ -1985,29 +1992,29 @@ function accountBusinessActionsRoutes(http, account) {
1985
1992
  let before, dispatched = false;
1986
1993
  const stillCurrent = async () => {
1987
1994
  try {
1988
- return before !== void 0 && sameAccount$1(before, await account.identity());
1995
+ return before !== void 0 && sameAccount$2(before, await account.identity());
1989
1996
  } catch {
1990
1997
  return false;
1991
1998
  }
1992
1999
  };
1993
2000
  try {
1994
- 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);
1995
2002
  let body;
1996
2003
  try {
1997
2004
  body = object$2(uniqueBusinessJson(await request.text()));
1998
2005
  } catch {
1999
- return failure(400, "INVALID_INPUT", true);
2006
+ return failure$1(400, "INVALID_INPUT", true);
2000
2007
  }
2001
2008
  if (body === void 0 || Object.keys(body).some((key) => ![
2002
2009
  "operation_id",
2003
2010
  "expected_user_id",
2004
2011
  "payload"
2005
- ].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);
2006
2013
  const parsed = validateBusinessAction(kind, body.payload);
2007
- if (parsed === void 0) return failure(400, "INVALID_INPUT", true);
2014
+ if (parsed === void 0) return failure$1(400, "INVALID_INPUT", true);
2008
2015
  before = await account.identity();
2009
- if (!before.signedIn || before.userId === void 0) return failure(401, "ACCOUNT_UNAVAILABLE", true);
2010
- 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);
2011
2018
  dispatched = true;
2012
2019
  const raw = await http.json(`/v1/account/${parsed.wire}`, {
2013
2020
  method: parsed.method,
@@ -2020,24 +2027,24 @@ function accountBusinessActionsRoutes(http, account) {
2020
2027
  });
2021
2028
  if (!await stillCurrent()) {
2022
2029
  http.invalidateAccountSnapshots();
2023
- return failure(409, "ACCOUNT_CHANGED", false);
2030
+ return failure$1(409, "ACCOUNT_CHANGED", false);
2024
2031
  }
2025
2032
  const receipt = object$2(projectBusinessReceipt(object$2(raw)?.data));
2026
2033
  const expectedAction = kind === "redeem/apply" ? "redeem" : kind.replace("/", ".");
2027
- 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);
2028
2035
  if (receipt.state === "succeeded") http.invalidateAccountSnapshots();
2029
- return answer$2(200, {
2036
+ return answer$3(200, {
2030
2037
  code: 0,
2031
2038
  data: receipt
2032
2039
  });
2033
2040
  } catch (error) {
2034
2041
  if (before !== void 0 && !await stillCurrent()) {
2035
2042
  http.invalidateAccountSnapshots();
2036
- return failure(409, "ACCOUNT_CHANGED", !dispatched);
2043
+ return failure$1(409, "ACCOUNT_CHANGED", !dispatched);
2037
2044
  }
2038
2045
  if (error instanceof MediaError) {
2039
2046
  const status = error.details.status ?? 502;
2040
- 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 });
2041
2048
  const refused = [
2042
2049
  400,
2043
2050
  401,
@@ -2045,9 +2052,9 @@ function accountBusinessActionsRoutes(http, account) {
2045
2052
  413,
2046
2053
  422
2047
2054
  ].includes(status);
2048
- return failure(status, refused ? error.code : "ACCOUNT_ACTION_UNKNOWN", refused);
2055
+ return failure$1(status, refused ? error.code : "ACCOUNT_ACTION_UNKNOWN", refused);
2049
2056
  }
2050
- return failure(502, "ACCOUNT_ACTION_UNKNOWN", !dispatched);
2057
+ return failure$1(502, "ACCOUNT_ACTION_UNKNOWN", !dispatched);
2051
2058
  }
2052
2059
  }
2053
2060
  }));
@@ -2056,7 +2063,7 @@ function accountBusinessActionsRoutes(http, account) {
2056
2063
  //#region src/account/center.ts
2057
2064
  const CENTER_PREFIX = "/api/dsh-vibedev/account-center";
2058
2065
  const obj = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2059
- function answer$1(status, body) {
2066
+ function answer$2(status, body) {
2060
2067
  return new Response(JSON.stringify(body), {
2061
2068
  status,
2062
2069
  headers: {
@@ -2065,7 +2072,7 @@ function answer$1(status, body) {
2065
2072
  }
2066
2073
  });
2067
2074
  }
2068
- function sameAccount(before, after) {
2075
+ function sameAccount$1(before, after) {
2069
2076
  return before.signedIn && after.signedIn && before.userId === after.userId && (before.userId !== void 0 || before.credential.token === after.credential.token);
2070
2077
  }
2071
2078
  function accountCenterRoutes(http, account) {
@@ -2077,7 +2084,7 @@ function accountCenterRoutes(http, account) {
2077
2084
  let before;
2078
2085
  const changed = () => {
2079
2086
  http.invalidateAccountSnapshots();
2080
- return answer$1(409, { error: {
2087
+ return answer$2(409, { error: {
2081
2088
  code: "ACCOUNT_CHANGED",
2082
2089
  message: "账号已切换,请刷新页面。"
2083
2090
  } });
@@ -2085,14 +2092,14 @@ function accountCenterRoutes(http, account) {
2085
2092
  try {
2086
2093
  const params = new URL(request.url, "http://host").searchParams;
2087
2094
  const parsed = centerQuery(path, params);
2088
- if (parsed === void 0) return answer$1(400, { error: {
2095
+ if (parsed === void 0) return answer$2(400, { error: {
2089
2096
  code: "INVALID_INPUT",
2090
2097
  category: "invalid_input",
2091
2098
  message: "筛选参数不符合要求。"
2092
2099
  } });
2093
2100
  const { query, wire, fresh } = parsed;
2094
2101
  before = await account.identity();
2095
- if (!before.signedIn) return answer$1(401, { error: {
2102
+ if (!before.signedIn) return answer$2(401, { error: {
2096
2103
  code: "AUTHENTICATION_REQUIRED",
2097
2104
  category: "authentication",
2098
2105
  message: "请先登录 VibeDev。"
@@ -2103,30 +2110,30 @@ function accountCenterRoutes(http, account) {
2103
2110
  timeoutMs: 3e4,
2104
2111
  signal: request.signal,
2105
2112
  busyRetries: 0,
2106
- isCurrentAccount: async () => sameAccount(before, await account.identity())
2113
+ isCurrentAccount: async () => sameAccount$1(before, await account.identity())
2107
2114
  };
2108
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);
2109
2116
  const after = await account.identity();
2110
- if (!sameAccount(before, after)) return changed();
2117
+ if (!sameAccount$1(before, after)) return changed();
2111
2118
  const projected = projectCenterRoute(path, obj(data)?.data ?? data);
2112
- if (projected === void 0) return answer$1(502, { error: {
2119
+ if (projected === void 0) return answer$2(502, { error: {
2113
2120
  code: "ACCOUNT_READ_UNAVAILABLE",
2114
2121
  category: "service_unavailable"
2115
2122
  } });
2116
- return answer$1(200, {
2123
+ return answer$2(200, {
2117
2124
  code: 0,
2118
2125
  data: projected
2119
2126
  });
2120
2127
  } catch (error) {
2121
- if (error instanceof MediaError && error.code === "ACCOUNT_CHANGED" || before !== void 0 && !sameAccount(before, await account.identity())) return changed();
2122
- if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405)) return answer$1(200, { unsupported: true });
2123
- 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: {
2124
2131
  code: error.code,
2125
2132
  category: error.details.category,
2126
2133
  message: error.message,
2127
2134
  request_id: error.details.requestId
2128
2135
  } });
2129
- return answer$1(502, { error: {
2136
+ return answer$2(502, { error: {
2130
2137
  code: "ACCOUNT_READ_UNAVAILABLE",
2131
2138
  category: "service_unavailable",
2132
2139
  message: "账户信息暂时无法获取,请稍后刷新。"
@@ -2796,8 +2803,8 @@ const unavailable = () => json$2(200, {
2796
2803
  items: [],
2797
2804
  unread: 0
2798
2805
  });
2799
- const record$11 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
2800
- 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;
2801
2808
  const identifier = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
2802
2809
  /**
2803
2810
  * One announcement from the wire, with every field it needs and nothing else.
@@ -2805,12 +2812,12 @@ const identifier = (value) => typeof value === "number" && Number.isSafeInteger(
2805
2812
  * @returns the announcement, or undefined when the entry cannot be rendered.
2806
2813
  */
2807
2814
  function parseAnnouncement(value) {
2808
- const item = record$11(value);
2815
+ const item = record$13(value);
2809
2816
  if (item === void 0) return void 0;
2810
2817
  const id = identifier(item.id);
2811
- const title = text$7(item.title);
2812
- const content = text$7(item.content);
2813
- 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);
2814
2821
  if (id === void 0 || title === void 0 || content === void 0 || createdAt === void 0) return void 0;
2815
2822
  return {
2816
2823
  id,
@@ -2820,7 +2827,7 @@ function parseAnnouncement(value) {
2820
2827
  notifyMode: item.notify_mode === "popup" ? "popup" : "silent",
2821
2828
  ...typeof item.starts_at === "string" ? { startsAt: item.starts_at } : {},
2822
2829
  ...typeof item.ends_at === "string" ? { endsAt: item.ends_at } : {},
2823
- readAt: text$7(item.read_at) ?? null
2830
+ readAt: text$8(item.read_at) ?? null
2824
2831
  };
2825
2832
  }
2826
2833
  /**
@@ -2830,7 +2837,7 @@ function parseAnnouncement(value) {
2830
2837
  */
2831
2838
  function entriesOf(payload) {
2832
2839
  if (Array.isArray(payload)) return payload;
2833
- const data = record$11(payload)?.data;
2840
+ const data = record$13(payload)?.data;
2834
2841
  return Array.isArray(data) ? data : void 0;
2835
2842
  }
2836
2843
  /**
@@ -2914,7 +2921,7 @@ function announcementRoutes({ http, account }) {
2914
2921
  fetch: async (incoming) => {
2915
2922
  const entered = await enter(incoming);
2916
2923
  if (entered instanceof Response) return entered;
2917
- const body = record$11(await incoming.json().catch(() => void 0));
2924
+ const body = record$13(await incoming.json().catch(() => void 0));
2918
2925
  const id = identifier(body?.id);
2919
2926
  if (id === void 0) return json$2(400, { error: {
2920
2927
  code: "ANNOUNCEMENT_INVALID_ID",
@@ -3886,7 +3893,7 @@ const invalid = (field) => json(400, { error: {
3886
3893
  code: "FEEDBACK_INVALID",
3887
3894
  field
3888
3895
  } });
3889
- 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;
3890
3897
  /**
3891
3898
  * The feedback routes.
3892
3899
  * @param options - the uploader's submit, the recent errors and the credential check.
@@ -3904,7 +3911,7 @@ function feedbackRoutes(options) {
3904
3911
  requestBody: "buffered",
3905
3912
  fetch: async (request) => {
3906
3913
  try {
3907
- const body = record$10(await request.json().catch(() => void 0));
3914
+ const body = record$12(await request.json().catch(() => void 0));
3908
3915
  if (body === void 0) return invalid("body");
3909
3916
  if (body.category !== void 0 && body.category !== null && !isCategory(body.category)) return invalid("category");
3910
3917
  if (body.text !== void 0 && typeof body.text !== "string") return invalid("text");
@@ -3914,7 +3921,7 @@ function feedbackRoutes(options) {
3914
3921
  if (text === void 0 && category === void 0) return invalid("text");
3915
3922
  let content;
3916
3923
  if (body.attachment !== void 0 && body.attachment !== null) {
3917
- const given = record$10(body.attachment)?.content;
3924
+ const given = record$12(body.attachment)?.content;
3918
3925
  if (typeof given !== "string" || given === "" || Buffer$1.byteLength(given, "utf8") > 262144) return invalid("attachment");
3919
3926
  content = given;
3920
3927
  }
@@ -3999,7 +4006,8 @@ const ACCOUNT_PAGES = [
3999
4006
  "redeem",
4000
4007
  "affiliate",
4001
4008
  "profile",
4002
- "messages"
4009
+ "messages",
4010
+ "voice_profiles"
4003
4011
  ];
4004
4012
  //#endregion
4005
4013
  //#region src/gateway/http.ts
@@ -5121,8 +5129,8 @@ const CALLBACK_PATH = "/dsh-media/callback";
5121
5129
  function base64url(data) {
5122
5130
  return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5123
5131
  }
5124
- const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
5125
- 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;
5126
5134
  /**
5127
5135
  * Read a token answer (`redeem` or `refresh`).
5128
5136
  * @param body - the parsed envelope `{code, data}` or a bare data object.
@@ -5131,18 +5139,18 @@ const text$6 = (value) => typeof value === "string" && value.trim() !== "" ? val
5131
5139
  * @returns the grant, or undefined when the answer lacks tokens.
5132
5140
  */
5133
5141
  function parseGrant(body, now, previous) {
5134
- const envelope = record$9(body);
5135
- const data = record$9(envelope?.data) ?? envelope;
5136
- const accessToken = text$6(data?.access_token);
5137
- 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);
5138
5146
  if (data === void 0 || accessToken === void 0 || refreshToken === void 0) return void 0;
5139
5147
  const seconds = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
5140
- const user = record$9(data.user);
5141
- 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;
5142
5150
  const parsedUser = user === void 0 ? previous?.user : {
5143
- ...text$6(user.id) === void 0 && typeof user.id !== "number" ? {} : { id: String(user.id) },
5144
- ...text$6(user.email) === void 0 ? {} : { email: text$6(user.email) },
5145
- ...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) }
5146
5154
  };
5147
5155
  return {
5148
5156
  accessToken,
@@ -5562,8 +5570,8 @@ var PluginLogin = class {
5562
5570
  return;
5563
5571
  }
5564
5572
  if (!live()) return;
5565
- const envelope = record$9(body);
5566
- 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;
5567
5575
  if (parsed === void 0) {
5568
5576
  answer(502, "VibeDev", failurePage({
5569
5577
  ...this.attempt,
@@ -5747,13 +5755,15 @@ const REASONING_LEVELS = [
5747
5755
  "xhigh",
5748
5756
  "max"
5749
5757
  ];
5758
+ /** The file kinds a model can take natively, in the order `nativeMedia` lists them. */
5759
+ const NATIVE_MEDIA = ["audio", "video"];
5750
5760
  /** The endpoint each protocol is called on, as `allowed_endpoints` lists it. */
5751
5761
  const ENDPOINT = {
5752
5762
  "anthropic-messages": "/v1/messages",
5753
5763
  "openai-responses": "/v1/responses",
5754
5764
  "openai-completions": "/v1/chat/completions"
5755
5765
  };
5756
- 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;
5757
5767
  const strings$1 = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
5758
5768
  const positive$2 = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
5759
5769
  const price$1 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
@@ -5807,15 +5817,15 @@ function reasoningLevelsOf(value) {
5807
5817
  * @returns the chat models, in catalog order; entries that are not chat models or cannot be called are left out.
5808
5818
  */
5809
5819
  function parseCatalog(body) {
5810
- const list = Array.isArray(body) ? body : record$8(body)?.data;
5820
+ const list = Array.isArray(body) ? body : record$10(body)?.data;
5811
5821
  if (!Array.isArray(list)) return [];
5812
5822
  const models = [];
5813
5823
  const seen = /* @__PURE__ */ new Set();
5814
5824
  for (const raw of list) {
5815
- const entry = record$8(raw);
5825
+ const entry = record$10(raw);
5816
5826
  const id = typeof entry?.id === "string" ? entry.id.trim() : "";
5817
5827
  if (entry === void 0 || id === "" || seen.has(id)) continue;
5818
- const capabilities = record$8(entry.capabilities);
5828
+ const capabilities = record$10(entry.capabilities);
5819
5829
  if (capabilities === void 0) continue;
5820
5830
  if (typeof entry.media_type === "string" && entry.media_type !== "") continue;
5821
5831
  if (typeof entry.internal_role === "string" && entry.internal_role !== "") continue;
@@ -5828,8 +5838,9 @@ function parseCatalog(body) {
5828
5838
  const levels = reasoningLevelsOf(capabilities.reasoning_levels);
5829
5839
  const defaultReasoning = typeof capabilities.default_reasoning === "string" && levels?.includes(capabilities.default_reasoning) ? capabilities.default_reasoning : void 0;
5830
5840
  const inputs = strings$1(capabilities.input_modalities) ?? [];
5841
+ const nativeMedia = api === "openai-completions" ? NATIVE_MEDIA.filter((kind) => inputs.includes(kind)) : [];
5831
5842
  const maxInputTokens = positive$2(capabilities.max_input_tokens);
5832
- const rawFamily = record$8(entry.model_family);
5843
+ const rawFamily = record$10(entry.model_family);
5833
5844
  const familyId = typeof rawFamily?.id === "string" ? rawFamily.id.trim() : "";
5834
5845
  const familyLabel = typeof rawFamily?.label === "string" ? rawFamily.label.trim() : "";
5835
5846
  seen.add(id);
@@ -5845,6 +5856,7 @@ function parseCatalog(body) {
5845
5856
  ...maxInputTokens === void 0 ? {} : { maxInputTokens },
5846
5857
  maxTokens: positive$2(capabilities.max_output_tokens) ?? 32768,
5847
5858
  input: inputs.includes("image") ? ["text", "image"] : ["text"],
5859
+ ...nativeMedia.length === 0 ? {} : { nativeMedia },
5848
5860
  ...levels === void 0 ? {} : { reasoningLevels: levels },
5849
5861
  ...defaultReasoning === void 0 ? {} : { defaultReasoning },
5850
5862
  adaptiveThinking: capabilities.adaptive_thinking === true,
@@ -6111,6 +6123,313 @@ function toPiAssistant(message, onDegrade) {
6111
6123
  }
6112
6124
  }
6113
6125
  //#endregion
6126
+ //#region src/llm/native-files.ts
6127
+ /**
6128
+ * Native audio/video delivery for the gateway's Chat Completions models.
6129
+ *
6130
+ * Adapted from the VibeDev fork of DeepSeek Harness `@deepseek-ai/dsh-llm-pi-ai` (src/native-files.ts, vibedev
6131
+ * 5be6bcec; MIT, Copyright (c) 2026 DeepSeek — see THIRD-PARTY-NOTICES.txt). Keep it in step with upstream.
6132
+ *
6133
+ * Request assembly (the host's LLM runtime) decides which audio/video occurrences a request carries natively: the
6134
+ * current turn's user messages and tool results (DSH 0.2.3-era VibeDev hosts: only the latest user message that
6135
+ * carries files), only kinds the model declares, within 14 MiB per file and 20 MiB of base64 per request, and never
6136
+ * for an auxiliary call. It leaves each kept `{type:'file'}` block right after the file's handle text. This module
6137
+ * reads the kept files' bytes and serializes them; it decides nothing beyond a defensive re-check of the same size
6138
+ * ceilings and of the media types the gateway's models take ({@link GEMINI_INLINE_MEDIA_TYPES}).
6139
+ *
6140
+ * pi-ai's Context has no file content, so conversion leaves one marker text part where each delivered file belongs
6141
+ * and the payload hook swaps every marker for an OpenAI-compatible `file` content part carrying the bytes as a data
6142
+ * URL: `{"type":"file","file":{"file_data":"data:<mediaType>;base64,<…>"}}`. The gateway turns it into the
6143
+ * provider's own form (Gemini `inlineData`, say). A Chat Completions `tool` message carries text only, so a file in a
6144
+ * tool result moves to a `user` message right after that run of tool messages, the way pi-ai sends tool-result
6145
+ * images (see {@link injectNativeFiles}).
6146
+ *
6147
+ * Nothing here can fail a request: a file without a target, a host without `readFileRequest`, a read that fails or
6148
+ * a file over a ceiling all fall back to the handle text that is already in the message, with a warning. Only
6149
+ * cancellation propagates.
6150
+ *
6151
+ * Hosts whose `@deepseek-ai/dsh-llm` and `@deepseek-ai/dsh-attachment` predate native files (DSH 0.2.2-rc.5,
6152
+ * upstream 0.2.3) never keep a file block, so none of this runs there; the types the newer packages declare are
6153
+ * restated structurally below so the plugin builds and loads against either.
6154
+ *
6155
+ * @module dsh-vibedev/llm/native-files
6156
+ */
6157
+ /**
6158
+ * A named export of `@deepseek-ai/dsh-llm` that older hosts do not have. Read off the module namespace, never as a
6159
+ * named import: a missing named import of an ES module fails the plugin's whole load, a missing namespace member is
6160
+ * just undefined.
6161
+ */
6162
+ function hostNumber(name) {
6163
+ const value = dshLlm[name];
6164
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
6165
+ }
6166
+ /** Raw-byte ceiling for one natively delivered file: the host's `NATIVE_FILE_MAX_BYTES`, 14 MiB where it has none. */
6167
+ const NATIVE_FILE_MAX_BYTES = hostNumber("NATIVE_FILE_MAX_BYTES") ?? 14680064;
6168
+ /** Ceiling on the base64 total of a request's native files: the host's own, 20 MiB where it has none. */
6169
+ const NATIVE_FILE_MAX_REQUEST_BASE64_BYTES = hostNumber("NATIVE_FILE_MAX_REQUEST_BASE64_BYTES") ?? 20971520;
6170
+ /**
6171
+ * Media types the gateway's Chat Completions models take inline: the containers Gemini documents for inline
6172
+ * audio/video, spelled as the host's `sniffFileMediaType` spells them. Anything else (Matroska, M4A, Opus, AMR,
6173
+ * WMA, …) keeps its handle text only: one type the provider refuses would fail the whole request.
6174
+ */
6175
+ const GEMINI_INLINE_MEDIA_TYPES = Object.freeze([
6176
+ "video/mp4",
6177
+ "video/mpeg",
6178
+ "video/quicktime",
6179
+ "video/x-msvideo",
6180
+ "video/x-flv",
6181
+ "video/webm",
6182
+ "video/x-ms-wmv",
6183
+ "video/3gpp",
6184
+ "audio/mpeg",
6185
+ "audio/wav",
6186
+ "audio/aiff",
6187
+ "audio/aac",
6188
+ "audio/ogg",
6189
+ "audio/flac"
6190
+ ]);
6191
+ /** Text that opens the user message carrying tool-result media. */
6192
+ const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
6193
+ /** Text pi-ai opens its tool-result image follow-up with; media joins that message. */
6194
+ const PI_TOOL_RESULT_IMAGE_TEXT = "Attached image(s) from tool result:";
6195
+ /** pi-ai's bridge between tool results and a user message under `requiresAssistantAfterToolResult`. */
6196
+ const PI_TOOL_RESULT_BRIDGE = "I have processed the tool results.";
6197
+ /**
6198
+ * Text part that holds one delivered file's place until the payload hook replaces it. Deterministic, so identical
6199
+ * histories convert identically, and NUL-delimited, so no user-authored text block equals it.
6200
+ * @param index - position in {@link PiFileRequestContext.delivered}.
6201
+ * @returns the marker text.
6202
+ */
6203
+ function nativeFileMarker(index) {
6204
+ return `\u0000dsh-native-file:${index}\u0000`;
6205
+ }
6206
+ /** Length of the base64 encoding of `bytes` raw bytes. */
6207
+ function base64Length(bytes) {
6208
+ return Math.ceil(bytes / 3) * 4;
6209
+ }
6210
+ /**
6211
+ * Read every file the request delivers natively, once per attachment. A file whose target is gone, whose read fails
6212
+ * (the host's `ATTACHMENT_PROJECTION_UNSUPPORTED` for a media type outside the target's list included), whose sniffed
6213
+ * media type the target does not accept, or that breaks a ceiling is left out, so its occurrences keep only their
6214
+ * handle text; cancellation still propagates. When the base64 total of the occurrences read exceeds
6215
+ * {@link NATIVE_FILE_MAX_REQUEST_BASE64_BYTES} (a host that did not budget them), the earliest files are left out
6216
+ * first, as request assembly would.
6217
+ * @param messages - converted history; user- and tool-role file blocks are read.
6218
+ * @param attachments - durable provider of the verbatim bytes.
6219
+ * @param files - route target and degrade observer.
6220
+ * @param signal - request cancellation.
6221
+ * @returns request bytes by attachment id.
6222
+ */
6223
+ async function readNativeFiles(messages, attachments, files, signal) {
6224
+ const refs = /* @__PURE__ */ new Map();
6225
+ const occurrences = /* @__PURE__ */ new Map();
6226
+ for (const message of messages) {
6227
+ if (message.role !== "user" && message.role !== "tool") continue;
6228
+ for (const block of message.content) {
6229
+ if (block.type !== "file") continue;
6230
+ const id = block.attachment.attachmentId;
6231
+ if (!refs.has(id)) refs.set(id, block.attachment);
6232
+ occurrences.set(id, (occurrences.get(id) ?? 0) + 1);
6233
+ }
6234
+ }
6235
+ const read = /* @__PURE__ */ new Map();
6236
+ if (refs.size === 0) return read;
6237
+ const readFileRequest = attachments.readFileRequest;
6238
+ if (typeof readFileRequest !== "function") {
6239
+ for (const ref of refs.values()) files.onDegrade?.(ref, "the attachment provider cannot read request files");
6240
+ return read;
6241
+ }
6242
+ for (const [id, ref] of refs) {
6243
+ let target;
6244
+ try {
6245
+ target = files.target(ref);
6246
+ } catch {
6247
+ target = void 0;
6248
+ }
6249
+ if (target === void 0) {
6250
+ files.onDegrade?.(ref, "the route offers no native file target");
6251
+ continue;
6252
+ }
6253
+ const maxBytes = Math.min(target.maxBytes, NATIVE_FILE_MAX_BYTES);
6254
+ if (ref.bytes > maxBytes) {
6255
+ files.onDegrade?.(ref, `the file has ${ref.bytes} bytes, over the ${maxBytes}-byte native file limit`);
6256
+ continue;
6257
+ }
6258
+ try {
6259
+ const file = await readFileRequest.call(attachments, ref, {
6260
+ ...target,
6261
+ maxBytes
6262
+ }, signal);
6263
+ if (!(file.data instanceof Uint8Array) || typeof file.mediaType !== "string" || file.mediaType === "") throw new Error("the attachment provider returned no bytes or media type");
6264
+ if (file.data.byteLength > maxBytes) throw new Error(`the file read has ${file.data.byteLength} bytes, over the ${maxBytes}-byte native file limit`);
6265
+ if (!(target.mediaTypes ?? GEMINI_INLINE_MEDIA_TYPES).includes(file.mediaType)) throw new Error(`the route does not accept media type ${file.mediaType}`);
6266
+ read.set(id, file);
6267
+ } catch (error) {
6268
+ signal?.throwIfAborted();
6269
+ files.onDegrade?.(ref, error instanceof Error ? error.message : String(error));
6270
+ }
6271
+ }
6272
+ const order = [...read.keys()];
6273
+ let total = order.reduce((sum, id) => sum + base64Length(read.get(id).data.byteLength) * (occurrences.get(id) ?? 1), 0);
6274
+ for (const id of order) {
6275
+ if (total <= NATIVE_FILE_MAX_REQUEST_BASE64_BYTES) break;
6276
+ const file = read.get(id);
6277
+ total -= base64Length(file.data.byteLength) * (occurrences.get(id) ?? 1);
6278
+ read.delete(id);
6279
+ files.onDegrade?.(file.attachment, `the request's native files exceed the ${NATIVE_FILE_MAX_REQUEST_BASE64_BYTES}-byte base64 budget`);
6280
+ }
6281
+ return read;
6282
+ }
6283
+ /**
6284
+ * The Chat Completions content part for one delivered file.
6285
+ * @param file - bytes and sniffed media type.
6286
+ * @returns the part the gateway accepts.
6287
+ */
6288
+ function nativeFilePart(file) {
6289
+ return {
6290
+ type: "file",
6291
+ file: { file_data: `data:${file.mediaType};base64,${Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength).toString("base64")}` }
6292
+ };
6293
+ }
6294
+ function isRecord$1(value) {
6295
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6296
+ }
6297
+ function isToolMessage(message) {
6298
+ return isRecord$1(message) && message.role === "tool";
6299
+ }
6300
+ /** pi-ai's tool-result image follow-up, whose image parts the moved media joins. */
6301
+ function isImageFollowUp(message) {
6302
+ if (!isRecord$1(message) || message.role !== "user" || !Array.isArray(message.content)) return false;
6303
+ const first = message.content[0];
6304
+ return isRecord$1(first) && first.type === "text" && first.text === PI_TOOL_RESULT_IMAGE_TEXT;
6305
+ }
6306
+ function isToolResultBridge(message) {
6307
+ return isRecord$1(message) && message.role === "assistant" && message.content === PI_TOOL_RESULT_BRIDGE;
6308
+ }
6309
+ /**
6310
+ * Take the markers out of one tool message. pi-ai joins a tool result's text parts with newlines and each marker is a
6311
+ * part of its own (the conversion puts them after the result's text), so dropping the marker lines leaves exactly
6312
+ * the text the result has without its files.
6313
+ */
6314
+ function stripToolMarkers(message, markers) {
6315
+ const files = [];
6316
+ const content = message.content;
6317
+ if (typeof content === "string") {
6318
+ if (!content.includes("\0")) return {
6319
+ message,
6320
+ files
6321
+ };
6322
+ const lines = content.split("\n").filter((line) => {
6323
+ const file = markers.get(line);
6324
+ if (file !== void 0) files.push(file);
6325
+ return file === void 0;
6326
+ });
6327
+ if (files.length === 0) return {
6328
+ message,
6329
+ files
6330
+ };
6331
+ const text = lines.join("\n");
6332
+ return {
6333
+ message: {
6334
+ ...message,
6335
+ content: text.length > 0 ? text : "(see attached media)"
6336
+ },
6337
+ files
6338
+ };
6339
+ }
6340
+ if (Array.isArray(content)) {
6341
+ const parts = content.filter((part) => {
6342
+ const file = isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? markers.get(part.text) : void 0;
6343
+ if (file !== void 0) files.push(file);
6344
+ return file === void 0;
6345
+ });
6346
+ if (files.length > 0) return {
6347
+ message: {
6348
+ ...message,
6349
+ content: parts
6350
+ },
6351
+ files
6352
+ };
6353
+ }
6354
+ return {
6355
+ message,
6356
+ files
6357
+ };
6358
+ }
6359
+ /**
6360
+ * Put every delivered file part into a Chat Completions payload. A marker part in a user message becomes the file
6361
+ * part in place. A Chat Completions `tool` message holds text only, so markers in a run of consecutive `tool`
6362
+ * messages leave the tool text (the handle text stays) and their parts, in tool-result then block order, go to the
6363
+ * user message right after the run: appended to pi-ai's "Attached image(s) from tool result:" message when pi-ai
6364
+ * added one, otherwise in a new `{role:'user',content:[{type:'text',text:'Attached media from tool result:'},…]}`,
6365
+ * preceded by pi-ai's bridging assistant message when the model requires one.
6366
+ * @param payload - the request body pi-ai built.
6367
+ * @param delivered - file parts by marker index.
6368
+ * @param options - the model's tool-result ordering rule.
6369
+ * @returns a shallow-copied payload, or undefined to keep it when no marker is present.
6370
+ */
6371
+ function injectNativeFiles(payload, delivered, options = {}) {
6372
+ if (delivered.length === 0 || !isRecord$1(payload) || !Array.isArray(payload.messages)) return void 0;
6373
+ const markers = new Map(delivered.map((part, index) => [nativeFileMarker(index), part]));
6374
+ const fileOf = (part) => isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? markers.get(part.text) : void 0;
6375
+ const inPlace = (message) => {
6376
+ if (!isRecord$1(message) || !Array.isArray(message.content)) return message;
6377
+ const parts = message.content;
6378
+ if (!parts.some((part) => fileOf(part) !== void 0)) return message;
6379
+ return {
6380
+ ...message,
6381
+ content: parts.map((part) => fileOf(part) ?? part)
6382
+ };
6383
+ };
6384
+ const original = payload.messages;
6385
+ const messages = [];
6386
+ let changed = false;
6387
+ let index = 0;
6388
+ while (index < original.length) {
6389
+ if (!isToolMessage(original[index])) {
6390
+ const message = inPlace(original[index]);
6391
+ changed ||= message !== original[index];
6392
+ messages.push(message);
6393
+ index++;
6394
+ continue;
6395
+ }
6396
+ const moved = [];
6397
+ for (; index < original.length && isToolMessage(original[index]); index++) {
6398
+ const stripped = stripToolMarkers(original[index], markers);
6399
+ messages.push(stripped.message);
6400
+ moved.push(...stripped.files);
6401
+ }
6402
+ if (moved.length === 0) continue;
6403
+ changed = true;
6404
+ const bridged = isToolResultBridge(original[index]) ? 1 : 0;
6405
+ const followUp = original[index + bridged];
6406
+ if (isImageFollowUp(followUp)) {
6407
+ if (bridged === 1) messages.push(original[index]);
6408
+ messages.push({
6409
+ ...followUp,
6410
+ content: [...followUp.content, ...moved]
6411
+ });
6412
+ index += bridged + 1;
6413
+ continue;
6414
+ }
6415
+ if (options.assistantAfterToolResult === true) messages.push({
6416
+ role: "assistant",
6417
+ content: PI_TOOL_RESULT_BRIDGE
6418
+ });
6419
+ messages.push({
6420
+ role: "user",
6421
+ content: [{
6422
+ type: "text",
6423
+ text: TOOL_RESULT_MEDIA_TEXT
6424
+ }, ...moved]
6425
+ });
6426
+ }
6427
+ return changed ? {
6428
+ ...payload,
6429
+ messages
6430
+ } : void 0;
6431
+ }
6432
+ //#endregion
6114
6433
  //#region src/llm/context.ts
6115
6434
  /**
6116
6435
  * Copied (by way of the VibeDev app) from DeepSeek Harness `@deepseek-ai/dsh-llm-pi-ai` (src/context.ts,
@@ -6119,7 +6438,8 @@ function toPiAssistant(message, onDegrade) {
6119
6438
  * so the gateway adapter can choose a wire protocol per model. Keep it in step with upstream.
6120
6439
  *
6121
6440
  * Kept in step with 0.2.3 for what changes at run time: the request-image target (see `requestImageTarget`) and the text of a
6122
- * system message (see `systemText`).
6441
+ * system message (see `systemText`). Native audio/video files (`files`, see ./native-files.ts) follow the VibeDev fork
6442
+ * (vibedev 5be6bcec).
6123
6443
  *
6124
6444
  * Harness request-history conversion into pi-ai's Context vocabulary.
6125
6445
  *
@@ -6161,8 +6481,9 @@ function assertSupportedHistory(messages) {
6161
6481
  if (message.role !== "user" && message.role !== "tool" && contentHasImage(message.content)) throw new LlmError(`pi-ai cannot represent an image in an in-history ${message.role} message`, "UNSUPPORTED_CONTENT");
6162
6482
  }
6163
6483
  }
6164
- function userContent(blocks, requestImages, resolveImageAccess) {
6484
+ function userContent(blocks, requestImages, resolveImageAccess, files) {
6165
6485
  const content = [];
6486
+ let markers = 0;
6166
6487
  for (const block of blocks) switch (block.type) {
6167
6488
  case "text":
6168
6489
  if (block.text.length > 0) content.push({
@@ -6170,6 +6491,17 @@ function userContent(blocks, requestImages, resolveImageAccess) {
6170
6491
  text: block.text
6171
6492
  });
6172
6493
  break;
6494
+ case "file": {
6495
+ const file = files?.read.get(block.attachment.attachmentId);
6496
+ if (files === void 0 || file === void 0) break;
6497
+ content.push({
6498
+ type: "text",
6499
+ text: nativeFileMarker(files.delivered.length)
6500
+ });
6501
+ files.delivered.push(nativeFilePart(file));
6502
+ markers++;
6503
+ break;
6504
+ }
6173
6505
  case "image": {
6174
6506
  const version = requestImages.get(block.attachment.attachmentId);
6175
6507
  content.push({
@@ -6184,9 +6516,27 @@ function userContent(blocks, requestImages, resolveImageAccess) {
6184
6516
  break;
6185
6517
  }
6186
6518
  }
6187
- if (content.every((block) => block.type === "text")) return content.map((block) => block.text).join("");
6519
+ if (markers === 0 && content.every((block) => block.type === "text")) return content.map((block) => block.text).join("");
6188
6520
  return content;
6189
6521
  }
6522
+ /**
6523
+ * A tool result's content with its native file markers. pi-ai sends a tool result as one text joined with newlines,
6524
+ * and the payload hook moves each marker's file to a user message after the tool messages (a `tool` message holds
6525
+ * text only), dropping the marker's line. A text-only result keeps its text joined as without files, with the markers
6526
+ * after it, so the tool text the model reads is the same whether or not a file went along.
6527
+ */
6528
+ function toolContent(blocks, requestImages, resolveImageAccess, files) {
6529
+ const before = files?.delivered.length ?? 0;
6530
+ const content = userContent(blocks, requestImages, resolveImageAccess, files);
6531
+ if (typeof content === "string" || files === void 0 || files.delivered.length === before) return content;
6532
+ if (!content.every((block) => block.type === "text")) return content;
6533
+ const markers = new Set(files.delivered.slice(before).map((_, index) => nativeFileMarker(before + index)));
6534
+ const text = content.filter((block) => !markers.has(block.text)).map((block) => block.text).join("");
6535
+ return [...text.length > 0 ? [{
6536
+ type: "text",
6537
+ text
6538
+ }] : [], ...content.filter((block) => markers.has(block.text))];
6539
+ }
6190
6540
  function collectImageRefs(blocks, refs) {
6191
6541
  for (const block of blocks) if (block.type === "image") {
6192
6542
  if (block.offloaded !== true) refs.set(block.attachment.attachmentId, block.attachment);
@@ -6315,15 +6665,19 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
6315
6665
  if (offloadImages > 0) throw new LlmError(`pi-ai request images exceed the ${maxRequestImageBytes}-byte base64 bound; ${offloadImages} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages });
6316
6666
  }
6317
6667
  const exactMessages = projectOffloadedImages(split.messages, (ref) => offloadedImageText(ref, resolveImageAccess(ref)));
6668
+ const files = images.files === void 0 ? void 0 : {
6669
+ read: await readNativeFiles(split.messages, attachments, images.files, options.signal),
6670
+ delivered: images.files.delivered
6671
+ };
6318
6672
  const toolNames = /* @__PURE__ */ new Map();
6319
6673
  const messages = [];
6320
6674
  for (const message of exactMessages) {
6321
6675
  if (appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade)) continue;
6322
6676
  if (message.role === "tool") {
6323
- messages.push(toolResultOf(message, toolNames, userContent(message.content, requestImages, resolveImageAccess)));
6677
+ messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files)));
6324
6678
  continue;
6325
6679
  }
6326
- const content = userContent(message.content, requestImages, resolveImageAccess);
6680
+ const content = userContent(message.content, requestImages, resolveImageAccess, files);
6327
6681
  messages.push({
6328
6682
  role: "user",
6329
6683
  content,
@@ -6993,7 +7347,7 @@ const PRICE_CONTEXT_QUERY = "scope=platform&period=7d&sort=recommended&page=1&pa
6993
7347
  const DEFAULT_TIMEOUT_MS = 1e4;
6994
7348
  /** The same label for an English surface. */
6995
7349
  const DEFAULT_PROMOTION_BADGE_EN = "Limited-time offer";
6996
- 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;
6997
7351
  const string = (value) => typeof value === "string" && value.trim() !== "" ? value : void 0;
6998
7352
  const amount$1 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
6999
7353
  const groupId = (value) => {
@@ -7008,7 +7362,7 @@ function instant$1(value) {
7008
7362
  return Number.isFinite(parsed) ? parsed : void 0;
7009
7363
  }
7010
7364
  function tier(value) {
7011
- const source = record$7(value);
7365
+ const source = record$9(value);
7012
7366
  if (source === void 0) return void 0;
7013
7367
  const prevSpendMin = amount$1(source.prev_spend_min);
7014
7368
  const discountRate = amount$1(source.discount_rate);
@@ -7024,7 +7378,7 @@ function tier(value) {
7024
7378
  * @returns the promotion with its window resolved, or undefined.
7025
7379
  */
7026
7380
  function parsePromotion(value) {
7027
- const source = record$7(value);
7381
+ const source = record$9(value);
7028
7382
  if (source === void 0) return void 0;
7029
7383
  const model = string(source.model);
7030
7384
  const startsAt = string(source.starts_at);
@@ -7174,16 +7528,16 @@ var PromotionService = class {
7174
7528
  }
7175
7529
  /** The pricing group the account center already prices this account with. */
7176
7530
  async priceGroup() {
7177
- 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}`, {
7178
7532
  timeoutMs: this.timeoutMs,
7179
7533
  busyRetries: 0
7180
7534
  }));
7181
- const data = record$7(answer?.data) ?? answer;
7182
- 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);
7183
7537
  }
7184
7538
  /** The public list. `anonymous` keeps a signed-out or broken sign-in from changing the answer. */
7185
7539
  async list() {
7186
- const data = record$7(await this.options.http.json(PROMOTIONS_PATH, {
7540
+ const data = record$9(await this.options.http.json(PROMOTIONS_PATH, {
7187
7541
  anonymous: true,
7188
7542
  timeoutMs: this.timeoutMs,
7189
7543
  busyRetries: 0
@@ -7357,6 +7711,19 @@ function reasoningInfo(model, catalog) {
7357
7711
  ...starting === void 0 ? {} : { defaultEffort: ReasoningEffortId(effortOf(starting)) }
7358
7712
  } };
7359
7713
  }
7714
+ /**
7715
+ * The modalities the host reads for one model: pi-ai's `input` (text, image) plus the media files the model takes
7716
+ * natively. The host's request assembly keeps an audio/video file block only for a model that lists its kind here.
7717
+ * `ModelModality` names only text and image in the Harness types this plugin builds against; the VibeDev fork adds
7718
+ * audio and video, and older hosts ignore modalities they do not know.
7719
+ */
7720
+ function inputModalitiesOf(model, catalog) {
7721
+ return [...model.input, ...catalog?.nativeMedia ?? []];
7722
+ }
7723
+ /** Warn about one native file that goes as handle text alone; the default {@link GatewayAdapterOptions.onNativeFileDegrade}. */
7724
+ function warnNativeFileDegrade(detail) {
7725
+ console.warn(`dsh-vibedev: sending "${detail.file}" to ${detail.provider}/${detail.model} as its file handle text only: ${detail.reason}`);
7726
+ }
7360
7727
  /** A JSON object payload pi-ai is about to send, or undefined for anything else. */
7361
7728
  function objectPayload(payload) {
7362
7729
  return typeof payload === "object" && payload !== null && !Array.isArray(payload) ? payload : void 0;
@@ -7429,6 +7796,30 @@ var GatewayAdapter = class extends LlmAdapter {
7429
7796
  maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7430
7797
  });
7431
7798
  }
7799
+ /**
7800
+ * The raw-byte target under which this route delivers one audio/video file natively (the VibeDev fork's
7801
+ * `LlmAdapter.fileRequestTarget`; hosts without it never ask). Chat Completions models that declare audio or video
7802
+ * get the host's per-file ceiling and the media types they take inline (`GEMINI_INLINE_MEDIA_TYPES`; hosts that
7803
+ * predate `mediaTypes` ignore it, and the plugin checks it again after the read); every other model — Claude over
7804
+ * Messages, GPT over Responses, a model that declares neither — gets none, so request assembly sends those files as
7805
+ * handle text. Synchronous and I/O-free; request assembly also checks the file's kind against the model's
7806
+ * `inputModalities`.
7807
+ *
7808
+ * Not marked `override`: the Harness types this plugin builds against do not declare the hook yet.
7809
+ */
7810
+ fileRequestTarget(provider, model, _file) {
7811
+ return this.fileTargetIn(this.current(), provider, model);
7812
+ }
7813
+ /** {@link fileRequestTarget} on one snapshot, so a request reads its files under the catalog it began with. */
7814
+ fileTargetIn(snapshot, provider, model) {
7815
+ if (!this.owns(provider)) return void 0;
7816
+ const entry = snapshot.byId.get(model);
7817
+ if (entry === void 0 || entry.api !== "openai-completions" || (entry.nativeMedia?.length ?? 0) === 0) return void 0;
7818
+ return snapshot.models.getModel(provider, model) === void 0 ? void 0 : {
7819
+ maxBytes: NATIVE_FILE_MAX_BYTES,
7820
+ mediaTypes: GEMINI_INLINE_MEDIA_TYPES
7821
+ };
7822
+ }
7432
7823
  providerInfo(provider) {
7433
7824
  this.assertOwned(provider);
7434
7825
  const relay = this.config.relayProvider;
@@ -7450,7 +7841,8 @@ var GatewayAdapter = class extends LlmAdapter {
7450
7841
  const promotions = await this.promotions();
7451
7842
  return listed.filter((model) => !hideRelay || !relayIdentity(model.id).relay).map((model) => {
7452
7843
  const promotion = promotions.get(model.id);
7453
- const family = snapshot.byId.get(model.id)?.family;
7844
+ const entry = snapshot.byId.get(model.id);
7845
+ const family = entry?.family;
7454
7846
  const pinOrder = preferred.get(model.id);
7455
7847
  const picker = family === void 0 && pinOrder === void 0 ? void 0 : {
7456
7848
  ...family === void 0 ? {} : { family },
@@ -7460,7 +7852,7 @@ var GatewayAdapter = class extends LlmAdapter {
7460
7852
  provider,
7461
7853
  id: model.id,
7462
7854
  name: model.name,
7463
- inputModalities: [...model.input],
7855
+ inputModalities: inputModalitiesOf(model, entry),
7464
7856
  ...picker === void 0 ? {} : { picker },
7465
7857
  ...promotion === void 0 ? {} : {
7466
7858
  badge: promotionBadge(promotion),
@@ -7489,7 +7881,7 @@ var GatewayAdapter = class extends LlmAdapter {
7489
7881
  provider,
7490
7882
  id,
7491
7883
  name: model.name,
7492
- inputModalities: [...model.input],
7884
+ inputModalities: inputModalitiesOf(model, catalog),
7493
7885
  context: { contextWindow: model.contextWindow },
7494
7886
  defaultMaxTokens: model.maxTokens,
7495
7887
  ...reasoningInfo(model, catalog)
@@ -7529,7 +7921,9 @@ var GatewayAdapter = class extends LlmAdapter {
7529
7921
  try {
7530
7922
  const containsImage = options.messages.some((message) => contentHasImage(message.content));
7531
7923
  if (containsImage && !model.input.includes("image")) throw new LlmError(`VibeDev model "${model.id}" does not support image input`, "UNSUPPORTED_CONTENT");
7532
- const attachments = containsImage ? this.config.resolveAttachments?.() : void 0;
7924
+ const carriesFiles = (message) => (message.role === "user" || message.role === "tool") && message.content.some((block) => block.type === "file");
7925
+ const containsNativeFile = model.api === "openai-completions" && options.messages.some(carriesFiles);
7926
+ const attachments = containsImage || containsNativeFile ? this.config.resolveAttachments?.() : void 0;
7533
7927
  if (containsImage && attachments === void 0) throw new LlmError("image input requires the durable attachment service", "UNSUPPORTED_CONTENT");
7534
7928
  const onReplayDegrade = (reason) => {
7535
7929
  this.config.onReplayDegrade?.({
@@ -7538,6 +7932,21 @@ var GatewayAdapter = class extends LlmAdapter {
7538
7932
  reason
7539
7933
  });
7540
7934
  };
7935
+ const onNativeFileDegrade = (file, reason) => {
7936
+ try {
7937
+ (this.config.onNativeFileDegrade ?? warnNativeFileDegrade)({
7938
+ provider: options.provider,
7939
+ model: options.model,
7940
+ file,
7941
+ reason
7942
+ });
7943
+ } catch {}
7944
+ };
7945
+ if (containsNativeFile && attachments === void 0) for (const message of options.messages) {
7946
+ if (!carriesFiles(message)) continue;
7947
+ for (const block of message.content) if (block.type === "file") onNativeFileDegrade(block.attachment.name, "no durable attachment service to read it from");
7948
+ }
7949
+ const nativeFiles = [];
7541
7950
  const context = attachments === void 0 ? toPiContext(options, void 0, onReplayDegrade) : await toPiContext({
7542
7951
  ...options,
7543
7952
  signal: watchdog.signal
@@ -7548,7 +7957,14 @@ var GatewayAdapter = class extends LlmAdapter {
7548
7957
  requestImagePolicy: {
7549
7958
  maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
7550
7959
  maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7551
- }
7960
+ },
7961
+ ...containsNativeFile ? { files: {
7962
+ target: () => this.fileTargetIn(snapshot, options.provider, options.model),
7963
+ onDegrade: (ref, reason) => {
7964
+ onNativeFileDegrade(ref.name, reason);
7965
+ },
7966
+ delivered: nativeFiles
7967
+ } } : {}
7552
7968
  }, onReplayDegrade);
7553
7969
  const enabledReasoning = reasoning === void 0 || reasoning === "off" ? void 0 : reasoning;
7554
7970
  const offersNone = catalog.reasoningLevels?.includes("none") === true;
@@ -7594,7 +8010,8 @@ var GatewayAdapter = class extends LlmAdapter {
7594
8010
  ...sessionId === void 0 ? {} : { sessionId },
7595
8011
  off: reasoning === "off" && offersNone,
7596
8012
  reasoning: enabledReasoning !== void 0,
7597
- claudeCacheTtl
8013
+ claudeCacheTtl,
8014
+ nativeFiles
7598
8015
  }),
7599
8016
  fetch: observingFetch,
7600
8017
  onResponse: (received) => {
@@ -7663,7 +8080,9 @@ var GatewayAdapter = class extends LlmAdapter {
7663
8080
  /**
7664
8081
  * Fit pi-ai's payload to the gateway: Chat Completions gets the session's cache key (pi-ai sends it
7665
8082
  * only to api.openai.com), "off" is spelled out where the catalog offers `none`, and Responses
7666
- * drops `temperature` while reasoning, which reasoning models refuse.
8083
+ * drops `temperature` while reasoning, which reasoning models refuse. Chat Completions also gets
8084
+ * its native audio/video files: each marker the conversion left becomes a `file` part, in place in
8085
+ * a user message and in a user message after the tool messages for a tool result.
7667
8086
  */
7668
8087
  shapePayload(payload, model, request) {
7669
8088
  const body = objectPayload(payload);
@@ -7676,6 +8095,10 @@ var GatewayAdapter = class extends LlmAdapter {
7676
8095
  shaped.thinking = { type: "disabled" };
7677
8096
  delete shaped.reasoning_effort;
7678
8097
  } else if (request.off) shaped.reasoning_effort = "none";
8098
+ if (request.nativeFiles !== void 0 && request.nativeFiles.length > 0) {
8099
+ const assistantAfterToolResult = model.compat?.requiresAssistantAfterToolResult === true;
8100
+ return injectNativeFiles(shaped, request.nativeFiles, { assistantAfterToolResult }) ?? shaped;
8101
+ }
7679
8102
  break;
7680
8103
  case "openai-responses":
7681
8104
  if (request.off) shaped.reasoning = {
@@ -7828,6 +8251,9 @@ function installGatewayModels(ctx, options) {
7828
8251
  onReplayDegrade: ({ provider, model, reason }) => {
7829
8252
  ctx.logger.warn(`dsh-vibedev: unusable replay state on assistant history for "${provider}/${model}"; sending provider-neutral content (${reason})`);
7830
8253
  },
8254
+ onNativeFileDegrade: ({ provider, model, file, reason }) => {
8255
+ ctx.logger.warn(`dsh-vibedev: sending "${file}" to ${provider}/${model} as its file handle text only: ${reason}`);
8256
+ },
7831
8257
  ...options.onRequestEnded === void 0 ? {} : { onRequestEnded: options.onRequestEnded },
7832
8258
  ...options.promotions === void 0 ? {} : { promotions: options.promotions }
7833
8259
  });
@@ -7954,7 +8380,7 @@ function installGatewayModels(ctx, options) {
7954
8380
  const PROMOTIONS_ROUTE = "/api/dsh-vibedev/promotions";
7955
8381
  /** How long the page waits for a promotion answer before showing prices without labels. */
7956
8382
  const ROUTE_WAIT_MS = 2e3;
7957
- const answer = (body) => new Response(JSON.stringify(body), {
8383
+ const answer$1 = (body) => new Response(JSON.stringify(body), {
7958
8384
  status: 200,
7959
8385
  headers: {
7960
8386
  "content-type": "application/json",
@@ -7979,7 +8405,7 @@ function promotionRoutes(promotions) {
7979
8405
  items = [];
7980
8406
  }
7981
8407
  const group = promotions.snapshotGroup();
7982
- return answer({
8408
+ return answer$1({
7983
8409
  code: 0,
7984
8410
  data: {
7985
8411
  items,
@@ -8026,10 +8452,10 @@ const FIRST_LOOK_MS = 1e3;
8026
8452
  const LOOK_STEP_MAX_MS = 1e4;
8027
8453
  /** Uploads this library starts for one file: its own, and one more after another upload of the file ended without it. */
8028
8454
  const OWN_UPLOADS = 2;
8029
- const record$6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8030
- 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;
8031
8457
  const httpUrl$1 = (value) => {
8032
- const url = text$5(value);
8458
+ const url = text$6(value);
8033
8459
  return url !== void 0 && /^https?:\/\//i.test(url) ? url : void 0;
8034
8460
  };
8035
8461
  /**
@@ -8039,17 +8465,17 @@ const httpUrl$1 = (value) => {
8039
8465
  * @returns the asset facts, or undefined when the answer names no usable URL.
8040
8466
  */
8041
8467
  function parseAsset(body, fallbackType) {
8042
- const raw = record$6(body);
8043
- const assetId = text$5(raw?.asset_id);
8468
+ const raw = record$8(body);
8469
+ const assetId = text$6(raw?.asset_id);
8044
8470
  const referenceUrl = httpUrl$1(raw?.reference_url);
8045
8471
  if (raw === void 0 || assetId === void 0 || referenceUrl === void 0) return void 0;
8046
8472
  const contentUrl = httpUrl$1(raw.content_url);
8047
- const expiresAt = text$5(raw.expires_at);
8473
+ const expiresAt = text$6(raw.expires_at);
8048
8474
  const duration = raw.duration_ms;
8049
8475
  return {
8050
8476
  assetId,
8051
8477
  referenceUrl,
8052
- contentType: text$5(raw.content_type) ?? fallbackType,
8478
+ contentType: text$6(raw.content_type) ?? fallbackType,
8053
8479
  ...contentUrl === void 0 ? {} : { contentUrl },
8054
8480
  ...expiresAt === void 0 ? {} : { expiresAt },
8055
8481
  ...typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? { durationMs: duration } : {}
@@ -8189,7 +8615,7 @@ var MediaLibrary = class {
8189
8615
  }
8190
8616
  /** `POST /uploads`: the asset when the library already holds the file, else the upload it hands out. */
8191
8617
  async declare(media, purpose, sha256, signal) {
8192
- 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", {
8193
8619
  method: "POST",
8194
8620
  json: {
8195
8621
  filename: media.name,
@@ -8200,7 +8626,7 @@ var MediaLibrary = class {
8200
8626
  },
8201
8627
  signal
8202
8628
  }));
8203
- const assetId = text$5(created?.asset_id);
8629
+ const assetId = text$6(created?.asset_id);
8204
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");
8205
8631
  if (created.upload_required !== false) return {
8206
8632
  kind: "upload",
@@ -8223,10 +8649,10 @@ var MediaLibrary = class {
8223
8649
  }
8224
8650
  /** PUT the bytes where `uploads` said, then `complete`. */
8225
8651
  async put(media, sha256, assetId, created, signal) {
8226
- 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);
8227
8653
  if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
8228
8654
  const headers = { "content-type": media.mime };
8229
- 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;
8230
8656
  await this.http.send(uploadUrl, {
8231
8657
  method: "PUT",
8232
8658
  body: media.data,
@@ -8288,8 +8714,8 @@ const AUDIO_GENERATION_KINDS = [
8288
8714
  "speech",
8289
8715
  "transcription"
8290
8716
  ];
8291
- const record$5 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8292
- 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;
8293
8719
  const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
8294
8720
  const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
8295
8721
  const positive$1 = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : void 0;
@@ -8336,15 +8762,15 @@ function parseModes(raw) {
8336
8762
  const version = field(raw, "modes_schema_version");
8337
8763
  const modesRaw = raw.modes;
8338
8764
  if (version === void 0 && modesRaw === void 0) return {};
8339
- 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 };
8340
8766
  const modes = {};
8341
8767
  for (const mode of VIDEO_MODES) {
8342
- const entry = record$5(modesRaw[mode]);
8768
+ const entry = record$7(modesRaw[mode]);
8343
8769
  if (entry === void 0) continue;
8344
- const inputsRaw = record$5(entry.inputs) ?? {};
8770
+ const inputsRaw = record$7(entry.inputs) ?? {};
8345
8771
  const inputs = {};
8346
8772
  for (const [key, limitRaw] of Object.entries(inputsRaw)) {
8347
- const limit = record$5(limitRaw);
8773
+ const limit = record$7(limitRaw);
8348
8774
  const min = count(limit?.min);
8349
8775
  const max = count(limit?.max);
8350
8776
  if (!VIDEO_INPUTS.includes(key) || limit === void 0 || min === void 0 || max === void 0 || min > max) return { unreadableModesVersion: 1 };
@@ -8453,11 +8879,11 @@ function parseVideoCapabilities(raw) {
8453
8879
  if (Array.isArray(combinationsRaw)) {
8454
8880
  const combinations = [];
8455
8881
  for (const item of combinationsRaw) {
8456
- const entry = record$5(item);
8882
+ const entry = record$7(item);
8457
8883
  if (entry === void 0) continue;
8458
8884
  const duration = positive$1(field(entry, "duration_seconds"));
8459
- const ratio = text$4(entry.ratio);
8460
- const resolution = text$4(entry.resolution);
8885
+ const ratio = text$5(entry.ratio);
8886
+ const resolution = text$5(entry.resolution);
8461
8887
  combinations.push({
8462
8888
  ...duration === void 0 ? {} : { duration },
8463
8889
  ...ratio === void 0 ? {} : { ratio },
@@ -8547,12 +8973,12 @@ const PRICE_UNITS = [
8547
8973
  ];
8548
8974
  /** The audio block: `entry.audio`, else `capabilities.audio`, else the fields flattened into `capabilities`. */
8549
8975
  function audioBlock(entry, capabilities) {
8550
- const own = record$5(entry.audio) ?? record$5(capabilities.audio);
8976
+ const own = record$7(entry.audio) ?? record$7(capabilities.audio);
8551
8977
  if (own !== void 0) return own;
8552
8978
  return field(capabilities, "generation_kind") !== void 0 ? capabilities : void 0;
8553
8979
  }
8554
8980
  function stringChoices(raw) {
8555
- const choices = record$5(raw);
8981
+ const choices = record$7(raw);
8556
8982
  if (choices === void 0) return void 0;
8557
8983
  const out = {};
8558
8984
  for (const [name, values] of Object.entries(choices)) {
@@ -8596,7 +9022,7 @@ function parseReferenceLimits(raw, form) {
8596
9022
  if (mimes !== void 0 && mimes.length > 0) limits.mimes = mimes;
8597
9023
  const exclusive = list(raw, "mutually_exclusive_with") ?? list(raw, "exclusive_with");
8598
9024
  if (exclusive !== void 0 && exclusive.length > 0) limits.exclusiveWith = exclusive;
8599
- 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);
8600
9026
  if (purpose !== void 0) limits.purpose = purpose;
8601
9027
  return limits;
8602
9028
  }
@@ -8625,11 +9051,11 @@ function seedReferenceLimits(raw) {
8625
9051
  function parseOutputFormats(raw) {
8626
9052
  const declared = field(raw, "output_formats");
8627
9053
  if (!Array.isArray(declared)) return void 0;
8628
- 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"));
8629
9055
  const formats = [];
8630
9056
  for (const item of declared) {
8631
- const entry = record$5(item);
8632
- 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();
8633
9059
  if (format === void 0 || formats.some((known) => known.format === format)) continue;
8634
9060
  const sampleRates = (entry === void 0 ? void 0 : field(entry, "sample_rates")) ?? rates?.[format];
8635
9061
  const valid = Array.isArray(sampleRates) ? sampleRates.filter((rate) => positive$1(rate) !== void 0 && Number.isInteger(rate)) : [];
@@ -8648,20 +9074,20 @@ function parseOutputFormats(raw) {
8648
9074
  * @returns the declared capabilities; `generationKind` is absent unless declared.
8649
9075
  */
8650
9076
  function parseAudioCapabilities(raw) {
8651
- const kindRaw = text$4(field(raw, "generation_kind"))?.toLowerCase();
9077
+ const kindRaw = text$5(field(raw, "generation_kind"))?.toLowerCase();
8652
9078
  const generationKind = AUDIO_GENERATION_KINDS.includes(kindRaw ?? "") ? kindRaw : void 0;
8653
- const billingRaw = text$4(field(raw, "billing_unit"))?.toLowerCase();
9079
+ const billingRaw = text$5(field(raw, "billing_unit"))?.toLowerCase();
8654
9080
  const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
8655
- const promptField = text$4(field(raw, "prompt_field"));
9081
+ const promptField = text$5(field(raw, "prompt_field"));
8656
9082
  const requestFields = list(raw, "request_fields") ?? [];
8657
9083
  const union = [
8658
9084
  "reference_audio_input",
8659
9085
  "reference_image_input",
8660
9086
  "speaker_input"
8661
9087
  ].some((name) => bool(raw, name) !== void 0);
8662
- 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);
8663
9089
  const outputFormats = parseOutputFormats(raw);
8664
- const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
9090
+ const defaultFormat = text$5(field(raw, "default_format"))?.toLowerCase();
8665
9091
  const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
8666
9092
  const watermarkFields = list(raw, "watermark_fields");
8667
9093
  const result = { requestFields };
@@ -8673,6 +9099,7 @@ function parseAudioCapabilities(raw) {
8673
9099
  if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
8674
9100
  if (choices !== void 0) result.choices = choices;
8675
9101
  if (watermarkFields !== void 0 && watermarkFields.length > 0) result.watermarkFields = watermarkFields;
9102
+ if (bool(raw, "supports_voice_cover") === true) result.supportsVoiceCover = true;
8676
9103
  for (const [key, ...names] of [
8677
9104
  [
8678
9105
  "maxPromptChars",
@@ -8701,13 +9128,13 @@ function parseAudioCapabilities(raw) {
8701
9128
  return result;
8702
9129
  }
8703
9130
  function parsePricing(value, audioUnit) {
8704
- const raw = record$5(value);
9131
+ const raw = record$7(value);
8705
9132
  if (raw === void 0) return void 0;
8706
9133
  const unit = (item) => PRICE_UNITS.includes(item) ? item : item === void 0 && audioUnit !== void 0 ? audioUnit : void 0;
8707
9134
  const tiers = [];
8708
9135
  if (Array.isArray(raw.tiers)) for (const entry of raw.tiers) {
8709
- const tier = record$5(entry);
8710
- const name = text$4(tier?.tier);
9136
+ const tier = record$7(entry);
9137
+ const name = text$5(tier?.tier);
8711
9138
  const tierUnit = unit(tier?.unit);
8712
9139
  const amount = typeof tier?.amount === "number" && Number.isFinite(tier.amount) && tier.amount >= 0 ? tier.amount : void 0;
8713
9140
  if (name !== void 0 && tierUnit !== void 0 && amount !== void 0) tiers.push({
@@ -8716,12 +9143,12 @@ function parsePricing(value, audioUnit) {
8716
9143
  amount
8717
9144
  });
8718
9145
  }
8719
- const fallback = record$5(raw.default);
9146
+ const fallback = record$7(raw.default);
8720
9147
  const fallbackUnit = unit(fallback?.unit);
8721
9148
  const fallbackAmount = typeof fallback?.amount === "number" && Number.isFinite(fallback.amount) && fallback.amount >= 0 ? fallback.amount : void 0;
8722
9149
  if (tiers.length === 0 && (fallbackUnit === void 0 || fallbackAmount === void 0)) return void 0;
8723
9150
  return {
8724
- currency: text$4(raw.currency) ?? "CNY",
9151
+ currency: text$5(raw.currency) ?? "CNY",
8725
9152
  tiers,
8726
9153
  ...fallbackUnit === void 0 || fallbackAmount === void 0 ? {} : { default: {
8727
9154
  unit: fallbackUnit,
@@ -8744,7 +9171,7 @@ function condition(raw, snake) {
8744
9171
  */
8745
9172
  function parseVideoPricing(value) {
8746
9173
  if (value === void 0 || value === null) return {};
8747
- const raw = record$5(value);
9174
+ const raw = record$7(value);
8748
9175
  if (raw === void 0) return { videoPricingIssue: "invalid" };
8749
9176
  if (field(raw, "schema_version") !== 1) return { videoPricingIssue: "unknown-schema" };
8750
9177
  const invalid = { videoPricingIssue: "invalid" };
@@ -8754,9 +9181,9 @@ function parseVideoPricing(value) {
8754
9181
  if (!Array.isArray(rulesRaw) || rulesRaw.length === 0) return invalid;
8755
9182
  const rules = [];
8756
9183
  for (const item of rulesRaw) {
8757
- const entry = record$5(item);
9184
+ const entry = record$7(item);
8758
9185
  if (entry === void 0) return invalid;
8759
- const resolution = text$4(field(entry, "resolution"));
9186
+ const resolution = text$5(field(entry, "resolution"));
8760
9187
  const perMillion = price(field(entry, "price_per_million_tokens"));
8761
9188
  const estimateRaw = field(entry, "estimated_price_per_second");
8762
9189
  const perSecond = estimateRaw === void 0 || estimateRaw === null ? void 0 : price(estimateRaw);
@@ -8784,10 +9211,10 @@ function parseVideoPricing(value) {
8784
9211
  }
8785
9212
  /** Which kind of media model a catalog entry is, or undefined for a chat or internal model. */
8786
9213
  function kindOf(entry, capabilities, audio) {
8787
- if (text$4(entry.internal_role) !== void 0) return void 0;
9214
+ if (text$5(entry.internal_role) !== void 0) return void 0;
8788
9215
  if (audio?.generationKind === "transcription") return "transcription";
8789
9216
  if (audio?.generationKind !== void 0) return "audio";
8790
- const mediaType = text$4(entry.media_type);
9217
+ const mediaType = text$5(entry.media_type);
8791
9218
  if (mediaType === "video" || mediaType === "image" || mediaType === "audio" || mediaType === "transcription") return mediaType;
8792
9219
  if (capabilities.transcription === true || capabilities.realtime_transcription === true) return "transcription";
8793
9220
  const outputs = strings(capabilities.output_modalities) ?? strings(entry.output_modalities) ?? [];
@@ -8806,22 +9233,22 @@ function kindOf(entry, capabilities, audio) {
8806
9233
  * @returns the media models, in catalog order.
8807
9234
  */
8808
9235
  function parseMediaCatalog(body) {
8809
- const entries = Array.isArray(body) ? body : record$5(body)?.data;
9236
+ const entries = Array.isArray(body) ? body : record$7(body)?.data;
8810
9237
  if (!Array.isArray(entries)) return [];
8811
9238
  const models = [];
8812
9239
  const seen = /* @__PURE__ */ new Set();
8813
9240
  for (const item of entries) {
8814
- const entry = record$5(item);
8815
- const id = text$4(entry?.id);
9241
+ const entry = record$7(item);
9242
+ const id = text$5(entry?.id);
8816
9243
  if (entry === void 0 || id === void 0 || seen.has(id)) continue;
8817
- const capabilities = record$5(entry.capabilities) ?? {};
9244
+ const capabilities = record$7(entry.capabilities) ?? {};
8818
9245
  const audioRaw = audioBlock(entry, capabilities);
8819
9246
  const audio = audioRaw === void 0 ? void 0 : parseAudioCapabilities(audioRaw);
8820
9247
  const kind = kindOf(entry, capabilities, audio);
8821
9248
  if (kind === void 0) continue;
8822
9249
  seen.add(id);
8823
- const name = text$4(entry.display_name) ?? id;
8824
- const description = text$4(entry.description);
9250
+ const name = text$5(entry.display_name) ?? id;
9251
+ const description = text$5(entry.description);
8825
9252
  const pricing = parsePricing(entry.media_pricing, audio?.billingUnit);
8826
9253
  const { videoPricing, videoPricingIssue } = parseVideoPricing(field(entry, "video_pricing"));
8827
9254
  const inputModalities = strings(capabilities.input_modalities) ?? strings(entry.input_modalities) ?? [];
@@ -8830,7 +9257,7 @@ function parseMediaCatalog(body) {
8830
9257
  let video;
8831
9258
  if (kind === "video") video = {
8832
9259
  ...parseVideoCapabilities(capabilities),
8833
- ...parseVideoCapabilities(record$5(entry.video) ?? {})
9260
+ ...parseVideoCapabilities(record$7(entry.video) ?? {})
8834
9261
  };
8835
9262
  const imageSizes = kind === "image" ? optionList(field(capabilities, "image_sizes")) : void 0;
8836
9263
  const imageRatios = kind === "image" ? optionList(field(capabilities, "image_ratios")) : void 0;
@@ -9453,7 +9880,7 @@ var GatewayFetchError = class extends WebError {
9453
9880
  this.name = "GatewayFetchError";
9454
9881
  }
9455
9882
  };
9456
- function record$4(value) {
9883
+ function record$6(value) {
9457
9884
  return typeof value === "object" && value !== null && !Array.isArray(value);
9458
9885
  }
9459
9886
  function positive(value) {
@@ -9493,14 +9920,14 @@ function invalidCapability() {
9493
9920
  }
9494
9921
  /** Decode only the fixed advertised Fetch V1 lane; absence is not a request to probe an endpoint. */
9495
9922
  function readGatewayFetchCapability(payload) {
9496
- if (record$4(payload) && (payload.error !== void 0 || typeof payload.code === "number" && payload.code !== 0)) throw invalidCapability();
9497
- 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;
9498
9925
  const capabilities = payload.data.capabilities;
9499
9926
  if (capabilities === void 0) return void 0;
9500
9927
  if (!Array.isArray(capabilities)) throw invalidCapability();
9501
9928
  if (!capabilities.includes("web-fetch-v1")) return void 0;
9502
9929
  const value = payload.data.web_fetch;
9503
- 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();
9504
9931
  return {
9505
9932
  path: FETCH_PATH,
9506
9933
  mode: "extracted_content",
@@ -9521,7 +9948,7 @@ function normalizedRequest(value) {
9521
9948
  }
9522
9949
  /** Decode extraction facts without claiming an observed target status, final address or completeness. */
9523
9950
  function decodeGatewayFetchResponse(payload, requestedUrl, maxBodyCharacters) {
9524
- 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();
9525
9952
  try {
9526
9953
  if (normalizedRequest(payload.requested_url) !== normalizedRequest(requestedUrl)) throw invalidResponse();
9527
9954
  } catch {
@@ -9550,8 +9977,8 @@ function decodeGatewayFetchResponse(payload, requestedUrl, maxBodyCharacters) {
9550
9977
  }
9551
9978
  function dependencyFailure(error, stage) {
9552
9979
  if (error instanceof GatewayFetchError) return error;
9553
- const source = record$4(error) ? error : void 0;
9554
- 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;
9555
9982
  const failure = gatewayFailureWithHeaders({ error: {
9556
9983
  code: safeId(source?.code),
9557
9984
  message: typeof source?.message === "string" ? source.message : void 0,
@@ -9634,7 +10061,7 @@ async function readJson(response, maxBytes, signal) {
9634
10061
  }
9635
10062
  function gatewayError(response, payload) {
9636
10063
  const parsed = gatewayFailureWithHeaders(payload, response.headers);
9637
- 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;
9638
10065
  const code = safeId(parsed.code) ?? "WEB_FETCH_FAILED";
9639
10066
  const requestId = safeRequestId(parsed.requestId) ?? safeRequestId(response.headers.get("x-request-id"));
9640
10067
  const wait = retryAfterMs(response.headers.get("retry-after")) ?? (positive(source?.retry_after_seconds) ? source.retry_after_seconds * 1e3 : void 0);
@@ -10062,7 +10489,7 @@ var GatewaySearchError = class extends WebError {
10062
10489
  function isRecord(value) {
10063
10490
  return typeof value === "object" && value !== null && !Array.isArray(value);
10064
10491
  }
10065
- function text$3(value) {
10492
+ function text$4(value) {
10066
10493
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : void 0;
10067
10494
  }
10068
10495
  /** The gateway's own words for a failure, for error messages: ` (CODE: message)`. */
@@ -10144,9 +10571,9 @@ function mapSearchResponse(payload) {
10144
10571
  const sources = [];
10145
10572
  for (const item of payload.results) {
10146
10573
  if (!isRecord(item) || typeof item.url !== "string" || !URL.canParse(item.url)) continue;
10147
- const title = text$3(item.title);
10148
- const snippet = text$3(item.snippet);
10149
- 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);
10150
10577
  sources.push({
10151
10578
  url: item.url,
10152
10579
  ...title === void 0 ? {} : { title },
@@ -10154,7 +10581,7 @@ function mapSearchResponse(payload) {
10154
10581
  ...publishedAt === void 0 ? {} : { publishedAt }
10155
10582
  });
10156
10583
  }
10157
- 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);
10158
10585
  return {
10159
10586
  ...answers.length === 0 ? {} : { content: answers.join("\n\n") },
10160
10587
  sources,
@@ -11335,113 +11762,591 @@ function quotedCny(quote) {
11335
11762
  return quote.status === "estimate" ? format(roundHalfUp(decimal(quote.amountCny), 2), 2) : void 0;
11336
11763
  }
11337
11764
  //#endregion
11338
- //#region src/audio/request.ts
11765
+ //#region src/audio/voice-profiles.ts
11339
11766
  /**
11340
- * Audio generation requests — music, podcasts and speech — checked against what
11341
- * the chosen model declares in the catalog's `audio` block, and turned into the
11342
- * body of `POST /v1/audio/generations`.
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:
11343
11770
  *
11344
- * Each kind sends only its own fields:
11345
- *
11346
- * | kind | wire fields |
11347
- * | ------- | --------------------------------------------------------------- |
11348
- * | music | model, prompt, lyrics, genre, mood, gender |
11349
- * | podcast | model, prompt, source_url |
11350
- * | speech | as declared; Seed: model, text_prompt, references, audio_config, watermark |
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 |
11351
11776
  *
11352
- * Seed (`seed-audio-1.0`) parses its body strictly: each reference is an object
11353
- * naming its input (`{"audio_url": "<url>"}`) and the watermark an object
11354
- * (`{"aigc_watermark": true}`); the model's declaration says so (the inputs of
11355
- * its reference union, `watermark_fields`), and only such a model gets them.
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`.
11356
11781
  *
11357
- * The main text goes in the model's `prompt_field`. A field the model does not
11358
- * declare in `request_fields` is refused before anything is uploaded or charged;
11359
- * music and podcasts never take speech references, output formats, sample rates
11360
- * or a duration. Speech references, formats and sample rates come from the
11361
- * catalog only (count, size, length, mutual exclusions, the sample rates of
11362
- * each format), never from a fixed list.
11363
- * @module dsh-vibedev/audio/request
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
11364
11786
  */
11365
- const AUDIO_MAKE_KINDS = [
11366
- "music",
11367
- "podcast",
11368
- "speech"
11369
- ];
11370
- /** The standard wire fields of a kind, for a model that declares none (speech declares its own). */
11371
- const STANDARD_FIELDS = {
11372
- music: [
11373
- "model",
11374
- "prompt",
11375
- "lyrics",
11376
- "genre",
11377
- "mood",
11378
- "gender"
11379
- ],
11380
- podcast: [
11381
- "model",
11382
- "prompt",
11383
- "source_url"
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"
11384
11809
  ],
11385
- speech: []
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
+ ]
11386
11826
  };
11387
- /** Fields that belong to speech only: references, the output format and sample rate, a duration. */
11388
- const SPEECH_ONLY = [
11389
- "references",
11390
- "format",
11391
- "sampleRate",
11392
- "duration"
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
+ }
11393
11862
  ];
11394
- /** Default limit on one reference file when the catalog states none. */
11395
- const DEFAULT_REFERENCE_BYTES = 20971520;
11396
- const OPERATION_ID = /^[\w-]{8,80}$/;
11397
- const has = (value) => value !== void 0 && value.trim() !== "";
11398
11863
  /**
11399
- * What an audio model makes, from its declaration only.
11400
- * @param model - the model.
11401
- * @returns the kind, or undefined when the catalog does not declare it.
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.
11402
11867
  */
11403
- function audioKindOf(model) {
11404
- return model.kind === "audio" ? model.audioKind : void 0;
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));
11405
11871
  }
11406
- /** The wire fields a model takes. */
11407
- function requestFieldsOf(model) {
11408
- const kind = audioKindOf(model);
11409
- const declared = model.audio?.requestFields ?? [];
11410
- if (declared.length > 0) return declared;
11411
- return kind === void 0 ? [] : STANDARD_FIELDS[kind];
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";
11412
11906
  }
11413
- /** The field the main text goes in. */
11414
- function promptFieldOf(model) {
11415
- const declared = model.audio?.promptField;
11416
- if (declared !== void 0) return declared;
11417
- const fields = requestFieldsOf(model);
11418
- return [
11419
- "prompt",
11420
- "text_prompt",
11421
- "text",
11422
- "input"
11423
- ].find((name) => fields.includes(name));
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;
11424
11926
  }
11425
- function refuse(message, field) {
11426
- throw localInputError(message, "AUDIO_OPTION_INVALID", field === void 0 ? {} : { field });
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;
11427
11939
  }
11428
- /** Check one value against the model's declared choices for a field. */
11429
- function checkChoice(audio, wire, value) {
11430
- const choices = audio?.choices?.[wire];
11431
- 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);
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
+ };
11432
11974
  }
11433
- /** The output format and sample rate a speech request uses, from the declared formats only. */
11434
- function audioConfigOf(model, format, sampleRate) {
11435
- const formats = model.audio?.outputFormats ?? [];
11436
- if (formats.length === 0) {
11437
- if (format !== void 0 || sampleRate !== void 0) refuse(`${model.id} declares no output formats, so format and sample_rate cannot be chosen.`, "format");
11438
- return;
11439
- }
11440
- const wanted = format?.trim().toLowerCase();
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
12211
+ //#region src/audio/request.ts
12212
+ /**
12213
+ * Audio generation requests — music, podcasts and speech — checked against what
12214
+ * the chosen model declares in the catalog's `audio` block, and turned into the
12215
+ * body of `POST /v1/audio/generations`.
12216
+ *
12217
+ * Each kind sends only its own fields:
12218
+ *
12219
+ * | kind | wire fields |
12220
+ * | ------- | --------------------------------------------------------------- |
12221
+ * | music | model, prompt, lyrics, genre, mood, gender; as declared: style, title, instrumental, voice_id, source_audio_url, audio_weight, mode |
12222
+ * | podcast | model, prompt, source_url |
12223
+ * | speech | as declared; Seed: model, text_prompt, references, audio_config, watermark |
12224
+ *
12225
+ * Seed (`seed-audio-1.0`) parses its body strictly: each reference is an object
12226
+ * naming its input (`{"audio_url": "<url>"}`) and the watermark an object
12227
+ * (`{"aigc_watermark": true}`); the model's declaration says so (the inputs of
12228
+ * its reference union, `watermark_fields`), and only such a model gets them.
12229
+ *
12230
+ * The main text goes in the model's `prompt_field`. A field the model does not
12231
+ * declare in `request_fields` is refused before anything is uploaded or charged;
12232
+ * music and podcasts never take speech references, output formats, sample rates
12233
+ * or a duration. Speech references, formats and sample rates come from the
12234
+ * catalog only (count, size, length, mutual exclusions, the sample rates of
12235
+ * each format), never from a fixed list.
12236
+ * @module dsh-vibedev/audio/request
12237
+ */
12238
+ const AUDIO_MAKE_KINDS = [
12239
+ "music",
12240
+ "podcast",
12241
+ "speech"
12242
+ ];
12243
+ /** The standard wire fields of a kind, for a model that declares none (speech declares its own). */
12244
+ const STANDARD_FIELDS = {
12245
+ music: [
12246
+ "model",
12247
+ "prompt",
12248
+ "lyrics",
12249
+ "genre",
12250
+ "mood",
12251
+ "gender"
12252
+ ],
12253
+ podcast: [
12254
+ "model",
12255
+ "prompt",
12256
+ "source_url"
12257
+ ],
12258
+ speech: []
12259
+ };
12260
+ /** Fields that belong to speech only: references, the output format and sample rate, a duration. */
12261
+ const SPEECH_ONLY = [
12262
+ "references",
12263
+ "format",
12264
+ "sampleRate",
12265
+ "duration"
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;
12299
+ /** Default limit on one reference file when the catalog states none. */
12300
+ const DEFAULT_REFERENCE_BYTES = 20971520;
12301
+ const OPERATION_ID = /^[\w-]{8,80}$/;
12302
+ const has = (value) => value !== void 0 && value.trim() !== "";
12303
+ /**
12304
+ * What an audio model makes, from its declaration only.
12305
+ * @param model - the model.
12306
+ * @returns the kind, or undefined when the catalog does not declare it.
12307
+ */
12308
+ function audioKindOf(model) {
12309
+ return model.kind === "audio" ? model.audioKind : void 0;
12310
+ }
12311
+ /** The wire fields a model takes. */
12312
+ function requestFieldsOf(model) {
12313
+ const kind = audioKindOf(model);
12314
+ const declared = model.audio?.requestFields ?? [];
12315
+ if (declared.length > 0) return declared;
12316
+ return kind === void 0 ? [] : STANDARD_FIELDS[kind];
12317
+ }
12318
+ /** The field the main text goes in. */
12319
+ function promptFieldOf(model) {
12320
+ const declared = model.audio?.promptField;
12321
+ if (declared !== void 0) return declared;
12322
+ const fields = requestFieldsOf(model);
12323
+ return [
12324
+ "prompt",
12325
+ "text_prompt",
12326
+ "text",
12327
+ "input"
12328
+ ].find((name) => fields.includes(name));
12329
+ }
12330
+ function refuse$1(message, field) {
12331
+ throw localInputError(message, "AUDIO_OPTION_INVALID", field === void 0 ? {} : { field });
12332
+ }
12333
+ /** Check one value against the model's declared choices for a field. */
12334
+ function checkChoice(audio, wire, value) {
12335
+ const choices = audio?.choices?.[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);
12337
+ }
12338
+ /** The output format and sample rate a speech request uses, from the declared formats only. */
12339
+ function audioConfigOf(model, format, sampleRate) {
12340
+ const formats = model.audio?.outputFormats ?? [];
12341
+ if (formats.length === 0) {
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");
12343
+ return;
12344
+ }
12345
+ const wanted = format?.trim().toLowerCase();
11441
12346
  const chosen = wanted === void 0 || wanted === "" ? formats.find((item) => item.format === model.audio?.defaultFormat) ?? formats[0] : formats.find((item) => item.format === wanted);
11442
- 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");
11443
12348
  if (sampleRate !== void 0) {
11444
- 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");
11445
12350
  return {
11446
12351
  format: chosen.format,
11447
12352
  sample_rate: sampleRate
@@ -11469,19 +12374,24 @@ function audioRequestBody(model, request) {
11469
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" });
11470
12375
  if (kind !== "speech") for (const name of SPEECH_ONLY) {
11471
12376
  const value = request[name];
11472
- 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);
11473
12381
  }
11474
12382
  const takes = (wire) => fields.includes(wire);
11475
12383
  const body = { model: model.id };
11476
12384
  const promptField = promptFieldOf(model);
11477
12385
  const prompt = request.prompt?.trim();
11478
12386
  if (has(prompt)) {
11479
- if (promptField === void 0) refuse(`${model.id} takes no text prompt.`, "prompt");
11480
- 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);
11481
12389
  body[promptField] = prompt;
11482
12390
  }
11483
12391
  for (const [key, wire] of [
11484
12392
  ["lyrics", "lyrics"],
12393
+ ["style", "style"],
12394
+ ["title", "title"],
11485
12395
  ["genre", "genre"],
11486
12396
  ["mood", "mood"],
11487
12397
  ["gender", "gender"],
@@ -11489,28 +12399,53 @@ function audioRequestBody(model, request) {
11489
12399
  ]) {
11490
12400
  const value = request[key]?.trim();
11491
12401
  if (!has(value)) continue;
11492
- 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);
11493
12403
  checkChoice(audio, wire, value);
11494
- 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);
11495
12405
  body[wire] = value;
11496
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");
11497
12432
  if (request.duration !== void 0) {
11498
- 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");
11499
12434
  body.duration = request.duration;
11500
12435
  }
11501
12436
  if (request.watermark !== void 0) {
11502
- if (!takes("watermark")) refuse(`${model.id} does not take watermark.`, "watermark");
12437
+ if (!takes("watermark")) refuse$1(`${model.id} does not take watermark.`, "watermark");
11503
12438
  const fields = audio?.watermarkFields;
11504
12439
  if (fields === void 0) body.watermark = request.watermark;
11505
12440
  else if (fields.includes("aigc_watermark")) body.watermark = { aigc_watermark: request.watermark };
11506
- 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");
11507
12442
  }
11508
12443
  if (request.format !== void 0 || request.sampleRate !== void 0 || takes("audio_config")) {
11509
- 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");
11510
12445
  const config = audioConfigOf(model, request.format, request.sampleRate);
11511
12446
  if (config !== void 0) body.audio_config = config;
11512
12447
  }
11513
- 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");
11514
12449
  if (kind === "music" && !has(prompt)) throw localInputError("Music needs a prompt describing the song.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
11515
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" });
11516
12451
  if (kind === "speech" && !has(prompt)) throw localInputError("Speech needs the text to speak.", "AUDIO_PROMPT_REQUIRED", { field: promptField ?? "prompt" });
@@ -11519,10 +12454,10 @@ function audioRequestBody(model, request) {
11519
12454
  /** Load, check and upload the reference audio of a speech request; their measured lengths are checked too. */
11520
12455
  async function uploadReferences(runtime, call, model, sources, body) {
11521
12456
  const limits = model.audio?.references;
11522
- if (limits === void 0) refuse(`${model.id} does not take reference audio.`, "references");
11523
- 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");
11524
12459
  const clash = (limits.exclusiveWith ?? []).filter((name) => body[name] !== void 0);
11525
- 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");
11526
12461
  const maxBytes = limits.maxBytes ?? DEFAULT_REFERENCE_BYTES;
11527
12462
  const loaded = [];
11528
12463
  for (const source of sources) {
@@ -11550,12 +12485,85 @@ async function uploadReferences(runtime, call, model, sources, body) {
11550
12485
  return checked;
11551
12486
  }
11552
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
+ /**
11553
12549
  * Choose the model for a request: the one named (an id or an alias), else the
11554
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.
11555
12556
  */
11556
12557
  async function chooseAudioModel(runtime, request, signal) {
11557
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" });
11558
- 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
+ }
11559
12567
  const model = await runtime.findModel(request.model, signal);
11560
12568
  if (model.kind !== "audio") throw localInputError(`${model.id} is not an audio generation model.`, "MODEL_KIND_MISMATCH", { field: "model" });
11561
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" });
@@ -11579,10 +12587,18 @@ async function prepareAudioTask(runtime, call, request, save) {
11579
12587
  const body = audioRequestBody(model, request);
11580
12588
  const references = request.references ?? [];
11581
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);
11582
- 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());
11583
12592
  const quote = quoteAudio(model);
12593
+ const mode = kind === "music" ? musicModeOf(request) : "generate";
11584
12594
  const what = {
11585
- music: {
12595
+ music: mode === "voice_cover" ? {
12596
+ en: "a voice cover",
12597
+ zh: "一首音色翻唱"
12598
+ } : mode === "cover" ? {
12599
+ en: "a cover",
12600
+ zh: "一首翻唱"
12601
+ } : {
11586
12602
  en: "a song",
11587
12603
  zh: "一首音乐"
11588
12604
  },
@@ -11655,6 +12671,8 @@ function audioFormOf(model) {
11655
12671
  });
11656
12672
  for (const [key, wire] of [
11657
12673
  ["lyrics", "lyrics"],
12674
+ ["style", "style"],
12675
+ ["title", "title"],
11658
12676
  ["genre", "genre"],
11659
12677
  ["mood", "mood"],
11660
12678
  ["gender", "gender"],
@@ -11669,6 +12687,22 @@ function audioFormOf(model) {
11669
12687
  ...choices === void 0 ? {} : { choices }
11670
12688
  });
11671
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
+ });
11672
12706
  if (kind === "speech") {
11673
12707
  if (fields.includes("references") && audio?.references !== void 0) out.push({
11674
12708
  key: "references",
@@ -11709,7 +12743,7 @@ function audioFormOf(model) {
11709
12743
  }
11710
12744
  //#endregion
11711
12745
  //#region src/tasks/progress.ts
11712
- 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;
11713
12747
  const nonNegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
11714
12748
  const position = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
11715
12749
  const instant = (value) => {
@@ -11752,7 +12786,7 @@ function progressOf$1(value) {
11752
12786
  return number > 1 ? number / 100 : number;
11753
12787
  }
11754
12788
  function timingOf(value, receivedAt) {
11755
- const raw = record$3(value);
12789
+ const raw = record$4(value);
11756
12790
  if (raw === void 0) return void 0;
11757
12791
  const serverTime = instant(raw.server_time);
11758
12792
  const skew = serverTime === void 0 ? 0 : receivedAt - serverTime;
@@ -11781,7 +12815,7 @@ function timingOf(value, receivedAt) {
11781
12815
  };
11782
12816
  }
11783
12817
  function queueOf(value) {
11784
- const raw = record$3(value);
12818
+ const raw = record$4(value);
11785
12819
  if (raw === void 0) return void 0;
11786
12820
  const facts = {
11787
12821
  position: position(raw.position),
@@ -12457,7 +13491,7 @@ const REFERENCE_TYPES = [
12457
13491
  "image/webp"
12458
13492
  ];
12459
13493
  const SIZE = /^\d{2,5}x\d{2,5}$/;
12460
- 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;
12461
13495
  const text$2 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
12462
13496
  const noPaths = { readPath: () => Promise.reject(new MediaError("The gateway returned an unexpected image reference.", "GATEWAY_BAD_RESPONSE")) };
12463
13497
  /**
@@ -12468,11 +13502,11 @@ const noPaths = { readPath: () => Promise.reject(new MediaError("The gateway ret
12468
13502
  * @returns the images and the revised prompt, when the model returned one.
12469
13503
  */
12470
13504
  async function decodeImages(runtime, body, signal) {
12471
- const items = record$2(body)?.data;
13505
+ const items = record$3(body)?.data;
12472
13506
  const images = [];
12473
13507
  let revisedPrompt;
12474
13508
  for (const item of Array.isArray(items) ? items : []) {
12475
- const entry = record$2(item);
13509
+ const entry = record$3(item);
12476
13510
  if (entry === void 0) continue;
12477
13511
  revisedPrompt ??= text$2(entry.revised_prompt);
12478
13512
  const b64 = text$2(entry.b64_json);
@@ -13911,7 +14945,7 @@ var MediaHostService = class {
13911
14945
  * the answer arrived.
13912
14946
  * @module dsh-vibedev/tasks/remote
13913
14947
  */
13914
- 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;
13915
14949
  const text$1 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
13916
14950
  const httpUrl = (value) => {
13917
14951
  const url = text$1(value);
@@ -13955,9 +14989,9 @@ const seconds = (value) => {
13955
14989
  /** The blocks billing facts are read from, in order: `billing`, `usage`, `effective`, then the answer itself. */
13956
14990
  function billingBlocks(raw) {
13957
14991
  return [
13958
- record$1(raw.billing),
13959
- record$1(raw.usage),
13960
- record$1(raw.effective),
14992
+ record$2(raw.billing),
14993
+ record$2(raw.usage),
14994
+ record$2(raw.effective),
13961
14995
  raw
13962
14996
  ].filter((block) => block !== void 0);
13963
14997
  }
@@ -14010,7 +15044,7 @@ function billedLengths(raw) {
14010
15044
  };
14011
15045
  }
14012
15046
  function errorOf(raw) {
14013
- const nested = record$1(raw.error);
15047
+ const nested = record$2(raw.error);
14014
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);
14015
15049
  const code = text$1(nested?.code) ?? text$1(nested?.type) ?? text$1(raw.error_code);
14016
15050
  if (message === void 0 && code === void 0) return void 0;
@@ -14029,7 +15063,7 @@ function errorOf(raw) {
14029
15063
  };
14030
15064
  }
14031
15065
  function receiptFacts(raw) {
14032
- const effective = record$1(raw.effective) ?? {};
15066
+ const effective = record$2(raw.effective) ?? {};
14033
15067
  const source = effective.billing_source;
14034
15068
  return {
14035
15069
  ...Object.fromEntries(Object.entries({
@@ -14050,7 +15084,7 @@ function progressOf(value) {
14050
15084
  return Math.min(100, Math.round(value <= 1 && value !== 0 ? value * 100 : value));
14051
15085
  }
14052
15086
  function receipt(raw) {
14053
- const effective = record$1(raw.effective) ?? {};
15087
+ const effective = record$2(raw.effective) ?? {};
14054
15088
  const estimatedCny = amount(effective.estimated_cny);
14055
15089
  const chargedCny = amount(effective.charged_cny) ?? amount(raw.charged_cny);
14056
15090
  return {
@@ -14066,12 +15100,12 @@ function receipt(raw) {
14066
15100
  * @returns the task, or undefined when the answer names no task id.
14067
15101
  */
14068
15102
  function parseVideoTask(body, receivedAt = Date.now()) {
14069
- const raw = record$1(body);
15103
+ const raw = record$2(body);
14070
15104
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
14071
15105
  if (raw === void 0 || id === void 0) return void 0;
14072
15106
  const status = text$1(raw.status) ?? "queued";
14073
- const video = record$1(raw.video) ?? {};
14074
- 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) ?? {};
14075
15109
  const url = httpUrl(video.url) ?? httpUrl(asset.content_url) ?? httpUrl(raw.url) ?? httpUrl(asset.reference_url);
14076
15110
  const durationMs = typeof asset.duration_ms === "number" && asset.duration_ms > 0 ? asset.duration_ms : void 0;
14077
15111
  const seconds = typeof raw.seconds === "number" ? raw.seconds : typeof raw.seconds === "string" ? Number(raw.seconds) : void 0;
@@ -14107,14 +15141,14 @@ function parseVideoTask(body, receivedAt = Date.now()) {
14107
15141
  * @returns the task, or undefined when the answer names no task id.
14108
15142
  */
14109
15143
  function parseAudioTask(body, receivedAt = Date.now()) {
14110
- const raw = record$1(body);
15144
+ const raw = record$2(body);
14111
15145
  const id = text$1(raw?.id) ?? text$1(raw?.task_id);
14112
15146
  if (raw === void 0 || id === void 0) return void 0;
14113
15147
  const status = text$1(raw.status) ?? "queued";
14114
15148
  const state = stateOf(status);
14115
15149
  const outputs = [];
14116
15150
  if (Array.isArray(raw.outputs)) for (const [index, item] of raw.outputs.entries()) {
14117
- const output = record$1(item);
15151
+ const output = record$2(item);
14118
15152
  if (output === void 0) continue;
14119
15153
  const url = httpUrl(output.content_url) ?? httpUrl(output.url);
14120
15154
  const contentType = text$1(output.content_type);
@@ -15286,7 +16320,7 @@ function mediaAccountTool(runtime, chain, login) {
15286
16320
  function audioGenerateTool(runtime) {
15287
16321
  return defineTool({
15288
16322
  name: "audio_generate",
15289
- 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.",
15290
16324
  parameters: {
15291
16325
  type: {
15292
16326
  type: "string",
@@ -15314,6 +16348,30 @@ function audioGenerateTool(runtime) {
15314
16348
  type: "string",
15315
16349
  description: "Music only: the singer's voice, such as male or female."
15316
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
+ },
15317
16375
  source_url: {
15318
16376
  type: "string",
15319
16377
  description: "Podcast only: an http(s) page for the hosts to discuss."
@@ -15400,6 +16458,12 @@ function audioGenerateTool(runtime) {
15400
16458
  ...args.genre === void 0 ? {} : { genre: args.genre },
15401
16459
  ...args.mood === void 0 ? {} : { mood: args.mood },
15402
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 },
15403
16467
  ...args.source_url === void 0 ? {} : { sourceUrl: args.source_url },
15404
16468
  ...args.references === void 0 ? {} : { references: args.references },
15405
16469
  ...args.format === void 0 ? {} : { format: args.format },
@@ -15479,6 +16543,7 @@ function describeAudioModel(model) {
15479
16543
  if (model.audioKind === void 0) return "does not declare what kind of audio it makes; it cannot be used for generation";
15480
16544
  const fields = requestFieldsOf(model).filter((name) => name !== "model");
15481
16545
  const parts = [`fields: ${fields.join(", ") || "none declared"}`];
16546
+ if (audio?.supportsVoiceCover === true) parts.push("supports voice covers (voice_id)");
15482
16547
  const prompt = promptFieldOf(model);
15483
16548
  if (prompt !== void 0 && prompt !== "prompt") parts.push(`the text goes in ${prompt}`);
15484
16549
  const references = audio?.references;
@@ -15717,7 +16782,7 @@ const ACCEPTED = [
15717
16782
  "video/mp4",
15718
16783
  "video/webm"
15719
16784
  ];
15720
- 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;
15721
16786
  const text = (value) => typeof value === "string" ? value : void 0;
15722
16787
  /**
15723
16788
  * The length of a PCM WAV file from its header.
@@ -15842,19 +16907,19 @@ function audioTranscribeTool(runtime) {
15842
16907
  busyRetries: BUSY_RETRIES,
15843
16908
  maxBusyWaitMs: 3e4
15844
16909
  });
15845
- let answer = record(await response.json().catch(() => void 0));
16910
+ let answer = record$1(await response.json().catch(() => void 0));
15846
16911
  const started = runtime.now();
15847
16912
  while (text(answer?.text) === void 0) {
15848
16913
  const id = text(answer?.id) ?? text(answer?.task_id);
15849
16914
  const status = text(answer?.status)?.toLowerCase();
15850
16915
  if (status === "failed" || status === "error" || status === "cancelled") {
15851
- const error = record(answer?.error);
16916
+ const error = record$1(answer?.error);
15852
16917
  throw new MediaError(`The transcription failed${error === void 0 ? "" : ` (${text(error.code) ?? ""}: ${text(error.message) ?? ""})`}; failed transcriptions are not charged.`, "TRANSCRIPTION_FAILED");
15853
16918
  }
15854
16919
  if (id === void 0) throw new MediaError("The VibeDev gateway returned neither a transcript nor a task.", "GATEWAY_BAD_RESPONSE");
15855
16920
  if (runtime.now() - started > POLL_LIMIT_MS) throw new MediaError(`The transcription task ${id} did not finish within 15 minutes.`, "TRANSCRIPTION_TIMEOUT");
15856
16921
  await sleep(POLL_MS, exec.signal);
15857
- answer = record(await runtime.http.json(`/v1/audio/transcriptions/${encodeURIComponent(id)}`, {
16922
+ answer = record$1(await runtime.http.json(`/v1/audio/transcriptions/${encodeURIComponent(id)}`, {
15858
16923
  timeoutMs: 3e4,
15859
16924
  signal: exec.signal
15860
16925
  }));
@@ -15876,6 +16941,388 @@ function audioTranscribeTool(runtime) {
15876
16941
  });
15877
16942
  }
15878
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
15879
17326
  //#region src/index.ts
15880
17327
  /**
15881
17328
  * dsh-vibedev (formerly dsh-media): the VibeDev account and the VibeDev
@@ -15899,8 +17346,6 @@ function audioTranscribeTool(runtime) {
15899
17346
  * ```
15900
17347
  * @module dsh-vibedev
15901
17348
  */
15902
- /** Requests that are charged: generations and transcriptions (uploads and reads are free). */
15903
- const PAID_PATH = /^\/v1\/(?:images|videos|audio)(?:\/|$)/;
15904
17349
  /**
15905
17350
  * How long a model listing waits for promotion labels before it answers without
15906
17351
  * them. A picker must never wait on decoration.
@@ -16003,7 +17448,7 @@ const Config = Schema.object({
16003
17448
  stateDir: "Plugin data folder (empty for the default)"
16004
17449
  }
16005
17450
  });
16006
- 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.";
16007
17452
  function apply(ctx, config) {
16008
17453
  const origin = normalizeGatewayOrigin(config.gatewayOrigin);
16009
17454
  const stateDir = stateDirectory(config.stateDir);
@@ -16045,7 +17490,7 @@ function apply(ctx, config) {
16045
17490
  resolveCredential: () => chain.resolve(),
16046
17491
  rejectToken: (credential) => chain.reject(credential),
16047
17492
  onAccepted: ({ method, path }) => {
16048
- if (method === "POST" && PAID_PATH.test(path)) spent();
17493
+ if (isPaidRequest(method, path)) spent();
16049
17494
  }
16050
17495
  });
16051
17496
  const promotions = new PromotionService({ http });
@@ -16089,6 +17534,10 @@ function apply(ctx, config) {
16089
17534
  jobs: () => ctx.get("jobs"),
16090
17535
  log: warn
16091
17536
  });
17537
+ const voices = new VoiceProfiles({
17538
+ http,
17539
+ upload: (media, purpose, signal) => runtime.library.upload(media, purpose, signal)
17540
+ });
16092
17541
  for (const tool of [
16093
17542
  mediaModelsTool(runtime),
16094
17543
  imageGenerateTool(runtime),
@@ -16096,7 +17545,10 @@ function apply(ctx, config) {
16096
17545
  audioGenerateTool(runtime),
16097
17546
  audioTranscribeTool(runtime),
16098
17547
  mediaTasksTool(runtime),
16099
- mediaAccountTool(runtime, chain, login)
17548
+ mediaAccountTool(runtime, chain, login),
17549
+ voiceProfileCreateTool(runtime, voices),
17550
+ voiceProfileListTool(voices),
17551
+ voiceProfileDeleteTool(runtime, voices)
16100
17552
  ]) ctx.tools.register(tool);
16101
17553
  const accountContext = async () => {
16102
17554
  const identity = await account?.identity();
@@ -16217,6 +17669,7 @@ function apply(ctx, config) {
16217
17669
  for (const accountRoute of [
16218
17670
  ...accountRoutes(accountService),
16219
17671
  ...accountCenterRoutes(http, accountService),
17672
+ ...voiceProfileRoutes(voices, accountService),
16220
17673
  ...announcementRoutes({
16221
17674
  http,
16222
17675
  account: accountService