@vibedev-si/dsh-vibedev 0.11.6 → 0.13.0

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
@@ -51,7 +51,7 @@ const MIN_READ_SPACING_MS = 5e3;
51
51
  */
52
52
  const CATALOG_REFRESH_GAP_MS = 6e4;
53
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
+ const text$11 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
55
55
  /**
56
56
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
57
57
  * writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
@@ -63,7 +63,7 @@ function amountOf(value) {
63
63
  if (!Number.isFinite(value)) return void 0;
64
64
  raw = String(value);
65
65
  if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
66
- } else raw = text$10(value);
66
+ } else raw = text$11(value);
67
67
  return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
68
68
  }
69
69
  /** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
@@ -233,6 +233,7 @@ var AccountService = class {
233
233
  primary: this.options.primary === true,
234
234
  ...this.navigation === void 0 || this.navigation.expiresAt <= this.now() ? {} : { accountCenter: this.navigation },
235
235
  ...pending === void 0 ? {} : { pending },
236
+ ...this.options.login.remote ? { signInMode: "remote" } : {},
236
237
  ...attempt === void 0 ? {} : { attempt }
237
238
  };
238
239
  if (credential === void 0) return {
@@ -308,11 +309,11 @@ var AccountService = class {
308
309
  const body = record$17(await response.json().catch(() => void 0));
309
310
  const data = record$17(body?.data) ?? body;
310
311
  const balance = amountOf(data?.balance);
311
- const currency = text$10(data?.currency) ?? "CNY";
312
+ const currency = text$11(data?.currency) ?? "CNY";
312
313
  const frozen = amountOf(data?.frozen_balance);
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);
314
+ const id = typeof data?.id === "number" ? String(data.id) : text$11(data?.id);
315
+ const nickname = text$11(data?.nickname) ?? text$11(data?.username);
316
+ const email = text$11(data?.email);
316
317
  const user = id === void 0 && nickname === void 0 && email === void 0 ? void 0 : {
317
318
  ...id === void 0 ? {} : { id },
318
319
  ...email === void 0 ? {} : { email },
@@ -609,7 +610,7 @@ function normalizeErrorStage(value) {
609
610
  function record$16(value) {
610
611
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
611
612
  }
612
- function text$9(value) {
613
+ function text$10(value) {
613
614
  return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
614
615
  }
615
616
  function count$1(value) {
@@ -618,7 +619,7 @@ function count$1(value) {
618
619
  /** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
619
620
  function amount$2(value) {
620
621
  if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
621
- const raw = text$9(value);
622
+ const raw = text$10(value);
622
623
  return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
623
624
  }
624
625
  /**
@@ -636,12 +637,12 @@ function parseGatewayFailure(body) {
636
637
  if (root === void 0) return {};
637
638
  const source = record$16(root.error) ?? root;
638
639
  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);
640
+ const gatewayCode = text$10(source.gateway_code) ?? text$10(root.gateway_code);
641
+ const code = gatewayCode ?? text$10(source.code) ?? text$10(source.type) ?? text$10(root.reason);
642
+ const message = text$10(source.message) ?? (typeof root.error === "string" ? text$10(root.error) : void 0);
643
+ const field = text$10(source.field) ?? text$10(metadata?.field);
644
+ const rule = text$10(source.rule) ?? text$10(metadata?.rule);
645
+ const rechargeUrl = text$10(source.recharge_url) ?? text$10(root.recharge_url);
645
646
  const numbers = {
646
647
  active: count$1(source.active),
647
648
  limit: count$1(source.limit)
@@ -651,19 +652,19 @@ function parseGatewayFailure(body) {
651
652
  availableCny: amount$2(source.available_cny),
652
653
  pendingCny: amount$2(source.pending_cny)
653
654
  };
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);
655
+ const submissionState = text$10(source.submission_state) ?? text$10(root.submission_state);
656
+ const retryAction = text$10(source.retry_action) ?? text$10(root.retry_action);
657
+ const assetId = text$10(source.asset_id) ?? text$10(root.asset_id);
657
658
  return {
658
659
  ...gatewayCode === void 0 ? {} : { gatewayCode },
659
660
  ...Object.fromEntries(Object.entries({
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),
661
+ category: normalizeErrorCategory(text$10(source.category) ?? text$10(root.category), code),
662
+ stage: normalizeErrorStage(text$10(source.stage) ?? text$10(root.stage)),
663
+ requestId: text$10(source.request_id) ?? text$10(root.request_id),
664
+ taskId: text$10(source.task_id) ?? text$10(root.task_id),
665
+ operationId: text$10(source.operation_id) ?? text$10(root.operation_id),
666
+ billingState: text$10(source.billing_state) ?? text$10(root.billing_state),
667
+ retryAt: text$10(source.retry_at) ?? text$10(root.retry_at),
667
668
  retryAfterSeconds: count$1(source.retry_after_seconds) ?? count$1(root.retry_after_seconds)
668
669
  }).filter(([, value]) => value !== void 0)),
669
670
  ...code === void 0 ? {} : { code },
@@ -730,11 +731,11 @@ function gatewayFailureWithHeaders(body, headers) {
730
731
  const failure = parseGatewayFailure(body);
731
732
  return {
732
733
  ...failure,
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"))
734
+ code: failure.gatewayCode ?? text$10(headers.get("x-vibedev-error-code")) ?? failure.code,
735
+ category: normalizeErrorCategory(failure.category ?? text$10(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$10(headers.get("x-vibedev-error-code")) ?? failure.code),
736
+ requestId: failure.requestId ?? text$10(headers.get("x-request-id")),
737
+ retryAction: failure.retryAction ?? text$10(headers.get("x-vibedev-retry-action")),
738
+ retryAt: failure.retryAt ?? text$10(headers.get("x-vibedev-retry-at"))
738
739
  };
739
740
  }
740
741
  function isUserAuthenticationFailure(failure) {
@@ -743,14 +744,14 @@ function isUserAuthenticationFailure(failure) {
743
744
  function sdkGatewayFailure(message, headers = {}) {
744
745
  const prefix = /\bvibedev:([A-Z][A-Z0-9_]{1,100}):/.exec(message)?.[1];
745
746
  const legacy = /["'](?:gateway_code|code)["']\s*:\s*["'](APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)["']/.exec(message)?.[1];
746
- const code = text$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
+ const code = text$10(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
748
+ const category = text$10(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
748
749
  if (code === void 0 && category === void 0) return void 0;
749
750
  return {
750
751
  code,
751
752
  category: normalizeErrorCategory(category, code),
752
- requestId: text$9(headers["x-request-id"]),
753
- retryAction: text$9(headers["x-vibedev-retry-action"])
753
+ requestId: text$10(headers["x-request-id"]),
754
+ retryAction: text$10(headers["x-vibedev-retry-action"])
754
755
  };
755
756
  }
756
757
  //#endregion
@@ -2402,7 +2403,9 @@ const EXPLANATIONS = {
2402
2403
  "gateway-unavailable": ["登录网关暂时不可用,请稍后重新登录。", "The sign-in gateway is temporarily unavailable. Start sign-in again later."],
2403
2404
  protocol: ["登录网关返回了无效的凭据格式,请稍后重新登录。", "The gateway returned an invalid credential response. Start sign-in again later."],
2404
2405
  storage: ["无法准备或保存本地登录凭据,请检查存储权限后重新登录。", "Local sign-in credentials could not be prepared or saved. Check storage permissions and start sign-in again."],
2405
- callback: ["无法启动或使用本地登录回调,请重新登录。", "The local sign-in callback could not be started or used. Start sign-in again."]
2406
+ callback: ["无法启动或使用本地登录回调,请重新登录。", "The local sign-in callback could not be started or used. Start sign-in again."],
2407
+ "edge-assertion": ["登录回调没有经过 VibeDev 远程入口(缺少或重复的身份断言),请从 VibeDev 远程入口打开这台主机后重新登录。", "The sign-in callback did not come through the VibeDev remote entry (its identity assertion is missing or repeated). Open this host through the VibeDev remote entry and start sign-in again."],
2408
+ "owner-mismatch": ["这台主机不是由你当前登录的账号打开的。请用打开这台主机的 VibeDev 账号登录。", "This host was not opened by the account you are signing in with. Sign in with the VibeDev account that opened this host."]
2406
2409
  };
2407
2410
  const STAGES = {
2408
2411
  listen: ["本地回调监听", "Local callback listener"],
@@ -2425,8 +2428,12 @@ const escapeHtml = (text) => text.replace(/[&<>"']/g, (character) => ({
2425
2428
  "'": "&#39;"
2426
2429
  })[character]);
2427
2430
  /** Only our fixed explanation and escaped safe enum/status fields reach the browser. */
2428
- function failurePage(attempt) {
2429
- return `<h1>Sign-in failed.</h1><p>${escapeHtml(failureMessage(attempt))}</p><p>请回到对话重新登录。</p>`;
2431
+ function failurePage(attempt, returnTo) {
2432
+ return `<h1>Sign-in failed.</h1><p>${escapeHtml(failureMessage(attempt))}</p>` + (returnTo === void 0 ? "<p>请回到对话重新登录。</p>" : returnLink(returnTo, "请回到 VibeDev 重新登录。", "Return to VibeDev and sign in again."));
2433
+ }
2434
+ /** A link back to the VibeDev page this remote sign-in started from. */
2435
+ function returnLink(url, chinese, english) {
2436
+ return `<p>${escapeHtml(chinese)} ${escapeHtml(english)}</p><p><a href="${escapeHtml(url)}">回到 VibeDev · Return to VibeDev</a></p>`;
2430
2437
  }
2431
2438
  /** Explicit log allowlist; adding fields to the public attempt never expands log output. */
2432
2439
  function attemptLog(event, attempt) {
@@ -2476,7 +2483,7 @@ function refusedRedirect(error) {
2476
2483
  return false;
2477
2484
  }
2478
2485
  /** Wait for work, ending early with the signal's reason when it aborts; the work itself keeps running. */
2479
- function untilAborted(work, signal) {
2486
+ function untilAborted$1(work, signal) {
2480
2487
  return new Promise((resolve, reject) => {
2481
2488
  const onAbort = () => {
2482
2489
  reject(signal.reason);
@@ -2607,7 +2614,7 @@ var ChatConsentHostService = class {
2607
2614
  if (signal.aborted) return stopped();
2608
2615
  let identity;
2609
2616
  try {
2610
- identity = await untilAborted(this.options.identity(), signal);
2617
+ identity = await untilAborted$1(this.options.identity(), signal);
2611
2618
  } catch {
2612
2619
  return signal.aborted ? stopped() : refuse("failed", { reason: "account-unavailable" });
2613
2620
  }
@@ -2804,7 +2811,7 @@ const unavailable = () => json$2(200, {
2804
2811
  unread: 0
2805
2812
  });
2806
2813
  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;
2814
+ const text$9 = (value) => typeof value === "string" ? value : void 0;
2808
2815
  const identifier = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
2809
2816
  /**
2810
2817
  * One announcement from the wire, with every field it needs and nothing else.
@@ -2815,9 +2822,9 @@ function parseAnnouncement(value) {
2815
2822
  const item = record$13(value);
2816
2823
  if (item === void 0) return void 0;
2817
2824
  const id = identifier(item.id);
2818
- const title = text$8(item.title);
2819
- const content = text$8(item.content);
2820
- const createdAt = text$8(item.created_at);
2825
+ const title = text$9(item.title);
2826
+ const content = text$9(item.content);
2827
+ const createdAt = text$9(item.created_at);
2821
2828
  if (id === void 0 || title === void 0 || content === void 0 || createdAt === void 0) return void 0;
2822
2829
  return {
2823
2830
  id,
@@ -2827,7 +2834,7 @@ function parseAnnouncement(value) {
2827
2834
  notifyMode: item.notify_mode === "popup" ? "popup" : "silent",
2828
2835
  ...typeof item.starts_at === "string" ? { startsAt: item.starts_at } : {},
2829
2836
  ...typeof item.ends_at === "string" ? { endsAt: item.ends_at } : {},
2830
- readAt: text$8(item.read_at) ?? null
2837
+ readAt: text$9(item.read_at) ?? null
2831
2838
  };
2832
2839
  }
2833
2840
  /**
@@ -5117,6 +5124,10 @@ function grantStorage(root, credentials, selectedOrigin = DEFAULT_GATEWAY_ORIGIN
5117
5124
  * 127.0.0.1; the gateway issues a plugin session (`client=vibedev-plugin`)
5118
5125
  * whose access token is refreshed with a rotating refresh token.
5119
5126
  *
5127
+ * Remote sign-in (0.11.7): a cloud host reached through the VibeDev remote entry sets `remoteBaseUrl`; the callback is
5128
+ * then `https://<host id>.h.vibedev.studio/api/dsh-vibedev/sign-in/callback` on the host's own web server, and the
5129
+ * redeem carries the remote entry's `X-VibeDev-Edge-Assertion` from that callback request as `edge_assertion`.
5130
+ *
5120
5131
  * Contract (gateway vibedev204):
5121
5132
  * - browser: `{origin}/vibedev-link?callback=http://127.0.0.1:<port>/<path>&state&response_type=code&code_challenge&code_challenge_method=S256&client=vibedev-plugin`
5122
5133
  * - `POST /api/v1/vibedev/link/redeem {code, code_verifier, token_type:'app', client, device_id, device_model, os_version}`
@@ -5124,13 +5135,64 @@ function grantStorage(root, credentials, selectedOrigin = DEFAULT_GATEWAY_ORIGIN
5124
5135
  * - `POST /api/v1/vibedev/app-token/revoke` (bearer or `{refresh_token}`): always 204
5125
5136
  * @module dsh-vibedev/auth/login
5126
5137
  */
5138
+ /** The host route the gateway returns a remote sign-in to (registered on the DSH web server). */
5139
+ const REMOTE_CALLBACK_PATH = "/api/dsh-vibedev/sign-in/callback";
5140
+ /** An assertion is a compact JWS; anything longer than this is not one. */
5141
+ const MAX_ASSERTION_LENGTH = 8192;
5142
+ /**
5143
+ * Read the remote entry's assertion from the raw header list: exactly one header, holding one compact JWS
5144
+ * (three base64url parts). Its signature is checked by the gateway, never here; it is never logged.
5145
+ * @param rawHeaders - Node's `rawHeaders` (name, value, name, value, …), where repeated headers stay apart.
5146
+ * @returns the assertion, or why there is no usable one.
5147
+ */
5148
+ function readEdgeAssertion(rawHeaders) {
5149
+ const values = [];
5150
+ for (let index = 0; index + 1 < rawHeaders.length; index += 2) if (rawHeaders[index]?.toLowerCase() === "x-vibedev-edge-assertion") values.push(rawHeaders[index + 1] ?? "");
5151
+ if (values.length === 0) return { kind: "missing" };
5152
+ if (values.length > 1) return { kind: "multiple" };
5153
+ const value = values[0].trim();
5154
+ if (value === "") return { kind: "missing" };
5155
+ if (value.length > MAX_ASSERTION_LENGTH || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(value)) return { kind: "malformed" };
5156
+ return {
5157
+ kind: "one",
5158
+ value
5159
+ };
5160
+ }
5161
+ /**
5162
+ * Check a configured remote sign-in origin: https, an origin only (no path, query, credentials).
5163
+ * @param value - the setting.
5164
+ * @returns the origin without a trailing slash, or undefined when blank.
5165
+ * @throws Error naming the rule it breaks.
5166
+ */
5167
+ function remoteSignInOrigin(value) {
5168
+ const trimmed = value?.trim() ?? "";
5169
+ if (trimmed === "") return void 0;
5170
+ let url;
5171
+ try {
5172
+ url = new URL(trimmed);
5173
+ } catch {
5174
+ throw new Error("remoteSignInBaseUrl must be an absolute https URL");
5175
+ }
5176
+ if (url.protocol !== "https:") throw new Error("remoteSignInBaseUrl must use https");
5177
+ if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "" || url.pathname !== "/" && url.pathname !== "") throw new Error("remoteSignInBaseUrl must be an origin only, such as https://<host id>.h.vibedev.studio");
5178
+ return url.origin;
5179
+ }
5127
5180
  const REFRESH_MARGIN_MS = 12e4;
5128
5181
  const CALLBACK_PATH = "/dsh-media/callback";
5182
+ /**
5183
+ * The error code of a gateway refusal body; nothing else of it is read. The gateway's standard envelope is
5184
+ * `{code: <HTTP status number>, message, reason: <error code>}` (`response.ErrorWithDetails`), so `reason` comes first;
5185
+ * a string `{code}` or `{error: {code}}` is still understood.
5186
+ */
5187
+ function refusalCode(body) {
5188
+ const raw = record$11(body);
5189
+ return text$8(raw?.reason) ?? text$8(raw?.code) ?? text$8(record$11(raw?.error)?.code);
5190
+ }
5129
5191
  function base64url(data) {
5130
5192
  return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5131
5193
  }
5132
5194
  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;
5195
+ const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
5134
5196
  /**
5135
5197
  * Read a token answer (`redeem` or `refresh`).
5136
5198
  * @param body - the parsed envelope `{code, data}` or a bare data object.
@@ -5141,16 +5203,16 @@ const text$7 = (value) => typeof value === "string" && value.trim() !== "" ? val
5141
5203
  function parseGrant(body, now, previous) {
5142
5204
  const envelope = record$11(body);
5143
5205
  const data = record$11(envelope?.data) ?? envelope;
5144
- const accessToken = text$7(data?.access_token);
5145
- const refreshToken = text$7(data?.refresh_token);
5206
+ const accessToken = text$8(data?.access_token);
5207
+ const refreshToken = text$8(data?.refresh_token);
5146
5208
  if (data === void 0 || accessToken === void 0 || refreshToken === void 0) return void 0;
5147
5209
  const seconds = (value, fallback) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
5148
5210
  const user = record$11(data.user);
5149
- const sessionId = text$7(data.session_id) ?? previous?.sessionId;
5211
+ const sessionId = text$8(data.session_id) ?? previous?.sessionId;
5150
5212
  const parsedUser = user === void 0 ? previous?.user : {
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) }
5213
+ ...text$8(user.id) === void 0 && typeof user.id !== "number" ? {} : { id: String(user.id) },
5214
+ ...text$8(user.email) === void 0 ? {} : { email: text$8(user.email) },
5215
+ ...text$8(user.nickname) === void 0 ? {} : { nickname: text$8(user.nickname) }
5154
5216
  };
5155
5217
  return {
5156
5218
  accessToken,
@@ -5199,6 +5261,8 @@ var PluginLogin = class {
5199
5261
  listeners = /* @__PURE__ */ new Set();
5200
5262
  now;
5201
5263
  origin;
5264
+ /** The host's public origin for a remote sign-in, else undefined (the desktop's loopback flow). */
5265
+ remoteBase;
5202
5266
  /**
5203
5267
  * @param options - gateway origin, storage and test seams.
5204
5268
  */
@@ -5206,6 +5270,12 @@ var PluginLogin = class {
5206
5270
  this.options = options;
5207
5271
  this.now = options.now ?? Date.now;
5208
5272
  this.origin = normalizeGatewayOrigin(options.origin);
5273
+ const remote = options.remoteBaseUrl?.trim().replace(/\/+$/, "");
5274
+ this.remoteBase = remote === void 0 || remote === "" ? void 0 : remote;
5275
+ }
5276
+ /** Whether sign-in returns to this host through the remote entry (a cloud host) rather than a loopback port. */
5277
+ get remote() {
5278
+ return this.remoteBase !== void 0;
5209
5279
  }
5210
5280
  readStored(notify) {
5211
5281
  if (this.reading !== void 0) return this.reading;
@@ -5399,7 +5469,7 @@ var PluginLogin = class {
5399
5469
  if (this.pending !== void 0 && !this.pending.committing && this.pending.expiresAt <= this.now()) this.pending.cancel("expired");
5400
5470
  const active = this.pending ?? this.beginSignIn();
5401
5471
  const started = await active.ready;
5402
- const opened = request.open === false || this.pending !== active ? false : await (this.options.openBrowser ?? openInBrowser)(started.url).catch(() => false);
5472
+ const opened = request.open === false || this.remoteBase !== void 0 || this.pending !== active ? false : await (this.options.openBrowser ?? openInBrowser)(started.url).catch(() => false);
5403
5473
  return {
5404
5474
  ...started,
5405
5475
  opened
@@ -5460,6 +5530,8 @@ var PluginLogin = class {
5460
5530
  ready,
5461
5531
  done,
5462
5532
  committing: false,
5533
+ remote: this.remoteBase !== void 0,
5534
+ receive: () => void 0,
5463
5535
  cancel: (phase) => {
5464
5536
  if (!finished && !active.committing) fail(phase === "expired" ? { errorCode: "timeout" } : {}, phase);
5465
5537
  }
@@ -5485,20 +5557,13 @@ var PluginLogin = class {
5485
5557
  if (!live()) return active;
5486
5558
  timer = setTimeout(() => active.cancel("expired"), Math.max(0, expiresAt - this.now()));
5487
5559
  timer.unref();
5488
- const callback = (request, response) => {
5489
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
5490
- if (url.pathname !== CALLBACK_PATH) {
5491
- response.writeHead(404).end();
5492
- return;
5493
- }
5494
- const answer = (status, title, body) => {
5495
- response.writeHead(status, {
5496
- "content-type": "text/html; charset=utf-8",
5497
- "cache-control": "no-store"
5498
- }).end(PAGE(title, body));
5499
- };
5500
- if (request.method !== "GET") {
5501
- response.setHeader("allow", "GET");
5560
+ const remote = this.remoteBase;
5561
+ const failed = (failure) => failurePage({
5562
+ ...this.attempt,
5563
+ ...failure
5564
+ }, remote === void 0 ? void 0 : `${remote}/`);
5565
+ const receive = (url, method, answer, edge) => {
5566
+ if (method !== "GET") {
5502
5567
  answer(405, "VibeDev", "<h1>Use GET for sign-in.</h1><p>请使用浏览器登录回调。</p>");
5503
5568
  return;
5504
5569
  }
@@ -5514,6 +5579,15 @@ var PluginLogin = class {
5514
5579
  return;
5515
5580
  }
5516
5581
  claimed = true;
5582
+ let edgeAssertion;
5583
+ if (remote !== void 0) {
5584
+ if (edge?.kind !== "one") {
5585
+ answer(400, "VibeDev", failed({ errorCode: "edge-assertion" }));
5586
+ fail({ errorCode: "edge-assertion" });
5587
+ return;
5588
+ }
5589
+ edgeAssertion = edge.value;
5590
+ }
5517
5591
  this.transition(id, {
5518
5592
  phase: "exchanging",
5519
5593
  stage: "device"
@@ -5534,7 +5608,8 @@ var PluginLogin = class {
5534
5608
  client: this.options.client ?? "vibedev-plugin",
5535
5609
  device_id: deviceId,
5536
5610
  device_model: `${platform()}-${arch()}`.slice(0, 128),
5537
- os_version: release().slice(0, 128)
5611
+ os_version: release().slice(0, 128),
5612
+ ...edgeAssertion === void 0 ? {} : { edge_assertion: edgeAssertion }
5538
5613
  }, void 0, signal);
5539
5614
  if (!live()) {
5540
5615
  response.body?.cancel().catch(() => void 0);
@@ -5546,12 +5621,11 @@ var PluginLogin = class {
5546
5621
  return;
5547
5622
  }
5548
5623
  if (!response.ok) {
5549
- response.body?.cancel().catch(() => void 0);
5550
- const errorCode = response.status === 429 || response.status >= 500 ? "gateway-unavailable" : response.status >= 400 && response.status < 500 ? "gateway-refused" : "protocol";
5551
- answer(502, "VibeDev", failurePage({
5552
- ...this.attempt,
5553
- errorCode
5554
- }));
5624
+ const owner = remote !== void 0 && response.status === 403 && refusalCode(await response.json().catch(() => void 0)) === "REMOTE_SIGN_IN_OWNER_MISMATCH";
5625
+ if (remote === void 0 || response.status !== 403) response.body?.cancel().catch(() => void 0);
5626
+ if (!live()) return;
5627
+ const errorCode = owner ? "owner-mismatch" : response.status === 429 || response.status >= 500 ? "gateway-unavailable" : response.status >= 400 && response.status < 500 ? "gateway-refused" : "protocol";
5628
+ answer(owner ? 403 : 502, "VibeDev", failed({ errorCode }));
5555
5629
  fail({ errorCode });
5556
5630
  return;
5557
5631
  }
@@ -5562,10 +5636,7 @@ var PluginLogin = class {
5562
5636
  if (!live()) return;
5563
5637
  const transport = transportFailure(error);
5564
5638
  const failure = transport.networkCode !== void 0 || transport.errorCode === "timeout" ? transport : { errorCode: "protocol" };
5565
- answer(502, "VibeDev", failurePage({
5566
- ...this.attempt,
5567
- ...failure
5568
- }));
5639
+ answer(502, "VibeDev", failed(failure));
5569
5640
  fail(failure);
5570
5641
  return;
5571
5642
  }
@@ -5573,10 +5644,7 @@ var PluginLogin = class {
5573
5644
  const envelope = record$11(body);
5574
5645
  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;
5575
5646
  if (parsed === void 0) {
5576
- answer(502, "VibeDev", failurePage({
5577
- ...this.attempt,
5578
- errorCode: "protocol"
5579
- }));
5647
+ answer(502, "VibeDev", failed({ errorCode: "protocol" }));
5580
5648
  fail({ errorCode: "protocol" });
5581
5649
  return;
5582
5650
  }
@@ -5591,19 +5659,58 @@ var PluginLogin = class {
5591
5659
  } catch (error) {
5592
5660
  if (finished || this.pending !== active) return;
5593
5661
  const failure = this.attempt?.stage === "device" || this.attempt?.stage === "persist" ? { errorCode: "storage" } : transportFailure(error);
5594
- answer(502, "VibeDev", failurePage({
5595
- ...this.attempt,
5596
- ...failure
5597
- }));
5662
+ answer(502, "VibeDev", failed(failure));
5598
5663
  fail(failure);
5599
5664
  return;
5600
5665
  }
5601
- answer(200, "VibeDev", "<h1>Signed in to VibeDev.</h1><p>已登录 VibeDev,可以关闭此页面,回到对话继续。</p><p>You can close this tab and return to the conversation.</p>");
5666
+ answer(200, "VibeDev", remote === void 0 ? "<h1>Signed in to VibeDev.</h1><p>已登录 VibeDev,可以关闭此页面,回到对话继续。</p><p>You can close this tab and return to the conversation.</p>" : `<h1>Signed in to VibeDev.</h1>${returnLink(`${remote}/`, "登录成功,可以关闭此页,回到 VibeDev 继续。", "You can close this tab and return to VibeDev.")}`);
5602
5667
  finish();
5603
5668
  this.transition(id, { phase: "succeeded" }, "terminal");
5604
5669
  resolveDone(grant);
5605
5670
  })();
5606
5671
  };
5672
+ active.receive = receive;
5673
+ const authorize = (callback) => {
5674
+ const url = `${this.origin}/vibedev-link?${new URLSearchParams({
5675
+ callback,
5676
+ state,
5677
+ response_type: "code",
5678
+ code_challenge: challenge,
5679
+ code_challenge_method: "S256",
5680
+ client: this.options.client ?? "vibedev-plugin"
5681
+ }).toString()}`;
5682
+ active.url = url;
5683
+ this.transition(id, {
5684
+ phase: "waiting-browser",
5685
+ stage: void 0
5686
+ });
5687
+ if (live()) resolveReady({
5688
+ url,
5689
+ expiresAt,
5690
+ done
5691
+ });
5692
+ };
5693
+ if (remote !== void 0) {
5694
+ if (this.options.remoteCallbackReady?.() === false) {
5695
+ fail({ errorCode: "callback" });
5696
+ return active;
5697
+ }
5698
+ authorize(`${remote}${REMOTE_CALLBACK_PATH}`);
5699
+ return active;
5700
+ }
5701
+ const callback = (request, response) => {
5702
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
5703
+ if (url.pathname !== CALLBACK_PATH) {
5704
+ response.writeHead(404).end();
5705
+ return;
5706
+ }
5707
+ receive(url, request.method, (status, title, body) => {
5708
+ response.writeHead(status, {
5709
+ "content-type": "text/html; charset=utf-8",
5710
+ "cache-control": "no-store"
5711
+ }).end(PAGE(title, body));
5712
+ });
5713
+ };
5607
5714
  try {
5608
5715
  server = createServer(callback);
5609
5716
  server.on("error", () => {
@@ -5618,30 +5725,41 @@ var PluginLogin = class {
5618
5725
  return;
5619
5726
  }
5620
5727
  const port = (server?.address()).port;
5621
- const url = `${this.origin}/vibedev-link?${new URLSearchParams({
5622
- callback: `http://127.0.0.1:${port}${CALLBACK_PATH}`,
5623
- state,
5624
- response_type: "code",
5625
- code_challenge: challenge,
5626
- code_challenge_method: "S256",
5627
- client: this.options.client ?? "vibedev-plugin"
5628
- }).toString()}`;
5629
- active.url = url;
5630
- this.transition(id, {
5631
- phase: "waiting-browser",
5632
- stage: void 0
5633
- });
5634
- if (live()) resolveReady({
5635
- url,
5636
- expiresAt,
5637
- done
5638
- });
5728
+ authorize(`http://127.0.0.1:${port}${CALLBACK_PATH}`);
5639
5729
  });
5640
5730
  } catch {
5641
5731
  if (!finished) fail({ errorCode: "callback" });
5642
5732
  }
5643
5733
  return active;
5644
5734
  }
5735
+ /**
5736
+ * The remote callback route's request (`GET /api/dsh-vibedev/sign-in/callback` on the host's web server): finish the
5737
+ * waiting remote sign-in, or answer why it cannot be finished. Always answers.
5738
+ * @param url - the request URL (only its query is read).
5739
+ * @param method - the request method.
5740
+ * @param edge - what the request carried in `X-VibeDev-Edge-Assertion` (see {@link readEdgeAssertion}).
5741
+ * @returns the page to answer with.
5742
+ */
5743
+ receiveRemoteCallback(url, method, edge) {
5744
+ const page = (status, title, body) => ({
5745
+ status,
5746
+ html: PAGE(title, body)
5747
+ });
5748
+ const active = this.pending;
5749
+ const back = this.remoteBase === void 0 ? "" : returnLink(`${this.remoteBase}/`, "请回到 VibeDev 重新登录。", "Return to VibeDev and sign in again.");
5750
+ if (active === void 0 || !active.remote) return Promise.resolve(page(410, "VibeDev", `<h1>This sign-in link has already been used.</h1><p>此登录链接已使用过或已失效。</p>${back}`));
5751
+ return new Promise((resolve) => {
5752
+ let answered = false;
5753
+ const answer = (status, title, body) => {
5754
+ if (!answered) {
5755
+ answered = true;
5756
+ resolve(page(status, title, body));
5757
+ }
5758
+ };
5759
+ active.done.then(() => answer(200, "VibeDev", "<h1>Signed in to VibeDev.</h1>"), () => answer(410, "VibeDev", `<h1>Sign-in could not be completed.</h1><p>登录已取消或已超时。</p>${back}`));
5760
+ active.receive(url, method, answer, edge);
5761
+ });
5762
+ }
5645
5763
  /** Sign out: revoke the session at the gateway (best effort) and forget it. */
5646
5764
  async signOut() {
5647
5765
  const attemptId = this.attempt?.id;
@@ -5664,6 +5782,43 @@ var PluginLogin = class {
5664
5782
  }
5665
5783
  };
5666
5784
  //#endregion
5785
+ //#region src/auth/remote-callback.ts
5786
+ const HEADERS = {
5787
+ "content-type": "text/html; charset=utf-8",
5788
+ "cache-control": "no-store",
5789
+ "referrer-policy": "no-referrer"
5790
+ };
5791
+ /**
5792
+ * The route's handler.
5793
+ * @param login - the plugin's sign-in.
5794
+ * @returns a web-server handler.
5795
+ */
5796
+ function remoteCallbackHandler(login) {
5797
+ return async (req, res, peer) => {
5798
+ if (peer === void 0) {
5799
+ res.writeHead(401, HEADERS).end("<!doctype html><meta charset=\"utf-8\"><h1>Unauthorized</h1>");
5800
+ return;
5801
+ }
5802
+ const url = new URL(req.url ?? "/", "http://host");
5803
+ const page = await login.receiveRemoteCallback(url, req.method, readEdgeAssertion(req.rawHeaders));
5804
+ res.writeHead(page.status, HEADERS).end(page.html);
5805
+ };
5806
+ }
5807
+ /**
5808
+ * Register the route.
5809
+ * @param server - the DSH web server.
5810
+ * @param login - the plugin's sign-in.
5811
+ * @returns the disposer.
5812
+ */
5813
+ function registerRemoteCallback(server, login) {
5814
+ return server.register({
5815
+ kind: "exact",
5816
+ path: REMOTE_CALLBACK_PATH,
5817
+ auth: "required",
5818
+ handler: remoteCallbackHandler(login)
5819
+ });
5820
+ }
5821
+ //#endregion
5667
5822
  //#region src/llm/limits.ts
5668
5823
  /**
5669
5824
  * Request limits the gateway adapter and its copied conversion modules read.
@@ -5816,7 +5971,7 @@ function reasoningLevelsOf(value) {
5816
5971
  * @param body - the decoded response: `{object, data: [...]}` or a bare array.
5817
5972
  * @returns the chat models, in catalog order; entries that are not chat models or cannot be called are left out.
5818
5973
  */
5819
- function parseCatalog(body) {
5974
+ function parseCatalog$1(body) {
5820
5975
  const list = Array.isArray(body) ? body : record$10(body)?.data;
5821
5976
  if (!Array.isArray(list)) return [];
5822
5977
  const models = [];
@@ -6123,6 +6278,141 @@ function toPiAssistant(message, onDegrade) {
6123
6278
  }
6124
6279
  }
6125
6280
  //#endregion
6281
+ //#region src/llm/file-placement.ts
6282
+ /** Chat Completions places tool-result media in the SDK's adjacent user message. */
6283
+ const TOOL_RESULT_MEDIA_TEXT = "Attached media from tool result:";
6284
+ const imageHeading = "Attached image(s) from tool result:";
6285
+ const bridge = "I have processed the tool results.";
6286
+ function isRecord$1(value) {
6287
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6288
+ }
6289
+ /**
6290
+ * Visit the user and tool text fields in which a generated attachment caption may appear.
6291
+ * @param messages - SDK Chat Completions messages.
6292
+ * @param visit - replace the visible text; content index -1 identifies a scalar string.
6293
+ * @returns messages with only the visited text fields replaced.
6294
+ */
6295
+ function mapMediaText(messages, visit) {
6296
+ return messages.map((message, index) => {
6297
+ if (!isRecord$1(message) || message.role !== "user" && message.role !== "tool") return message;
6298
+ const role = message.role;
6299
+ if (typeof message.content === "string") return {
6300
+ ...message,
6301
+ content: visit(message.content, role, index, -1)
6302
+ };
6303
+ if (!Array.isArray(message.content)) return message;
6304
+ const content = message.content.map((part, i) => isRecord$1(part) && part.type === "text" && typeof part.text === "string" ? {
6305
+ ...part,
6306
+ text: visit(part.text, role, index, i)
6307
+ } : part);
6308
+ return {
6309
+ ...message,
6310
+ content
6311
+ };
6312
+ });
6313
+ }
6314
+ /**
6315
+ * Strip every native file from message content, including in an unsupported role.
6316
+ * @param messages - SDK messages before placement of verified files.
6317
+ * @returns the filtered messages, or undefined if the body already has no files.
6318
+ */
6319
+ function stripVisibleNativeFiles(messages) {
6320
+ let changed = false;
6321
+ const stripped = messages.map((message) => {
6322
+ if (!isRecord$1(message) || !Array.isArray(message.content)) return message;
6323
+ const content = message.content.filter((part) => !isRecord$1(part) || part.type !== "file");
6324
+ if (content.length === message.content.length) return message;
6325
+ changed = true;
6326
+ return {
6327
+ ...message,
6328
+ content
6329
+ };
6330
+ });
6331
+ return changed ? stripped : void 0;
6332
+ }
6333
+ function toolMessage(item) {
6334
+ return isRecord$1(item) && item.role === "tool";
6335
+ }
6336
+ function imageFollowUp(item) {
6337
+ if (!isRecord$1(item) || item.role !== "user" || !Array.isArray(item.content)) return false;
6338
+ const first = item.content[0];
6339
+ return isRecord$1(first) && first.type === "text" && first.text === imageHeading && item.content.some((part) => isRecord$1(part) && part.type === "image_url");
6340
+ }
6341
+ /** Resolve exact user parts or tool-result lines. All other messages, calls and image parts keep their order. */
6342
+ function placeNativeFiles(payload, resolve, assistantAfterToolResult = false) {
6343
+ if (!isRecord$1(payload) || !Array.isArray(payload.messages)) return void 0;
6344
+ const original = payload.messages;
6345
+ const messages = [];
6346
+ let changed = false;
6347
+ let index = 0;
6348
+ while (index < original.length) {
6349
+ const message = original[index];
6350
+ if (!toolMessage(message)) {
6351
+ if (isRecord$1(message) && message.role === "user" && Array.isArray(message.content)) {
6352
+ const content = message.content.flatMap((part) => {
6353
+ if (!isRecord$1(part) || part.type !== "text" || typeof part.text !== "string") return [part];
6354
+ const replacement = resolve(part.text, "user", index);
6355
+ if (replacement === void 0) return [part];
6356
+ changed = true;
6357
+ return [...replacement];
6358
+ });
6359
+ messages.push({
6360
+ ...message,
6361
+ content
6362
+ });
6363
+ } else messages.push(message);
6364
+ index++;
6365
+ continue;
6366
+ }
6367
+ const moved = [];
6368
+ for (; index < original.length && toolMessage(original[index]); index++) {
6369
+ const tool = original[index];
6370
+ let stripped = false;
6371
+ const keep = (line) => {
6372
+ const replacement = resolve(line, "tool", index);
6373
+ if (replacement === void 0) return true;
6374
+ moved.push(...replacement);
6375
+ stripped = true;
6376
+ return false;
6377
+ };
6378
+ const content = typeof tool.content === "string" ? tool.content.split("\n").filter(keep).join("\n") || "(see attached media)" : Array.isArray(tool.content) ? tool.content.filter((part) => !(isRecord$1(part) && part.type === "text" && typeof part.text === "string") || keep(part.text)) : tool.content;
6379
+ changed ||= stripped;
6380
+ messages.push(stripped ? {
6381
+ ...tool,
6382
+ content
6383
+ } : tool);
6384
+ }
6385
+ if (!moved.length) continue;
6386
+ const next = original[index];
6387
+ const hasBridge = isRecord$1(next) && next.role === "assistant" && next.content === bridge;
6388
+ const followUp = original[index + Number(hasBridge)];
6389
+ if (imageFollowUp(followUp)) {
6390
+ if (hasBridge) messages.push(next);
6391
+ messages.push({
6392
+ ...followUp,
6393
+ content: [...followUp.content, ...moved]
6394
+ });
6395
+ index += 1 + Number(hasBridge);
6396
+ } else {
6397
+ if (assistantAfterToolResult) messages.push({
6398
+ role: "assistant",
6399
+ content: bridge
6400
+ });
6401
+ messages.push({
6402
+ role: "user",
6403
+ content: [{
6404
+ type: "text",
6405
+ text: TOOL_RESULT_MEDIA_TEXT
6406
+ }, ...moved]
6407
+ });
6408
+ }
6409
+ }
6410
+ return changed ? {
6411
+ ...payload,
6412
+ messages
6413
+ } : void 0;
6414
+ }
6415
+ //#endregion
6126
6416
  //#region src/llm/native-files.ts
6127
6417
  /**
6128
6418
  * Native audio/video delivery for the gateway's Chat Completions models.
@@ -6188,12 +6478,6 @@ const GEMINI_INLINE_MEDIA_TYPES = Object.freeze([
6188
6478
  "audio/ogg",
6189
6479
  "audio/flac"
6190
6480
  ]);
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
6481
  /**
6198
6482
  * Text part that holds one delivered file's place until the payload hook replaces it. Deterministic, so identical
6199
6483
  * histories convert identically, and NUL-delimited, so no user-authored text block equals it.
@@ -6257,8 +6541,8 @@ async function readNativeFiles(messages, attachments, files, signal) {
6257
6541
  }
6258
6542
  try {
6259
6543
  const file = await readFileRequest.call(attachments, ref, {
6260
- ...target,
6261
- maxBytes
6544
+ maxBytes,
6545
+ ...target.mediaTypes === void 0 ? {} : { mediaTypes: target.mediaTypes }
6262
6546
  }, signal);
6263
6547
  if (!(file.data instanceof Uint8Array) || typeof file.mediaType !== "string" || file.mediaType === "") throw new Error("the attachment provider returned no bytes or media type");
6264
6548
  if (file.data.byteLength > maxBytes) throw new Error(`the file read has ${file.data.byteLength} bytes, over the ${maxBytes}-byte native file limit`);
@@ -6291,143 +6575,11 @@ function nativeFilePart(file) {
6291
6575
  file: { file_data: `data:${file.mediaType};base64,${Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength).toString("base64")}` }
6292
6576
  };
6293
6577
  }
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
- */
6578
+ /** Place each marker from a request projected by a legacy host. */
6371
6579
  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;
6580
+ if (!delivered.length) return void 0;
6581
+ const markers = new Map(delivered.map((part, index) => [nativeFileMarker(index), [part]]));
6582
+ return placeNativeFiles(payload, (value) => markers.get(value), options.assistantAfterToolResult);
6431
6583
  }
6432
6584
  //#endregion
6433
6585
  //#region src/llm/context.ts
@@ -6481,7 +6633,7 @@ function assertSupportedHistory(messages) {
6481
6633
  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");
6482
6634
  }
6483
6635
  }
6484
- function userContent(blocks, requestImages, resolveImageAccess, files) {
6636
+ function userContent(blocks, requestImages, resolveImageAccess, files, isWireMarker) {
6485
6637
  const content = [];
6486
6638
  let markers = 0;
6487
6639
  for (const block of blocks) switch (block.type) {
@@ -6490,6 +6642,7 @@ function userContent(blocks, requestImages, resolveImageAccess, files) {
6490
6642
  type: "text",
6491
6643
  text: block.text
6492
6644
  });
6645
+ if (isWireMarker?.(block.text)) markers++;
6493
6646
  break;
6494
6647
  case "file": {
6495
6648
  const file = files?.read.get(block.attachment.attachmentId);
@@ -6525,17 +6678,18 @@ function userContent(blocks, requestImages, resolveImageAccess, files) {
6525
6678
  * text only), dropping the marker's line. A text-only result keeps its text joined as without files, with the markers
6526
6679
  * after it, so the tool text the model reads is the same whether or not a file went along.
6527
6680
  */
6528
- function toolContent(blocks, requestImages, resolveImageAccess, files) {
6681
+ function toolContent(blocks, requestImages, resolveImageAccess, files, isWireMarker) {
6529
6682
  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;
6683
+ const content = userContent(blocks, requestImages, resolveImageAccess, files, isWireMarker);
6684
+ if (typeof content === "string") return content;
6532
6685
  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("");
6686
+ const markers = new Set(files?.delivered.slice(before).map((_, index) => nativeFileMarker(before + index)));
6687
+ const isMarker = (block) => markers.has(block.text) || isWireMarker?.(block.text) === true;
6688
+ const text = content.filter((block) => !isMarker(block)).map((block) => block.text).join("");
6535
6689
  return [...text.length > 0 ? [{
6536
6690
  type: "text",
6537
6691
  text
6538
- }] : [], ...content.filter((block) => markers.has(block.text))];
6692
+ }] : [], ...content.filter(isMarker)];
6539
6693
  }
6540
6694
  function collectImageRefs(blocks, refs) {
6541
6695
  for (const block of blocks) if (block.type === "image") {
@@ -6674,10 +6828,10 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
6674
6828
  for (const message of exactMessages) {
6675
6829
  if (appendSystemOrAssistant(message, messages, toolNames, onReplayDegrade)) continue;
6676
6830
  if (message.role === "tool") {
6677
- messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files)));
6831
+ messages.push(toolResultOf(message, toolNames, toolContent(message.content, requestImages, resolveImageAccess, files, images.isWireMarker)));
6678
6832
  continue;
6679
6833
  }
6680
- const content = userContent(message.content, requestImages, resolveImageAccess, files);
6834
+ const content = userContent(message.content, requestImages, resolveImageAccess, files, images.isWireMarker);
6681
6835
  messages.push({
6682
6836
  role: "user",
6683
6837
  content,
@@ -6687,6 +6841,369 @@ async function toPiContextWithImages(options, images, onReplayDegrade) {
6687
6841
  return piContext(split.systemPrompt, options, messages);
6688
6842
  }
6689
6843
  //#endregion
6844
+ //#region src/llm/verified-files.ts
6845
+ /** Request-local projection and final Chat Completions file/handle reconciliation. Mirrored in llm-pi-ai. */
6846
+ function fileReceiptAttempt(observe) {
6847
+ if (!observe) return void 0;
6848
+ const attemptId = randomUUID();
6849
+ let snapshot;
6850
+ function emit(stage, httpStatus) {
6851
+ if (!snapshot) return;
6852
+ try {
6853
+ observe({
6854
+ attemptId,
6855
+ ...snapshot,
6856
+ stage,
6857
+ ...httpStatus === void 0 ? {} : { httpStatus }
6858
+ });
6859
+ } catch {}
6860
+ }
6861
+ return {
6862
+ payload: (files) => {
6863
+ snapshot = {
6864
+ fileCount: files.length,
6865
+ files: files.slice(0, 64)
6866
+ };
6867
+ emit("payload");
6868
+ },
6869
+ fetching: () => {
6870
+ emit("fetch");
6871
+ },
6872
+ responded: (status) => {
6873
+ emit("response", status);
6874
+ }
6875
+ };
6876
+ }
6877
+ const mismatch = "the stored attachment does not match its reference";
6878
+ const mapping = "the SDK could not verify the attachment position";
6879
+ const budget = "the request media budget is full; read this attachment separately";
6880
+ const noSelection = "the selected attachment is missing from this request";
6881
+ const clipName = /^clip-([a-f0-9]{12})-(\d+)-(\d+)ms\.mp4$/u;
6882
+ const kindOf$1 = (name) => {
6883
+ if (/\.(?:mp4|m4v|mov|webm|mkv|avi|mpeg|mpg|3gp|flv|wmv)$/iu.test(name)) return "video";
6884
+ if (/\.(?:mp3|wav|m4a|aac|flac|ogg|oga|opus|aiff|aif|amr|wma)$/iu.test(name)) return "audio";
6885
+ };
6886
+ const text$7 = (value) => ({
6887
+ type: "text",
6888
+ text: value
6889
+ });
6890
+ const referenceOnly = (label, why) => `${label} — reference only in this request (${why}).`;
6891
+ function describe(ref, mediaId, occurrence) {
6892
+ const range = occurrence?.rangeLabel && clipName.exec(ref.name);
6893
+ const name = JSON.stringify(ref.name);
6894
+ const label = occurrence?.rangeLabel ?? occurrence?.label ?? `Attachment ${mediaId}`;
6895
+ if (range && !label.includes(ref.name)) return `${label} · source ${range[1]} [${range[2]}, ${range[3]}) ms · ${name}`;
6896
+ return label.includes(ref.name) ? label : `${label} · ${name}`;
6897
+ }
6898
+ function eligibleTarget(slot, options) {
6899
+ const ref = slot.file.attachment;
6900
+ let target;
6901
+ try {
6902
+ target = options.target(ref);
6903
+ } catch {}
6904
+ const kind = kindOf$1(ref.name);
6905
+ if (!target || !Number.isSafeInteger(target.maxBytes) || target.maxBytes < 0 || !kind || options.modalities && !options.modalities.includes(kind)) slot.reason = "the route does not support this attachment";
6906
+ else if (!Number.isSafeInteger(ref.bytes) || ref.bytes < 0) slot.reason = mismatch;
6907
+ else if (ref.bytes > Math.min(target.maxBytes, options.maxBytes)) slot.reason = "the single-file size limit was exceeded";
6908
+ else slot.target = {
6909
+ maxBytes: Math.min(target.maxBytes, options.maxBytes),
6910
+ mediaTypes: target.mediaTypes ?? options.mediaTypes
6911
+ };
6912
+ }
6913
+ /** A projected request can only lose files here. For a direct call, choose the last eligible occurrence per ID. */
6914
+ function select(slots, unique, options) {
6915
+ const last = /* @__PURE__ */ new Map();
6916
+ const conflicts = /* @__PURE__ */ new Set();
6917
+ for (const slot of slots) {
6918
+ if (slot.reason) continue;
6919
+ eligibleTarget(slot, options);
6920
+ if (slot.reason) continue;
6921
+ const ref = slot.file.attachment;
6922
+ const previous = last.get(ref.attachmentId);
6923
+ if (previous && (previous.file.attachment.bytes !== ref.bytes || kindOf$1(previous.file.attachment.name) !== kindOf$1(ref.name))) conflicts.add(ref.attachmentId);
6924
+ last.set(ref.attachmentId, slot);
6925
+ }
6926
+ let total = 0;
6927
+ const candidates = [];
6928
+ for (const slot of slots) {
6929
+ if (slot.reason) continue;
6930
+ const ref = slot.file.attachment;
6931
+ const representative = last.get(ref.attachmentId);
6932
+ if (conflicts.has(ref.attachmentId)) slot.reason = mismatch;
6933
+ else if (unique && slot !== representative) slot.representative = representative;
6934
+ else {
6935
+ candidates.push(slot);
6936
+ total += 4 * Math.ceil(ref.bytes / 3);
6937
+ }
6938
+ }
6939
+ for (const slot of candidates) {
6940
+ if (total <= options.maxEncoded) break;
6941
+ slot.reason = budget;
6942
+ total -= 4 * Math.ceil(slot.file.attachment.bytes / 3);
6943
+ }
6944
+ for (const slot of slots) if (!last.has(slot.file.attachment.attachmentId)) last.set(slot.file.attachment.attachmentId, slot);
6945
+ return last;
6946
+ }
6947
+ async function readSelected(slots, options) {
6948
+ const read = options.attachments?.readFileRequest;
6949
+ const byId = /* @__PURE__ */ new Map();
6950
+ for (const slot of slots) {
6951
+ if (slot.reason || slot.representative) continue;
6952
+ options.signal.throwIfAborted();
6953
+ const ref = slot.file.attachment;
6954
+ let result = byId.get(ref.attachmentId);
6955
+ if (!result) {
6956
+ if (typeof read !== "function") result = "the attachment service cannot read request files";
6957
+ else try {
6958
+ const file = await read.call(options.attachments, ref, slot.target, options.signal);
6959
+ options.signal.throwIfAborted();
6960
+ if (!(file.data instanceof Uint8Array) || file.data.byteLength !== ref.bytes || file.bytes !== ref.bytes || file.attachment?.attachmentId !== ref.attachmentId || file.attachment.bytes !== ref.bytes) result = mismatch;
6961
+ else if (!slot.target.mediaTypes.includes(file.mediaType) || file.mediaType.split("/")[0] !== kindOf$1(ref.name)) result = "the stored media type does not match this file or route";
6962
+ else if (/^sha256:[a-f0-9]{64}$/u.test(ref.attachmentId) && `sha256:${createHash("sha256").update(file.data).digest("hex")}` !== ref.attachmentId) result = mismatch;
6963
+ else result = {
6964
+ type: "file",
6965
+ file: { file_data: `data:${file.mediaType};base64,${Buffer.from(file.data.buffer, file.data.byteOffset, file.data.byteLength).toString("base64")}` }
6966
+ };
6967
+ } catch (error) {
6968
+ options.signal.throwIfAborted();
6969
+ const code = isRecord$1(error) ? error.code : void 0;
6970
+ result = code === "ATTACHMENT_CORRUPT" ? mismatch : code === "ATTACHMENT_PROJECTION_UNSUPPORTED" ? "the stored media type or size is unsupported" : "the stored attachment could not be read";
6971
+ }
6972
+ byId.set(ref.attachmentId, result);
6973
+ }
6974
+ if (typeof result === "string") slot.reason = result;
6975
+ else slot.part = slot.range ? {
6976
+ ...result,
6977
+ file: {
6978
+ ...result.file,
6979
+ filename: ref.name
6980
+ }
6981
+ } : result;
6982
+ }
6983
+ }
6984
+ /** Replace only this attempt's tokens, wherever the SDK stored a string. Original payload/history stay immutable. */
6985
+ function mapStrings(value, visit) {
6986
+ if (typeof value === "string") return visit(value);
6987
+ if (Array.isArray(value)) return value.map((part) => mapStrings(part, visit));
6988
+ if (!isRecord$1(value)) return value;
6989
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapStrings(item, visit)]));
6990
+ }
6991
+ function receiptFiles(slots, invalid) {
6992
+ return slots.map((slot, index) => {
6993
+ const rep = slot.representative ?? slot;
6994
+ return {
6995
+ position: index + 1,
6996
+ mediaId: /^m[1-9]\d*$/u.test(slot.mediaId) ? slot.mediaId : `m${index + 1}`,
6997
+ bytes: Number.isSafeInteger(slot.file.attachment.bytes) && slot.file.attachment.bytes >= 0 ? slot.file.attachment.bytes : 0,
6998
+ state: rep.part && !invalid.has(rep) ? slot.representative ? "shared" : "included" : "reference-only"
6999
+ };
7000
+ });
7001
+ }
7002
+ /** Files in an actual SDK-supplied content array, not similarly spelled text inside tool arguments. */
7003
+ function payloadFiles(payload) {
7004
+ if (!isRecord$1(payload) || !Array.isArray(payload.messages)) return [];
7005
+ return payload.messages.flatMap((message) => isRecord$1(message) && Array.isArray(message.content) ? message.content.filter((part) => isRecord$1(part) && part.type === "file") : []);
7006
+ }
7007
+ function paired(anchor, file) {
7008
+ if (!file || anchor.role !== file.role || anchor.messageIndex !== file.messageIndex) return false;
7009
+ if (file.role === "user") return anchor.atEnd && anchor.contentIndex >= 0 && file.contentIndex === anchor.contentIndex + 1;
7010
+ return anchor.contentIndex < file.contentIndex || anchor.contentIndex === file.contentIndex && anchor.offset < file.offset;
7011
+ }
7012
+ function reconciler(prefix, markers, captions, slots, onDegrade) {
7013
+ return (payload, assistantAfterToolResult = false, written) => {
7014
+ const owners = /* @__PURE__ */ new Map();
7015
+ const invalid = /* @__PURE__ */ new Set();
7016
+ const ordered = [];
7017
+ if (!isRecord$1(payload) || !Array.isArray(payload.messages)) throw new Error("Unable to verify the Chat Completions message envelope.");
7018
+ if (!markers.size) {
7019
+ const messages = stripVisibleNativeFiles(payload.messages);
7020
+ written?.(receiptFiles(slots, invalid));
7021
+ return messages ? {
7022
+ ...payload,
7023
+ messages
7024
+ } : void 0;
7025
+ }
7026
+ placeNativeFiles(payload, (value, role, index) => {
7027
+ const slot = markers.get(value);
7028
+ if (!slot) return void 0;
7029
+ if (slot.role !== role || owners.has(slot)) invalid.add(slot);
7030
+ owners.set(slot, index);
7031
+ ordered.push(slot);
7032
+ return [];
7033
+ });
7034
+ const counts = /* @__PURE__ */ new Map();
7035
+ const locations = /* @__PURE__ */ new Map();
7036
+ const tokens = new RegExp(`${prefix}(?:f|h)\\d+!`, "gu");
7037
+ mapMediaText(payload.messages, (value, role, messageIndex, contentIndex) => {
7038
+ if (value.includes(prefix)) for (const match of value.matchAll(tokens)) {
7039
+ const token = match[0];
7040
+ counts.set(token, (counts.get(token) ?? 0) + 1);
7041
+ locations.set(token, {
7042
+ role,
7043
+ messageIndex,
7044
+ contentIndex,
7045
+ offset: match.index,
7046
+ atEnd: match.index + token.length === value.length
7047
+ });
7048
+ }
7049
+ return value;
7050
+ });
7051
+ for (const [marker, slot] of markers) if (counts.get(marker) !== 1 || !owners.has(slot)) invalid.add(slot);
7052
+ const absent = [];
7053
+ const fileLocation = new Map([...markers].map(([marker, slot]) => [slot, locations.get(marker)]));
7054
+ for (const caption of captions) {
7055
+ const anchor = locations.get(caption.marker);
7056
+ if (!anchor || anchor.role !== caption.role) {
7057
+ invalid.add(caption.slot);
7058
+ absent.push(caption);
7059
+ } else if (counts.get(caption.marker) !== 1 || caption.anchor && !paired(anchor, fileLocation.get(caption.slot))) invalid.add(caption.slot);
7060
+ }
7061
+ const actual = ordered.filter((slot) => !invalid.has(slot));
7062
+ if ([...markers.values()].filter((slot) => !invalid.has(slot)).some((slot, i) => slot !== actual[i])) for (const slot of markers.values()) invalid.add(slot);
7063
+ const placement = placeNativeFiles(payload, (value, role) => {
7064
+ const slot = markers.get(value);
7065
+ if (!slot) return void 0;
7066
+ if (invalid.has(slot)) return [];
7067
+ return role === "tool" || slot.range ? [text$7(slot.label), slot.part] : [slot.part];
7068
+ }, assistantAfterToolResult);
7069
+ let messages = isRecord$1(placement) && Array.isArray(placement.messages) ? placement.messages : payload.messages;
7070
+ const expected = [...markers.values()].filter((slot) => !invalid.has(slot));
7071
+ const materialized = payloadFiles({ messages });
7072
+ if (materialized.length !== expected.length || materialized.some((part, index) => part !== expected[index]?.part)) {
7073
+ for (const slot of markers.values()) invalid.add(slot);
7074
+ messages = stripVisibleNativeFiles(payload.messages) ?? payload.messages;
7075
+ }
7076
+ const status = /* @__PURE__ */ new Map();
7077
+ for (const caption of captions) {
7078
+ const delivery = caption.duplicate ? `same content as ${caption.slot.mediaId}, included once` : "included";
7079
+ status.set(caption.marker, invalid.has(caption.slot) ? referenceOnly(caption.label, mapping) : `${caption.label} — ${delivery} in this request.`);
7080
+ }
7081
+ for (const caption of absent) status.delete(caption.marker);
7082
+ for (const slot of invalid) onDegrade?.(slot.mediaId, mapping);
7083
+ const residue = new RegExp(`${prefix.slice(1)}(?:[fh]\\d*!?)?`, "gu");
7084
+ messages = mapMediaText(messages, (value) => value.includes(prefix) ? value.replace(tokens, (token) => status.get(token) ?? "") : value);
7085
+ const cleaned = mapStrings({
7086
+ ...payload,
7087
+ messages
7088
+ }, (value) => value.includes(prefix.slice(1)) ? value.replace(tokens, "").replace(residue, "") : value);
7089
+ if (absent.length) {
7090
+ const output = cleaned.messages;
7091
+ if (assistantAfterToolResult && isRecord$1(output.at(-1)) && output.at(-1).role === "tool") output.push({
7092
+ role: "assistant",
7093
+ content: "I have processed the tool results."
7094
+ });
7095
+ output.push({
7096
+ role: "user",
7097
+ content: [...new Set(absent.map((item) => referenceOnly(item.label, mapping)))].join("\n")
7098
+ });
7099
+ }
7100
+ written?.(receiptFiles(slots, invalid));
7101
+ return cleaned;
7102
+ };
7103
+ }
7104
+ /** Prepare only the blocks already handed to this adapter. An old host's absent policy keeps its legacy path. */
7105
+ async function prepareVerifiedFiles(request, options) {
7106
+ if (request.nativeFilePolicy !== "unique-v1" && (request.nativeFilePolicy !== "legacy" || !request.nativeFileOccurrences)) return void 0;
7107
+ const occurrences = request.nativeFileOccurrences;
7108
+ const fileEntries = new Map(occurrences?.filter((item) => item.file && item.status === "selected").map((item) => [item.file, item]));
7109
+ const handles = new Map(occurrences?.filter((item) => item.status === "selected" || item.status === "duplicate").map((item) => [item.handle, item]));
7110
+ const missing = new Set(handles.keys());
7111
+ const slots = [];
7112
+ const at = /* @__PURE__ */ new Map();
7113
+ const ids = /* @__PURE__ */ new Map();
7114
+ const messages = request.messages.map((message) => {
7115
+ if (message.role !== "user" && message.role !== "tool") return message;
7116
+ const role = message.role;
7117
+ return {
7118
+ ...message,
7119
+ content: message.content.map((block, position) => {
7120
+ if (block.type === "text") missing.delete(block);
7121
+ if (block.type !== "file") return block;
7122
+ const ref = block.attachment;
7123
+ const entry = fileEntries.get(block);
7124
+ const mediaId = entry?.mediaId ?? ids.get(ref.attachmentId) ?? `m${ids.size + 1}`;
7125
+ ids.set(ref.attachmentId, mediaId);
7126
+ const file = { ...block };
7127
+ const slot = {
7128
+ file,
7129
+ role,
7130
+ mediaId,
7131
+ label: describe(ref, mediaId, entry),
7132
+ range: !!entry?.rangeLabel
7133
+ };
7134
+ if (request.purpose !== void 0) slot.reason = "auxiliary requests use file references";
7135
+ else if (occurrences && (!entry || entry.attachmentId !== ref.attachmentId || message.content[position - 1] !== entry.handle)) slot.reason = noSelection;
7136
+ slots.push(slot);
7137
+ at.set(file, slot);
7138
+ return file;
7139
+ })
7140
+ };
7141
+ });
7142
+ if (!slots.length && !occurrences?.length) return void 0;
7143
+ const detached = [...missing].map((handle) => handles.get(handle));
7144
+ if (detached.length) {
7145
+ const affected = new Set(detached.map((item) => item.attachmentId));
7146
+ for (const slot of slots) if (affected.has(slot.file.attachment.attachmentId)) slot.reason = mapping;
7147
+ }
7148
+ const last = select(slots, request.nativeFilePolicy === "unique-v1", options);
7149
+ await readSelected(slots, options);
7150
+ const originalToSlot = /* @__PURE__ */ new Map();
7151
+ let index = 0;
7152
+ for (const message of request.messages) if (message.role === "user" || message.role === "tool") {
7153
+ for (const block of message.content) if (block.type === "file") originalToSlot.set(block, slots[index++]);
7154
+ }
7155
+ const prefix = `!dsh-native-file-${randomUUID()}-`;
7156
+ const markers = /* @__PURE__ */ new Map();
7157
+ const captions = [];
7158
+ const feedback = (slot, role, label, duplicate, anchor) => {
7159
+ const rep = slot?.representative ?? slot;
7160
+ if (!rep?.part) return referenceOnly(label, rep?.reason ?? noSelection);
7161
+ const marker = `${prefix}h${captions.length}!`;
7162
+ captions.push({
7163
+ marker,
7164
+ slot: rep,
7165
+ role,
7166
+ label,
7167
+ duplicate,
7168
+ anchor
7169
+ });
7170
+ return marker;
7171
+ };
7172
+ for (const slot of slots) if (slot.reason) options.onDegrade?.(slot.mediaId, slot.reason);
7173
+ const projected = messages.map((message) => {
7174
+ if (message.role !== "tool" && message.role !== "user") return message;
7175
+ return {
7176
+ ...message,
7177
+ content: message.content.flatMap((block) => {
7178
+ const entry = block.type === "text" && handles.get(block);
7179
+ if (entry) {
7180
+ const slot = entry.file ? originalToSlot.get(entry.file) : last.get(entry.attachmentId);
7181
+ return [text$7(`${entry.referenceText}\n${feedback(slot, message.role, entry.label, entry.status === "duplicate", entry.status === "selected")}`)];
7182
+ }
7183
+ if (block.type !== "file") return [block];
7184
+ const slot = at.get(block);
7185
+ const parts = [];
7186
+ if (!occurrences || !slot.part && slot.reason === noSelection) parts.push(text$7(feedback(slot, message.role, slot.label, !!slot.representative, !slot.representative)));
7187
+ if (slot.part) {
7188
+ const marker = `${prefix}f${markers.size}!`;
7189
+ markers.set(marker, slot);
7190
+ parts.push(text$7(marker));
7191
+ }
7192
+ return parts;
7193
+ })
7194
+ };
7195
+ });
7196
+ if (detached.length) projected.push({
7197
+ role: "user",
7198
+ content: [text$7(`Media status for this request:\n${detached.map((item) => referenceOnly(item.label, mapping)).join("\n")}`)]
7199
+ });
7200
+ return {
7201
+ messages: projected,
7202
+ isMarker: (value) => markers.has(value),
7203
+ inject: reconciler(prefix, markers, captions, slots, options.onDegrade)
7204
+ };
7205
+ }
7206
+ //#endregion
6690
7207
  //#region node_modules/@earendil-works/pi-ai/dist/utils/overflow.js
6691
7208
  /**
6692
7209
  * Regex patterns to detect context overflow errors from different providers.
@@ -7817,7 +8334,8 @@ var GatewayAdapter = class extends LlmAdapter {
7817
8334
  if (entry === void 0 || entry.api !== "openai-completions" || (entry.nativeMedia?.length ?? 0) === 0) return void 0;
7818
8335
  return snapshot.models.getModel(provider, model) === void 0 ? void 0 : {
7819
8336
  maxBytes: NATIVE_FILE_MAX_BYTES,
7820
- mediaTypes: GEMINI_INLINE_MEDIA_TYPES
8337
+ mediaTypes: GEMINI_INLINE_MEDIA_TYPES,
8338
+ supportsRangeLabels: true
7821
8339
  };
7822
8340
  }
7823
8341
  providerInfo(provider) {
@@ -7903,7 +8421,7 @@ var GatewayAdapter = class extends LlmAdapter {
7903
8421
  }
7904
8422
  async *streamWithSnapshot(options, snapshot, preparedTtl) {
7905
8423
  try {
7906
- var _usingCtx$1 = _usingCtx();
8424
+ var _usingCtx$2 = _usingCtx();
7907
8425
  if (options.stop !== void 0) throw new LlmError("the VibeDev gateway adapter does not support GenerateOptions.stop", "UNSUPPORTED_OPTION");
7908
8426
  const { model, catalog } = this.modelOf(snapshot, options.provider, options.model);
7909
8427
  const claudeCacheTtl = preparedTtl ?? this.cacheTtlFor(model);
@@ -7916,7 +8434,7 @@ var GatewayAdapter = class extends LlmAdapter {
7916
8434
  const consumer = new AbortController();
7917
8435
  const upstream = options.signal === void 0 ? consumer.signal : AbortSignal.any([options.signal, consumer.signal]);
7918
8436
  const streamIdleTimeoutMs = this.config.streamIdleTimeoutMs ?? 3e5;
7919
- const watchdog = _usingCtx$1.u(idleWatchdog(upstream, streamIdleTimeoutMs, "LLM_STREAM_IDLE_TIMEOUT"));
8437
+ const watchdog = _usingCtx$2.u(idleWatchdog(upstream, streamIdleTimeoutMs, "LLM_STREAM_IDLE_TIMEOUT"));
7920
8438
  let answered = false;
7921
8439
  try {
7922
8440
  const containsImage = options.messages.some((message) => contentHasImage(message.content));
@@ -7942,13 +8460,27 @@ var GatewayAdapter = class extends LlmAdapter {
7942
8460
  });
7943
8461
  } catch {}
7944
8462
  };
7945
- if (containsNativeFile && attachments === void 0) for (const message of options.messages) {
8463
+ const verified = model.api === "openai-completions" ? await prepareVerifiedFiles(options, {
8464
+ attachments,
8465
+ target: () => this.fileTargetIn(snapshot, options.provider, options.model),
8466
+ mediaTypes: GEMINI_INLINE_MEDIA_TYPES,
8467
+ modalities: catalog.nativeMedia,
8468
+ maxBytes: NATIVE_FILE_MAX_BYTES,
8469
+ maxEncoded: NATIVE_FILE_MAX_REQUEST_BASE64_BYTES,
8470
+ onDegrade: onNativeFileDegrade,
8471
+ signal: watchdog.signal
8472
+ }) : void 0;
8473
+ if (!verified && containsNativeFile && attachments === void 0) for (const message of options.messages) {
7946
8474
  if (!carriesFiles(message)) continue;
7947
8475
  for (const block of message.content) if (block.type === "file") onNativeFileDegrade(block.attachment.name, "no durable attachment service to read it from");
7948
8476
  }
7949
8477
  const nativeFiles = [];
7950
- const context = attachments === void 0 ? toPiContext(options, void 0, onReplayDegrade) : await toPiContext({
8478
+ const request = verified ? {
7951
8479
  ...options,
8480
+ messages: verified.messages
8481
+ } : options;
8482
+ const context = attachments === void 0 ? toPiContext(request, void 0, onReplayDegrade) : await toPiContext({
8483
+ ...request,
7952
8484
  signal: watchdog.signal
7953
8485
  }, {
7954
8486
  attachments,
@@ -7958,7 +8490,8 @@ var GatewayAdapter = class extends LlmAdapter {
7958
8490
  maxPixels: DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET,
7959
8491
  maxBytes: DEFAULT_REQUEST_IMAGE_MAX_BYTES
7960
8492
  },
7961
- ...containsNativeFile ? { files: {
8493
+ ...verified ? { isWireMarker: verified.isMarker } : {},
8494
+ ...containsNativeFile && !verified ? { files: {
7962
8495
  target: () => this.fileTargetIn(snapshot, options.provider, options.model),
7963
8496
  onDegrade: (ref, reason) => {
7964
8497
  onNativeFileDegrade(ref.name, reason);
@@ -7970,14 +8503,17 @@ var GatewayAdapter = class extends LlmAdapter {
7970
8503
  const offersNone = catalog.reasoningLevels?.includes("none") === true;
7971
8504
  for (let attempt = 0;; attempt++) {
7972
8505
  const token = credential.token;
8506
+ const receipt = verified && fileReceiptAttempt(this.config.onNativeFileReceipt);
7973
8507
  let response;
7974
8508
  const observingFetch = async (input, init) => {
7975
8509
  const url = input instanceof Request ? input.url : String(input);
7976
8510
  if (new URL(url).origin !== snapshot.origin) throw new Error("Refusing a model request to another gateway origin.");
8511
+ receipt?.fetching();
7977
8512
  const received = await fetch(input, {
7978
8513
  ...init,
7979
8514
  redirect: "error"
7980
8515
  });
8516
+ receipt?.responded(received.status);
7981
8517
  answered = true;
7982
8518
  response = {
7983
8519
  status: received.status,
@@ -8011,7 +8547,11 @@ var GatewayAdapter = class extends LlmAdapter {
8011
8547
  off: reasoning === "off" && offersNone,
8012
8548
  reasoning: enabledReasoning !== void 0,
8013
8549
  claudeCacheTtl,
8014
- nativeFiles
8550
+ nativeFiles,
8551
+ ...verified ? {
8552
+ verified,
8553
+ receipt
8554
+ } : {}
8015
8555
  }),
8016
8556
  fetch: observingFetch,
8017
8557
  onResponse: (received) => {
@@ -8072,9 +8612,9 @@ var GatewayAdapter = class extends LlmAdapter {
8072
8612
  } catch {}
8073
8613
  }
8074
8614
  } catch (_) {
8075
- _usingCtx$1.e = _;
8615
+ _usingCtx$2.e = _;
8076
8616
  } finally {
8077
- _usingCtx$1.d();
8617
+ _usingCtx$2.d();
8078
8618
  }
8079
8619
  }
8080
8620
  /**
@@ -8095,6 +8635,10 @@ var GatewayAdapter = class extends LlmAdapter {
8095
8635
  shaped.thinking = { type: "disabled" };
8096
8636
  delete shaped.reasoning_effort;
8097
8637
  } else if (request.off) shaped.reasoning_effort = "none";
8638
+ if (request.verified) {
8639
+ const bridge = model.compat?.requiresAssistantAfterToolResult === true;
8640
+ return request.verified.inject(shaped, bridge, request.receipt?.payload) ?? shaped;
8641
+ }
8098
8642
  if (request.nativeFiles !== void 0 && request.nativeFiles.length > 0) {
8099
8643
  const assistantAfterToolResult = model.compat?.requiresAssistantAfterToolResult === true;
8100
8644
  return injectNativeFiles(shaped, request.nativeFiles, { assistantAfterToolResult }) ?? shaped;
@@ -8254,6 +8798,9 @@ function installGatewayModels(ctx, options) {
8254
8798
  onNativeFileDegrade: ({ provider, model, file, reason }) => {
8255
8799
  ctx.logger.warn(`dsh-vibedev: sending "${file}" to ${provider}/${model} as its file handle text only: ${reason}`);
8256
8800
  },
8801
+ onNativeFileReceipt: (receipt) => {
8802
+ ctx.logger.debug(`dsh-vibedev native media: ${JSON.stringify(receipt)}`);
8803
+ },
8257
8804
  ...options.onRequestEnded === void 0 ? {} : { onRequestEnded: options.onRequestEnded },
8258
8805
  ...options.promotions === void 0 ? {} : { promotions: options.promotions }
8259
8806
  });
@@ -8312,7 +8859,7 @@ function installGatewayModels(ctx, options) {
8312
8859
  if (response.status === 401) await options.rejectCredential(credential).catch(() => void 0);
8313
8860
  if (!response.ok) throw new Error(`gateway catalog answered HTTP ${response.status}`);
8314
8861
  hidden = void 0;
8315
- publish(preferredFirst(parseCatalog(await response.json()), options.preferredModels()));
8862
+ publish(preferredFirst(parseCatalog$1(await response.json()), options.preferredModels()));
8316
8863
  } catch (error) {
8317
8864
  ctx.logger.warn("dsh-vibedev: catalog read failed: %o", error);
8318
8865
  }
@@ -8714,6 +9261,13 @@ const AUDIO_GENERATION_KINDS = [
8714
9261
  "speech",
8715
9262
  "transcription"
8716
9263
  ];
9264
+ /** How an audio model is billed (`audio.billing_unit`). */
9265
+ const AUDIO_BILLING_UNITS = [
9266
+ "generation",
9267
+ "original_second",
9268
+ "minute",
9269
+ "character"
9270
+ ];
8717
9271
  const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8718
9272
  const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
8719
9273
  const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
@@ -8969,7 +9523,8 @@ const PRICE_UNITS = [
8969
9523
  "generation",
8970
9524
  "second",
8971
9525
  "original_second",
8972
- "minute"
9526
+ "minute",
9527
+ "character"
8973
9528
  ];
8974
9529
  /** The audio block: `entry.audio`, else `capabilities.audio`, else the fields flattened into `capabilities`. */
8975
9530
  function audioBlock(entry, capabilities) {
@@ -9077,7 +9632,8 @@ function parseAudioCapabilities(raw) {
9077
9632
  const kindRaw = text$5(field(raw, "generation_kind"))?.toLowerCase();
9078
9633
  const generationKind = AUDIO_GENERATION_KINDS.includes(kindRaw ?? "") ? kindRaw : void 0;
9079
9634
  const billingRaw = text$5(field(raw, "billing_unit"))?.toLowerCase();
9080
- const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
9635
+ const billingUnit = AUDIO_BILLING_UNITS.includes(billingRaw ?? "") ? billingRaw : void 0;
9636
+ const hanCharacterWeight = positive$1(field(raw, "han_character_weight")) ?? (billingUnit === "character" ? 2 : void 0);
9081
9637
  const promptField = text$5(field(raw, "prompt_field"));
9082
9638
  const requestFields = list(raw, "request_fields") ?? [];
9083
9639
  const union = [
@@ -9094,6 +9650,7 @@ function parseAudioCapabilities(raw) {
9094
9650
  if (generationKind !== void 0) result.generationKind = generationKind;
9095
9651
  if (promptField !== void 0) result.promptField = promptField;
9096
9652
  if (billingUnit !== void 0) result.billingUnit = billingUnit;
9653
+ if (hanCharacterWeight !== void 0) result.hanCharacterWeight = hanCharacterWeight;
9097
9654
  if (references !== void 0) result.references = references;
9098
9655
  if (outputFormats !== void 0) result.outputFormats = outputFormats;
9099
9656
  if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
@@ -9209,7 +9766,25 @@ function parseVideoPricing(value) {
9209
9766
  rules
9210
9767
  } };
9211
9768
  }
9212
- /** Which kind of media model a catalog entry is, or undefined for a chat or internal model. */
9769
+ /**
9770
+ * Whether a catalog entry is a realtime speech model: `media_type: "speech"`, or a `speech` block (`vibedev-asr`,
9771
+ * `vibedev-tts`). Such a model serves the desktop's voice input and read-aloud, never the media tools — whatever its
9772
+ * modalities say: a read-aloud lane outputs audio, and would otherwise look like an audio generator.
9773
+ * @param entry - one entry of `/v1/models`.
9774
+ * @returns whether it is one.
9775
+ */
9776
+ function isRealtimeSpeechEntry(entry) {
9777
+ const raw = record$7(entry);
9778
+ return raw !== void 0 && (text$5(raw.media_type)?.toLowerCase() === "speech" || record$7(raw.speech) !== void 0);
9779
+ }
9780
+ /** The other ids an entry answers to: trimmed, blanks and its own id left out. */
9781
+ function aliasesOf(entry, id) {
9782
+ return (strings(entry.aliases) ?? []).map((alias) => alias.trim()).filter((alias) => alias !== "" && alias !== id);
9783
+ }
9784
+ /**
9785
+ * Which kind of media model a catalog entry is, or undefined for a chat or internal model. Realtime speech entries
9786
+ * never get here (see {@link isRealtimeSpeechEntry}).
9787
+ */
9213
9788
  function kindOf(entry, capabilities, audio) {
9214
9789
  if (text$5(entry.internal_role) !== void 0) return void 0;
9215
9790
  if (audio?.generationKind === "transcription") return "transcription";
@@ -9233,14 +9808,39 @@ function kindOf(entry, capabilities, audio) {
9233
9808
  * @returns the media models, in catalog order.
9234
9809
  */
9235
9810
  function parseMediaCatalog(body) {
9811
+ return parseCatalog(body).models;
9812
+ }
9813
+ /**
9814
+ * Parse a `/v1/models` body into its media models, with the realtime speech models kept apart: they are never media
9815
+ * models (see {@link isRealtimeSpeechEntry}), and are listed only so a name that refers to one can be told what it is.
9816
+ * @param body - `{data:[...]}` or a bare array.
9817
+ * @returns the media models and the realtime speech models, each in catalog order.
9818
+ */
9819
+ function parseCatalog(body) {
9236
9820
  const entries = Array.isArray(body) ? body : record$7(body)?.data;
9237
- if (!Array.isArray(entries)) return [];
9821
+ if (!Array.isArray(entries)) return {
9822
+ models: [],
9823
+ realtimeSpeech: []
9824
+ };
9238
9825
  const models = [];
9826
+ const realtimeSpeech = [];
9239
9827
  const seen = /* @__PURE__ */ new Set();
9240
9828
  for (const item of entries) {
9241
9829
  const entry = record$7(item);
9242
9830
  const id = text$5(entry?.id);
9243
9831
  if (entry === void 0 || id === void 0 || seen.has(id)) continue;
9832
+ if (isRealtimeSpeechEntry(entry)) {
9833
+ if (!realtimeSpeech.some((known) => known.id === id)) {
9834
+ const aliases = aliasesOf(entry, id);
9835
+ const lane = text$5(record$7(entry.speech)?.lane)?.toLowerCase();
9836
+ realtimeSpeech.push({
9837
+ id,
9838
+ ...aliases.length === 0 ? {} : { aliases },
9839
+ ...lane === void 0 ? {} : { lane }
9840
+ });
9841
+ }
9842
+ continue;
9843
+ }
9244
9844
  const capabilities = record$7(entry.capabilities) ?? {};
9245
9845
  const audioRaw = audioBlock(entry, capabilities);
9246
9846
  const audio = audioRaw === void 0 ? void 0 : parseAudioCapabilities(audioRaw);
@@ -9253,7 +9853,7 @@ function parseMediaCatalog(body) {
9253
9853
  const { videoPricing, videoPricingIssue } = parseVideoPricing(field(entry, "video_pricing"));
9254
9854
  const inputModalities = strings(capabilities.input_modalities) ?? strings(entry.input_modalities) ?? [];
9255
9855
  const endpoints = strings(capabilities.allowed_endpoints) ?? [];
9256
- const aliases = (strings(entry.aliases) ?? []).map((alias) => alias.trim()).filter((alias) => alias !== "" && alias !== id);
9856
+ const aliases = aliasesOf(entry, id);
9257
9857
  let video;
9258
9858
  if (kind === "video") video = {
9259
9859
  ...parseVideoCapabilities(capabilities),
@@ -9280,7 +9880,10 @@ function parseMediaCatalog(body) {
9280
9880
  ...audioKind === void 0 ? {} : { audioKind }
9281
9881
  });
9282
9882
  }
9283
- return models;
9883
+ return {
9884
+ models,
9885
+ realtimeSpeech
9886
+ };
9284
9887
  }
9285
9888
  //#endregion
9286
9889
  //#region src/media/sources.ts
@@ -9590,6 +10193,15 @@ function modelNamed(models, wanted) {
9590
10193
  const lower = wanted.toLowerCase();
9591
10194
  return models.find((model) => model.id === wanted) ?? models.find((model) => model.id.toLowerCase() === lower) ?? models.find((model) => (model.aliases ?? []).some((alias) => alias.toLowerCase() === lower));
9592
10195
  }
10196
+ /**
10197
+ * Why a realtime speech model cannot be used by the media tools, for a request that names one.
10198
+ * @param model - the realtime speech model.
10199
+ * @returns the sentence.
10200
+ */
10201
+ function realtimeSpeechRefusal(model) {
10202
+ const use = model.lane === "asr" ? "voice input" : model.lane === "tts" ? "read-aloud" : "voice input and read-aloud";
10203
+ return `${model.id} is a realtime speech model (the VibeDev app's ${use}), not a media model, so the media tools cannot use it.`;
10204
+ }
9593
10205
  const CATALOG_TTL_MS = 12e4;
9594
10206
  /** Wait for a shared promise under one caller's signal without cancelling it for the others. */
9595
10207
  function abortable$1(promise, signal) {
@@ -9642,20 +10254,29 @@ var MediaRuntime = class {
9642
10254
  * The media models this account can use. Cached for two minutes; a failed
9643
10255
  * refresh falls back to the last list for up to an hour.
9644
10256
  * @param signal - cancels the request.
9645
- * @returns the models, in catalog order.
10257
+ * @returns the models, in catalog order.
10258
+ */
10259
+ async models(signal) {
10260
+ return (await this.parsedCatalog(signal)).models;
10261
+ }
10262
+ /**
10263
+ * The catalog as the media tools read it: the media models, and the realtime speech models kept apart from them
10264
+ * (only so a request that names one can be told what it is). Cached as {@link models} describes.
10265
+ * @param signal - cancels the request.
10266
+ * @returns the parsed catalog.
9646
10267
  */
9647
- async models(signal) {
10268
+ async parsedCatalog(signal) {
9648
10269
  const cached = this.catalog;
9649
- if (cached !== void 0 && this.now() - cached.at < CATALOG_TTL_MS) return cached.models;
10270
+ if (cached !== void 0 && this.now() - cached.at < CATALOG_TTL_MS) return cached.parsed;
9650
10271
  if (this.fetching === void 0) {
9651
10272
  const generation = this.generation;
9652
10273
  const fetching = this.http.json("/v1/models", { timeoutMs: 3e4 }).then((body) => {
9653
- const models = parseMediaCatalog(body);
10274
+ const parsed = parseCatalog(body);
9654
10275
  if (generation === this.generation) this.catalog = {
9655
- models,
10276
+ parsed,
9656
10277
  at: this.now()
9657
10278
  };
9658
- return models;
10279
+ return parsed;
9659
10280
  }).finally(() => {
9660
10281
  if (this.fetching === fetching) this.fetching = void 0;
9661
10282
  });
@@ -9666,7 +10287,7 @@ var MediaRuntime = class {
9666
10287
  return await abortable$1(this.fetching, signal);
9667
10288
  } catch (error) {
9668
10289
  if (signal?.aborted === true) throw error;
9669
- if (cached !== void 0 && this.now() - cached.at < 36e5 && !(error instanceof MediaError && error.code === "NOT_SIGNED_IN")) return cached.models;
10290
+ if (cached !== void 0 && this.now() - cached.at < 36e5 && !(error instanceof MediaError && error.code === "NOT_SIGNED_IN")) return cached.parsed;
9670
10291
  throw error;
9671
10292
  }
9672
10293
  }
@@ -9692,12 +10313,16 @@ var MediaRuntime = class {
9692
10313
  * @returns the model.
9693
10314
  */
9694
10315
  async pickModel(kind, slot, requested, accept, signal) {
9695
- const models = await this.models(signal);
10316
+ const { models, realtimeSpeech } = await this.parsedCatalog(signal);
9696
10317
  const ofKind = models.filter((model) => model.kind === kind && servesSlot(model, slot));
9697
10318
  const wanted = requested?.trim();
9698
10319
  if (wanted !== void 0 && wanted !== "") {
9699
10320
  const found = modelNamed(models, wanted);
9700
- if (found === void 0) throw localInputError(`There is no model "${wanted}" on this VibeDev account. ${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`, "MODEL_NOT_FOUND", { field: "model" });
10321
+ if (found === void 0) {
10322
+ const offered = `${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`;
10323
+ const speech = modelNamed(realtimeSpeech, wanted);
10324
+ throw localInputError(speech === void 0 ? `There is no model "${wanted}" on this VibeDev account. ${offered}` : `${realtimeSpeechRefusal(speech)} ${offered}`, "MODEL_NOT_FOUND", { field: "model" });
10325
+ }
9701
10326
  if (!ofKind.includes(found)) {
9702
10327
  if (found.kind === "audio" && found.audioKind === void 0) throw localInputError(`${found.id} does not declare what kind of audio it makes, so it cannot be used for ${slotLabel(slot).toLowerCase()}.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
9703
10328
  throw localInputError(`${found.id} is not a ${slotLabel(slot).toLowerCase()} model. ${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`, "MODEL_KIND_MISMATCH", { field: "model" });
@@ -9711,16 +10336,19 @@ var MediaRuntime = class {
9711
10336
  return (accept === void 0 ? void 0 : ordered.find((model) => accept(model))) ?? ordered[0];
9712
10337
  }
9713
10338
  /**
9714
- * The model a name refers to, whatever its kind.
10339
+ * The media model a name refers to, whatever its kind.
9715
10340
  * @param requested - an id or alias.
9716
10341
  * @param signal - cancels the catalog request.
9717
10342
  * @returns the model.
9718
- * @throws {@link MediaError} when the account has no such model.
10343
+ * @throws {@link MediaError} `MODEL_NOT_FOUND` when the account has no such media model; for a realtime speech model
10344
+ * the message says that is what it is.
9719
10345
  */
9720
10346
  async findModel(requested, signal) {
9721
- const found = modelNamed(await this.models(signal), requested.trim());
9722
- if (found === void 0) throw localInputError(`There is no model "${requested}" on this VibeDev account.`, "MODEL_NOT_FOUND", { field: "model" });
9723
- return found;
10347
+ const { models, realtimeSpeech } = await this.parsedCatalog(signal);
10348
+ const found = modelNamed(models, requested.trim());
10349
+ if (found !== void 0) return found;
10350
+ const speech = modelNamed(realtimeSpeech, requested.trim());
10351
+ throw localInputError(speech === void 0 ? `There is no model "${requested}" on this VibeDev account.` : realtimeSpeechRefusal(speech), "MODEL_NOT_FOUND", { field: "model" });
9724
10352
  }
9725
10353
  /**
9726
10354
  * The workspace of the calling session.
@@ -10721,6 +11349,697 @@ var GatewaySearchProvider = class {
10721
11349
  }
10722
11350
  };
10723
11351
  //#endregion
11352
+ //#region src/speech/availability.ts
11353
+ const READY$1 = Object.freeze({ phase: "ready" });
11354
+ const SIGN_IN_REQUIRED = Object.freeze({
11355
+ phase: "unavailable",
11356
+ reason: "sign-in-required"
11357
+ });
11358
+ /** Whether two states would read the same to a registry. */
11359
+ function same(a, b) {
11360
+ return a.phase === b.phase && (a.phase !== "failed" || b.phase === "failed" && a.message === b.message);
11361
+ }
11362
+ /**
11363
+ * Published sign-in state. It starts as needing a sign-in; the newest check wins, a check that changes nothing tells
11364
+ * nobody, and a stopped source publishes nothing.
11365
+ */
11366
+ var CredentialAvailability = class {
11367
+ signedIn;
11368
+ current = SIGN_IN_REQUIRED;
11369
+ listeners = /* @__PURE__ */ new Set();
11370
+ round = 0;
11371
+ stopped = false;
11372
+ /**
11373
+ * @param signedIn - whether a VibeDev credential resolves now; rerun whenever the sign-in may have changed.
11374
+ */
11375
+ constructor(signedIn) {
11376
+ this.signedIn = signedIn;
11377
+ }
11378
+ /** @returns the latest published state. */
11379
+ snapshot() {
11380
+ return this.current;
11381
+ }
11382
+ /** @param listener - told after the state changed. @returns unsubscribe. */
11383
+ subscribe(listener) {
11384
+ this.listeners.add(listener);
11385
+ return () => {
11386
+ this.listeners.delete(listener);
11387
+ };
11388
+ }
11389
+ /** Check the sign-in again: a cloud provider has nothing to download. */
11390
+ prepare() {
11391
+ this.refresh();
11392
+ }
11393
+ /** Nothing runs between checks, so there is nothing to cancel. */
11394
+ async cancel() {}
11395
+ /**
11396
+ * Check the credential and publish the result. A check that fails publishes `failed` with a fixed diagnostic: the
11397
+ * error of a credential read may name a stored grant, so its message is not repeated.
11398
+ * @returns after this check settles, whether or not a newer one replaced it.
11399
+ */
11400
+ async refresh() {
11401
+ const round = ++this.round;
11402
+ let next;
11403
+ try {
11404
+ next = await this.signedIn() ? READY$1 : SIGN_IN_REQUIRED;
11405
+ } catch {
11406
+ next = {
11407
+ phase: "failed",
11408
+ message: "The VibeDev sign-in could not be read."
11409
+ };
11410
+ }
11411
+ if (round !== this.round || this.stopped || same(next, this.current)) return;
11412
+ this.current = next;
11413
+ for (const listener of [...this.listeners]) try {
11414
+ listener();
11415
+ } catch {}
11416
+ }
11417
+ /** Stop publishing; checks still running settle without telling anyone. */
11418
+ stop() {
11419
+ this.stopped = true;
11420
+ this.listeners.clear();
11421
+ }
11422
+ };
11423
+ //#endregion
11424
+ //#region src/speech/host.ts
11425
+ /**
11426
+ * The Host's own copies of the speech packages. Each specifier is widened to `string` so TypeScript resolves no
11427
+ * package the plugin does not install; the build keeps each one as a literal dynamic import of the package, external
11428
+ * like every `@deepseek-ai/*` package, and `scripts/check-package.mjs` finds both among the peers.
11429
+ */
11430
+ const HOST_SPEECH_MODULES = {
11431
+ speechToText: () => import("@deepseek-ai/dsh-experimental-speech-to-text"),
11432
+ textToSpeech: () => import("@deepseek-ai/dsh-text-to-speech")
11433
+ };
11434
+ /**
11435
+ * The classified failure class a Host package exports, when it does. DSH 0.2.3-alpha.2 has the recognition package
11436
+ * without `SpeechTranscriptionError` and no synthesis package at all; there, and wherever loading fails, the answer is
11437
+ * undefined and nothing is registered.
11438
+ * @param load - imports the Host package.
11439
+ * @param name - the exported class.
11440
+ * @returns the class, or undefined.
11441
+ */
11442
+ async function hostErrorClass(load, name) {
11443
+ let module;
11444
+ try {
11445
+ module = await load();
11446
+ } catch {
11447
+ return;
11448
+ }
11449
+ const value = typeof module === "object" && module !== null ? module[name] : void 0;
11450
+ return typeof value === "function" ? value : void 0;
11451
+ }
11452
+ const SPEECH_MAX_BUSY_WAIT_MS = 2e3;
11453
+ /** One gateway call, remembering the credential its last attempt carried. */
11454
+ var GatewayCall = class {
11455
+ gateway;
11456
+ /** The credential of the last attempt: a rejected development key needs another key, not a sign-in. */
11457
+ credential;
11458
+ /** @param gateway - the plugin's gateway client and credential chain. */
11459
+ constructor(gateway) {
11460
+ this.gateway = gateway;
11461
+ }
11462
+ /**
11463
+ * Send through the plugin's gateway client with the speech busy policy.
11464
+ * @param path - the gateway path.
11465
+ * @param request - method, body, signal and deadline.
11466
+ * @returns the 2xx response, body unread.
11467
+ * @throws {@link MediaError} for every refusal, with the gateway's code and status.
11468
+ */
11469
+ send(path, request) {
11470
+ return this.gateway.http.send(path, {
11471
+ busyRetries: 1,
11472
+ maxBusyWaitMs: SPEECH_MAX_BUSY_WAIT_MS,
11473
+ ...request,
11474
+ resolveCredential: async () => {
11475
+ const credential = await this.gateway.resolveCredential();
11476
+ this.credential = credential;
11477
+ return credential;
11478
+ }
11479
+ });
11480
+ }
11481
+ };
11482
+ /**
11483
+ * Classify a failed call.
11484
+ * @param error - what the gateway client threw.
11485
+ * @param credential - the credential the call carried last.
11486
+ * @param inputCodes - the gateway codes that refuse the input itself (`SPEECH_AUDIO_*`, `SPEECH_TEXT_*`).
11487
+ * @returns the class and a diagnostic without the gateway's prose, the credential, audio or text.
11488
+ */
11489
+ function classifyFailure(error, credential, inputCodes) {
11490
+ if (!(error instanceof MediaError)) return {
11491
+ kind: "service-error",
11492
+ diagnostic: `unexpected ${error instanceof Error ? error.name : typeof error}`
11493
+ };
11494
+ const { status, requestId } = error.details;
11495
+ const diagnostic = [
11496
+ status === void 0 ? void 0 : `HTTP ${status}`,
11497
+ error.code,
11498
+ requestId === void 0 ? void 0 : `request ${requestId}`
11499
+ ].filter((part) => part !== void 0).join(", ");
11500
+ return {
11501
+ kind: failureClass(error, credential, inputCodes),
11502
+ diagnostic
11503
+ };
11504
+ }
11505
+ function failureClass(error, credential, inputCodes) {
11506
+ switch (error.code) {
11507
+ case "NOT_SIGNED_IN": return "sign-in-required";
11508
+ case "GATEWAY_TIMEOUT": return "timeout";
11509
+ case "GATEWAY_UNREACHABLE": return "service-unavailable";
11510
+ }
11511
+ const status = error.details.status;
11512
+ if (status === 401) return credential?.kind === "key" ? "api-key-invalid" : "sign-in-required";
11513
+ if (status === 402 || error.code === "INSUFFICIENT_BALANCE") return "quota-exceeded";
11514
+ if (status === 429) return "rate-limited";
11515
+ if (status === 503) return "service-unavailable";
11516
+ if (status === 408 || status === 504) return "timeout";
11517
+ if (status === 413 || (status === 400 || status === 422) && inputCodes.test(error.code)) return "rejected-input";
11518
+ return "service-error";
11519
+ }
11520
+ /**
11521
+ * Settle with `work`, or reject with the signal's reason as soon as it aborts. The abort reaches the request through
11522
+ * its own signal; this only keeps a body read that undici leaves pending after an abort from holding the caller, and a
11523
+ * registry joining the call, past the cancellation.
11524
+ * @param signal - cancellation.
11525
+ * @param work - the call.
11526
+ * @returns the call's own outcome when it settles first.
11527
+ */
11528
+ function untilAborted(signal, work) {
11529
+ return new Promise((resolve, reject) => {
11530
+ const onAbort = () => {
11531
+ reject(signal.reason);
11532
+ };
11533
+ if (signal.aborted) onAbort();
11534
+ else signal.addEventListener("abort", onAbort, { once: true });
11535
+ work.then((value) => {
11536
+ signal.removeEventListener("abort", onAbort);
11537
+ resolve(value);
11538
+ }, (error) => {
11539
+ signal.removeEventListener("abort", onAbort);
11540
+ reject(error);
11541
+ });
11542
+ });
11543
+ }
11544
+ /**
11545
+ * Read a small body completely, or give up past `limit` bytes.
11546
+ * @param response - the gateway's answer.
11547
+ * @param limit - the most bytes read.
11548
+ * @returns the text, or undefined when the body is larger.
11549
+ */
11550
+ async function boundedText(response, limit) {
11551
+ if (response.body === null) return "";
11552
+ const chunks = [];
11553
+ let total = 0;
11554
+ for await (const chunk of response.body) {
11555
+ total += chunk.byteLength;
11556
+ if (total > limit) return void 0;
11557
+ chunks.push(chunk);
11558
+ }
11559
+ return Buffer.concat(chunks).toString("utf8");
11560
+ }
11561
+ //#endregion
11562
+ //#region src/speech/wave.ts
11563
+ /**
11564
+ * The recordings `POST /v1/vibedev/speech/asr` accepts, checked before anything is sent: 16-bit PCM WAV, mono or
11565
+ * stereo, 8–48 kHz, at most 8 MiB and 120 seconds (the Host sends 16 kHz mono). And the request body: one
11566
+ * multipart `file` field.
11567
+ * @module dsh-vibedev/speech/wave
11568
+ */
11569
+ /** Largest recording file the gateway accepts. */
11570
+ const MAX_RECORDING_BYTES = 8388608;
11571
+ /** A recording the gateway would refuse; the message names the broken rule and carries no audio. */
11572
+ var RecordingRejected = class extends Error {
11573
+ name = "RecordingRejected";
11574
+ };
11575
+ /** The 4-character ASCII tag at `offset`. */
11576
+ function tag(audio, offset) {
11577
+ return String.fromCharCode(audio[offset] ?? 0, audio[offset + 1] ?? 0, audio[offset + 2] ?? 0, audio[offset + 3] ?? 0);
11578
+ }
11579
+ /**
11580
+ * Check a recording against the gateway's limits.
11581
+ * @param audio - the WAV file, sent unchanged.
11582
+ * @returns its duration in seconds.
11583
+ * @throws {@link RecordingRejected} for anything the gateway would refuse.
11584
+ */
11585
+ function recordingSeconds(audio) {
11586
+ if (audio.byteLength > 8388608) throw new RecordingRejected(`The recording is ${audio.byteLength} bytes; the service accepts at most ${MAX_RECORDING_BYTES}.`);
11587
+ if (audio.byteLength < 12 || tag(audio, 0) !== "RIFF" || tag(audio, 8) !== "WAVE") throw new RecordingRejected("The recording is not a WAV file.");
11588
+ const view = new DataView(audio.buffer, audio.byteOffset, audio.byteLength);
11589
+ let format;
11590
+ let dataBytes;
11591
+ for (let offset = 12; offset + 8 <= audio.byteLength;) {
11592
+ const id = tag(audio, offset);
11593
+ const size = view.getUint32(offset + 4, true);
11594
+ const start = offset + 8;
11595
+ if (id === "fmt ") {
11596
+ if (size < 16 || start + 16 > audio.byteLength) throw new RecordingRejected("The recording's WAV format chunk is incomplete.");
11597
+ format = {
11598
+ code: view.getUint16(start, true),
11599
+ channels: view.getUint16(start + 2, true),
11600
+ rate: view.getUint32(start + 4, true),
11601
+ blockAlign: view.getUint16(start + 12, true),
11602
+ bits: view.getUint16(start + 14, true)
11603
+ };
11604
+ } else if (id === "data") {
11605
+ dataBytes = Math.min(size, audio.byteLength - start);
11606
+ break;
11607
+ }
11608
+ offset = start + size + size % 2;
11609
+ }
11610
+ if (format === void 0 || dataBytes === void 0) throw new RecordingRejected("The recording has no WAV format or data chunk.");
11611
+ if (format.code !== 1 || format.bits !== 16) throw new RecordingRejected("The recording must be 16-bit PCM.");
11612
+ if (format.channels !== 1 && format.channels !== 2) throw new RecordingRejected(`The recording has ${format.channels} channels; the service takes mono or stereo.`);
11613
+ if (format.rate < 8e3 || format.rate > 48e3) throw new RecordingRejected(`The recording is sampled at ${format.rate} Hz; the service takes 8–48 kHz.`);
11614
+ if (format.blockAlign !== format.channels * 2) throw new RecordingRejected("The recording's WAV block alignment does not match 16-bit PCM.");
11615
+ const frames = Math.floor(dataBytes / format.blockAlign);
11616
+ if (frames === 0) throw new RecordingRejected("The recording holds no audio.");
11617
+ const seconds = frames / format.rate;
11618
+ if (seconds > 120) throw new RecordingRejected(`The recording is ${seconds.toFixed(1)} s long; the service accepts at most 120 s.`);
11619
+ return seconds;
11620
+ }
11621
+ /**
11622
+ * Encode the recording as the gateway's single `file` field. Bytes rather than `FormData`: a request cancelled before
11623
+ * undici reads a `FormData` body leaves its pump rejecting unhandled, and a busy retry sends the same bytes again.
11624
+ * @param recording - the WAV file.
11625
+ * @returns the body and its content type.
11626
+ */
11627
+ function multipartBody(recording) {
11628
+ const boundary = `vibedev-speech-${randomUUID()}`;
11629
+ return {
11630
+ body: Buffer.concat([
11631
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="recording.wav"\r\nContent-Type: audio/wav\r\n\r\n`),
11632
+ recording,
11633
+ Buffer.from(`\r\n--${boundary}--\r\n`)
11634
+ ]),
11635
+ contentType: `multipart/form-data; boundary=${boundary}`
11636
+ };
11637
+ }
11638
+ //#endregion
11639
+ //#region src/speech/recognition.ts
11640
+ /** The provider id the VibeDev desktop's voice input recognizes as VibeDev's. */
11641
+ const RECOGNITION_PROVIDER_ID = "vibedev-asr";
11642
+ /** The gateway's recognition endpoint. */
11643
+ const ASR_PATH = "/v1/vibedev/speech/asr";
11644
+ /**
11645
+ * Deadline for one recognition, busy retry included: 30 s, as the Host's DeepSeek recognizer allows, and half a second
11646
+ * more for each second of audio, since the upload and the recognition grow with it (6.9 s took 2.5 s; 120 s gets 90 s).
11647
+ */
11648
+ const RECOGNITION_TIMEOUT_MS = 3e4;
11649
+ const TIMEOUT_PER_AUDIO_SECOND_MS = 500;
11650
+ /**
11651
+ * The deadline for one recording.
11652
+ * @param seconds - its length.
11653
+ * @returns milliseconds.
11654
+ */
11655
+ function recognitionTimeoutMs(seconds) {
11656
+ return RECOGNITION_TIMEOUT_MS + Math.ceil(seconds * TIMEOUT_PER_AUDIO_SECOND_MS);
11657
+ }
11658
+ /** The most bytes of an answer that are read; a transcript of two minutes of speech is a few kilobytes. */
11659
+ const MAX_ANSWER_BYTES = 262144;
11660
+ /** Gateway codes that refuse the recording itself. */
11661
+ const AUDIO_CODES = /^SPEECH_AUDIO_/;
11662
+ const CODES$1 = {
11663
+ "sign-in-required": "sign-in-required",
11664
+ "api-key-invalid": "api-key-invalid",
11665
+ "rate-limited": "rate-limited",
11666
+ "quota-exceeded": "quota-exceeded",
11667
+ "service-unavailable": "service-unavailable",
11668
+ "rejected-input": "invalid-audio",
11669
+ timeout: "timeout",
11670
+ "service-error": "service-error"
11671
+ };
11672
+ /**
11673
+ * Build the recognizer.
11674
+ * @param options - the gateway, the Host's error class and the sign-in state.
11675
+ * @returns the provider to register with `ctx.speechToText`.
11676
+ */
11677
+ function createRecognition(options) {
11678
+ return {
11679
+ info: {
11680
+ id: RECOGNITION_PROVIDER_ID,
11681
+ name: "VibeDev",
11682
+ location: "cloud",
11683
+ languages: ["auto"]
11684
+ },
11685
+ preparation: options.availability,
11686
+ transcribe: (input, signal) => transcribe(options, input.audio, signal)
11687
+ };
11688
+ }
11689
+ async function transcribe(options, audio, signal) {
11690
+ const started = performance.now();
11691
+ signal.throwIfAborted();
11692
+ const fail = (code, message) => new options.errorClass(code, message);
11693
+ let seconds;
11694
+ try {
11695
+ seconds = recordingSeconds(audio);
11696
+ } catch (error) {
11697
+ if (error instanceof RecordingRejected) throw fail("invalid-audio", error.message);
11698
+ throw error;
11699
+ }
11700
+ const { body, contentType } = multipartBody(audio);
11701
+ const timeoutMs = options.timeoutMs ?? recognitionTimeoutMs(seconds);
11702
+ const deadline = AbortSignal.timeout(timeoutMs);
11703
+ const live = AbortSignal.any([signal, deadline]);
11704
+ const call = new GatewayCall(options.gateway);
11705
+ let answer;
11706
+ try {
11707
+ answer = await untilAborted(live, (async () => {
11708
+ return await boundedText(await call.send(ASR_PATH, {
11709
+ method: "POST",
11710
+ body,
11711
+ headers: { "content-type": contentType },
11712
+ signal: live,
11713
+ timeoutMs
11714
+ }), MAX_ANSWER_BYTES);
11715
+ })());
11716
+ } catch (error) {
11717
+ signal.throwIfAborted();
11718
+ if (deadline.aborted) throw fail("timeout", `VibeDev speech recognition did not answer within ${timeoutMs} ms.`);
11719
+ const failure = classifyFailure(error, call.credential, AUDIO_CODES);
11720
+ options.gateway.log(`dsh-vibedev: ${RECOGNITION_PROVIDER_ID} failed (${CODES$1[failure.kind]}): ${failure.diagnostic}`);
11721
+ if (failure.kind === "sign-in-required") options.availability.refresh();
11722
+ throw fail(CODES$1[failure.kind], `VibeDev speech recognition failed: ${failure.diagnostic}.`);
11723
+ }
11724
+ const result = parseTranscript(answer);
11725
+ if (result === void 0) {
11726
+ options.gateway.log(`dsh-vibedev: ${RECOGNITION_PROVIDER_ID} failed (service-error): the answer is not a transcript`);
11727
+ throw fail("service-error", "VibeDev speech recognition answered without a transcript.");
11728
+ }
11729
+ return {
11730
+ text: result.text,
11731
+ audioSeconds: result.durationMs === void 0 ? seconds : result.durationMs / 1e3,
11732
+ inferenceSeconds: (performance.now() - started) / 1e3
11733
+ };
11734
+ }
11735
+ /** `{ text, duration_ms }` from the answer, or undefined when it is not one. */
11736
+ function parseTranscript(answer) {
11737
+ if (answer === void 0) return void 0;
11738
+ let body;
11739
+ try {
11740
+ body = JSON.parse(answer);
11741
+ } catch {
11742
+ return;
11743
+ }
11744
+ if (typeof body !== "object" || body === null) return void 0;
11745
+ const { text, duration_ms: duration } = body;
11746
+ if (typeof text !== "string") return void 0;
11747
+ return {
11748
+ text,
11749
+ durationMs: typeof duration === "number" && Number.isFinite(duration) && duration >= 0 ? duration : void 0
11750
+ };
11751
+ }
11752
+ //#endregion
11753
+ //#region src/speech/synthesis.ts
11754
+ /**
11755
+ * `vibedev-tts`: speech synthesis through the VibeDev gateway (`POST /v1/vibedev/speech/tts`), billed to the VibeDev
11756
+ * account. The text goes up as `{ text, voice_id, format: 'pcm', filter_markdown: false }`, and the audio streams back
11757
+ * as headerless 24 kHz signed 16-bit little-endian mono PCM, in chunks passed on as they arrive (the first one after
11758
+ * about two seconds).
11759
+ * @module dsh-vibedev/speech/synthesis
11760
+ */
11761
+ /** The provider id the VibeDev desktop's read-aloud recognizes as VibeDev's. */
11762
+ const SYNTHESIS_PROVIDER_ID = "vibedev-tts";
11763
+ /** The gateway's synthesis endpoint. */
11764
+ const TTS_PATH = "/v1/vibedev/speech/tts";
11765
+ /** The gateway's voices, in menu order: `stella` (the default) and `tide`. */
11766
+ const SYNTHESIS_VOICES = Object.freeze(["stella", "tide"]);
11767
+ /** Sample rate of the gateway's `pcm` format. */
11768
+ const SYNTHESIS_SAMPLE_RATE = 24e3;
11769
+ /** Longest text one request takes. */
11770
+ const SYNTHESIS_MAX_CHARACTERS = 5e3;
11771
+ /**
11772
+ * The gateway client's deadline for one attempt also bounds reading its body, which streams for as long as the text
11773
+ * takes to speak; the idle deadline above bounds every wait instead.
11774
+ */
11775
+ const NO_ATTEMPT_DEADLINE_MS = 2147483647;
11776
+ const IDLE = "VIBEDEV_TTS_IDLE";
11777
+ /** Gateway codes that refuse the text itself. */
11778
+ const TEXT_CODES = /^SPEECH_TEXT_/;
11779
+ /** The most bytes of an error report read under status 200. */
11780
+ const MAX_REPORT_BYTES = 16384;
11781
+ const CODES = {
11782
+ "sign-in-required": "sign-in-required",
11783
+ "api-key-invalid": "api-key-invalid",
11784
+ "rate-limited": "rate-limited",
11785
+ "quota-exceeded": "quota-exceeded",
11786
+ "service-unavailable": "service-unavailable",
11787
+ "rejected-input": "text-rejected",
11788
+ timeout: "timeout",
11789
+ "service-error": "service-error"
11790
+ };
11791
+ /** A failure the provider found itself, already classified. */
11792
+ var Refusal = class extends Error {
11793
+ code;
11794
+ /** @param code - the registry's failure class. @param message - Host diagnostic. @param options - the cause. */
11795
+ constructor(code, message, options) {
11796
+ super(message, options);
11797
+ this.code = code;
11798
+ }
11799
+ };
11800
+ /**
11801
+ * Build the synthesizer.
11802
+ * @param options - the gateway, the Host's error class and the sign-in state.
11803
+ * @returns the provider to register with `ctx.textToSpeech`.
11804
+ */
11805
+ function createSynthesis(options) {
11806
+ return {
11807
+ info: {
11808
+ id: SYNTHESIS_PROVIDER_ID,
11809
+ name: "VibeDev",
11810
+ location: "cloud",
11811
+ audio: {
11812
+ encoding: "pcm-s16le",
11813
+ sampleRate: SYNTHESIS_SAMPLE_RATE
11814
+ },
11815
+ maxCharacters: SYNTHESIS_MAX_CHARACTERS,
11816
+ voices: SYNTHESIS_VOICES
11817
+ },
11818
+ availability: options.availability,
11819
+ synthesize: (input, signal) => synthesize(options, input, signal)
11820
+ };
11821
+ }
11822
+ /**
11823
+ * Pass the audio on chunk by chunk. Each wait for audio is bounded while a consumer is asking (time the consumer takes
11824
+ * between pulls does not count), the caller's abort ends the request at once, also while nobody is pulling, and audio
11825
+ * already passed on stays valid when a later pull fails.
11826
+ */
11827
+ async function* synthesize(options, input, caller) {
11828
+ try {
11829
+ var _usingCtx$1 = _usingCtx();
11830
+ caller.throwIfAborted();
11831
+ const idleMs = options.idleTimeoutMs ?? 3e4;
11832
+ const consumer = new AbortController();
11833
+ const watchdog = _usingCtx$1.u(idleWatchdog(AbortSignal.any([consumer.signal, caller]), idleMs, IDLE));
11834
+ const call = new GatewayCall(options.gateway);
11835
+ const audio = request(call, input, watchdog.signal);
11836
+ try {
11837
+ for (;;) {
11838
+ const next = await untilAborted(caller, watchdog.next(audio));
11839
+ if (next.done === true) return;
11840
+ yield next.value;
11841
+ }
11842
+ } catch (error) {
11843
+ if (timeoutOf(watchdog.signal, IDLE) !== void 0) {
11844
+ options.gateway.log(`dsh-vibedev: ${SYNTHESIS_PROVIDER_ID} failed (timeout): no audio within ${idleMs} ms`);
11845
+ throw new options.errorClass("timeout", `No VibeDev speech audio arrived within ${idleMs} ms.`);
11846
+ }
11847
+ caller.throwIfAborted();
11848
+ if (error instanceof Refusal) {
11849
+ options.gateway.log(`dsh-vibedev: ${SYNTHESIS_PROVIDER_ID} failed (${error.code}): ${error.message}`);
11850
+ throw new options.errorClass(error.code, error.message, error.cause === void 0 ? void 0 : { cause: error.cause });
11851
+ }
11852
+ const failure = classifyFailure(error, call.credential, TEXT_CODES);
11853
+ options.gateway.log(`dsh-vibedev: ${SYNTHESIS_PROVIDER_ID} failed (${CODES[failure.kind]}): ${failure.diagnostic}`);
11854
+ if (failure.kind === "sign-in-required") options.availability.refresh();
11855
+ throw new options.errorClass(CODES[failure.kind], `VibeDev speech synthesis failed: ${failure.diagnostic}.`);
11856
+ } finally {
11857
+ consumer.abort();
11858
+ audio.return(void 0).catch(() => {});
11859
+ }
11860
+ } catch (_) {
11861
+ _usingCtx$1.e = _;
11862
+ } finally {
11863
+ _usingCtx$1.d();
11864
+ }
11865
+ }
11866
+ /** One request: its answer head through the gateway client, then the audio body as it arrives. */
11867
+ async function* request(call, input, signal) {
11868
+ const response = await call.send(TTS_PATH, {
11869
+ method: "POST",
11870
+ signal,
11871
+ timeoutMs: NO_ATTEMPT_DEADLINE_MS,
11872
+ headers: { accept: "application/octet-stream, application/json" },
11873
+ json: {
11874
+ text: input.text,
11875
+ voice_id: input.voice,
11876
+ format: "pcm",
11877
+ filter_markdown: false
11878
+ }
11879
+ });
11880
+ if (response.headers.get("content-type")?.toLowerCase().startsWith("application/json") === true || response.body === null) {
11881
+ const report = await boundedText(response, MAX_REPORT_BYTES).catch(() => void 0);
11882
+ const code = report === void 0 ? void 0 : reportCode(report);
11883
+ throw new Refusal("service-error", `VibeDev speech synthesis answered HTTP ${response.status} without audio${code === void 0 ? "" : ` (${code})`}.`);
11884
+ }
11885
+ let received = 0;
11886
+ try {
11887
+ for await (const chunk of response.body) {
11888
+ if (chunk.byteLength === 0) continue;
11889
+ received += chunk.byteLength;
11890
+ yield chunk;
11891
+ }
11892
+ } catch (error) {
11893
+ if (signal.aborted) throw error;
11894
+ throw new Refusal("service-error", `The VibeDev speech audio ended early after ${received} bytes.`, { cause: error });
11895
+ }
11896
+ if (received === 0) throw new Refusal("service-error", "VibeDev speech synthesis returned no audio.");
11897
+ }
11898
+ /** The gateway's error code in a JSON report, when it names one. */
11899
+ function reportCode(report) {
11900
+ try {
11901
+ const body = JSON.parse(report);
11902
+ const code = body?.error?.code ?? body?.code;
11903
+ return typeof code === "string" && /^[A-Za-z0-9_.-]{1,80}$/.test(code) ? code : void 0;
11904
+ } catch {
11905
+ return;
11906
+ }
11907
+ }
11908
+ //#endregion
11909
+ //#region src/speech/sign-in.ts
11910
+ /**
11911
+ * The client service that opens the VibeDev sign-in for another plugin: `vibedevSignIn`. Pure declarations only, so
11912
+ * the browser half bundles this module as it is and the Host half publishes the same contract in its types.
11913
+ *
11914
+ * Contract (dsh-vibedev 0.12.0). The VibeDev desktop's voice input and read-aloud offer "登录 VibeDev" while their
11915
+ * provider is a VibeDev one (`vibedev-asr`, `vibedev-tts`; any `vibedev-*` id) and it reports
11916
+ * `{ phase: 'unavailable', reason: 'sign-in-required' }` or fails with `sign-in-required`; that action calls
11917
+ * `open()`. The service is provided in a client's root scope while that client can read the VibeDev account (the
11918
+ * Host answered its account read, as it does for the owner's desktop window or web page; a peer the plugin's routes
11919
+ * refuse never gets it), and is withdrawn when the plugin's client unloads. Consumers follow it with
11920
+ * `ctx.inject(['vibedevSignIn'], …)` and offer the action only while it is present; they declare the context member
11921
+ * themselves, for example:
11922
+ *
11923
+ * ```ts
11924
+ * import type { VibeDevSignIn } from '@vibedev-si/dsh-vibedev'
11925
+ * declare module '@deepseek-ai/cordis' {
11926
+ * interface Context { vibedevSignIn: VibeDevSignIn }
11927
+ * }
11928
+ * ```
11929
+ * @module dsh-vibedev/speech/sign-in
11930
+ */
11931
+ /** The service name: `ctx.get('vibedevSignIn')`. Kept as it is: the VibeDev desktop looks it up by this name. */
11932
+ const VIBEDEV_SIGN_IN_SERVICE = "vibedevSignIn";
11933
+ //#endregion
11934
+ //#region src/speech/index.ts
11935
+ /**
11936
+ * Register the speech providers wherever the Host's registries can take them, for as long as they are there.
11937
+ * @param ctx - the plugin context.
11938
+ * @param wiring - the gateway client, the credential chain and the sign-in changes.
11939
+ */
11940
+ function installSpeech(ctx, wiring) {
11941
+ const modules = wiring.modules ?? HOST_SPEECH_MODULES;
11942
+ const listeners = /* @__PURE__ */ new Set();
11943
+ const changed = () => {
11944
+ for (const listener of [...listeners]) listener();
11945
+ };
11946
+ const onChange = (listener) => {
11947
+ listeners.add(listener);
11948
+ return () => {
11949
+ listeners.delete(listener);
11950
+ };
11951
+ };
11952
+ ctx.effect(() => wiring.onSignInChange(changed), "dsh-vibedev: speech sign-in changes");
11953
+ ctx.inject(["deepseekAccount"], (accountCtx) => {
11954
+ accountCtx.effect(() => {
11955
+ const controller = new AbortController();
11956
+ const account = accountCtx.deepseekAccount;
11957
+ if (typeof account.watch === "function") {
11958
+ const views = account.watch(controller.signal);
11959
+ (async () => {
11960
+ try {
11961
+ for await (const _view of views) changed();
11962
+ } catch {}
11963
+ })();
11964
+ }
11965
+ changed();
11966
+ return () => {
11967
+ controller.abort();
11968
+ changed();
11969
+ };
11970
+ }, "dsh-vibedev: speech account watch");
11971
+ });
11972
+ join$1(ctx, wiring, onChange, {
11973
+ service: "speechToText",
11974
+ providerId: RECOGNITION_PROVIDER_ID,
11975
+ load: modules.speechToText,
11976
+ errorName: "SpeechTranscriptionError",
11977
+ register: (registry, errorClass, availability) => registry.register(createRecognition({
11978
+ gateway: wiring,
11979
+ errorClass,
11980
+ availability,
11981
+ ...wiring.recognitionTimeoutMs === void 0 ? {} : { timeoutMs: wiring.recognitionTimeoutMs }
11982
+ }))
11983
+ });
11984
+ join$1(ctx, wiring, onChange, {
11985
+ service: "textToSpeech",
11986
+ providerId: SYNTHESIS_PROVIDER_ID,
11987
+ load: modules.textToSpeech,
11988
+ errorName: "SpeechSynthesisError",
11989
+ register: (registry, errorClass, availability) => registry.register(createSynthesis({
11990
+ gateway: wiring,
11991
+ errorClass,
11992
+ availability,
11993
+ ...wiring.synthesisIdleTimeoutMs === void 0 ? {} : { idleTimeoutMs: wiring.synthesisIdleTimeoutMs }
11994
+ }))
11995
+ });
11996
+ }
11997
+ /**
11998
+ * While the registry service is present: load its package, and register the provider when the package exports the
11999
+ * error class. The provider leaves with the service, and with the plugin.
12000
+ */
12001
+ function join$1(ctx, wiring, onChange, registration) {
12002
+ ctx.inject([registration.service], (scoped) => {
12003
+ scoped.effect(() => {
12004
+ let active = true;
12005
+ let availability;
12006
+ let unsubscribe;
12007
+ let unregister;
12008
+ (async () => {
12009
+ const errorClass = await hostErrorClass(registration.load, registration.errorName);
12010
+ if (!active) return;
12011
+ if (errorClass === void 0) {
12012
+ scoped.logger.debug(`dsh-vibedev: this DSH's ${registration.service} exports no ${registration.errorName}; ${registration.providerId} is not registered`);
12013
+ return;
12014
+ }
12015
+ const registry = scoped.get(registration.service);
12016
+ if (typeof registry?.register !== "function") return;
12017
+ const source = new CredentialAvailability(async () => await wiring.resolveCredential() !== void 0);
12018
+ try {
12019
+ unregister = registration.register(registry, errorClass, source);
12020
+ } catch (error) {
12021
+ source.stop();
12022
+ wiring.log(`dsh-vibedev: ${registration.providerId} was not registered: ${error instanceof Error ? error.message : String(error)}`);
12023
+ return;
12024
+ }
12025
+ availability = source;
12026
+ unsubscribe = onChange(() => {
12027
+ source.refresh();
12028
+ });
12029
+ source.refresh();
12030
+ })().catch((error) => {
12031
+ wiring.log(`dsh-vibedev: ${registration.providerId} was not registered: ${error instanceof Error ? error.message : String(error)}`);
12032
+ });
12033
+ return async () => {
12034
+ active = false;
12035
+ unsubscribe?.();
12036
+ availability?.stop();
12037
+ await unregister?.();
12038
+ };
12039
+ }, `dsh-vibedev: ${registration.providerId}`);
12040
+ });
12041
+ }
12042
+ //#endregion
10724
12043
  //#region src/content/errors.ts
10725
12044
  /**
10726
12045
  * The content library's failures. Callers of `vibedevContent` (dsh-film's
@@ -11255,6 +12574,13 @@ function toNumber(value) {
11255
12574
  * Token price is never shown as an unconditional per-second price, never as
11256
12575
  * 未定价 and never as free — and what cannot be estimated says so.
11257
12576
  *
12577
+ * Speech billed per character (`character`) is quoted on the text as it is
12578
+ * sent: each Chinese character (a CJK unified ideograph, any extension) counts
12579
+ * as the model's `han_character_weight` (2 when undeclared), every other
12580
+ * character — letters, digits, spaces, line breaks, punctuation, the `@AudioN`
12581
+ * reference markers — as 1. How the gateway counts is final, so such a quote
12582
+ * always says the gateway's settlement decides.
12583
+ *
11258
12584
  * A model without a price is "not priced" (未定价), never free: only a price the
11259
12585
  * catalog states as zero is shown as ¥0.
11260
12586
  * @module dsh-vibedev/pricing
@@ -11287,12 +12613,13 @@ function tierFor(pricing, wanted) {
11287
12613
  return pricing.tiers.length === 1 ? pricing.tiers[0] : void 0;
11288
12614
  }
11289
12615
  /**
11290
- * The unit after a price: `/s`, `/原始秒`, `/次`.
12616
+ * The unit after a price: `/s`, `/原始秒`, `/次`, `/计费字符(汉字按 2 个算)`.
11291
12617
  * @param unit - the price unit.
11292
12618
  * @param kind - the kind of model, which names a generation (an image, a video, a request).
12619
+ * @param hanWeight - per character: what one Chinese character counts as.
11293
12620
  * @returns the suffix in both languages.
11294
12621
  */
11295
- function unitSuffix(unit, kind) {
12622
+ function unitSuffix(unit, kind, hanWeight = 2) {
11296
12623
  switch (unit) {
11297
12624
  case "second": return {
11298
12625
  en: "/s",
@@ -11306,6 +12633,13 @@ function unitSuffix(unit, kind) {
11306
12633
  en: "/min",
11307
12634
  zh: "/分钟"
11308
12635
  };
12636
+ case "character": {
12637
+ const weight = format(decimal(hanWeight));
12638
+ return {
12639
+ en: ` per billable character (Chinese characters count as ${weight})`,
12640
+ zh: `/计费字符(汉字按 ${weight} 个算)`
12641
+ };
12642
+ }
11309
12643
  default: return kind === "image" ? {
11310
12644
  en: " per image",
11311
12645
  zh: "/张"
@@ -11315,6 +12649,22 @@ function unitSuffix(unit, kind) {
11315
12649
  };
11316
12650
  }
11317
12651
  }
12652
+ /** What one Chinese character of a model's text counts as under per-character billing. */
12653
+ function hanWeightOf(model) {
12654
+ return model.audio?.hanCharacterWeight ?? 2;
12655
+ }
12656
+ /** A unit price as shown: per-character prices exactly (`¥0.0003`, `¥0.00025`), the others as {@link yuan} does. */
12657
+ function unitPrice(unit, amount) {
12658
+ return unit === "character" ? exactYuan(amount) : yuan(amount);
12659
+ }
12660
+ /** Chinese characters: CJK unified ideographs, every extension included (Unicode's `Unified_Ideograph`). */
12661
+ const HAN_CHARACTERS = /\p{Unified_Ideograph}/gu;
12662
+ /** `han × weight + other`, exactly. */
12663
+ function billableCount(text, hanWeight) {
12664
+ const han = text.match(HAN_CHARACTERS)?.length ?? 0;
12665
+ const other = [...text].length - han;
12666
+ return add(multiply(decimal(han), decimal(hanWeight)), decimal(other));
12667
+ }
11318
12668
  /** Shown for a model whose `video_pricing` this plugin cannot use. */
11319
12669
  const VIDEO_PRICING_UNSUPPORTED = {
11320
12670
  en: "this plugin version does not support this video pricing mode: estimate unavailable; billed by actual video Token usage",
@@ -11352,8 +12702,8 @@ function describeTokenPricing(pricing, lang) {
11352
12702
  return lang === "zh" ? `视频 Token 计价:${rules.join(";")}` : `video Token pricing (billed by actual video Tokens): ${rules.join(", ")}`;
11353
12703
  }
11354
12704
  /**
11355
- * A one-line price for listings: `¥0.10 per image`, `¥0.99/s (720p)`; `not priced` without a price.
11356
- * A video Token price lists its rules (`视频 Token 计价:480p 无参考视频 ¥60.06/百万 Token(预计 ¥0.5819/秒)…`).
12705
+ * A one-line price for listings: `¥0.10 per image`, `¥0.99/s (720p)`, `¥0.0003/计费字符(汉字按 2 个算)`; `not priced`
12706
+ * without a price. A video Token price lists its rules (`视频 Token 计价:480p 无参考视频 ¥60.06/百万 Token(预计 ¥0.5819/秒)…`).
11357
12707
  * @param model - the model.
11358
12708
  * @param lang - the language.
11359
12709
  * @returns the price line.
@@ -11363,9 +12713,9 @@ function describePrice(model, lang = "en") {
11363
12713
  if (model.videoPricing !== void 0) return describeTokenPricing(model.videoPricing, lang);
11364
12714
  const pricing = model.pricing;
11365
12715
  if (pricing === void 0) return UNPRICED[lang];
11366
- const per = (unit) => unitSuffix(unit, model.kind)[lang];
11367
- const parts = pricing.tiers.map((tier) => `${yuan(tier.amount)}${per(tier.unit)} (${tier.tier})`);
11368
- if (pricing.default !== void 0 && (pricing.tiers.length === 0 || !pricing.tiers.some((tier) => tier.amount === pricing.default?.amount && tier.unit === pricing.default.unit))) parts.push(`${yuan(pricing.default.amount)}${per(pricing.default.unit)}${pricing.tiers.length === 0 ? "" : lang === "zh" ? "(其他)" : " otherwise"}`);
12716
+ const per = (unit, amount) => `${unitPrice(unit, amount)}${unitSuffix(unit, model.kind, hanWeightOf(model))[lang]}`;
12717
+ const parts = pricing.tiers.map((tier) => `${per(tier.unit, tier.amount)} (${tier.tier})`);
12718
+ if (pricing.default !== void 0 && (pricing.tiers.length === 0 || !pricing.tiers.some((tier) => tier.amount === pricing.default?.amount && tier.unit === pricing.default.unit))) parts.push(`${per(pricing.default.unit, pricing.default.amount)}${pricing.tiers.length === 0 ? "" : lang === "zh" ? "(其他)" : " otherwise"}`);
11369
12719
  return parts.length === 0 ? UNPRICED[lang] : parts.join(", ");
11370
12720
  }
11371
12721
  /**
@@ -11388,23 +12738,84 @@ function legacyVideoPrice(model, resolution) {
11388
12738
  const only = model.video?.resolutions?.length === 1 ? model.video.resolutions[0] : void 0;
11389
12739
  return tierFor(model.pricing, resolution ?? only);
11390
12740
  }
12741
+ /** Shown wherever the catalog gives an audio model no price. */
12742
+ const AUDIO_UNPRICED_BASIS = {
12743
+ en: "The catalog states no price for this model; the gateway receipt shows the charge.",
12744
+ zh: "目录未给出价格,以网关结算为准。"
12745
+ };
12746
+ /**
12747
+ * An estimate in yuan, without the sign: half up to two decimals (`0.37`); below ¥0.10, to four (`0.0036`), and
12748
+ * exactly when even that would round it away, so a short text never reads as ¥0.00.
12749
+ */
12750
+ function estimateText(amount) {
12751
+ if (amount.units === 0n) return "0.00";
12752
+ if (toNumber(amount) >= .1) return format(roundHalfUp(amount, 2), 2);
12753
+ const rounded = roundHalfUp(amount, 4);
12754
+ return format(rounded.units === 0n ? amount : rounded, 2);
12755
+ }
12756
+ /** Quote speech billed per character: on the text as sent, when there is one. */
12757
+ function quoteCharacters(model, price, text) {
12758
+ const weight = hanWeightOf(model);
12759
+ const count = text === void 0 || text === "" ? void 0 : billableCount(text, weight);
12760
+ const facts = {
12761
+ unit: "character",
12762
+ hanCharacterWeight: weight,
12763
+ ...count === void 0 ? {} : { billableCharacters: toNumber(count) }
12764
+ };
12765
+ if (price === void 0) return {
12766
+ priced: false,
12767
+ ...facts,
12768
+ label: UNPRICED,
12769
+ basis: AUDIO_UNPRICED_BASIS
12770
+ };
12771
+ const suffix = unitSuffix("character", model.kind, weight);
12772
+ const each = unitPrice("character", price.amount);
12773
+ const label = {
12774
+ en: `${each}${suffix.en}`,
12775
+ zh: `${each}${suffix.zh}`
12776
+ };
12777
+ const base = {
12778
+ priced: true,
12779
+ ...facts,
12780
+ unitPriceCny: price.amount,
12781
+ label
12782
+ };
12783
+ const counts = format(decimal(weight));
12784
+ if (count === void 0) return {
12785
+ ...base,
12786
+ basis: {
12787
+ en: `${label.en}, counted on the text read aloud; final billing follows the gateway receipt`,
12788
+ zh: `${label.zh},按朗读文本计费,实际以网关结算为准`
12789
+ }
12790
+ };
12791
+ const amount = multiply(decimal(price.amount), count);
12792
+ const shown = `¥${estimateText(amount)}`;
12793
+ return {
12794
+ ...base,
12795
+ amountCny: toNumber(amount),
12796
+ basis: {
12797
+ en: `about ${shown} (${each} per billable character, Chinese characters count as ${counts}, ${format(count)} billable characters); final billing follows the gateway receipt`,
12798
+ zh: `约 ${shown}(${each}/计费字符,汉字按 ${counts} 个算,共 ${format(count)} 个计费字符),实际以网关结算为准`
12799
+ }
12800
+ };
12801
+ }
11391
12802
  /**
11392
12803
  * Quote an audio request: music, podcast and speech generation, or a transcription.
11393
12804
  * @param model - the audio or transcription model.
11394
- * @param inputSeconds - for a transcription, the measured length of the input, when known.
12805
+ * @param input - for a transcription, the measured length of the input in seconds (or `{inputSeconds}`); for speech
12806
+ * billed per character, `{text}`: the text as it is sent. Without them the quote gives the unit price only.
11395
12807
  * @returns the quote; `priced: false` (未定价) when the catalog gives no usable price.
11396
12808
  */
11397
- function quoteAudio(model, inputSeconds) {
12809
+ function quoteAudio(model, input) {
12810
+ const { inputSeconds, text } = typeof input === "number" ? { inputSeconds: input } : input ?? {};
11398
12811
  const price = model.pricing === void 0 ? void 0 : tierFor(model.pricing, void 0);
11399
12812
  const unit = price?.unit ?? model.audio?.billingUnit;
12813
+ if (unit === "character") return quoteCharacters(model, price, text);
11400
12814
  if (price === void 0 || unit === void 0 || unit === "second") return {
11401
12815
  priced: false,
11402
12816
  ...unit === void 0 ? {} : { unit },
11403
12817
  label: UNPRICED,
11404
- basis: {
11405
- en: "The catalog states no price for this model; the gateway receipt shows the charge.",
11406
- zh: "目录未给出价格,以网关结算为准。"
11407
- }
12818
+ basis: AUDIO_UNPRICED_BASIS
11408
12819
  };
11409
12820
  const suffix = unitSuffix(unit, model.kind);
11410
12821
  const label = {
@@ -11451,6 +12862,16 @@ function quoteAudio(model, inputSeconds) {
11451
12862
  }
11452
12863
  };
11453
12864
  }
12865
+ /**
12866
+ * The estimate an audio task records: two decimals (`0.50`); per character, four below ¥0.10 (`0.0036`) so a short
12867
+ * text is never recorded as 0.00.
12868
+ * @param quote - the quote.
12869
+ * @returns the amount in yuan, or undefined without an amount.
12870
+ */
12871
+ function audioQuotedCny(quote) {
12872
+ if (quote.amountCny === void 0) return void 0;
12873
+ return quote.unit === "character" ? estimateText(decimal(quote.amountCny)) : quote.amountCny.toFixed(2);
12874
+ }
11454
12875
  /** Shown wherever video Token pricing gives no estimate. */
11455
12876
  const TOKEN_UNAVAILABLE = {
11456
12877
  en: "estimate unavailable; billed by actual video Token usage",
@@ -12654,8 +14075,9 @@ function withAudioMarkers(text, references) {
12654
14075
  }
12655
14076
  /**
12656
14077
  * Everything before an audio submission: choose the model, check every field
12657
- * against its declaration, upload and measure speech references, price it,
12658
- * confirm the spending, and build the task under the operation's key.
14078
+ * against its declaration, upload and measure speech references, price it
14079
+ * (speech billed per character on the text as sent, `@AudioN` markers
14080
+ * included), confirm the spending, and build the task under the operation's key.
12659
14081
  * @param runtime - the media runtime.
12660
14082
  * @param call - the tool call or host call.
12661
14083
  * @param request - what to generate.
@@ -12686,7 +14108,8 @@ async function prepareAudioTask(runtime, call, request, save) {
12686
14108
  if (length > 400) notes.push(`The speech text is ${length} characters; up to 400 per request is recommended (the model reads longer texts faster). For long narration, split it into parts and pass the same references with every part so the voice stays the same.`);
12687
14109
  }
12688
14110
  if (kind === "music" && has(request.sourceAudio)) body.source_audio_url = await uploadSourceAudio(runtime, call, request.sourceAudio.trim());
12689
- const quote = quoteAudio(model);
14111
+ const spoken = kind === "speech" && promptField !== void 0 && typeof body[promptField] === "string" ? body[promptField] : void 0;
14112
+ const quote = quoteAudio(model, spoken === void 0 ? void 0 : { text: spoken });
12690
14113
  const mode = kind === "music" ? musicModeOf(request) : "generate";
12691
14114
  const what = {
12692
14115
  music: mode === "voice_cover" ? {
@@ -12709,9 +14132,10 @@ async function prepareAudioTask(runtime, call, request, save) {
12709
14132
  }
12710
14133
  }[kind];
12711
14134
  await runtime.confirmSpending(call, "audio_generate", {
12712
- en: `Generate ${what.en} with ${model.id}: ${quote.basis.en}.`,
12713
- zh: `用 ${model.id} 生成${what.zh}:${quote.basis.zh}。`
14135
+ en: sentence(`Generate ${what.en} with ${model.id}: ${quote.basis.en}`, "."),
14136
+ zh: sentence(`用 ${model.id} 生成${what.zh}:${quote.basis.zh}`, "。")
12714
14137
  });
14138
+ const estimatedCny = audioQuotedCny(quote);
12715
14139
  const now = runtime.now();
12716
14140
  const prompt = request.prompt?.trim();
12717
14141
  return {
@@ -12733,7 +14157,7 @@ async function prepareAudioTask(runtime, call, request, save) {
12733
14157
  body,
12734
14158
  status: "submitting",
12735
14159
  audioKind: kind,
12736
- ...quote.amountCny === void 0 ? {} : { estimatedCny: quote.amountCny.toFixed(2) },
14160
+ ...estimatedCny === void 0 ? {} : { estimatedCny },
12737
14161
  ...quote.unit === void 0 ? {} : { billing: {
12738
14162
  unit: quote.unit,
12739
14163
  ...quote.unitPriceCny === void 0 ? {} : { unitPriceCny: String(quote.unitPriceCny) }
@@ -12742,6 +14166,10 @@ async function prepareAudioTask(runtime, call, request, save) {
12742
14166
  ...notes.length === 0 ? {} : { notes }
12743
14167
  };
12744
14168
  }
14169
+ /** A sentence ended once: a text that already ends in a stop (a price basis can) gets no second one. */
14170
+ function sentence(text, stop) {
14171
+ return /[.。!!??]$/.test(text) ? text : `${text}${stop}`;
14172
+ }
12745
14173
  function excerptOf(text, max = 60) {
12746
14174
  const flat = text.replace(/\s+/g, " ").trim();
12747
14175
  const chars = [...flat];
@@ -16418,7 +17846,7 @@ function mediaAccountTool(runtime, chain, login) {
16418
17846
  function audioGenerateTool(runtime) {
16419
17847
  return defineTool({
16420
17848
  name: "audio_generate",
16421
- 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; to keep a fixed voice you must pass references, the reference audio of that voice) 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. Speech voices: the references decide the voice, and the plugin puts @Audio1 @Audio2 … in front of the text so the model uses them. When the user wants a dialogue with several characters, pass one reference per voice and mark in the text which reference reads each passage with @Audio1/@Audio2/@Audio3 (references[0] is @Audio1); a text that already holds such a marker is sent as written. Voice-overs: generate one batch of voice-over in one continuous call where you can, rather than many separate calls: the same model reads the same text with quite different pace and pauses from one call to the next (two runs measured 2 s apart), so parts from separate calls do not keep the same rhythm. When it must be split (over about 400 characters, say), keep the same references, the same format and sample rate, and submit the parts one after another in the same piece of work; parts without the same references also change voice.",
17849
+ 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; to keep a fixed voice you must pass references, the reference audio of that voice) 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 or per billable character of the text sent, as each model states). 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. Speech voices: the references decide the voice, and the plugin puts @Audio1 @Audio2 … in front of the text so the model uses them. When the user wants a dialogue with several characters, pass one reference per voice and mark in the text which reference reads each passage with @Audio1/@Audio2/@Audio3 (references[0] is @Audio1); a text that already holds such a marker is sent as written. Voice-overs: generate one batch of voice-over in one continuous call where you can, rather than many separate calls: the same model reads the same text with quite different pace and pauses from one call to the next (two runs measured 2 s apart), so parts from separate calls do not keep the same rhythm. When it must be split (over about 400 characters, say), keep the same references, the same format and sample rate, and submit the parts one after another in the same piece of work; parts without the same references also change voice.",
16422
17850
  parameters: {
16423
17851
  type: {
16424
17852
  type: "string",
@@ -16589,7 +18017,7 @@ function audioGenerateTool(runtime) {
16589
18017
  ...base,
16590
18018
  status: accepted.status,
16591
18019
  jobId,
16592
- message: `${unconfirmed ? `${name} task ${accepted.id} (${model.id}): ${UNCONFIRMED_NOTE}` : `${name} task submitted to ${model.id}.`} Background job ${jobId} reports when it finishes; files are saved under ${runtime.display(exec, accepted.outputDir)}. ${accepted.estimatedCny === void 0 ? `Price: ${quote.basis.en}. ` : `Estimated ${yuan(Number(accepted.estimatedCny))}, charged only if it succeeds. `}Carry on with other work meanwhile; there is no need to poll.` + advice
18020
+ message: `${unconfirmed ? `${name} task ${accepted.id} (${model.id}): ${UNCONFIRMED_NOTE}` : `${name} task submitted to ${model.id}.`} Background job ${jobId} reports when it finishes; files are saved under ${runtime.display(exec, accepted.outputDir)}. ${accepted.estimatedCny === void 0 ? `Price: ${quote.basis.en.replace(/\.$/, "")}. ` : `Estimated ${yuan(Number(accepted.estimatedCny))}, charged only if it succeeds. `}Carry on with other work meanwhile; there is no need to poll.` + advice
16593
18021
  };
16594
18022
  const final = await waitForTask(runtime, exec, accepted);
16595
18023
  return {
@@ -17045,15 +18473,15 @@ function audioTranscribeTool(runtime) {
17045
18473
  * Which accepted gateway requests may have spent money, so the balance is read again after them.
17046
18474
  * @module dsh-vibedev/gateway/paid-path
17047
18475
  */
17048
- /** Generations and transcriptions (uploads and reads are free). */
17049
- const PAID_PATH = /^\/v1\/(?:images|videos|audio)(?:\/|$)/;
18476
+ /** Generations, transcriptions and realtime speech (`/v1/vibedev/speech/asr|tts`); uploads and reads are free. */
18477
+ const PAID_PATH = /^\/v1\/(?:images|videos|audio|vibedev\/speech)(?:\/|$)/;
17050
18478
  /** Free paths under a paid prefix: voice profiles are created, listed and deleted without a charge. */
17051
18479
  const FREE_PATH = /^\/v1\/audio\/voice-profiles(?:\/|$)/;
17052
18480
  /**
17053
18481
  * Whether an accepted request may have been charged.
17054
18482
  * @param method - the HTTP method.
17055
18483
  * @param path - the request path, without the query.
17056
- * @returns true for a POST to a generation or transcription endpoint.
18484
+ * @returns true for a POST to a generation, transcription or speech endpoint.
17057
18485
  */
17058
18486
  function isPaidRequest(method, path) {
17059
18487
  return method === "POST" && PAID_PATH.test(path) && !FREE_PATH.test(path);
@@ -17460,6 +18888,7 @@ const Config = Schema.object({
17460
18888
  claudeCacheTtl: Schema.union(CLAUDE_CACHE_TTLS.map((value) => Schema.const(value))).default("default").volatile(),
17461
18889
  preferredModels: Schema.array(Schema.string()).default([]),
17462
18890
  openBrowserOnSignIn: Schema.boolean().default(true),
18891
+ remoteSignInBaseUrl: Schema.string().default(""),
17463
18892
  catalogRefreshMinutes: Schema.number().min(1).max(1440).default(30),
17464
18893
  resendWindowMs: Schema.natural().min(1e3).max(108e5).default(3e5),
17465
18894
  submitAttempts: Schema.natural().min(1).max(30).default(3),
@@ -17490,6 +18919,7 @@ const Config = Schema.object({
17490
18919
  claudeCacheTtl: "Claude 提示词缓存保留时间(默认 / 5分钟 / 1小时)",
17491
18920
  preferredModels: "排在最前的 VibeDev 模型(按顺序,留空按网关顺序)",
17492
18921
  openBrowserOnSignIn: "登录时自动打开系统浏览器",
18922
+ remoteSignInBaseUrl: "远程主机登录地址(云环境 / 远程访问用,如 https://<主机ID>.h.vibedev.studio;留空为桌面版本机登录)",
17493
18923
  catalogRefreshMinutes: "模型目录定时刷新间隔(分钟;没人打开余额卡片、账号菜单或设置时的兜底)",
17494
18924
  resendWindowMs: "原键提交核对窗口(毫秒;仅适用于新操作,默认5分钟)",
17495
18925
  submitAttempts: "原键首次提交总尝试数(含首次,默认3)",
@@ -17521,6 +18951,7 @@ const Config = Schema.object({
17521
18951
  claudeCacheTtl: "Claude prompt cache lifetime (default / 5 minutes / 1 hour)",
17522
18952
  preferredModels: "VibeDev models listed first, in this order (empty: the gateway's order)",
17523
18953
  openBrowserOnSignIn: "Open the system browser when signing in",
18954
+ remoteSignInBaseUrl: "Remote host sign-in origin (cloud hosts and remote access, such as https://<host id>.h.vibedev.studio; empty for the desktop's local sign-in)",
17524
18955
  catalogRefreshMinutes: "Model catalog refresh interval in minutes (the fallback when nobody opens the balance card, the account menu or Settings)",
17525
18956
  resendWindowMs: "Same-key recovery window in milliseconds (new operations only; default 5 minutes)",
17526
18957
  submitAttempts: "Initial same-key attempts including first dispatch (default 3)",
@@ -17556,13 +18987,34 @@ function apply(ctx, config) {
17556
18987
  ctx.logger.warn(message);
17557
18988
  };
17558
18989
  const storage = grantStorage(stateDir, () => ctx.get("credentials"), origin);
18990
+ let remoteBaseUrl;
18991
+ try {
18992
+ remoteBaseUrl = remoteSignInOrigin(config.remoteSignInBaseUrl);
18993
+ } catch (error) {
18994
+ warn(`dsh-vibedev: ${error.message}; remote sign-in is off`);
18995
+ }
18996
+ let remoteRoute = false;
17559
18997
  const login = new PluginLogin({
17560
18998
  origin,
17561
18999
  userAgent,
17562
19000
  log: warn,
17563
19001
  storage,
17564
19002
  client: config.client.trim() || "vibedev-plugin",
17565
- openBrowser: (url) => config.openBrowserOnSignIn ? openInBrowser(url) : Promise.resolve(false)
19003
+ openBrowser: (url) => config.openBrowserOnSignIn ? openInBrowser(url) : Promise.resolve(false),
19004
+ ...remoteBaseUrl === void 0 ? {} : {
19005
+ remoteBaseUrl,
19006
+ remoteCallbackReady: () => remoteRoute
19007
+ }
19008
+ });
19009
+ if (remoteBaseUrl !== void 0) ctx.inject(["webServer"], (webCtx) => {
19010
+ webCtx.effect(() => {
19011
+ const dispose = registerRemoteCallback(webCtx.webServer, login);
19012
+ remoteRoute = true;
19013
+ return () => {
19014
+ remoteRoute = false;
19015
+ dispose();
19016
+ };
19017
+ }, "dsh-vibedev: remote sign-in callback");
17566
19018
  });
17567
19019
  ctx.inject(["credentials"], (scoped) => {
17568
19020
  scoped.on("credentials/record-updated", (key) => {
@@ -17732,6 +19184,12 @@ function apply(ctx, config) {
17732
19184
  });
17733
19185
  });
17734
19186
  });
19187
+ installSpeech(ctx, {
19188
+ http,
19189
+ resolveCredential: () => chain.resolve(),
19190
+ onSignInChange: (listener) => login.onChange(listener),
19191
+ log: warn
19192
+ });
17735
19193
  const accountService = new AccountService({
17736
19194
  origin,
17737
19195
  userAgent,
@@ -17825,6 +19283,6 @@ function apply(ctx, config) {
17825
19283
  });
17826
19284
  }
17827
19285
  //#endregion
17828
- export { ACCOUNT_ROUTE_PREFIX, AccountService, CHAT_CONSENT_ENDPOINT_ORIGIN, CHAT_CONSENT_FIRST_PARTY_ORIGINS, CHAT_CONSENT_MAX_CALLBACK_LENGTH, CHAT_CONSENT_VERSION, ChatConsentHostService, Config, ContentError, ContentHostService, DEFAULT_CHAT_CONSENT_CALLBACK_URL, DEFAULT_CHAT_CONSENT_ENDPOINT, DESKTOP_CHAT_CONSENT_SERVICE, FEEDBACK_ATTACHMENT_ROUTE, FEEDBACK_ROUTE, GATEWAY_FETCH_PROVIDER_ID as FETCH_PROVIDER_ID, GatewayFetchProvider, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, NegotiatedGatewayFetchProvider, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_RELAY_ROUTE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, readChatConsentCallback, readChatConsentRequest, readChatConsentResult, readGatewayFetchCapability, version };
19286
+ export { ACCOUNT_ROUTE_PREFIX, AccountService, CHAT_CONSENT_ENDPOINT_ORIGIN, CHAT_CONSENT_FIRST_PARTY_ORIGINS, CHAT_CONSENT_MAX_CALLBACK_LENGTH, CHAT_CONSENT_VERSION, ChatConsentHostService, Config, ContentError, ContentHostService, DEFAULT_CHAT_CONSENT_CALLBACK_URL, DEFAULT_CHAT_CONSENT_ENDPOINT, DESKTOP_CHAT_CONSENT_SERVICE, FEEDBACK_ATTACHMENT_ROUTE, FEEDBACK_ROUTE, GATEWAY_FETCH_PROVIDER_ID as FETCH_PROVIDER_ID, GatewayFetchProvider, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, NegotiatedGatewayFetchProvider, RECOGNITION_PROVIDER_ID, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, SYNTHESIS_PROVIDER_ID, VIBEDEV_RELAY_ROUTE, VIBEDEV_ROUTE, VIBEDEV_SIGN_IN_SERVICE, apply, inject, name, parseMediaCatalog, readChatConsentCallback, readChatConsentRequest, readChatConsentResult, readGatewayFetchCapability, version };
17829
19287
 
17830
19288
  //# sourceMappingURL=index.js.map