@vibedev-si/dsh-vibedev 0.11.6 → 0.12.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
@@ -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 {
@@ -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
  }
@@ -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,8 +5135,59 @@ 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$7(raw?.reason) ?? text$7(raw?.code) ?? text$7(record$11(raw?.error)?.code);
5190
+ }
5129
5191
  function base64url(data) {
5130
5192
  return data.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
5131
5193
  }
@@ -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 = [];
@@ -7903,7 +8058,7 @@ var GatewayAdapter = class extends LlmAdapter {
7903
8058
  }
7904
8059
  async *streamWithSnapshot(options, snapshot, preparedTtl) {
7905
8060
  try {
7906
- var _usingCtx$1 = _usingCtx();
8061
+ var _usingCtx$2 = _usingCtx();
7907
8062
  if (options.stop !== void 0) throw new LlmError("the VibeDev gateway adapter does not support GenerateOptions.stop", "UNSUPPORTED_OPTION");
7908
8063
  const { model, catalog } = this.modelOf(snapshot, options.provider, options.model);
7909
8064
  const claudeCacheTtl = preparedTtl ?? this.cacheTtlFor(model);
@@ -7916,7 +8071,7 @@ var GatewayAdapter = class extends LlmAdapter {
7916
8071
  const consumer = new AbortController();
7917
8072
  const upstream = options.signal === void 0 ? consumer.signal : AbortSignal.any([options.signal, consumer.signal]);
7918
8073
  const streamIdleTimeoutMs = this.config.streamIdleTimeoutMs ?? 3e5;
7919
- const watchdog = _usingCtx$1.u(idleWatchdog(upstream, streamIdleTimeoutMs, "LLM_STREAM_IDLE_TIMEOUT"));
8074
+ const watchdog = _usingCtx$2.u(idleWatchdog(upstream, streamIdleTimeoutMs, "LLM_STREAM_IDLE_TIMEOUT"));
7920
8075
  let answered = false;
7921
8076
  try {
7922
8077
  const containsImage = options.messages.some((message) => contentHasImage(message.content));
@@ -8072,9 +8227,9 @@ var GatewayAdapter = class extends LlmAdapter {
8072
8227
  } catch {}
8073
8228
  }
8074
8229
  } catch (_) {
8075
- _usingCtx$1.e = _;
8230
+ _usingCtx$2.e = _;
8076
8231
  } finally {
8077
- _usingCtx$1.d();
8232
+ _usingCtx$2.d();
8078
8233
  }
8079
8234
  }
8080
8235
  /**
@@ -8312,7 +8467,7 @@ function installGatewayModels(ctx, options) {
8312
8467
  if (response.status === 401) await options.rejectCredential(credential).catch(() => void 0);
8313
8468
  if (!response.ok) throw new Error(`gateway catalog answered HTTP ${response.status}`);
8314
8469
  hidden = void 0;
8315
- publish(preferredFirst(parseCatalog(await response.json()), options.preferredModels()));
8470
+ publish(preferredFirst(parseCatalog$1(await response.json()), options.preferredModels()));
8316
8471
  } catch (error) {
8317
8472
  ctx.logger.warn("dsh-vibedev: catalog read failed: %o", error);
8318
8473
  }
@@ -8714,6 +8869,13 @@ const AUDIO_GENERATION_KINDS = [
8714
8869
  "speech",
8715
8870
  "transcription"
8716
8871
  ];
8872
+ /** How an audio model is billed (`audio.billing_unit`). */
8873
+ const AUDIO_BILLING_UNITS = [
8874
+ "generation",
8875
+ "original_second",
8876
+ "minute",
8877
+ "character"
8878
+ ];
8717
8879
  const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
8718
8880
  const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
8719
8881
  const strings = (value) => Array.isArray(value) && value.every((item) => typeof item === "string") ? value : void 0;
@@ -8969,7 +9131,8 @@ const PRICE_UNITS = [
8969
9131
  "generation",
8970
9132
  "second",
8971
9133
  "original_second",
8972
- "minute"
9134
+ "minute",
9135
+ "character"
8973
9136
  ];
8974
9137
  /** The audio block: `entry.audio`, else `capabilities.audio`, else the fields flattened into `capabilities`. */
8975
9138
  function audioBlock(entry, capabilities) {
@@ -9077,7 +9240,8 @@ function parseAudioCapabilities(raw) {
9077
9240
  const kindRaw = text$5(field(raw, "generation_kind"))?.toLowerCase();
9078
9241
  const generationKind = AUDIO_GENERATION_KINDS.includes(kindRaw ?? "") ? kindRaw : void 0;
9079
9242
  const billingRaw = text$5(field(raw, "billing_unit"))?.toLowerCase();
9080
- const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
9243
+ const billingUnit = AUDIO_BILLING_UNITS.includes(billingRaw ?? "") ? billingRaw : void 0;
9244
+ const hanCharacterWeight = positive$1(field(raw, "han_character_weight")) ?? (billingUnit === "character" ? 2 : void 0);
9081
9245
  const promptField = text$5(field(raw, "prompt_field"));
9082
9246
  const requestFields = list(raw, "request_fields") ?? [];
9083
9247
  const union = [
@@ -9094,6 +9258,7 @@ function parseAudioCapabilities(raw) {
9094
9258
  if (generationKind !== void 0) result.generationKind = generationKind;
9095
9259
  if (promptField !== void 0) result.promptField = promptField;
9096
9260
  if (billingUnit !== void 0) result.billingUnit = billingUnit;
9261
+ if (hanCharacterWeight !== void 0) result.hanCharacterWeight = hanCharacterWeight;
9097
9262
  if (references !== void 0) result.references = references;
9098
9263
  if (outputFormats !== void 0) result.outputFormats = outputFormats;
9099
9264
  if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
@@ -9209,7 +9374,25 @@ function parseVideoPricing(value) {
9209
9374
  rules
9210
9375
  } };
9211
9376
  }
9212
- /** Which kind of media model a catalog entry is, or undefined for a chat or internal model. */
9377
+ /**
9378
+ * Whether a catalog entry is a realtime speech model: `media_type: "speech"`, or a `speech` block (`vibedev-asr`,
9379
+ * `vibedev-tts`). Such a model serves the desktop's voice input and read-aloud, never the media tools — whatever its
9380
+ * modalities say: a read-aloud lane outputs audio, and would otherwise look like an audio generator.
9381
+ * @param entry - one entry of `/v1/models`.
9382
+ * @returns whether it is one.
9383
+ */
9384
+ function isRealtimeSpeechEntry(entry) {
9385
+ const raw = record$7(entry);
9386
+ return raw !== void 0 && (text$5(raw.media_type)?.toLowerCase() === "speech" || record$7(raw.speech) !== void 0);
9387
+ }
9388
+ /** The other ids an entry answers to: trimmed, blanks and its own id left out. */
9389
+ function aliasesOf(entry, id) {
9390
+ return (strings(entry.aliases) ?? []).map((alias) => alias.trim()).filter((alias) => alias !== "" && alias !== id);
9391
+ }
9392
+ /**
9393
+ * Which kind of media model a catalog entry is, or undefined for a chat or internal model. Realtime speech entries
9394
+ * never get here (see {@link isRealtimeSpeechEntry}).
9395
+ */
9213
9396
  function kindOf(entry, capabilities, audio) {
9214
9397
  if (text$5(entry.internal_role) !== void 0) return void 0;
9215
9398
  if (audio?.generationKind === "transcription") return "transcription";
@@ -9233,14 +9416,39 @@ function kindOf(entry, capabilities, audio) {
9233
9416
  * @returns the media models, in catalog order.
9234
9417
  */
9235
9418
  function parseMediaCatalog(body) {
9419
+ return parseCatalog(body).models;
9420
+ }
9421
+ /**
9422
+ * Parse a `/v1/models` body into its media models, with the realtime speech models kept apart: they are never media
9423
+ * models (see {@link isRealtimeSpeechEntry}), and are listed only so a name that refers to one can be told what it is.
9424
+ * @param body - `{data:[...]}` or a bare array.
9425
+ * @returns the media models and the realtime speech models, each in catalog order.
9426
+ */
9427
+ function parseCatalog(body) {
9236
9428
  const entries = Array.isArray(body) ? body : record$7(body)?.data;
9237
- if (!Array.isArray(entries)) return [];
9429
+ if (!Array.isArray(entries)) return {
9430
+ models: [],
9431
+ realtimeSpeech: []
9432
+ };
9238
9433
  const models = [];
9434
+ const realtimeSpeech = [];
9239
9435
  const seen = /* @__PURE__ */ new Set();
9240
9436
  for (const item of entries) {
9241
9437
  const entry = record$7(item);
9242
9438
  const id = text$5(entry?.id);
9243
9439
  if (entry === void 0 || id === void 0 || seen.has(id)) continue;
9440
+ if (isRealtimeSpeechEntry(entry)) {
9441
+ if (!realtimeSpeech.some((known) => known.id === id)) {
9442
+ const aliases = aliasesOf(entry, id);
9443
+ const lane = text$5(record$7(entry.speech)?.lane)?.toLowerCase();
9444
+ realtimeSpeech.push({
9445
+ id,
9446
+ ...aliases.length === 0 ? {} : { aliases },
9447
+ ...lane === void 0 ? {} : { lane }
9448
+ });
9449
+ }
9450
+ continue;
9451
+ }
9244
9452
  const capabilities = record$7(entry.capabilities) ?? {};
9245
9453
  const audioRaw = audioBlock(entry, capabilities);
9246
9454
  const audio = audioRaw === void 0 ? void 0 : parseAudioCapabilities(audioRaw);
@@ -9253,7 +9461,7 @@ function parseMediaCatalog(body) {
9253
9461
  const { videoPricing, videoPricingIssue } = parseVideoPricing(field(entry, "video_pricing"));
9254
9462
  const inputModalities = strings(capabilities.input_modalities) ?? strings(entry.input_modalities) ?? [];
9255
9463
  const endpoints = strings(capabilities.allowed_endpoints) ?? [];
9256
- const aliases = (strings(entry.aliases) ?? []).map((alias) => alias.trim()).filter((alias) => alias !== "" && alias !== id);
9464
+ const aliases = aliasesOf(entry, id);
9257
9465
  let video;
9258
9466
  if (kind === "video") video = {
9259
9467
  ...parseVideoCapabilities(capabilities),
@@ -9280,7 +9488,10 @@ function parseMediaCatalog(body) {
9280
9488
  ...audioKind === void 0 ? {} : { audioKind }
9281
9489
  });
9282
9490
  }
9283
- return models;
9491
+ return {
9492
+ models,
9493
+ realtimeSpeech
9494
+ };
9284
9495
  }
9285
9496
  //#endregion
9286
9497
  //#region src/media/sources.ts
@@ -9590,6 +9801,15 @@ function modelNamed(models, wanted) {
9590
9801
  const lower = wanted.toLowerCase();
9591
9802
  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
9803
  }
9804
+ /**
9805
+ * Why a realtime speech model cannot be used by the media tools, for a request that names one.
9806
+ * @param model - the realtime speech model.
9807
+ * @returns the sentence.
9808
+ */
9809
+ function realtimeSpeechRefusal(model) {
9810
+ const use = model.lane === "asr" ? "voice input" : model.lane === "tts" ? "read-aloud" : "voice input and read-aloud";
9811
+ return `${model.id} is a realtime speech model (the VibeDev app's ${use}), not a media model, so the media tools cannot use it.`;
9812
+ }
9593
9813
  const CATALOG_TTL_MS = 12e4;
9594
9814
  /** Wait for a shared promise under one caller's signal without cancelling it for the others. */
9595
9815
  function abortable$1(promise, signal) {
@@ -9645,17 +9865,26 @@ var MediaRuntime = class {
9645
9865
  * @returns the models, in catalog order.
9646
9866
  */
9647
9867
  async models(signal) {
9868
+ return (await this.parsedCatalog(signal)).models;
9869
+ }
9870
+ /**
9871
+ * The catalog as the media tools read it: the media models, and the realtime speech models kept apart from them
9872
+ * (only so a request that names one can be told what it is). Cached as {@link models} describes.
9873
+ * @param signal - cancels the request.
9874
+ * @returns the parsed catalog.
9875
+ */
9876
+ async parsedCatalog(signal) {
9648
9877
  const cached = this.catalog;
9649
- if (cached !== void 0 && this.now() - cached.at < CATALOG_TTL_MS) return cached.models;
9878
+ if (cached !== void 0 && this.now() - cached.at < CATALOG_TTL_MS) return cached.parsed;
9650
9879
  if (this.fetching === void 0) {
9651
9880
  const generation = this.generation;
9652
9881
  const fetching = this.http.json("/v1/models", { timeoutMs: 3e4 }).then((body) => {
9653
- const models = parseMediaCatalog(body);
9882
+ const parsed = parseCatalog(body);
9654
9883
  if (generation === this.generation) this.catalog = {
9655
- models,
9884
+ parsed,
9656
9885
  at: this.now()
9657
9886
  };
9658
- return models;
9887
+ return parsed;
9659
9888
  }).finally(() => {
9660
9889
  if (this.fetching === fetching) this.fetching = void 0;
9661
9890
  });
@@ -9666,7 +9895,7 @@ var MediaRuntime = class {
9666
9895
  return await abortable$1(this.fetching, signal);
9667
9896
  } catch (error) {
9668
9897
  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;
9898
+ if (cached !== void 0 && this.now() - cached.at < 36e5 && !(error instanceof MediaError && error.code === "NOT_SIGNED_IN")) return cached.parsed;
9670
9899
  throw error;
9671
9900
  }
9672
9901
  }
@@ -9692,12 +9921,16 @@ var MediaRuntime = class {
9692
9921
  * @returns the model.
9693
9922
  */
9694
9923
  async pickModel(kind, slot, requested, accept, signal) {
9695
- const models = await this.models(signal);
9924
+ const { models, realtimeSpeech } = await this.parsedCatalog(signal);
9696
9925
  const ofKind = models.filter((model) => model.kind === kind && servesSlot(model, slot));
9697
9926
  const wanted = requested?.trim();
9698
9927
  if (wanted !== void 0 && wanted !== "") {
9699
9928
  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" });
9929
+ if (found === void 0) {
9930
+ const offered = `${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`;
9931
+ const speech = modelNamed(realtimeSpeech, wanted);
9932
+ throw localInputError(speech === void 0 ? `There is no model "${wanted}" on this VibeDev account. ${offered}` : `${realtimeSpeechRefusal(speech)} ${offered}`, "MODEL_NOT_FOUND", { field: "model" });
9933
+ }
9701
9934
  if (!ofKind.includes(found)) {
9702
9935
  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
9936
  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 +9944,19 @@ var MediaRuntime = class {
9711
9944
  return (accept === void 0 ? void 0 : ordered.find((model) => accept(model))) ?? ordered[0];
9712
9945
  }
9713
9946
  /**
9714
- * The model a name refers to, whatever its kind.
9947
+ * The media model a name refers to, whatever its kind.
9715
9948
  * @param requested - an id or alias.
9716
9949
  * @param signal - cancels the catalog request.
9717
9950
  * @returns the model.
9718
- * @throws {@link MediaError} when the account has no such model.
9951
+ * @throws {@link MediaError} `MODEL_NOT_FOUND` when the account has no such media model; for a realtime speech model
9952
+ * the message says that is what it is.
9719
9953
  */
9720
9954
  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;
9955
+ const { models, realtimeSpeech } = await this.parsedCatalog(signal);
9956
+ const found = modelNamed(models, requested.trim());
9957
+ if (found !== void 0) return found;
9958
+ const speech = modelNamed(realtimeSpeech, requested.trim());
9959
+ throw localInputError(speech === void 0 ? `There is no model "${requested}" on this VibeDev account.` : realtimeSpeechRefusal(speech), "MODEL_NOT_FOUND", { field: "model" });
9724
9960
  }
9725
9961
  /**
9726
9962
  * The workspace of the calling session.
@@ -10721,6 +10957,697 @@ var GatewaySearchProvider = class {
10721
10957
  }
10722
10958
  };
10723
10959
  //#endregion
10960
+ //#region src/speech/availability.ts
10961
+ const READY$1 = Object.freeze({ phase: "ready" });
10962
+ const SIGN_IN_REQUIRED = Object.freeze({
10963
+ phase: "unavailable",
10964
+ reason: "sign-in-required"
10965
+ });
10966
+ /** Whether two states would read the same to a registry. */
10967
+ function same(a, b) {
10968
+ return a.phase === b.phase && (a.phase !== "failed" || b.phase === "failed" && a.message === b.message);
10969
+ }
10970
+ /**
10971
+ * Published sign-in state. It starts as needing a sign-in; the newest check wins, a check that changes nothing tells
10972
+ * nobody, and a stopped source publishes nothing.
10973
+ */
10974
+ var CredentialAvailability = class {
10975
+ signedIn;
10976
+ current = SIGN_IN_REQUIRED;
10977
+ listeners = /* @__PURE__ */ new Set();
10978
+ round = 0;
10979
+ stopped = false;
10980
+ /**
10981
+ * @param signedIn - whether a VibeDev credential resolves now; rerun whenever the sign-in may have changed.
10982
+ */
10983
+ constructor(signedIn) {
10984
+ this.signedIn = signedIn;
10985
+ }
10986
+ /** @returns the latest published state. */
10987
+ snapshot() {
10988
+ return this.current;
10989
+ }
10990
+ /** @param listener - told after the state changed. @returns unsubscribe. */
10991
+ subscribe(listener) {
10992
+ this.listeners.add(listener);
10993
+ return () => {
10994
+ this.listeners.delete(listener);
10995
+ };
10996
+ }
10997
+ /** Check the sign-in again: a cloud provider has nothing to download. */
10998
+ prepare() {
10999
+ this.refresh();
11000
+ }
11001
+ /** Nothing runs between checks, so there is nothing to cancel. */
11002
+ async cancel() {}
11003
+ /**
11004
+ * Check the credential and publish the result. A check that fails publishes `failed` with a fixed diagnostic: the
11005
+ * error of a credential read may name a stored grant, so its message is not repeated.
11006
+ * @returns after this check settles, whether or not a newer one replaced it.
11007
+ */
11008
+ async refresh() {
11009
+ const round = ++this.round;
11010
+ let next;
11011
+ try {
11012
+ next = await this.signedIn() ? READY$1 : SIGN_IN_REQUIRED;
11013
+ } catch {
11014
+ next = {
11015
+ phase: "failed",
11016
+ message: "The VibeDev sign-in could not be read."
11017
+ };
11018
+ }
11019
+ if (round !== this.round || this.stopped || same(next, this.current)) return;
11020
+ this.current = next;
11021
+ for (const listener of [...this.listeners]) try {
11022
+ listener();
11023
+ } catch {}
11024
+ }
11025
+ /** Stop publishing; checks still running settle without telling anyone. */
11026
+ stop() {
11027
+ this.stopped = true;
11028
+ this.listeners.clear();
11029
+ }
11030
+ };
11031
+ //#endregion
11032
+ //#region src/speech/host.ts
11033
+ /**
11034
+ * The Host's own copies of the speech packages. Each specifier is widened to `string` so TypeScript resolves no
11035
+ * package the plugin does not install; the build keeps each one as a literal dynamic import of the package, external
11036
+ * like every `@deepseek-ai/*` package, and `scripts/check-package.mjs` finds both among the peers.
11037
+ */
11038
+ const HOST_SPEECH_MODULES = {
11039
+ speechToText: () => import("@deepseek-ai/dsh-experimental-speech-to-text"),
11040
+ textToSpeech: () => import("@deepseek-ai/dsh-text-to-speech")
11041
+ };
11042
+ /**
11043
+ * The classified failure class a Host package exports, when it does. DSH 0.2.3-alpha.2 has the recognition package
11044
+ * without `SpeechTranscriptionError` and no synthesis package at all; there, and wherever loading fails, the answer is
11045
+ * undefined and nothing is registered.
11046
+ * @param load - imports the Host package.
11047
+ * @param name - the exported class.
11048
+ * @returns the class, or undefined.
11049
+ */
11050
+ async function hostErrorClass(load, name) {
11051
+ let module;
11052
+ try {
11053
+ module = await load();
11054
+ } catch {
11055
+ return;
11056
+ }
11057
+ const value = typeof module === "object" && module !== null ? module[name] : void 0;
11058
+ return typeof value === "function" ? value : void 0;
11059
+ }
11060
+ const SPEECH_MAX_BUSY_WAIT_MS = 2e3;
11061
+ /** One gateway call, remembering the credential its last attempt carried. */
11062
+ var GatewayCall = class {
11063
+ gateway;
11064
+ /** The credential of the last attempt: a rejected development key needs another key, not a sign-in. */
11065
+ credential;
11066
+ /** @param gateway - the plugin's gateway client and credential chain. */
11067
+ constructor(gateway) {
11068
+ this.gateway = gateway;
11069
+ }
11070
+ /**
11071
+ * Send through the plugin's gateway client with the speech busy policy.
11072
+ * @param path - the gateway path.
11073
+ * @param request - method, body, signal and deadline.
11074
+ * @returns the 2xx response, body unread.
11075
+ * @throws {@link MediaError} for every refusal, with the gateway's code and status.
11076
+ */
11077
+ send(path, request) {
11078
+ return this.gateway.http.send(path, {
11079
+ busyRetries: 1,
11080
+ maxBusyWaitMs: SPEECH_MAX_BUSY_WAIT_MS,
11081
+ ...request,
11082
+ resolveCredential: async () => {
11083
+ const credential = await this.gateway.resolveCredential();
11084
+ this.credential = credential;
11085
+ return credential;
11086
+ }
11087
+ });
11088
+ }
11089
+ };
11090
+ /**
11091
+ * Classify a failed call.
11092
+ * @param error - what the gateway client threw.
11093
+ * @param credential - the credential the call carried last.
11094
+ * @param inputCodes - the gateway codes that refuse the input itself (`SPEECH_AUDIO_*`, `SPEECH_TEXT_*`).
11095
+ * @returns the class and a diagnostic without the gateway's prose, the credential, audio or text.
11096
+ */
11097
+ function classifyFailure(error, credential, inputCodes) {
11098
+ if (!(error instanceof MediaError)) return {
11099
+ kind: "service-error",
11100
+ diagnostic: `unexpected ${error instanceof Error ? error.name : typeof error}`
11101
+ };
11102
+ const { status, requestId } = error.details;
11103
+ const diagnostic = [
11104
+ status === void 0 ? void 0 : `HTTP ${status}`,
11105
+ error.code,
11106
+ requestId === void 0 ? void 0 : `request ${requestId}`
11107
+ ].filter((part) => part !== void 0).join(", ");
11108
+ return {
11109
+ kind: failureClass(error, credential, inputCodes),
11110
+ diagnostic
11111
+ };
11112
+ }
11113
+ function failureClass(error, credential, inputCodes) {
11114
+ switch (error.code) {
11115
+ case "NOT_SIGNED_IN": return "sign-in-required";
11116
+ case "GATEWAY_TIMEOUT": return "timeout";
11117
+ case "GATEWAY_UNREACHABLE": return "service-unavailable";
11118
+ }
11119
+ const status = error.details.status;
11120
+ if (status === 401) return credential?.kind === "key" ? "api-key-invalid" : "sign-in-required";
11121
+ if (status === 402 || error.code === "INSUFFICIENT_BALANCE") return "quota-exceeded";
11122
+ if (status === 429) return "rate-limited";
11123
+ if (status === 503) return "service-unavailable";
11124
+ if (status === 408 || status === 504) return "timeout";
11125
+ if (status === 413 || (status === 400 || status === 422) && inputCodes.test(error.code)) return "rejected-input";
11126
+ return "service-error";
11127
+ }
11128
+ /**
11129
+ * Settle with `work`, or reject with the signal's reason as soon as it aborts. The abort reaches the request through
11130
+ * its own signal; this only keeps a body read that undici leaves pending after an abort from holding the caller, and a
11131
+ * registry joining the call, past the cancellation.
11132
+ * @param signal - cancellation.
11133
+ * @param work - the call.
11134
+ * @returns the call's own outcome when it settles first.
11135
+ */
11136
+ function untilAborted(signal, work) {
11137
+ return new Promise((resolve, reject) => {
11138
+ const onAbort = () => {
11139
+ reject(signal.reason);
11140
+ };
11141
+ if (signal.aborted) onAbort();
11142
+ else signal.addEventListener("abort", onAbort, { once: true });
11143
+ work.then((value) => {
11144
+ signal.removeEventListener("abort", onAbort);
11145
+ resolve(value);
11146
+ }, (error) => {
11147
+ signal.removeEventListener("abort", onAbort);
11148
+ reject(error);
11149
+ });
11150
+ });
11151
+ }
11152
+ /**
11153
+ * Read a small body completely, or give up past `limit` bytes.
11154
+ * @param response - the gateway's answer.
11155
+ * @param limit - the most bytes read.
11156
+ * @returns the text, or undefined when the body is larger.
11157
+ */
11158
+ async function boundedText(response, limit) {
11159
+ if (response.body === null) return "";
11160
+ const chunks = [];
11161
+ let total = 0;
11162
+ for await (const chunk of response.body) {
11163
+ total += chunk.byteLength;
11164
+ if (total > limit) return void 0;
11165
+ chunks.push(chunk);
11166
+ }
11167
+ return Buffer.concat(chunks).toString("utf8");
11168
+ }
11169
+ //#endregion
11170
+ //#region src/speech/wave.ts
11171
+ /**
11172
+ * The recordings `POST /v1/vibedev/speech/asr` accepts, checked before anything is sent: 16-bit PCM WAV, mono or
11173
+ * stereo, 8–48 kHz, at most 8 MiB and 120 seconds (the Host sends 16 kHz mono). And the request body: one
11174
+ * multipart `file` field.
11175
+ * @module dsh-vibedev/speech/wave
11176
+ */
11177
+ /** Largest recording file the gateway accepts. */
11178
+ const MAX_RECORDING_BYTES = 8388608;
11179
+ /** A recording the gateway would refuse; the message names the broken rule and carries no audio. */
11180
+ var RecordingRejected = class extends Error {
11181
+ name = "RecordingRejected";
11182
+ };
11183
+ /** The 4-character ASCII tag at `offset`. */
11184
+ function tag(audio, offset) {
11185
+ return String.fromCharCode(audio[offset] ?? 0, audio[offset + 1] ?? 0, audio[offset + 2] ?? 0, audio[offset + 3] ?? 0);
11186
+ }
11187
+ /**
11188
+ * Check a recording against the gateway's limits.
11189
+ * @param audio - the WAV file, sent unchanged.
11190
+ * @returns its duration in seconds.
11191
+ * @throws {@link RecordingRejected} for anything the gateway would refuse.
11192
+ */
11193
+ function recordingSeconds(audio) {
11194
+ if (audio.byteLength > 8388608) throw new RecordingRejected(`The recording is ${audio.byteLength} bytes; the service accepts at most ${MAX_RECORDING_BYTES}.`);
11195
+ if (audio.byteLength < 12 || tag(audio, 0) !== "RIFF" || tag(audio, 8) !== "WAVE") throw new RecordingRejected("The recording is not a WAV file.");
11196
+ const view = new DataView(audio.buffer, audio.byteOffset, audio.byteLength);
11197
+ let format;
11198
+ let dataBytes;
11199
+ for (let offset = 12; offset + 8 <= audio.byteLength;) {
11200
+ const id = tag(audio, offset);
11201
+ const size = view.getUint32(offset + 4, true);
11202
+ const start = offset + 8;
11203
+ if (id === "fmt ") {
11204
+ if (size < 16 || start + 16 > audio.byteLength) throw new RecordingRejected("The recording's WAV format chunk is incomplete.");
11205
+ format = {
11206
+ code: view.getUint16(start, true),
11207
+ channels: view.getUint16(start + 2, true),
11208
+ rate: view.getUint32(start + 4, true),
11209
+ blockAlign: view.getUint16(start + 12, true),
11210
+ bits: view.getUint16(start + 14, true)
11211
+ };
11212
+ } else if (id === "data") {
11213
+ dataBytes = Math.min(size, audio.byteLength - start);
11214
+ break;
11215
+ }
11216
+ offset = start + size + size % 2;
11217
+ }
11218
+ if (format === void 0 || dataBytes === void 0) throw new RecordingRejected("The recording has no WAV format or data chunk.");
11219
+ if (format.code !== 1 || format.bits !== 16) throw new RecordingRejected("The recording must be 16-bit PCM.");
11220
+ if (format.channels !== 1 && format.channels !== 2) throw new RecordingRejected(`The recording has ${format.channels} channels; the service takes mono or stereo.`);
11221
+ if (format.rate < 8e3 || format.rate > 48e3) throw new RecordingRejected(`The recording is sampled at ${format.rate} Hz; the service takes 8–48 kHz.`);
11222
+ if (format.blockAlign !== format.channels * 2) throw new RecordingRejected("The recording's WAV block alignment does not match 16-bit PCM.");
11223
+ const frames = Math.floor(dataBytes / format.blockAlign);
11224
+ if (frames === 0) throw new RecordingRejected("The recording holds no audio.");
11225
+ const seconds = frames / format.rate;
11226
+ if (seconds > 120) throw new RecordingRejected(`The recording is ${seconds.toFixed(1)} s long; the service accepts at most 120 s.`);
11227
+ return seconds;
11228
+ }
11229
+ /**
11230
+ * Encode the recording as the gateway's single `file` field. Bytes rather than `FormData`: a request cancelled before
11231
+ * undici reads a `FormData` body leaves its pump rejecting unhandled, and a busy retry sends the same bytes again.
11232
+ * @param recording - the WAV file.
11233
+ * @returns the body and its content type.
11234
+ */
11235
+ function multipartBody(recording) {
11236
+ const boundary = `vibedev-speech-${randomUUID()}`;
11237
+ return {
11238
+ body: Buffer.concat([
11239
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="recording.wav"\r\nContent-Type: audio/wav\r\n\r\n`),
11240
+ recording,
11241
+ Buffer.from(`\r\n--${boundary}--\r\n`)
11242
+ ]),
11243
+ contentType: `multipart/form-data; boundary=${boundary}`
11244
+ };
11245
+ }
11246
+ //#endregion
11247
+ //#region src/speech/recognition.ts
11248
+ /** The provider id the VibeDev desktop's voice input recognizes as VibeDev's. */
11249
+ const RECOGNITION_PROVIDER_ID = "vibedev-asr";
11250
+ /** The gateway's recognition endpoint. */
11251
+ const ASR_PATH = "/v1/vibedev/speech/asr";
11252
+ /**
11253
+ * Deadline for one recognition, busy retry included: 30 s, as the Host's DeepSeek recognizer allows, and half a second
11254
+ * 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).
11255
+ */
11256
+ const RECOGNITION_TIMEOUT_MS = 3e4;
11257
+ const TIMEOUT_PER_AUDIO_SECOND_MS = 500;
11258
+ /**
11259
+ * The deadline for one recording.
11260
+ * @param seconds - its length.
11261
+ * @returns milliseconds.
11262
+ */
11263
+ function recognitionTimeoutMs(seconds) {
11264
+ return RECOGNITION_TIMEOUT_MS + Math.ceil(seconds * TIMEOUT_PER_AUDIO_SECOND_MS);
11265
+ }
11266
+ /** The most bytes of an answer that are read; a transcript of two minutes of speech is a few kilobytes. */
11267
+ const MAX_ANSWER_BYTES = 262144;
11268
+ /** Gateway codes that refuse the recording itself. */
11269
+ const AUDIO_CODES = /^SPEECH_AUDIO_/;
11270
+ const CODES$1 = {
11271
+ "sign-in-required": "sign-in-required",
11272
+ "api-key-invalid": "api-key-invalid",
11273
+ "rate-limited": "rate-limited",
11274
+ "quota-exceeded": "quota-exceeded",
11275
+ "service-unavailable": "service-unavailable",
11276
+ "rejected-input": "invalid-audio",
11277
+ timeout: "timeout",
11278
+ "service-error": "service-error"
11279
+ };
11280
+ /**
11281
+ * Build the recognizer.
11282
+ * @param options - the gateway, the Host's error class and the sign-in state.
11283
+ * @returns the provider to register with `ctx.speechToText`.
11284
+ */
11285
+ function createRecognition(options) {
11286
+ return {
11287
+ info: {
11288
+ id: RECOGNITION_PROVIDER_ID,
11289
+ name: "VibeDev",
11290
+ location: "cloud",
11291
+ languages: ["auto"]
11292
+ },
11293
+ preparation: options.availability,
11294
+ transcribe: (input, signal) => transcribe(options, input.audio, signal)
11295
+ };
11296
+ }
11297
+ async function transcribe(options, audio, signal) {
11298
+ const started = performance.now();
11299
+ signal.throwIfAborted();
11300
+ const fail = (code, message) => new options.errorClass(code, message);
11301
+ let seconds;
11302
+ try {
11303
+ seconds = recordingSeconds(audio);
11304
+ } catch (error) {
11305
+ if (error instanceof RecordingRejected) throw fail("invalid-audio", error.message);
11306
+ throw error;
11307
+ }
11308
+ const { body, contentType } = multipartBody(audio);
11309
+ const timeoutMs = options.timeoutMs ?? recognitionTimeoutMs(seconds);
11310
+ const deadline = AbortSignal.timeout(timeoutMs);
11311
+ const live = AbortSignal.any([signal, deadline]);
11312
+ const call = new GatewayCall(options.gateway);
11313
+ let answer;
11314
+ try {
11315
+ answer = await untilAborted(live, (async () => {
11316
+ return await boundedText(await call.send(ASR_PATH, {
11317
+ method: "POST",
11318
+ body,
11319
+ headers: { "content-type": contentType },
11320
+ signal: live,
11321
+ timeoutMs
11322
+ }), MAX_ANSWER_BYTES);
11323
+ })());
11324
+ } catch (error) {
11325
+ signal.throwIfAborted();
11326
+ if (deadline.aborted) throw fail("timeout", `VibeDev speech recognition did not answer within ${timeoutMs} ms.`);
11327
+ const failure = classifyFailure(error, call.credential, AUDIO_CODES);
11328
+ options.gateway.log(`dsh-vibedev: ${RECOGNITION_PROVIDER_ID} failed (${CODES$1[failure.kind]}): ${failure.diagnostic}`);
11329
+ if (failure.kind === "sign-in-required") options.availability.refresh();
11330
+ throw fail(CODES$1[failure.kind], `VibeDev speech recognition failed: ${failure.diagnostic}.`);
11331
+ }
11332
+ const result = parseTranscript(answer);
11333
+ if (result === void 0) {
11334
+ options.gateway.log(`dsh-vibedev: ${RECOGNITION_PROVIDER_ID} failed (service-error): the answer is not a transcript`);
11335
+ throw fail("service-error", "VibeDev speech recognition answered without a transcript.");
11336
+ }
11337
+ return {
11338
+ text: result.text,
11339
+ audioSeconds: result.durationMs === void 0 ? seconds : result.durationMs / 1e3,
11340
+ inferenceSeconds: (performance.now() - started) / 1e3
11341
+ };
11342
+ }
11343
+ /** `{ text, duration_ms }` from the answer, or undefined when it is not one. */
11344
+ function parseTranscript(answer) {
11345
+ if (answer === void 0) return void 0;
11346
+ let body;
11347
+ try {
11348
+ body = JSON.parse(answer);
11349
+ } catch {
11350
+ return;
11351
+ }
11352
+ if (typeof body !== "object" || body === null) return void 0;
11353
+ const { text, duration_ms: duration } = body;
11354
+ if (typeof text !== "string") return void 0;
11355
+ return {
11356
+ text,
11357
+ durationMs: typeof duration === "number" && Number.isFinite(duration) && duration >= 0 ? duration : void 0
11358
+ };
11359
+ }
11360
+ //#endregion
11361
+ //#region src/speech/synthesis.ts
11362
+ /**
11363
+ * `vibedev-tts`: speech synthesis through the VibeDev gateway (`POST /v1/vibedev/speech/tts`), billed to the VibeDev
11364
+ * account. The text goes up as `{ text, voice_id, format: 'pcm', filter_markdown: false }`, and the audio streams back
11365
+ * as headerless 24 kHz signed 16-bit little-endian mono PCM, in chunks passed on as they arrive (the first one after
11366
+ * about two seconds).
11367
+ * @module dsh-vibedev/speech/synthesis
11368
+ */
11369
+ /** The provider id the VibeDev desktop's read-aloud recognizes as VibeDev's. */
11370
+ const SYNTHESIS_PROVIDER_ID = "vibedev-tts";
11371
+ /** The gateway's synthesis endpoint. */
11372
+ const TTS_PATH = "/v1/vibedev/speech/tts";
11373
+ /** The gateway's voices, in menu order: `stella` (the default) and `tide`. */
11374
+ const SYNTHESIS_VOICES = Object.freeze(["stella", "tide"]);
11375
+ /** Sample rate of the gateway's `pcm` format. */
11376
+ const SYNTHESIS_SAMPLE_RATE = 24e3;
11377
+ /** Longest text one request takes. */
11378
+ const SYNTHESIS_MAX_CHARACTERS = 5e3;
11379
+ /**
11380
+ * The gateway client's deadline for one attempt also bounds reading its body, which streams for as long as the text
11381
+ * takes to speak; the idle deadline above bounds every wait instead.
11382
+ */
11383
+ const NO_ATTEMPT_DEADLINE_MS = 2147483647;
11384
+ const IDLE = "VIBEDEV_TTS_IDLE";
11385
+ /** Gateway codes that refuse the text itself. */
11386
+ const TEXT_CODES = /^SPEECH_TEXT_/;
11387
+ /** The most bytes of an error report read under status 200. */
11388
+ const MAX_REPORT_BYTES = 16384;
11389
+ const CODES = {
11390
+ "sign-in-required": "sign-in-required",
11391
+ "api-key-invalid": "api-key-invalid",
11392
+ "rate-limited": "rate-limited",
11393
+ "quota-exceeded": "quota-exceeded",
11394
+ "service-unavailable": "service-unavailable",
11395
+ "rejected-input": "text-rejected",
11396
+ timeout: "timeout",
11397
+ "service-error": "service-error"
11398
+ };
11399
+ /** A failure the provider found itself, already classified. */
11400
+ var Refusal = class extends Error {
11401
+ code;
11402
+ /** @param code - the registry's failure class. @param message - Host diagnostic. @param options - the cause. */
11403
+ constructor(code, message, options) {
11404
+ super(message, options);
11405
+ this.code = code;
11406
+ }
11407
+ };
11408
+ /**
11409
+ * Build the synthesizer.
11410
+ * @param options - the gateway, the Host's error class and the sign-in state.
11411
+ * @returns the provider to register with `ctx.textToSpeech`.
11412
+ */
11413
+ function createSynthesis(options) {
11414
+ return {
11415
+ info: {
11416
+ id: SYNTHESIS_PROVIDER_ID,
11417
+ name: "VibeDev",
11418
+ location: "cloud",
11419
+ audio: {
11420
+ encoding: "pcm-s16le",
11421
+ sampleRate: SYNTHESIS_SAMPLE_RATE
11422
+ },
11423
+ maxCharacters: SYNTHESIS_MAX_CHARACTERS,
11424
+ voices: SYNTHESIS_VOICES
11425
+ },
11426
+ availability: options.availability,
11427
+ synthesize: (input, signal) => synthesize(options, input, signal)
11428
+ };
11429
+ }
11430
+ /**
11431
+ * Pass the audio on chunk by chunk. Each wait for audio is bounded while a consumer is asking (time the consumer takes
11432
+ * between pulls does not count), the caller's abort ends the request at once, also while nobody is pulling, and audio
11433
+ * already passed on stays valid when a later pull fails.
11434
+ */
11435
+ async function* synthesize(options, input, caller) {
11436
+ try {
11437
+ var _usingCtx$1 = _usingCtx();
11438
+ caller.throwIfAborted();
11439
+ const idleMs = options.idleTimeoutMs ?? 3e4;
11440
+ const consumer = new AbortController();
11441
+ const watchdog = _usingCtx$1.u(idleWatchdog(AbortSignal.any([consumer.signal, caller]), idleMs, IDLE));
11442
+ const call = new GatewayCall(options.gateway);
11443
+ const audio = request(call, input, watchdog.signal);
11444
+ try {
11445
+ for (;;) {
11446
+ const next = await untilAborted(caller, watchdog.next(audio));
11447
+ if (next.done === true) return;
11448
+ yield next.value;
11449
+ }
11450
+ } catch (error) {
11451
+ if (timeoutOf(watchdog.signal, IDLE) !== void 0) {
11452
+ options.gateway.log(`dsh-vibedev: ${SYNTHESIS_PROVIDER_ID} failed (timeout): no audio within ${idleMs} ms`);
11453
+ throw new options.errorClass("timeout", `No VibeDev speech audio arrived within ${idleMs} ms.`);
11454
+ }
11455
+ caller.throwIfAborted();
11456
+ if (error instanceof Refusal) {
11457
+ options.gateway.log(`dsh-vibedev: ${SYNTHESIS_PROVIDER_ID} failed (${error.code}): ${error.message}`);
11458
+ throw new options.errorClass(error.code, error.message, error.cause === void 0 ? void 0 : { cause: error.cause });
11459
+ }
11460
+ const failure = classifyFailure(error, call.credential, TEXT_CODES);
11461
+ options.gateway.log(`dsh-vibedev: ${SYNTHESIS_PROVIDER_ID} failed (${CODES[failure.kind]}): ${failure.diagnostic}`);
11462
+ if (failure.kind === "sign-in-required") options.availability.refresh();
11463
+ throw new options.errorClass(CODES[failure.kind], `VibeDev speech synthesis failed: ${failure.diagnostic}.`);
11464
+ } finally {
11465
+ consumer.abort();
11466
+ audio.return(void 0).catch(() => {});
11467
+ }
11468
+ } catch (_) {
11469
+ _usingCtx$1.e = _;
11470
+ } finally {
11471
+ _usingCtx$1.d();
11472
+ }
11473
+ }
11474
+ /** One request: its answer head through the gateway client, then the audio body as it arrives. */
11475
+ async function* request(call, input, signal) {
11476
+ const response = await call.send(TTS_PATH, {
11477
+ method: "POST",
11478
+ signal,
11479
+ timeoutMs: NO_ATTEMPT_DEADLINE_MS,
11480
+ headers: { accept: "application/octet-stream, application/json" },
11481
+ json: {
11482
+ text: input.text,
11483
+ voice_id: input.voice,
11484
+ format: "pcm",
11485
+ filter_markdown: false
11486
+ }
11487
+ });
11488
+ if (response.headers.get("content-type")?.toLowerCase().startsWith("application/json") === true || response.body === null) {
11489
+ const report = await boundedText(response, MAX_REPORT_BYTES).catch(() => void 0);
11490
+ const code = report === void 0 ? void 0 : reportCode(report);
11491
+ throw new Refusal("service-error", `VibeDev speech synthesis answered HTTP ${response.status} without audio${code === void 0 ? "" : ` (${code})`}.`);
11492
+ }
11493
+ let received = 0;
11494
+ try {
11495
+ for await (const chunk of response.body) {
11496
+ if (chunk.byteLength === 0) continue;
11497
+ received += chunk.byteLength;
11498
+ yield chunk;
11499
+ }
11500
+ } catch (error) {
11501
+ if (signal.aborted) throw error;
11502
+ throw new Refusal("service-error", `The VibeDev speech audio ended early after ${received} bytes.`, { cause: error });
11503
+ }
11504
+ if (received === 0) throw new Refusal("service-error", "VibeDev speech synthesis returned no audio.");
11505
+ }
11506
+ /** The gateway's error code in a JSON report, when it names one. */
11507
+ function reportCode(report) {
11508
+ try {
11509
+ const body = JSON.parse(report);
11510
+ const code = body?.error?.code ?? body?.code;
11511
+ return typeof code === "string" && /^[A-Za-z0-9_.-]{1,80}$/.test(code) ? code : void 0;
11512
+ } catch {
11513
+ return;
11514
+ }
11515
+ }
11516
+ //#endregion
11517
+ //#region src/speech/sign-in.ts
11518
+ /**
11519
+ * The client service that opens the VibeDev sign-in for another plugin: `vibedevSignIn`. Pure declarations only, so
11520
+ * the browser half bundles this module as it is and the Host half publishes the same contract in its types.
11521
+ *
11522
+ * Contract (dsh-vibedev 0.12.0). The VibeDev desktop's voice input and read-aloud offer "登录 VibeDev" while their
11523
+ * provider is a VibeDev one (`vibedev-asr`, `vibedev-tts`; any `vibedev-*` id) and it reports
11524
+ * `{ phase: 'unavailable', reason: 'sign-in-required' }` or fails with `sign-in-required`; that action calls
11525
+ * `open()`. The service is provided in a client's root scope while that client can read the VibeDev account (the
11526
+ * Host answered its account read, as it does for the owner's desktop window or web page; a peer the plugin's routes
11527
+ * refuse never gets it), and is withdrawn when the plugin's client unloads. Consumers follow it with
11528
+ * `ctx.inject(['vibedevSignIn'], …)` and offer the action only while it is present; they declare the context member
11529
+ * themselves, for example:
11530
+ *
11531
+ * ```ts
11532
+ * import type { VibeDevSignIn } from '@vibedev-si/dsh-vibedev'
11533
+ * declare module '@deepseek-ai/cordis' {
11534
+ * interface Context { vibedevSignIn: VibeDevSignIn }
11535
+ * }
11536
+ * ```
11537
+ * @module dsh-vibedev/speech/sign-in
11538
+ */
11539
+ /** The service name: `ctx.get('vibedevSignIn')`. Kept as it is: the VibeDev desktop looks it up by this name. */
11540
+ const VIBEDEV_SIGN_IN_SERVICE = "vibedevSignIn";
11541
+ //#endregion
11542
+ //#region src/speech/index.ts
11543
+ /**
11544
+ * Register the speech providers wherever the Host's registries can take them, for as long as they are there.
11545
+ * @param ctx - the plugin context.
11546
+ * @param wiring - the gateway client, the credential chain and the sign-in changes.
11547
+ */
11548
+ function installSpeech(ctx, wiring) {
11549
+ const modules = wiring.modules ?? HOST_SPEECH_MODULES;
11550
+ const listeners = /* @__PURE__ */ new Set();
11551
+ const changed = () => {
11552
+ for (const listener of [...listeners]) listener();
11553
+ };
11554
+ const onChange = (listener) => {
11555
+ listeners.add(listener);
11556
+ return () => {
11557
+ listeners.delete(listener);
11558
+ };
11559
+ };
11560
+ ctx.effect(() => wiring.onSignInChange(changed), "dsh-vibedev: speech sign-in changes");
11561
+ ctx.inject(["deepseekAccount"], (accountCtx) => {
11562
+ accountCtx.effect(() => {
11563
+ const controller = new AbortController();
11564
+ const account = accountCtx.deepseekAccount;
11565
+ if (typeof account.watch === "function") {
11566
+ const views = account.watch(controller.signal);
11567
+ (async () => {
11568
+ try {
11569
+ for await (const _view of views) changed();
11570
+ } catch {}
11571
+ })();
11572
+ }
11573
+ changed();
11574
+ return () => {
11575
+ controller.abort();
11576
+ changed();
11577
+ };
11578
+ }, "dsh-vibedev: speech account watch");
11579
+ });
11580
+ join$1(ctx, wiring, onChange, {
11581
+ service: "speechToText",
11582
+ providerId: RECOGNITION_PROVIDER_ID,
11583
+ load: modules.speechToText,
11584
+ errorName: "SpeechTranscriptionError",
11585
+ register: (registry, errorClass, availability) => registry.register(createRecognition({
11586
+ gateway: wiring,
11587
+ errorClass,
11588
+ availability,
11589
+ ...wiring.recognitionTimeoutMs === void 0 ? {} : { timeoutMs: wiring.recognitionTimeoutMs }
11590
+ }))
11591
+ });
11592
+ join$1(ctx, wiring, onChange, {
11593
+ service: "textToSpeech",
11594
+ providerId: SYNTHESIS_PROVIDER_ID,
11595
+ load: modules.textToSpeech,
11596
+ errorName: "SpeechSynthesisError",
11597
+ register: (registry, errorClass, availability) => registry.register(createSynthesis({
11598
+ gateway: wiring,
11599
+ errorClass,
11600
+ availability,
11601
+ ...wiring.synthesisIdleTimeoutMs === void 0 ? {} : { idleTimeoutMs: wiring.synthesisIdleTimeoutMs }
11602
+ }))
11603
+ });
11604
+ }
11605
+ /**
11606
+ * While the registry service is present: load its package, and register the provider when the package exports the
11607
+ * error class. The provider leaves with the service, and with the plugin.
11608
+ */
11609
+ function join$1(ctx, wiring, onChange, registration) {
11610
+ ctx.inject([registration.service], (scoped) => {
11611
+ scoped.effect(() => {
11612
+ let active = true;
11613
+ let availability;
11614
+ let unsubscribe;
11615
+ let unregister;
11616
+ (async () => {
11617
+ const errorClass = await hostErrorClass(registration.load, registration.errorName);
11618
+ if (!active) return;
11619
+ if (errorClass === void 0) {
11620
+ scoped.logger.debug(`dsh-vibedev: this DSH's ${registration.service} exports no ${registration.errorName}; ${registration.providerId} is not registered`);
11621
+ return;
11622
+ }
11623
+ const registry = scoped.get(registration.service);
11624
+ if (typeof registry?.register !== "function") return;
11625
+ const source = new CredentialAvailability(async () => await wiring.resolveCredential() !== void 0);
11626
+ try {
11627
+ unregister = registration.register(registry, errorClass, source);
11628
+ } catch (error) {
11629
+ source.stop();
11630
+ wiring.log(`dsh-vibedev: ${registration.providerId} was not registered: ${error instanceof Error ? error.message : String(error)}`);
11631
+ return;
11632
+ }
11633
+ availability = source;
11634
+ unsubscribe = onChange(() => {
11635
+ source.refresh();
11636
+ });
11637
+ source.refresh();
11638
+ })().catch((error) => {
11639
+ wiring.log(`dsh-vibedev: ${registration.providerId} was not registered: ${error instanceof Error ? error.message : String(error)}`);
11640
+ });
11641
+ return async () => {
11642
+ active = false;
11643
+ unsubscribe?.();
11644
+ availability?.stop();
11645
+ await unregister?.();
11646
+ };
11647
+ }, `dsh-vibedev: ${registration.providerId}`);
11648
+ });
11649
+ }
11650
+ //#endregion
10724
11651
  //#region src/content/errors.ts
10725
11652
  /**
10726
11653
  * The content library's failures. Callers of `vibedevContent` (dsh-film's
@@ -11255,6 +12182,13 @@ function toNumber(value) {
11255
12182
  * Token price is never shown as an unconditional per-second price, never as
11256
12183
  * 未定价 and never as free — and what cannot be estimated says so.
11257
12184
  *
12185
+ * Speech billed per character (`character`) is quoted on the text as it is
12186
+ * sent: each Chinese character (a CJK unified ideograph, any extension) counts
12187
+ * as the model's `han_character_weight` (2 when undeclared), every other
12188
+ * character — letters, digits, spaces, line breaks, punctuation, the `@AudioN`
12189
+ * reference markers — as 1. How the gateway counts is final, so such a quote
12190
+ * always says the gateway's settlement decides.
12191
+ *
11258
12192
  * A model without a price is "not priced" (未定价), never free: only a price the
11259
12193
  * catalog states as zero is shown as ¥0.
11260
12194
  * @module dsh-vibedev/pricing
@@ -11287,12 +12221,13 @@ function tierFor(pricing, wanted) {
11287
12221
  return pricing.tiers.length === 1 ? pricing.tiers[0] : void 0;
11288
12222
  }
11289
12223
  /**
11290
- * The unit after a price: `/s`, `/原始秒`, `/次`.
12224
+ * The unit after a price: `/s`, `/原始秒`, `/次`, `/计费字符(汉字按 2 个算)`.
11291
12225
  * @param unit - the price unit.
11292
12226
  * @param kind - the kind of model, which names a generation (an image, a video, a request).
12227
+ * @param hanWeight - per character: what one Chinese character counts as.
11293
12228
  * @returns the suffix in both languages.
11294
12229
  */
11295
- function unitSuffix(unit, kind) {
12230
+ function unitSuffix(unit, kind, hanWeight = 2) {
11296
12231
  switch (unit) {
11297
12232
  case "second": return {
11298
12233
  en: "/s",
@@ -11306,6 +12241,13 @@ function unitSuffix(unit, kind) {
11306
12241
  en: "/min",
11307
12242
  zh: "/分钟"
11308
12243
  };
12244
+ case "character": {
12245
+ const weight = format(decimal(hanWeight));
12246
+ return {
12247
+ en: ` per billable character (Chinese characters count as ${weight})`,
12248
+ zh: `/计费字符(汉字按 ${weight} 个算)`
12249
+ };
12250
+ }
11309
12251
  default: return kind === "image" ? {
11310
12252
  en: " per image",
11311
12253
  zh: "/张"
@@ -11315,6 +12257,22 @@ function unitSuffix(unit, kind) {
11315
12257
  };
11316
12258
  }
11317
12259
  }
12260
+ /** What one Chinese character of a model's text counts as under per-character billing. */
12261
+ function hanWeightOf(model) {
12262
+ return model.audio?.hanCharacterWeight ?? 2;
12263
+ }
12264
+ /** A unit price as shown: per-character prices exactly (`¥0.0003`, `¥0.00025`), the others as {@link yuan} does. */
12265
+ function unitPrice(unit, amount) {
12266
+ return unit === "character" ? exactYuan(amount) : yuan(amount);
12267
+ }
12268
+ /** Chinese characters: CJK unified ideographs, every extension included (Unicode's `Unified_Ideograph`). */
12269
+ const HAN_CHARACTERS = /\p{Unified_Ideograph}/gu;
12270
+ /** `han × weight + other`, exactly. */
12271
+ function billableCount(text, hanWeight) {
12272
+ const han = text.match(HAN_CHARACTERS)?.length ?? 0;
12273
+ const other = [...text].length - han;
12274
+ return add(multiply(decimal(han), decimal(hanWeight)), decimal(other));
12275
+ }
11318
12276
  /** Shown for a model whose `video_pricing` this plugin cannot use. */
11319
12277
  const VIDEO_PRICING_UNSUPPORTED = {
11320
12278
  en: "this plugin version does not support this video pricing mode: estimate unavailable; billed by actual video Token usage",
@@ -11352,8 +12310,8 @@ function describeTokenPricing(pricing, lang) {
11352
12310
  return lang === "zh" ? `视频 Token 计价:${rules.join(";")}` : `video Token pricing (billed by actual video Tokens): ${rules.join(", ")}`;
11353
12311
  }
11354
12312
  /**
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/秒)…`).
12313
+ * A one-line price for listings: `¥0.10 per image`, `¥0.99/s (720p)`, `¥0.0003/计费字符(汉字按 2 个算)`; `not priced`
12314
+ * without a price. A video Token price lists its rules (`视频 Token 计价:480p 无参考视频 ¥60.06/百万 Token(预计 ¥0.5819/秒)…`).
11357
12315
  * @param model - the model.
11358
12316
  * @param lang - the language.
11359
12317
  * @returns the price line.
@@ -11363,9 +12321,9 @@ function describePrice(model, lang = "en") {
11363
12321
  if (model.videoPricing !== void 0) return describeTokenPricing(model.videoPricing, lang);
11364
12322
  const pricing = model.pricing;
11365
12323
  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"}`);
12324
+ const per = (unit, amount) => `${unitPrice(unit, amount)}${unitSuffix(unit, model.kind, hanWeightOf(model))[lang]}`;
12325
+ const parts = pricing.tiers.map((tier) => `${per(tier.unit, tier.amount)} (${tier.tier})`);
12326
+ 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
12327
  return parts.length === 0 ? UNPRICED[lang] : parts.join(", ");
11370
12328
  }
11371
12329
  /**
@@ -11388,23 +12346,84 @@ function legacyVideoPrice(model, resolution) {
11388
12346
  const only = model.video?.resolutions?.length === 1 ? model.video.resolutions[0] : void 0;
11389
12347
  return tierFor(model.pricing, resolution ?? only);
11390
12348
  }
12349
+ /** Shown wherever the catalog gives an audio model no price. */
12350
+ const AUDIO_UNPRICED_BASIS = {
12351
+ en: "The catalog states no price for this model; the gateway receipt shows the charge.",
12352
+ zh: "目录未给出价格,以网关结算为准。"
12353
+ };
12354
+ /**
12355
+ * An estimate in yuan, without the sign: half up to two decimals (`0.37`); below ¥0.10, to four (`0.0036`), and
12356
+ * exactly when even that would round it away, so a short text never reads as ¥0.00.
12357
+ */
12358
+ function estimateText(amount) {
12359
+ if (amount.units === 0n) return "0.00";
12360
+ if (toNumber(amount) >= .1) return format(roundHalfUp(amount, 2), 2);
12361
+ const rounded = roundHalfUp(amount, 4);
12362
+ return format(rounded.units === 0n ? amount : rounded, 2);
12363
+ }
12364
+ /** Quote speech billed per character: on the text as sent, when there is one. */
12365
+ function quoteCharacters(model, price, text) {
12366
+ const weight = hanWeightOf(model);
12367
+ const count = text === void 0 || text === "" ? void 0 : billableCount(text, weight);
12368
+ const facts = {
12369
+ unit: "character",
12370
+ hanCharacterWeight: weight,
12371
+ ...count === void 0 ? {} : { billableCharacters: toNumber(count) }
12372
+ };
12373
+ if (price === void 0) return {
12374
+ priced: false,
12375
+ ...facts,
12376
+ label: UNPRICED,
12377
+ basis: AUDIO_UNPRICED_BASIS
12378
+ };
12379
+ const suffix = unitSuffix("character", model.kind, weight);
12380
+ const each = unitPrice("character", price.amount);
12381
+ const label = {
12382
+ en: `${each}${suffix.en}`,
12383
+ zh: `${each}${suffix.zh}`
12384
+ };
12385
+ const base = {
12386
+ priced: true,
12387
+ ...facts,
12388
+ unitPriceCny: price.amount,
12389
+ label
12390
+ };
12391
+ const counts = format(decimal(weight));
12392
+ if (count === void 0) return {
12393
+ ...base,
12394
+ basis: {
12395
+ en: `${label.en}, counted on the text read aloud; final billing follows the gateway receipt`,
12396
+ zh: `${label.zh},按朗读文本计费,实际以网关结算为准`
12397
+ }
12398
+ };
12399
+ const amount = multiply(decimal(price.amount), count);
12400
+ const shown = `¥${estimateText(amount)}`;
12401
+ return {
12402
+ ...base,
12403
+ amountCny: toNumber(amount),
12404
+ basis: {
12405
+ en: `about ${shown} (${each} per billable character, Chinese characters count as ${counts}, ${format(count)} billable characters); final billing follows the gateway receipt`,
12406
+ zh: `约 ${shown}(${each}/计费字符,汉字按 ${counts} 个算,共 ${format(count)} 个计费字符),实际以网关结算为准`
12407
+ }
12408
+ };
12409
+ }
11391
12410
  /**
11392
12411
  * Quote an audio request: music, podcast and speech generation, or a transcription.
11393
12412
  * @param model - the audio or transcription model.
11394
- * @param inputSeconds - for a transcription, the measured length of the input, when known.
12413
+ * @param input - for a transcription, the measured length of the input in seconds (or `{inputSeconds}`); for speech
12414
+ * billed per character, `{text}`: the text as it is sent. Without them the quote gives the unit price only.
11395
12415
  * @returns the quote; `priced: false` (未定价) when the catalog gives no usable price.
11396
12416
  */
11397
- function quoteAudio(model, inputSeconds) {
12417
+ function quoteAudio(model, input) {
12418
+ const { inputSeconds, text } = typeof input === "number" ? { inputSeconds: input } : input ?? {};
11398
12419
  const price = model.pricing === void 0 ? void 0 : tierFor(model.pricing, void 0);
11399
12420
  const unit = price?.unit ?? model.audio?.billingUnit;
12421
+ if (unit === "character") return quoteCharacters(model, price, text);
11400
12422
  if (price === void 0 || unit === void 0 || unit === "second") return {
11401
12423
  priced: false,
11402
12424
  ...unit === void 0 ? {} : { unit },
11403
12425
  label: UNPRICED,
11404
- basis: {
11405
- en: "The catalog states no price for this model; the gateway receipt shows the charge.",
11406
- zh: "目录未给出价格,以网关结算为准。"
11407
- }
12426
+ basis: AUDIO_UNPRICED_BASIS
11408
12427
  };
11409
12428
  const suffix = unitSuffix(unit, model.kind);
11410
12429
  const label = {
@@ -11451,6 +12470,16 @@ function quoteAudio(model, inputSeconds) {
11451
12470
  }
11452
12471
  };
11453
12472
  }
12473
+ /**
12474
+ * The estimate an audio task records: two decimals (`0.50`); per character, four below ¥0.10 (`0.0036`) so a short
12475
+ * text is never recorded as 0.00.
12476
+ * @param quote - the quote.
12477
+ * @returns the amount in yuan, or undefined without an amount.
12478
+ */
12479
+ function audioQuotedCny(quote) {
12480
+ if (quote.amountCny === void 0) return void 0;
12481
+ return quote.unit === "character" ? estimateText(decimal(quote.amountCny)) : quote.amountCny.toFixed(2);
12482
+ }
11454
12483
  /** Shown wherever video Token pricing gives no estimate. */
11455
12484
  const TOKEN_UNAVAILABLE = {
11456
12485
  en: "estimate unavailable; billed by actual video Token usage",
@@ -12654,8 +13683,9 @@ function withAudioMarkers(text, references) {
12654
13683
  }
12655
13684
  /**
12656
13685
  * 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.
13686
+ * against its declaration, upload and measure speech references, price it
13687
+ * (speech billed per character on the text as sent, `@AudioN` markers
13688
+ * included), confirm the spending, and build the task under the operation's key.
12659
13689
  * @param runtime - the media runtime.
12660
13690
  * @param call - the tool call or host call.
12661
13691
  * @param request - what to generate.
@@ -12686,7 +13716,8 @@ async function prepareAudioTask(runtime, call, request, save) {
12686
13716
  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
13717
  }
12688
13718
  if (kind === "music" && has(request.sourceAudio)) body.source_audio_url = await uploadSourceAudio(runtime, call, request.sourceAudio.trim());
12689
- const quote = quoteAudio(model);
13719
+ const spoken = kind === "speech" && promptField !== void 0 && typeof body[promptField] === "string" ? body[promptField] : void 0;
13720
+ const quote = quoteAudio(model, spoken === void 0 ? void 0 : { text: spoken });
12690
13721
  const mode = kind === "music" ? musicModeOf(request) : "generate";
12691
13722
  const what = {
12692
13723
  music: mode === "voice_cover" ? {
@@ -12709,9 +13740,10 @@ async function prepareAudioTask(runtime, call, request, save) {
12709
13740
  }
12710
13741
  }[kind];
12711
13742
  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}。`
13743
+ en: sentence(`Generate ${what.en} with ${model.id}: ${quote.basis.en}`, "."),
13744
+ zh: sentence(`用 ${model.id} 生成${what.zh}:${quote.basis.zh}`, "。")
12714
13745
  });
13746
+ const estimatedCny = audioQuotedCny(quote);
12715
13747
  const now = runtime.now();
12716
13748
  const prompt = request.prompt?.trim();
12717
13749
  return {
@@ -12733,7 +13765,7 @@ async function prepareAudioTask(runtime, call, request, save) {
12733
13765
  body,
12734
13766
  status: "submitting",
12735
13767
  audioKind: kind,
12736
- ...quote.amountCny === void 0 ? {} : { estimatedCny: quote.amountCny.toFixed(2) },
13768
+ ...estimatedCny === void 0 ? {} : { estimatedCny },
12737
13769
  ...quote.unit === void 0 ? {} : { billing: {
12738
13770
  unit: quote.unit,
12739
13771
  ...quote.unitPriceCny === void 0 ? {} : { unitPriceCny: String(quote.unitPriceCny) }
@@ -12742,6 +13774,10 @@ async function prepareAudioTask(runtime, call, request, save) {
12742
13774
  ...notes.length === 0 ? {} : { notes }
12743
13775
  };
12744
13776
  }
13777
+ /** A sentence ended once: a text that already ends in a stop (a price basis can) gets no second one. */
13778
+ function sentence(text, stop) {
13779
+ return /[.。!!??]$/.test(text) ? text : `${text}${stop}`;
13780
+ }
12745
13781
  function excerptOf(text, max = 60) {
12746
13782
  const flat = text.replace(/\s+/g, " ").trim();
12747
13783
  const chars = [...flat];
@@ -16418,7 +17454,7 @@ function mediaAccountTool(runtime, chain, login) {
16418
17454
  function audioGenerateTool(runtime) {
16419
17455
  return defineTool({
16420
17456
  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.",
17457
+ 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
17458
  parameters: {
16423
17459
  type: {
16424
17460
  type: "string",
@@ -16589,7 +17625,7 @@ function audioGenerateTool(runtime) {
16589
17625
  ...base,
16590
17626
  status: accepted.status,
16591
17627
  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
17628
+ 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
17629
  };
16594
17630
  const final = await waitForTask(runtime, exec, accepted);
16595
17631
  return {
@@ -17045,15 +18081,15 @@ function audioTranscribeTool(runtime) {
17045
18081
  * Which accepted gateway requests may have spent money, so the balance is read again after them.
17046
18082
  * @module dsh-vibedev/gateway/paid-path
17047
18083
  */
17048
- /** Generations and transcriptions (uploads and reads are free). */
17049
- const PAID_PATH = /^\/v1\/(?:images|videos|audio)(?:\/|$)/;
18084
+ /** Generations, transcriptions and realtime speech (`/v1/vibedev/speech/asr|tts`); uploads and reads are free. */
18085
+ const PAID_PATH = /^\/v1\/(?:images|videos|audio|vibedev\/speech)(?:\/|$)/;
17050
18086
  /** Free paths under a paid prefix: voice profiles are created, listed and deleted without a charge. */
17051
18087
  const FREE_PATH = /^\/v1\/audio\/voice-profiles(?:\/|$)/;
17052
18088
  /**
17053
18089
  * Whether an accepted request may have been charged.
17054
18090
  * @param method - the HTTP method.
17055
18091
  * @param path - the request path, without the query.
17056
- * @returns true for a POST to a generation or transcription endpoint.
18092
+ * @returns true for a POST to a generation, transcription or speech endpoint.
17057
18093
  */
17058
18094
  function isPaidRequest(method, path) {
17059
18095
  return method === "POST" && PAID_PATH.test(path) && !FREE_PATH.test(path);
@@ -17460,6 +18496,7 @@ const Config = Schema.object({
17460
18496
  claudeCacheTtl: Schema.union(CLAUDE_CACHE_TTLS.map((value) => Schema.const(value))).default("default").volatile(),
17461
18497
  preferredModels: Schema.array(Schema.string()).default([]),
17462
18498
  openBrowserOnSignIn: Schema.boolean().default(true),
18499
+ remoteSignInBaseUrl: Schema.string().default(""),
17463
18500
  catalogRefreshMinutes: Schema.number().min(1).max(1440).default(30),
17464
18501
  resendWindowMs: Schema.natural().min(1e3).max(108e5).default(3e5),
17465
18502
  submitAttempts: Schema.natural().min(1).max(30).default(3),
@@ -17490,6 +18527,7 @@ const Config = Schema.object({
17490
18527
  claudeCacheTtl: "Claude 提示词缓存保留时间(默认 / 5分钟 / 1小时)",
17491
18528
  preferredModels: "排在最前的 VibeDev 模型(按顺序,留空按网关顺序)",
17492
18529
  openBrowserOnSignIn: "登录时自动打开系统浏览器",
18530
+ remoteSignInBaseUrl: "远程主机登录地址(云环境 / 远程访问用,如 https://<主机ID>.h.vibedev.studio;留空为桌面版本机登录)",
17493
18531
  catalogRefreshMinutes: "模型目录定时刷新间隔(分钟;没人打开余额卡片、账号菜单或设置时的兜底)",
17494
18532
  resendWindowMs: "原键提交核对窗口(毫秒;仅适用于新操作,默认5分钟)",
17495
18533
  submitAttempts: "原键首次提交总尝试数(含首次,默认3)",
@@ -17521,6 +18559,7 @@ const Config = Schema.object({
17521
18559
  claudeCacheTtl: "Claude prompt cache lifetime (default / 5 minutes / 1 hour)",
17522
18560
  preferredModels: "VibeDev models listed first, in this order (empty: the gateway's order)",
17523
18561
  openBrowserOnSignIn: "Open the system browser when signing in",
18562
+ 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
18563
  catalogRefreshMinutes: "Model catalog refresh interval in minutes (the fallback when nobody opens the balance card, the account menu or Settings)",
17525
18564
  resendWindowMs: "Same-key recovery window in milliseconds (new operations only; default 5 minutes)",
17526
18565
  submitAttempts: "Initial same-key attempts including first dispatch (default 3)",
@@ -17556,13 +18595,34 @@ function apply(ctx, config) {
17556
18595
  ctx.logger.warn(message);
17557
18596
  };
17558
18597
  const storage = grantStorage(stateDir, () => ctx.get("credentials"), origin);
18598
+ let remoteBaseUrl;
18599
+ try {
18600
+ remoteBaseUrl = remoteSignInOrigin(config.remoteSignInBaseUrl);
18601
+ } catch (error) {
18602
+ warn(`dsh-vibedev: ${error.message}; remote sign-in is off`);
18603
+ }
18604
+ let remoteRoute = false;
17559
18605
  const login = new PluginLogin({
17560
18606
  origin,
17561
18607
  userAgent,
17562
18608
  log: warn,
17563
18609
  storage,
17564
18610
  client: config.client.trim() || "vibedev-plugin",
17565
- openBrowser: (url) => config.openBrowserOnSignIn ? openInBrowser(url) : Promise.resolve(false)
18611
+ openBrowser: (url) => config.openBrowserOnSignIn ? openInBrowser(url) : Promise.resolve(false),
18612
+ ...remoteBaseUrl === void 0 ? {} : {
18613
+ remoteBaseUrl,
18614
+ remoteCallbackReady: () => remoteRoute
18615
+ }
18616
+ });
18617
+ if (remoteBaseUrl !== void 0) ctx.inject(["webServer"], (webCtx) => {
18618
+ webCtx.effect(() => {
18619
+ const dispose = registerRemoteCallback(webCtx.webServer, login);
18620
+ remoteRoute = true;
18621
+ return () => {
18622
+ remoteRoute = false;
18623
+ dispose();
18624
+ };
18625
+ }, "dsh-vibedev: remote sign-in callback");
17566
18626
  });
17567
18627
  ctx.inject(["credentials"], (scoped) => {
17568
18628
  scoped.on("credentials/record-updated", (key) => {
@@ -17732,6 +18792,12 @@ function apply(ctx, config) {
17732
18792
  });
17733
18793
  });
17734
18794
  });
18795
+ installSpeech(ctx, {
18796
+ http,
18797
+ resolveCredential: () => chain.resolve(),
18798
+ onSignInChange: (listener) => login.onChange(listener),
18799
+ log: warn
18800
+ });
17735
18801
  const accountService = new AccountService({
17736
18802
  origin,
17737
18803
  userAgent,
@@ -17825,6 +18891,6 @@ function apply(ctx, config) {
17825
18891
  });
17826
18892
  }
17827
18893
  //#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 };
18894
+ 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
18895
 
17830
18896
  //# sourceMappingURL=index.js.map