@vibedev-si/dsh-vibedev 0.3.5 → 0.3.7

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
@@ -1,14 +1,15 @@
1
1
  import { p as lazyApi, r as createModels$1 } from "./models-CAcLevEN.js";
2
2
  import { createWriteStream, readFileSync } from "node:fs";
3
3
  import Schema from "@deepseek-ai/schemastery";
4
- import { createHash, randomBytes, randomUUID } from "node:crypto";
5
- import { link, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
6
4
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
7
- import { credentialKey } from "@deepseek-ai/dsh-credentials";
8
5
  import { arch, homedir, platform, release } from "node:os";
6
+ import { APP_IDENTITY, CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, HarnessError, IMAGE_OFFLOAD_REQUIRED_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload, resolveImageAttachmentAccess } from "@deepseek-ai/dsh-llm";
7
+ import { Buffer as Buffer$1 } from "node:buffer";
8
+ import { link, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
9
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
9
10
  import { Readable, Transform } from "node:stream";
10
11
  import { pipeline } from "node:stream/promises";
11
- import { CONTEXT_WINDOW_EXCEEDED_CODE, EMPTY_RESPONSE_CODE, HarnessError, IMAGE_OFFLOAD_REQUIRED_CODE, LlmAdapter, LlmError, QUOTA_EXCEEDED_CODE, ReasoningEffortId, attributionHeaders, contentHasImage, isContextWindowExceededError, isQuotaExceededError, offloadedImageText, projectOffloadedImages, requestImageHandleText, requiredImageOffload, resolveImageAttachmentAccess } from "@deepseek-ai/dsh-llm";
12
+ import { credentialKey } from "@deepseek-ai/dsh-credentials";
12
13
  import { spawn } from "node:child_process";
13
14
  import { createServer } from "node:http";
14
15
  import { idleWatchdog, timeoutOf } from "@deepseek-ai/dsh-timeout";
@@ -40,7 +41,14 @@ const WAIT_MS = 8e3;
40
41
  const SETTLE_READS_MS = [1500, 8e3];
41
42
  /** Reads after charges are at least this far apart. */
42
43
  const MIN_READ_SPACING_MS = 5e3;
43
- const record$8 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
44
+ /**
45
+ * An explicit read of the account (`?fresh=1`: the balance card opening on a balance older than 10 s, the account
46
+ * menu, 刷新, Settings opening) also reads the model catalog again, at most once in this long. The route's own reads
47
+ * (at start, on a sign-in change, every `catalogRefreshMinutes`) are untouched: they are what keeps the pickers
48
+ * current when nobody opens anything.
49
+ */
50
+ const CATALOG_REFRESH_GAP_MS = 6e4;
51
+ const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
44
52
  const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
45
53
  /**
46
54
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
@@ -81,6 +89,9 @@ var AccountService = class {
81
89
  lastGood;
82
90
  /** The latest read failed, after the last one that succeeded. */
83
91
  failure;
92
+ /** When the last catalog read an explicit read started began, and that read while it runs. */
93
+ catalogReadAt = Number.NEGATIVE_INFINITY;
94
+ catalogRead;
84
95
  /**
85
96
  * @param options - origin, credential chain, the plugin's sign-in and the route's model state.
86
97
  */
@@ -167,18 +178,36 @@ var AccountService = class {
167
178
  };
168
179
  }
169
180
  /**
181
+ * Read the model catalog again, without waiting for it: at most one read a minute and one at a time. A read that
182
+ * changed the list (a model the gateway published or withdrew) is told to the pages at once, through the long
183
+ * poll; one that changed nothing, or failed, tells them nothing.
184
+ */
185
+ refreshModels() {
186
+ const refresh = this.options.refreshCatalog;
187
+ if (refresh === void 0 || this.catalogRead !== void 0 || this.now() - this.catalogReadAt < CATALOG_REFRESH_GAP_MS) return;
188
+ this.catalogReadAt = this.now();
189
+ const before = JSON.stringify(this.options.models());
190
+ const read = Promise.resolve().then(() => refresh()).then(() => {
191
+ if (JSON.stringify(this.options.models()) !== before) this.changed();
192
+ }, () => void 0).finally(() => {
193
+ if (this.catalogRead === read) this.catalogRead = void 0;
194
+ });
195
+ this.catalogRead = read;
196
+ }
197
+ /**
170
198
  * The account as it stands.
171
- * @param fresh - read the balance again instead of reusing a recent read.
199
+ * @param fresh - read the balance again instead of reusing a recent read, and the model catalog with it (at most
200
+ * once a minute; the answer does not wait for it).
172
201
  * @returns the view.
173
202
  */
174
203
  async view(fresh = false) {
175
204
  const credential = await this.options.chain.resolve().catch(() => void 0);
205
+ if (fresh && credential !== void 0) this.refreshModels();
176
206
  const source = credential === void 0 ? "none" : credential.kind === "account" ? "host" : credential.kind;
177
207
  const pending = this.options.login.pendingSignIn();
178
208
  const attempt = this.options.login.signInAttempt();
179
209
  const base = {
180
210
  source,
181
- models: this.options.models(),
182
211
  links: this.links(),
183
212
  primary: this.options.primary === true,
184
213
  ...pending === void 0 ? {} : { pending },
@@ -186,6 +215,7 @@ var AccountService = class {
186
215
  };
187
216
  if (credential === void 0) return {
188
217
  ...base,
218
+ models: this.options.models(),
189
219
  revision: this.revision
190
220
  };
191
221
  const [grantUser, read] = await Promise.all([credential.kind === "plugin" ? this.options.login.user().catch(() => void 0) : Promise.resolve(void 0), this.me(credential.token, fresh)]);
@@ -195,6 +225,7 @@ var AccountService = class {
195
225
  const failedAt = this.failure?.token === credential.token ? this.failure.at : void 0;
196
226
  return {
197
227
  ...base,
228
+ models: this.options.models(),
198
229
  ...user === void 0 ? {} : { user },
199
230
  ...me.balance === void 0 ? {} : { balance: me.balance },
200
231
  ...me.readAt === void 0 ? {} : { readAt: me.readAt },
@@ -203,6 +234,24 @@ var AccountService = class {
203
234
  };
204
235
  }
205
236
  /**
237
+ * Who is signed in now, with the VibeDev user id when it can be known (a recent `/auth/me` read is reused, as for
238
+ * the pages).
239
+ * @returns the identity.
240
+ */
241
+ async identity() {
242
+ const credential = await this.options.chain.resolve().catch(() => void 0);
243
+ if (credential === void 0) return { signedIn: false };
244
+ const read = await this.me(credential.token, false);
245
+ const good = this.lastGood?.token === credential.token ? this.lastGood.read : void 0;
246
+ let userId = read.user?.id ?? good?.user?.id;
247
+ if (userId === void 0 && credential.kind === "plugin") userId = (await this.options.login.user().catch(() => void 0))?.id;
248
+ return {
249
+ signedIn: true,
250
+ credential,
251
+ userId
252
+ };
253
+ }
254
+ /**
206
255
  * `GET /v1/account/auth/me` for one token. A read younger than the TTL is
207
256
  * reused; an older one is answered at once while a new read runs behind it.
208
257
  */
@@ -234,8 +283,8 @@ var AccountService = class {
234
283
  redirect: "error"
235
284
  });
236
285
  if (!response.ok) return {};
237
- const body = record$8(await response.json().catch(() => void 0));
238
- const data = record$8(body?.data) ?? body;
286
+ const body = record$9(await response.json().catch(() => void 0));
287
+ const data = record$9(body?.data) ?? body;
239
288
  const balance = amountOf(data?.balance);
240
289
  const currency = text$8(data?.currency) ?? "CNY";
241
290
  const frozen = amountOf(data?.frozen_balance);
@@ -342,7 +391,7 @@ function userOf(user) {
342
391
  ...nickname === void 0 ? {} : { nickname }
343
392
  };
344
393
  }
345
- function json$1(status, body) {
394
+ function json$2(status, body) {
346
395
  return new Response(JSON.stringify(body), {
347
396
  status,
348
397
  headers: {
@@ -352,9 +401,9 @@ function json$1(status, body) {
352
401
  });
353
402
  }
354
403
  function failure(error) {
355
- const candidate = record$8(error)?.code;
404
+ const candidate = record$9(error)?.code;
356
405
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
357
- return json$1(500, { error: {
406
+ return json$2(500, { error: {
358
407
  code,
359
408
  message: code === "SIGN_IN_CANCELLED" ? "Sign-in was cancelled. 登录已取消。" : code === "SIGN_IN_TIMEOUT" ? "Sign-in expired. 登录已超时,请重新登录。" : "The account request could not be completed. 账号请求未完成,请查看登录诊断后重试。"
360
409
  } });
@@ -375,7 +424,7 @@ function accountRoutes(account) {
375
424
  const query = new URL(request.url, "http://host").searchParams;
376
425
  const since = query.get("since");
377
426
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
378
- return json$1(200, await account.view(query.get("fresh") === "1"));
427
+ return json$2(200, await account.view(query.get("fresh") === "1"));
379
428
  } catch (error) {
380
429
  return failure(error);
381
430
  }
@@ -387,8 +436,8 @@ function accountRoutes(account) {
387
436
  requestBody: "buffered",
388
437
  fetch: async (request) => {
389
438
  try {
390
- const body = record$8(await request.json().catch(() => void 0));
391
- return json$1(200, await account.signIn(body?.open !== false));
439
+ const body = record$9(await request.json().catch(() => void 0));
440
+ return json$2(200, await account.signIn(body?.open !== false));
392
441
  } catch (error) {
393
442
  return failure(error);
394
443
  }
@@ -400,7 +449,7 @@ function accountRoutes(account) {
400
449
  requestBody: "buffered",
401
450
  fetch: () => {
402
451
  account.cancel();
403
- return Promise.resolve(json$1(200, { ok: true }));
452
+ return Promise.resolve(json$2(200, { ok: true }));
404
453
  }
405
454
  },
406
455
  {
@@ -409,7 +458,7 @@ function accountRoutes(account) {
409
458
  requestBody: "buffered",
410
459
  fetch: async () => {
411
460
  try {
412
- return await account.signOut() ? json$1(200, { ok: true }) : json$1(409, { error: {
461
+ return await account.signOut() ? json$2(200, { ok: true }) : json$2(409, { error: {
413
462
  code: "SIGNED_IN_BY_APP",
414
463
  message: "The VibeDev account is the app's sign-in; sign out in the app."
415
464
  } });
@@ -427,7 +476,7 @@ const LATENCY_ROUTE = "/api/dsh-vibedev/latency";
427
476
  /** Timed requests after the first one. */
428
477
  const TIMED_REQUESTS = 4;
429
478
  /** Each request gets this long, its body included. */
430
- const REQUEST_TIMEOUT_MS = 5e3;
479
+ const REQUEST_TIMEOUT_MS$1 = 5e3;
431
480
  /** A result is answered again for this long; `fresh` measures anyway. */
432
481
  const RESULT_TTL_MS = 6e4;
433
482
  /** One turn of the event loop, after which the previous request's connection is back in the pool. */
@@ -530,7 +579,7 @@ var LatencyProbe = class {
530
579
  },
531
580
  cache: "no-store",
532
581
  redirect: "error",
533
- signal: (this.options.timeout ?? ((ms) => AbortSignal.timeout(ms)))(REQUEST_TIMEOUT_MS)
582
+ signal: (this.options.timeout ?? ((ms) => AbortSignal.timeout(ms)))(REQUEST_TIMEOUT_MS$1)
534
583
  };
535
584
  const started = this.clock();
536
585
  const response = await (this.options.fetch ?? globalThis.fetch)(`${this.options.origin}/health`, init);
@@ -540,7 +589,7 @@ var LatencyProbe = class {
540
589
  return elapsed;
541
590
  }
542
591
  };
543
- function json(status, body) {
592
+ function json$1(status, body) {
544
593
  return new Response(JSON.stringify(body), {
545
594
  status,
546
595
  headers: {
@@ -561,9 +610,9 @@ function latencyRoutes(probe) {
561
610
  requestBody: "buffered",
562
611
  fetch: async (request) => {
563
612
  try {
564
- return json(200, await probe.measure(new URL(request.url, "http://host").searchParams.get("fresh") === "1"));
613
+ return json$1(200, await probe.measure(new URL(request.url, "http://host").searchParams.get("fresh") === "1"));
565
614
  } catch {
566
- return json(500, { error: {
615
+ return json$1(500, { error: {
567
616
  code: "INTERNAL",
568
617
  message: "The latency could not be measured. 网络延迟没有测成,请稍后重试。"
569
618
  } });
@@ -572,6 +621,328 @@ function latencyRoutes(probe) {
572
621
  }];
573
622
  }
574
623
  //#endregion
624
+ //#region src/feedback/wire.ts
625
+ /**
626
+ * The feedback upload contract: `POST {origin}/v1/account/feedback` with the
627
+ * account's credential (the one `GET /v1/account/auth/me` carries) and a
628
+ * strict JSON body — the gateway refuses unknown fields, so a body holds
629
+ * nothing else. Limits: text at most 4,000 code points, an attachment at most
630
+ * 256 KiB of UTF-8, the whole body at most 300 KiB; short fields carry no
631
+ * control characters. Text and attachments are measured as the gateway stores
632
+ * them, with U+0000 as U+FFFD.
633
+ * @module dsh-vibedev/feedback/wire
634
+ */
635
+ /** Gateway path of the upload. */
636
+ const FEEDBACK_PATH = "/v1/account/feedback";
637
+ /** The categories DeepSeek Harness files feedback under (`FEEDBACK_CATEGORIES` in @deepseek-ai/dsh-command-feedback). */
638
+ const FEEDBACK_CATEGORIES = [
639
+ "task-result",
640
+ "instruction-following",
641
+ "product-interaction",
642
+ "service-stability",
643
+ "resource-cost",
644
+ "security-privacy-permission",
645
+ "other"
646
+ ];
647
+ const MAX_TEXT_CODE_POINTS = 4e3;
648
+ const MAX_ATTACHMENT_BYTES = 262144;
649
+ const MAX_BODY_BYTES = 307200;
650
+ /** Control characters: C0, DEL and C1. */
651
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
652
+ /**
653
+ * Free text as the gateway stores and measures it: U+0000 becomes U+FFFD (PostgreSQL text cannot hold it), three bytes
654
+ * instead of one, before any limit is checked (submission.go sanitizeFreeText, then the size checks). Measuring the
655
+ * text as stored keeps an attachment near 256 KiB with NULs in it from being refused as too large.
656
+ * @param value - the text.
657
+ * @returns the text as it will be stored.
658
+ */
659
+ function asStored(value) {
660
+ return value.replaceAll("\0", "�");
661
+ }
662
+ /**
663
+ * A short field as the gateway accepts it: no control characters, trimmed, at most `max` code points.
664
+ * @param value - anything.
665
+ * @param max - the longest value, in code points.
666
+ * @returns the field, or undefined when nothing is left.
667
+ */
668
+ function shortField(value, max) {
669
+ if (typeof value !== "string") return void 0;
670
+ const cut = [...value.replace(CONTROL, "").trim()].slice(0, max).join("");
671
+ return cut === "" ? void 0 : cut;
672
+ }
673
+ /**
674
+ * Free text as the gateway accepts it: line breaks and tabs kept, U+0000 as the U+FFFD the gateway stores, other
675
+ * control characters dropped, trimmed, at most 4,000 code points.
676
+ * @param value - anything.
677
+ * @returns the text, or undefined when blank.
678
+ */
679
+ function feedbackText(value) {
680
+ if (typeof value !== "string") return void 0;
681
+ const cleaned = asStored(value).replace(/[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "").trim();
682
+ if (cleaned === "") return void 0;
683
+ return [...cleaned].slice(0, MAX_TEXT_CODE_POINTS).join("");
684
+ }
685
+ /** The number of code points, the unit the gateway counts text in. */
686
+ function codePoints(text) {
687
+ let count = 0;
688
+ for (const _ of text) count++;
689
+ return count;
690
+ }
691
+ /**
692
+ * Whether a value is one of the feedback categories.
693
+ * @param value - anything.
694
+ * @returns true for a category.
695
+ */
696
+ function isCategory(value) {
697
+ return typeof value === "string" && FEEDBACK_CATEGORIES.includes(value);
698
+ }
699
+ const TRUNCATED = "\n…[truncated]";
700
+ /**
701
+ * Text cut to at most `maxBytes` of UTF-8 on a code-point boundary, with a marker when anything was cut.
702
+ * @param content - the text.
703
+ * @param maxBytes - the budget.
704
+ * @returns the text, unchanged when it fits.
705
+ */
706
+ function fitUtf8(content, maxBytes) {
707
+ if (Buffer$1.byteLength(content, "utf8") <= maxBytes) return content;
708
+ const budget = Math.max(0, maxBytes - Buffer$1.byteLength(TRUNCATED, "utf8"));
709
+ let used = 0;
710
+ let end = 0;
711
+ for (const character of content) {
712
+ const size = Buffer$1.byteLength(character, "utf8");
713
+ if (used + size > budget) break;
714
+ used += size;
715
+ end += character.length;
716
+ }
717
+ return `${content.slice(0, end)}${TRUNCATED}`;
718
+ }
719
+ /**
720
+ * Whether a draft says anything the gateway accepts: text, a rating or a category.
721
+ * @param draft - the draft.
722
+ * @returns true when it can be sent.
723
+ */
724
+ function isSendable(draft) {
725
+ return draft.text !== void 0 || draft.rating !== void 0 || draft.category !== void 0;
726
+ }
727
+ /**
728
+ * The body for a draft: only the fields the contract names, none of them empty; the attachment cut to its limit and
729
+ * then, if need be, to what the whole body allows.
730
+ * @param id - the idempotency key.
731
+ * @param draft - what the feedback says.
732
+ * @param client - which app sent it.
733
+ * @returns the body.
734
+ */
735
+ function feedbackBody(id, draft, client) {
736
+ const sessionRef = shortField(draft.context?.sessionRef, 128);
737
+ const messageRef = shortField(draft.context?.messageRef, 128);
738
+ const text = feedbackText(draft.text);
739
+ const base = {
740
+ id,
741
+ source: draft.source,
742
+ ...draft.rating === void 0 ? {} : { rating: draft.rating },
743
+ ...draft.category === void 0 ? {} : { category: draft.category },
744
+ ...text === void 0 ? {} : { text },
745
+ client,
746
+ ...sessionRef === void 0 && messageRef === void 0 ? {} : { context: {
747
+ ...sessionRef === void 0 ? {} : { sessionRef },
748
+ ...messageRef === void 0 ? {} : { messageRef }
749
+ } }
750
+ };
751
+ const attachment = draft.attachment;
752
+ if (attachment === void 0 || attachment.content === "") return base;
753
+ let content = fitUtf8(asStored(attachment.content), MAX_ATTACHMENT_BYTES);
754
+ let body = {
755
+ ...base,
756
+ attachment: {
757
+ kind: attachment.kind,
758
+ consent: true,
759
+ content
760
+ }
761
+ };
762
+ for (let over = bodyBytes(body) - MAX_BODY_BYTES; over > 0; over = bodyBytes(body) - MAX_BODY_BYTES) {
763
+ content = fitUtf8(content, Buffer$1.byteLength(content, "utf8") - over - 64);
764
+ body = {
765
+ ...base,
766
+ attachment: {
767
+ kind: attachment.kind,
768
+ consent: true,
769
+ content
770
+ }
771
+ };
772
+ }
773
+ return body;
774
+ }
775
+ /**
776
+ * The same draft with its attachment cut to half (after the gateway refused the body as too large).
777
+ * @param body - the refused body.
778
+ * @param id - the new body's id (a changed body is a new upload).
779
+ * @returns the smaller body, or undefined when there is no attachment left to cut.
780
+ */
781
+ function halveAttachment(body, id) {
782
+ const attachment = body.attachment;
783
+ if (attachment === void 0) return void 0;
784
+ const stored = asStored(attachment.content);
785
+ const bytes = Buffer$1.byteLength(stored, "utf8");
786
+ if (bytes <= 1024) {
787
+ const { attachment: _dropped, ...rest } = body;
788
+ return {
789
+ ...rest,
790
+ id
791
+ };
792
+ }
793
+ return {
794
+ ...body,
795
+ id,
796
+ attachment: {
797
+ ...attachment,
798
+ content: fitUtf8(stored, Math.floor(bytes / 2))
799
+ }
800
+ };
801
+ }
802
+ /** The size of a body on the wire. */
803
+ function bodyBytes(body) {
804
+ return Buffer$1.byteLength(JSON.stringify(body), "utf8");
805
+ }
806
+ //#endregion
807
+ //#region src/feedback/client-info.ts
808
+ /**
809
+ * The `client` block of a feedback upload: which VibeDev app the Host serves,
810
+ * its version, the DeepSeek Harness and plugin versions, the operating system
811
+ * and the locale.
812
+ * @module dsh-vibedev/feedback/client-info
813
+ */
814
+ /**
815
+ * This process's facts.
816
+ * @returns the facts.
817
+ */
818
+ function hostFacts() {
819
+ let locale;
820
+ try {
821
+ locale = Intl.DateTimeFormat().resolvedOptions().locale;
822
+ } catch {
823
+ locale = void 0;
824
+ }
825
+ return {
826
+ versions: process.versions,
827
+ hasIpc: typeof process.send === "function",
828
+ execPath: process.execPath,
829
+ platform: process.platform,
830
+ arch: process.arch,
831
+ osRelease: release(),
832
+ locale
833
+ };
834
+ }
835
+ /**
836
+ * Which app the Host serves. The VibeDev desktop app starts its Host from the window process on its own executable in
837
+ * Electron's Node mode, with an IPC channel back (apps/desktop/src/host-process.ts: `spawn(process.execPath, …,
838
+ * { stdio: [..., 'ipc'] })`); in that mode `process.versions.electron` is still set. `vibedev-app web` runs the same
839
+ * executable from a terminal, without that channel, and a DeepSeek Harness install runs on Node: both serve the
840
+ * browser. (Checked against VibeDev 0.2.1-rc.2.20261019.3: Electron 44.7.0, `process.send` present only with IPC.)
841
+ * @param facts - the process facts.
842
+ * @returns `vibedev-desktop` or `vibedev-web`.
843
+ */
844
+ function hostApp(facts) {
845
+ return typeof facts.versions.electron === "string" && facts.hasIpc ? "vibedev-desktop" : "vibedev-web";
846
+ }
847
+ /**
848
+ * The desktop app's own version, from its manifest beside the executable (`resources/app.asar/package.json`; on macOS
849
+ * `Contents/Resources`), which Electron's Node mode reads like any file.
850
+ * @param facts - the process facts.
851
+ * @param read - reads a file as text (a test seam).
852
+ * @returns the version, or undefined when there is no manifest to read.
853
+ */
854
+ function desktopAppVersion(facts, read = (path) => readFileSync(path, "utf8")) {
855
+ const base = dirname(facts.execPath);
856
+ for (const manifest of [join(base, "resources", "app.asar", "package.json"), join(base, "..", "Resources", "app.asar", "package.json")]) try {
857
+ const version = JSON.parse(read(manifest)).version;
858
+ if (typeof version === "string" && version !== "") return version;
859
+ } catch {}
860
+ }
861
+ /**
862
+ * The client block for this Host.
863
+ * @param facts - the process facts.
864
+ * @param pluginVersion - this plugin's version.
865
+ * @param dshVersion - DeepSeek Harness's version (the LLM runtime's own manifest, as its User-Agent reports).
866
+ * @param read - reads the desktop manifest (a test seam).
867
+ * @returns the block, every field within the contract's limits.
868
+ */
869
+ function clientInfo(facts, pluginVersion, dshVersion = APP_IDENTITY.version, read) {
870
+ const app = hostApp(facts);
871
+ const appVersion = typeof facts.versions.electron === "string" ? shortField(desktopAppVersion(facts, read), 64) : void 0;
872
+ const platform = shortField(facts.platform, 32);
873
+ const osVersion = shortField(facts.osRelease, 128);
874
+ const arch = shortField(facts.arch, 32);
875
+ const locale = shortField(facts.locale, 64);
876
+ const dsh = shortField(dshVersion, 64);
877
+ const plugin = shortField(pluginVersion, 64);
878
+ return {
879
+ app,
880
+ ...appVersion === void 0 ? {} : { appVersion },
881
+ ...dsh === void 0 ? {} : { dshVersion: dsh },
882
+ ...plugin === void 0 ? {} : { pluginVersion: plugin },
883
+ ...platform === void 0 || osVersion === void 0 || arch === void 0 ? {} : { os: {
884
+ platform,
885
+ version: osVersion,
886
+ arch
887
+ } },
888
+ ...locale === void 0 ? {} : { locale }
889
+ };
890
+ }
891
+ //#endregion
892
+ //#region src/feedback/observe.ts
893
+ /**
894
+ * The feedback one newly appended event carries.
895
+ * @param owner - the Session the event was appended to.
896
+ * @param event - the event.
897
+ * @returns the draft, or undefined for anything else (another event, a deletion, inherited or empty feedback).
898
+ */
899
+ function draftFromEvent(owner, event) {
900
+ if (event.seq < owner.inheritedEventCount) return void 0;
901
+ let draft;
902
+ switch (event.type) {
903
+ case "feedback/record": {
904
+ const { text, category } = event.data;
905
+ draft = {
906
+ source: "command",
907
+ ...text === void 0 ? {} : { text },
908
+ ...isCategory(category) ? { category } : {},
909
+ context: { sessionRef: owner.id }
910
+ };
911
+ break;
912
+ }
913
+ case "feedback/message-put": {
914
+ if (event.data.sessionId !== owner.id) return void 0;
915
+ const { messageId, rating, note, category } = event.data.item;
916
+ draft = {
917
+ source: "message",
918
+ rating: rating === "positive" ? "up" : "down",
919
+ ...isCategory(category) ? { category } : {},
920
+ ...note === void 0 ? {} : { text: note },
921
+ context: {
922
+ sessionRef: event.data.sessionId,
923
+ messageRef: messageId
924
+ }
925
+ };
926
+ break;
927
+ }
928
+ default: return;
929
+ }
930
+ return isSendable(draft) ? draft : void 0;
931
+ }
932
+ /**
933
+ * The feedback a committed write to a Session that is not open carries: the inspection's last event.
934
+ * @param inspection - the committed log, the feedback last.
935
+ * @returns the draft, or undefined.
936
+ */
937
+ function draftFromCommitted(inspection) {
938
+ const last = inspection.events.at(-1);
939
+ if (last === void 0) return void 0;
940
+ return draftFromEvent({
941
+ id: inspection.meta.id,
942
+ inheritedEventCount: inspection.inheritedEventCount
943
+ }, last);
944
+ }
945
+ //#endregion
575
946
  //#region src/gateway/errors.ts
576
947
  /**
577
948
  * Failures the plugin reports to the model: a gateway refusal, or a request the
@@ -598,7 +969,7 @@ var MediaError = class extends HarnessError {
598
969
  this.details = details;
599
970
  }
600
971
  };
601
- function record$7(value) {
972
+ function record$8(value) {
602
973
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
603
974
  }
604
975
  function text$7(value) {
@@ -616,19 +987,22 @@ function amount$1(value) {
616
987
  /**
617
988
  * Read a gateway error body. The gateway answers in several shapes: OpenAI's
618
989
  * `{error:{code,message,type}}`, its own `{error:{code,message,retryable,field}}`,
619
- * the account API's `{code,message,reason}`, and a top-level `recharge_url` on
620
- * balance refusals. Media admission refusals add `active`/`limit` (task limit)
621
- * or `estimated_cny`/`available_cny`/`pending_cny` (balance).
990
+ * the account API's `{code,message,reason,metadata}` (a validation refusal names
991
+ * the field and the rule there: `metadata: {field, rule}`), and a top-level
992
+ * `recharge_url` on balance refusals. Media admission refusals add
993
+ * `active`/`limit` (task limit) or `estimated_cny`/`available_cny`/`pending_cny` (balance).
622
994
  * @param body - the parsed JSON body, or undefined when it was not JSON.
623
995
  * @returns the fields found.
624
996
  */
625
997
  function parseGatewayFailure(body) {
626
- const root = record$7(body);
998
+ const root = record$8(body);
627
999
  if (root === void 0) return {};
628
- const source = record$7(root.error) ?? root;
1000
+ const source = record$8(root.error) ?? root;
1001
+ const metadata = record$8(source.metadata) ?? record$8(root.metadata);
629
1002
  const code = text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
630
1003
  const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
631
- const field = text$7(source.field);
1004
+ const field = text$7(source.field) ?? text$7(metadata?.field);
1005
+ const rule = text$7(source.rule) ?? text$7(metadata?.rule);
632
1006
  const rechargeUrl = text$7(source.recharge_url) ?? text$7(root.recharge_url);
633
1007
  const numbers = {
634
1008
  active: count$1(source.active),
@@ -641,14 +1015,17 @@ function parseGatewayFailure(body) {
641
1015
  };
642
1016
  const submissionState = text$7(source.submission_state) ?? text$7(root.submission_state);
643
1017
  const retryAction = text$7(source.retry_action) ?? text$7(root.retry_action);
1018
+ const assetId = text$7(source.asset_id) ?? text$7(root.asset_id);
644
1019
  return {
645
1020
  ...code === void 0 ? {} : { code },
646
1021
  ...message === void 0 ? {} : { message },
647
1022
  ...field === void 0 ? {} : { field },
1023
+ ...rule === void 0 ? {} : { rule },
648
1024
  ...typeof source.retryable === "boolean" ? { retryable: source.retryable } : {},
649
1025
  ...submissionState === void 0 ? {} : { submissionState: submissionState.toLowerCase() },
650
1026
  ...retryAction === void 0 ? {} : { retryAction: retryAction.toLowerCase() },
651
1027
  ...rechargeUrl === void 0 ? {} : { rechargeUrl },
1028
+ ...assetId === void 0 ? {} : { assetId },
652
1029
  ...Object.fromEntries(Object.entries({
653
1030
  ...numbers,
654
1031
  ...amounts
@@ -748,109 +1125,1195 @@ async function renameWithRetry(from, to) {
748
1125
  await new Promise((resolve) => setTimeout(resolve, 50 * 2 ** attempt));
749
1126
  }
750
1127
  }
751
- /**
752
- * Move a complete temporary file to the first free name `dir/stem.ext`
753
- * (then `stem-2.ext`, ...), never replacing an existing file.
754
- * @param temporary - the complete file.
755
- * @param dir - the destination directory, created when missing.
756
- * @param stem - the file-name stem.
757
- * @param extension - the extension, without a dot.
758
- * @returns the final path.
759
- */
760
- async function placeFile(temporary, dir, stem, extension) {
761
- await mkdir(dir, { recursive: true });
762
- let linkable = true;
763
- for (let attempt = 1; attempt < 1e3; attempt++) {
764
- const path = join(dir, `${attempt === 1 ? stem : `${stem}-${attempt}`}.${extension}`);
765
- if (linkable) try {
766
- await link(temporary, path);
767
- await rm(temporary, { force: true });
768
- return path;
769
- } catch (error) {
770
- if (error.code === "EEXIST") continue;
771
- linkable = false;
1128
+ /**
1129
+ * Move a complete temporary file to the first free name `dir/stem.ext`
1130
+ * (then `stem-2.ext`, ...), never replacing an existing file.
1131
+ * @param temporary - the complete file.
1132
+ * @param dir - the destination directory, created when missing.
1133
+ * @param stem - the file-name stem.
1134
+ * @param extension - the extension, without a dot.
1135
+ * @returns the final path.
1136
+ */
1137
+ async function placeFile(temporary, dir, stem, extension) {
1138
+ await mkdir(dir, { recursive: true });
1139
+ let linkable = true;
1140
+ for (let attempt = 1; attempt < 1e3; attempt++) {
1141
+ const path = join(dir, `${attempt === 1 ? stem : `${stem}-${attempt}`}.${extension}`);
1142
+ if (linkable) try {
1143
+ await link(temporary, path);
1144
+ await rm(temporary, { force: true });
1145
+ return path;
1146
+ } catch (error) {
1147
+ if (error.code === "EEXIST") continue;
1148
+ linkable = false;
1149
+ }
1150
+ try {
1151
+ await (await open(path, "wx")).close();
1152
+ } catch (error) {
1153
+ if (error.code === "EEXIST") continue;
1154
+ throw error;
1155
+ }
1156
+ await renameWithRetry(temporary, path);
1157
+ return path;
1158
+ }
1159
+ throw new MediaError(`Could not find a free file name for "${stem}.${extension}" in ${dir}.`, "OUTPUT_NAME_EXHAUSTED");
1160
+ }
1161
+ /**
1162
+ * Save bytes under the first free name `dir/stem.ext`.
1163
+ * @param dir - the destination directory.
1164
+ * @param stem - the file-name stem.
1165
+ * @param extension - the extension, without a dot.
1166
+ * @param data - the content.
1167
+ * @returns the final path.
1168
+ */
1169
+ async function saveNewFile(dir, stem, extension, data) {
1170
+ await mkdir(dir, { recursive: true });
1171
+ const temporary = join(dir, `.dsh-media-${randomUUID()}.part`);
1172
+ try {
1173
+ await writeFile(temporary, data);
1174
+ return await placeFile(temporary, dir, stem, extension);
1175
+ } finally {
1176
+ await rm(temporary, { force: true });
1177
+ }
1178
+ }
1179
+ /**
1180
+ * Write bytes atomically, replacing the file.
1181
+ * @param path - the final path.
1182
+ * @param data - the content.
1183
+ * @param options - `mode` for a file only its owner may read.
1184
+ */
1185
+ async function writeFileAtomic(path, data, options = {}) {
1186
+ await mkdir(dirname(path), { recursive: true });
1187
+ const temporary = join(dirname(path), `.${randomUUID()}.part`);
1188
+ try {
1189
+ await writeFile(temporary, data, options.mode === void 0 ? {} : { mode: options.mode });
1190
+ await renameWithRetry(temporary, path);
1191
+ } catch (error) {
1192
+ await rm(temporary, { force: true });
1193
+ throw error;
1194
+ }
1195
+ }
1196
+ /**
1197
+ * Stream a response body into a temporary file, replacing what was there.
1198
+ * @param response - a successful response whose body is unread.
1199
+ * @param temporary - where to write; the caller moves it into place when this resolves.
1200
+ * @param maxBytes - the largest accepted body.
1201
+ * @param signal - cancels the download.
1202
+ * @returns the number of bytes written.
1203
+ */
1204
+ async function downloadTo(response, temporary, maxBytes, signal) {
1205
+ const declared = Number(response.headers.get("content-length"));
1206
+ if (Number.isFinite(declared) && declared > maxBytes) {
1207
+ await response.body?.cancel().catch(() => void 0);
1208
+ throw new MediaError(`The generated file is ${(declared / 1048576).toFixed(1)} MiB, more than the ${(maxBytes / 1048576).toFixed(0)} MiB this plugin downloads.`, "OUTPUT_TOO_LARGE");
1209
+ }
1210
+ await mkdir(dirname(temporary), { recursive: true });
1211
+ await rm(temporary, { force: true });
1212
+ if (response.body === null) {
1213
+ const data = new Uint8Array(await response.arrayBuffer());
1214
+ if (data.byteLength > maxBytes) throw new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE");
1215
+ await writeFile(temporary, data);
1216
+ return data.byteLength;
1217
+ }
1218
+ let total = 0;
1219
+ const limit = new Transform({ transform(chunk, _encoding, callback) {
1220
+ total += chunk.byteLength;
1221
+ if (total > maxBytes) callback(new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE"));
1222
+ else callback(null, chunk);
1223
+ } });
1224
+ try {
1225
+ await pipeline(Readable.fromWeb(response.body), limit, createWriteStream(temporary), signal === void 0 ? {} : { signal });
1226
+ return total;
1227
+ } catch (error) {
1228
+ await rm(temporary, { force: true }).catch(() => void 0);
1229
+ throw error;
1230
+ }
1231
+ }
1232
+ const SOURCES = /* @__PURE__ */ new Set([
1233
+ "message",
1234
+ "command",
1235
+ "menu"
1236
+ ]);
1237
+ /** Whether something read from disk names an owner this version knows. */
1238
+ function isOwner(value) {
1239
+ const owner = value;
1240
+ if (typeof owner !== "object" || owner === null) return false;
1241
+ return owner.kind === "user" ? typeof owner.id === "string" && owner.id !== "" : owner.kind === "signed-out" || owner.kind === "unidentified";
1242
+ }
1243
+ /** Whether something read from disk is an item this version can send (an item without an owner is never sent). */
1244
+ function isItem(value) {
1245
+ const item = value;
1246
+ const body = item?.body;
1247
+ return typeof item === "object" && item !== null && typeof body === "object" && body !== null && typeof body.id === "string" && body.id !== "" && SOURCES.has(String(body.source)) && typeof body.client === "object" && body.client !== null && typeof body.client.app === "string" && (body.category === void 0 || body.category === null || isCategory(body.category)) && isOwner(item.owner) && typeof item.enqueuedAt === "number" && typeof item.attempts === "number" && typeof item.nextAt === "number";
1248
+ }
1249
+ /** The persistent queue. All changes are serialized; reads see the latest state. */
1250
+ var FeedbackQueue = class {
1251
+ file;
1252
+ options;
1253
+ state = [];
1254
+ loading;
1255
+ writing = Promise.resolve();
1256
+ now;
1257
+ /**
1258
+ * @param file - the queue file.
1259
+ * @param options - caps and the clock (test seams).
1260
+ */
1261
+ constructor(file, options = {}) {
1262
+ this.file = file;
1263
+ this.options = options;
1264
+ this.now = options.now ?? Date.now;
1265
+ }
1266
+ /** Read the file once; a missing or unreadable file is an empty queue (and is replaced on the next change). */
1267
+ load() {
1268
+ this.loading ??= (async () => {
1269
+ let parsed;
1270
+ try {
1271
+ parsed = JSON.parse(await readFile(this.file, "utf8"));
1272
+ } catch {
1273
+ parsed = void 0;
1274
+ }
1275
+ const items = parsed?.items;
1276
+ this.state = Array.isArray(items) ? items.filter(isItem) : [];
1277
+ if (this.prune()) await this.save();
1278
+ })();
1279
+ return this.loading;
1280
+ }
1281
+ /** The waiting items, oldest first. */
1282
+ items() {
1283
+ return this.state;
1284
+ }
1285
+ /**
1286
+ * Queue one body at the end.
1287
+ * @param body - the exact body to send.
1288
+ * @param owner - the VibeDev account it belongs to.
1289
+ */
1290
+ async add(body, owner) {
1291
+ await this.load();
1292
+ const before = this.state;
1293
+ this.state = [...this.state, {
1294
+ body,
1295
+ owner,
1296
+ enqueuedAt: this.now(),
1297
+ attempts: 0,
1298
+ nextAt: 0
1299
+ }];
1300
+ this.prune();
1301
+ try {
1302
+ await this.save();
1303
+ } catch (error) {
1304
+ this.state = before;
1305
+ throw error;
1306
+ }
1307
+ }
1308
+ /**
1309
+ * Record how an attempt ended without a final answer.
1310
+ * @param id - the item's body id.
1311
+ * @param change - the attempt count, when to try next, and what it ended with.
1312
+ */
1313
+ async update(id, change) {
1314
+ await this.load();
1315
+ this.state = this.state.map((item) => item.body.id === id ? {
1316
+ ...item,
1317
+ ...change
1318
+ } : item);
1319
+ await this.save();
1320
+ }
1321
+ /**
1322
+ * Give an item to an account (feedback given signed out, or by an account not identified then, on its first
1323
+ * attempt): from now on it goes out under that account only.
1324
+ * @param id - the item's body id.
1325
+ * @param owner - the account.
1326
+ */
1327
+ async bind(id, owner) {
1328
+ await this.load();
1329
+ this.state = this.state.map((item) => item.body.id === id ? {
1330
+ ...item,
1331
+ owner
1332
+ } : item);
1333
+ await this.save();
1334
+ }
1335
+ /**
1336
+ * Put a new body in an item's place (the gateway asked for a smaller one): same position and owner, attempts start
1337
+ * over.
1338
+ * @param id - the item's current body id.
1339
+ * @param body - the new body.
1340
+ */
1341
+ async replace(id, body) {
1342
+ await this.load();
1343
+ this.state = this.state.map((item) => item.body.id === id ? {
1344
+ body,
1345
+ owner: item.owner,
1346
+ enqueuedAt: item.enqueuedAt,
1347
+ attempts: 0,
1348
+ nextAt: 0
1349
+ } : item);
1350
+ await this.save();
1351
+ }
1352
+ /**
1353
+ * Take an item out (sent, or refused for good).
1354
+ * @param id - the item's body id.
1355
+ */
1356
+ async remove(id) {
1357
+ await this.load();
1358
+ this.state = this.state.filter((item) => item.body.id !== id);
1359
+ await this.save();
1360
+ }
1361
+ /**
1362
+ * Apply the caps: too old first, then the oldest past the count, then the oldest past the size.
1363
+ * @returns whether anything was dropped.
1364
+ */
1365
+ prune() {
1366
+ const before = this.state.length;
1367
+ const maxAge = this.options.maxAgeMs ?? 2592e6;
1368
+ const now = this.now();
1369
+ let items = this.state.filter((item) => now - item.enqueuedAt <= maxAge);
1370
+ const maxItems = this.options.maxItems ?? 200;
1371
+ if (items.length > maxItems) items = items.slice(items.length - maxItems);
1372
+ const maxBytes = this.options.maxBytes ?? 4194304;
1373
+ let total = items.reduce((sum, item) => sum + bodyBytes(item.body), 0);
1374
+ while (items.length > 1 && total > maxBytes) {
1375
+ total -= bodyBytes(items[0].body);
1376
+ items = items.slice(1);
1377
+ }
1378
+ this.state = items;
1379
+ return items.length !== before;
1380
+ }
1381
+ /** Write the current state; owner-only from creation, replaced atomically, one write at a time. */
1382
+ save() {
1383
+ const snapshot = {
1384
+ version: 1,
1385
+ items: this.state
1386
+ };
1387
+ const write = this.writing.then(() => writeFileAtomic(this.file, new TextEncoder().encode(JSON.stringify(snapshot)), { mode: 384 }));
1388
+ this.writing = write.catch(() => void 0);
1389
+ return write;
1390
+ }
1391
+ };
1392
+ //#endregion
1393
+ //#region src/feedback/recent-errors.ts
1394
+ const MAX_ENTRIES = 50;
1395
+ const MAX_MESSAGE = 500;
1396
+ /** Tool names remembered for calls whose result has not come back yet. */
1397
+ const MAX_PENDING_CALLS = 256;
1398
+ const oneLine = (text, max = MAX_MESSAGE) => {
1399
+ const flat = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
1400
+ const characters = [...flat];
1401
+ return characters.length <= max ? flat : `${characters.slice(0, max).join("")}…`;
1402
+ };
1403
+ /** The last failures this Host saw. */
1404
+ var RecentErrors = class {
1405
+ entries = [];
1406
+ toolNames = /* @__PURE__ */ new Map();
1407
+ now;
1408
+ max;
1409
+ /**
1410
+ * @param options - how many failures to keep, and the clock (test seams).
1411
+ */
1412
+ constructor(options = {}) {
1413
+ this.max = options.max ?? MAX_ENTRIES;
1414
+ this.now = options.now ?? Date.now;
1415
+ }
1416
+ /**
1417
+ * Note one appended event.
1418
+ * @param session - the Session it was appended to.
1419
+ * @param event - the event.
1420
+ */
1421
+ observe(session, event) {
1422
+ switch (event.type) {
1423
+ case "tool/call":
1424
+ this.toolNames.delete(event.data.callId);
1425
+ this.toolNames.set(event.data.callId, event.data.name);
1426
+ if (this.toolNames.size > MAX_PENDING_CALLS) this.toolNames.delete(this.toolNames.keys().next().value);
1427
+ break;
1428
+ case "tool/result": {
1429
+ const { message, error } = event.data;
1430
+ const tool = this.toolNames.get(message.toolCallId);
1431
+ this.toolNames.delete(message.toolCallId);
1432
+ if (message.isError !== true) break;
1433
+ const said = message.content.flatMap((block) => block.type === "text" ? [block.text] : []).join(" ");
1434
+ this.push({
1435
+ at: this.now(),
1436
+ sessionRef: session.id,
1437
+ kind: "tool",
1438
+ tool: tool ?? "unknown tool",
1439
+ ...error?.code === void 0 ? {} : { code: error.code },
1440
+ message: oneLine(error?.reason ?? (said || error?.name || "failed"))
1441
+ });
1442
+ break;
1443
+ }
1444
+ case "turn/end": {
1445
+ const reason = event.data.reason;
1446
+ if (reason.kind !== "error") break;
1447
+ this.push({
1448
+ at: this.now(),
1449
+ sessionRef: session.id,
1450
+ kind: "model",
1451
+ code: reason.error.code,
1452
+ ...reason.error.status === void 0 ? {} : { status: reason.error.status },
1453
+ message: oneLine(reason.error.message)
1454
+ });
1455
+ break;
1456
+ }
1457
+ }
1458
+ }
1459
+ push(entry) {
1460
+ this.entries.push(entry);
1461
+ if (this.entries.length > this.max) this.entries.splice(0, this.entries.length - this.max);
1462
+ }
1463
+ /** The kept failures, newest first. */
1464
+ list() {
1465
+ return [...this.entries].reverse();
1466
+ }
1467
+ /**
1468
+ * The attachment text: a header, then one line per failure, newest first, cut to the attachment limit (so what
1469
+ * gives way first is the oldest).
1470
+ * @returns the text, its line count and its size; empty when nothing failed.
1471
+ */
1472
+ attachment() {
1473
+ const list = this.list();
1474
+ if (list.length === 0) return {
1475
+ content: "",
1476
+ entries: 0,
1477
+ bytes: 0
1478
+ };
1479
+ const lines = list.map((entry) => {
1480
+ const what = entry.kind === "tool" ? `tool ${oneLine(entry.tool ?? "", 80)}` : "model";
1481
+ const code = [entry.code, entry.status === void 0 ? void 0 : `HTTP ${entry.status}`].filter(Boolean).join(" ");
1482
+ return `${new Date(entry.at).toISOString()} session ${entry.sessionRef} ${what}${code === "" ? "" : ` [${code}]`} ${entry.message}`;
1483
+ });
1484
+ const content = fitUtf8(`Recent errors in VibeDev (newest first, ${list.length})\n${lines.join("\n")}`, MAX_ATTACHMENT_BYTES);
1485
+ return {
1486
+ content,
1487
+ entries: list.length,
1488
+ bytes: Buffer$1.byteLength(content, "utf8")
1489
+ };
1490
+ }
1491
+ };
1492
+ //#endregion
1493
+ //#region src/feedback/routes.ts
1494
+ /**
1495
+ * The feedback dialog's Host routes (answers are never cached):
1496
+ *
1497
+ * - `GET /api/dsh-vibedev/feedback/attachment` — the exact text the "attach
1498
+ * recent errors" box would send, its line count and size;
1499
+ * - `POST /api/dsh-vibedev/feedback` — `{ category?, text?, attachment?:
1500
+ * { content }, locale? }`: queued as `source: 'menu'` (an attachment only as
1501
+ * an `error-log` the user consented to by ticking the box) and sent at once
1502
+ * when it can be; answers `sent`, `queued` (with why) or `rejected`. Nothing
1503
+ * is queued while nobody is signed in: feedback goes with the VibeDev
1504
+ * account, never anonymously.
1505
+ * @module dsh-vibedev/feedback/routes
1506
+ */
1507
+ const FEEDBACK_ROUTE = "/api/dsh-vibedev/feedback";
1508
+ const FEEDBACK_ATTACHMENT_ROUTE = "/api/dsh-vibedev/feedback/attachment";
1509
+ function json(status, body) {
1510
+ return new Response(JSON.stringify(body), {
1511
+ status,
1512
+ headers: {
1513
+ "content-type": "application/json; charset=utf-8",
1514
+ "cache-control": "no-store"
1515
+ }
1516
+ });
1517
+ }
1518
+ const invalid = (field) => json(400, { error: {
1519
+ code: "FEEDBACK_INVALID",
1520
+ field
1521
+ } });
1522
+ const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1523
+ /**
1524
+ * The feedback routes.
1525
+ * @param options - the uploader's submit, the recent errors and the credential check.
1526
+ * @returns routes for the client connection.
1527
+ */
1528
+ function feedbackRoutes(options) {
1529
+ return [{
1530
+ path: FEEDBACK_ATTACHMENT_ROUTE,
1531
+ methods: ["GET"],
1532
+ requestBody: "buffered",
1533
+ fetch: () => Promise.resolve(json(200, options.errors.attachment()))
1534
+ }, {
1535
+ path: FEEDBACK_ROUTE,
1536
+ methods: ["POST"],
1537
+ requestBody: "buffered",
1538
+ fetch: async (request) => {
1539
+ try {
1540
+ const body = record$7(await request.json().catch(() => void 0));
1541
+ if (body === void 0) return invalid("body");
1542
+ if (body.category !== void 0 && body.category !== null && !isCategory(body.category)) return invalid("category");
1543
+ if (body.text !== void 0 && typeof body.text !== "string") return invalid("text");
1544
+ if (typeof body.text === "string" && codePoints(body.text.trim()) > 4e3) return invalid("text");
1545
+ const text = feedbackText(body.text);
1546
+ const category = isCategory(body.category) ? body.category : void 0;
1547
+ if (text === void 0 && category === void 0) return invalid("text");
1548
+ let content;
1549
+ if (body.attachment !== void 0 && body.attachment !== null) {
1550
+ const given = record$7(body.attachment)?.content;
1551
+ if (typeof given !== "string" || given === "" || Buffer$1.byteLength(given, "utf8") > 262144) return invalid("attachment");
1552
+ content = given;
1553
+ }
1554
+ if (!await options.hasCredential()) return json(409, { error: { code: "SIGNED_OUT" } });
1555
+ return json(200, await options.submit({
1556
+ source: "menu",
1557
+ ...category === void 0 ? {} : { category },
1558
+ ...text === void 0 ? {} : { text },
1559
+ ...content === void 0 ? {} : { attachment: {
1560
+ kind: "error-log",
1561
+ consent: true,
1562
+ content
1563
+ } }
1564
+ }, shortField(body.locale, 64)));
1565
+ } catch {
1566
+ return json(500, { error: { code: "INTERNAL" } });
1567
+ }
1568
+ }
1569
+ }];
1570
+ }
1571
+ //#endregion
1572
+ //#region src/gateway/http.ts
1573
+ /**
1574
+ * HTTP client for the VibeDev gateway. Every gateway call goes through here so
1575
+ * authentication, refresh after a 401, balance refusals, busy back-off and
1576
+ * idempotency are handled once.
1577
+ *
1578
+ * The credential is attached only to requests on the gateway origin: upload
1579
+ * URLs and third-party links never see it.
1580
+ * @module dsh-vibedev/gateway/http
1581
+ */
1582
+ /** Error codes the gateway uses for "full right now, nothing was charged". */
1583
+ const BUSY_CODES = /* @__PURE__ */ new Set([
1584
+ "APP_TOKEN_UNAVAILABLE",
1585
+ "PROVIDER_CAPACITY_BUSY",
1586
+ "upstream_capacity_busy",
1587
+ "AUDIO_CAPACITY_BUSY",
1588
+ "AUDIO_NO_AVAILABLE_ACCOUNT",
1589
+ "WEB_SEARCH_BUSY",
1590
+ "WEB_SEARCH_RATE_LIMITED"
1591
+ ]);
1592
+ /**
1593
+ * The account already runs as many video or audio tasks as it may (HTTP 429).
1594
+ * Not retried here: a slot frees only when one of the user's tasks finishes.
1595
+ */
1596
+ const TASK_LIMIT_CODES = /* @__PURE__ */ new Set(["VIDEO_TASK_LIMIT_REACHED", "AUDIO_TASK_LIMIT_REACHED"]);
1597
+ const DEFAULT_TIMEOUT_MS = 6e4;
1598
+ const DEFAULT_BUSY_WAIT_MS = 2e3;
1599
+ /** The message for a call made while nobody is signed in. */
1600
+ const SIGN_IN_MESSAGE$1 = "VibeDev media generation needs a signed-in VibeDev account. Call media_account with action \"sign_in\": it opens the VibeDev sign-in page in the user's browser, where new users can also register. In the VibeDev app, the account signed in to the app is used automatically.";
1601
+ /** Read through a call so a check made before an `await` is not taken as still true after it. */
1602
+ function isAborted(signal) {
1603
+ return signal?.aborted === true;
1604
+ }
1605
+ /**
1606
+ * Wait, ending early (with {@link abortError}) when the signal aborts.
1607
+ * @param ms - how long.
1608
+ * @param signal - cancels the wait.
1609
+ */
1610
+ function delay$1(ms, signal) {
1611
+ return new Promise((resolve, reject) => {
1612
+ if (isAborted(signal)) {
1613
+ reject(abortError(signal));
1614
+ return;
1615
+ }
1616
+ const timer = setTimeout(() => {
1617
+ signal?.removeEventListener("abort", onAbort);
1618
+ resolve();
1619
+ }, ms);
1620
+ const onAbort = () => {
1621
+ clearTimeout(timer);
1622
+ reject(abortError(signal));
1623
+ };
1624
+ signal?.addEventListener("abort", onAbort, { once: true });
1625
+ });
1626
+ }
1627
+ /**
1628
+ * The error a cancelled media request ends with.
1629
+ * @param signal - the signal that aborted; its reason is the cause.
1630
+ * @returns the error (`ABORTED`).
1631
+ */
1632
+ function abortError(signal) {
1633
+ return new MediaError("The media request was cancelled.", "ABORTED", { retryable: true }, { cause: signal?.reason });
1634
+ }
1635
+ /** Gateway HTTP client. */
1636
+ var GatewayHttp = class {
1637
+ options;
1638
+ origin;
1639
+ /**
1640
+ * @param options - origin, credential plane, user agent and test seams.
1641
+ */
1642
+ constructor(options) {
1643
+ this.options = options;
1644
+ this.origin = options.origin.trim().replace(/\/+$/, "");
1645
+ }
1646
+ /** Absolute URL for a gateway path, or the URL itself when already absolute. */
1647
+ url(path) {
1648
+ return /^https?:\/\//i.test(path) ? path : `${this.origin}${path.startsWith("/") ? "" : "/"}${path}`;
1649
+ }
1650
+ /** Whether a URL is on the gateway origin, and so may carry the credential. */
1651
+ isGatewayUrl(url) {
1652
+ try {
1653
+ return new URL(url).origin === new URL(this.origin).origin;
1654
+ } catch {
1655
+ return false;
1656
+ }
1657
+ }
1658
+ /**
1659
+ * Send one request and return the successful response.
1660
+ * @param path - gateway path, or an absolute URL.
1661
+ * @param request - method, body, headers and retry policy.
1662
+ * @returns the 2xx response, body unread.
1663
+ * @throws {@link MediaError} for every refusal, with the gateway's code.
1664
+ */
1665
+ async send(path, request = {}) {
1666
+ const url = this.url(path);
1667
+ const authenticate = request.anonymous !== true && this.isGatewayUrl(url);
1668
+ let credential = authenticate ? await this.credential() : void 0;
1669
+ let refreshed = false;
1670
+ let busyRetries = request.busyRetries ?? 2;
1671
+ for (;;) {
1672
+ const response = await this.attempt(url, request, credential);
1673
+ if (response.ok) {
1674
+ if (authenticate) try {
1675
+ this.options.onAccepted?.({
1676
+ method: request.method ?? "GET",
1677
+ path: new URL(url).pathname
1678
+ });
1679
+ } catch {}
1680
+ return response;
1681
+ }
1682
+ const failure = parseGatewayFailure(await response.clone().json().catch(() => void 0));
1683
+ if (response.status === 401 && credential !== void 0 && credential.kind !== "key" && !refreshed) {
1684
+ refreshed = true;
1685
+ await this.options.rejectToken?.(credential);
1686
+ credential = await this.credential();
1687
+ continue;
1688
+ }
1689
+ const wait = retryAfterMs(response.headers.get("retry-after"));
1690
+ if (isBusy(response.status, failure, wait) && busyRetries > 0 && (wait ?? DEFAULT_BUSY_WAIT_MS) <= (request.maxBusyWaitMs ?? 15e3)) {
1691
+ busyRetries--;
1692
+ await (this.options.sleep ?? delay$1)(wait ?? DEFAULT_BUSY_WAIT_MS, request.signal);
1693
+ continue;
1694
+ }
1695
+ throw failureError$1(response.status, failure, wait);
1696
+ }
1697
+ }
1698
+ /**
1699
+ * Send one request and parse its JSON body.
1700
+ * @param path - gateway path, or an absolute URL.
1701
+ * @param request - method, body, headers and retry policy.
1702
+ * @returns the parsed body.
1703
+ */
1704
+ async json(path, request = {}) {
1705
+ const response = await this.send(path, request);
1706
+ try {
1707
+ return await response.json();
1708
+ } catch (error) {
1709
+ throw new MediaError(`The VibeDev gateway returned an unreadable answer for ${path}.`, "GATEWAY_BAD_RESPONSE", { status: response.status }, { cause: error });
1710
+ }
1711
+ }
1712
+ async credential() {
1713
+ const credential = await this.options.resolveCredential();
1714
+ if (credential === void 0) throw new MediaError(SIGN_IN_MESSAGE$1, "NOT_SIGNED_IN");
1715
+ return credential;
1716
+ }
1717
+ async attempt(url, request, credential) {
1718
+ if (isAborted(request.signal)) throw abortError(request.signal);
1719
+ const headers = {
1720
+ accept: "application/json",
1721
+ "user-agent": this.options.userAgent,
1722
+ ...request.headers
1723
+ };
1724
+ if (credential !== void 0) headers.authorization = `Bearer ${credential.token}`;
1725
+ if (request.idempotencyKey !== void 0) headers["idempotency-key"] = request.idempotencyKey;
1726
+ let body = request.body;
1727
+ if (request.json !== void 0) {
1728
+ body = JSON.stringify(request.json);
1729
+ headers["content-type"] = "application/json";
1730
+ }
1731
+ const timeout = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1732
+ const signal = request.signal === void 0 ? timeout : AbortSignal.any([request.signal, timeout]);
1733
+ try {
1734
+ return await (this.options.fetch ?? globalThis.fetch)(url, {
1735
+ method: request.method ?? (body === void 0 ? "GET" : "POST"),
1736
+ headers,
1737
+ ...body === void 0 ? {} : { body },
1738
+ redirect: "error",
1739
+ signal
1740
+ });
1741
+ } catch (error) {
1742
+ if (isAborted(request.signal)) throw abortError(request.signal);
1743
+ if (timeout.aborted) throw new MediaError(`The VibeDev gateway did not answer within ${Math.round((request.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3)} s.`, "GATEWAY_TIMEOUT", { retryable: true });
1744
+ throw new MediaError(`Could not reach the VibeDev gateway (${error instanceof Error ? error.message : String(error)}). Ask the user to check the network connection.`, "GATEWAY_UNREACHABLE", { retryable: true });
1745
+ }
1746
+ }
1747
+ };
1748
+ /**
1749
+ * Whether an answer means "full right now, nothing was charged": any 429 but a
1750
+ * task limit, or a 503 with a busy code or `Retry-After`. A bare 503 is an outage.
1751
+ */
1752
+ function isBusy(status, failure, wait) {
1753
+ if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return false;
1754
+ return status === 429 || status === 503 && (failure.code !== void 0 && BUSY_CODES.has(failure.code) || wait !== void 0);
1755
+ }
1756
+ /**
1757
+ * The error for an answer the client does not retry, worded for the model.
1758
+ * @param status - HTTP status.
1759
+ * @param failure - the parsed error body.
1760
+ * @param wait - Retry-After in milliseconds, when given.
1761
+ * @returns the error to throw.
1762
+ */
1763
+ function failureError$1(status, failure, wait) {
1764
+ const words = gatewayWords(failure);
1765
+ const { code: _code, message: _message, ...facts } = failure;
1766
+ const details = {
1767
+ status,
1768
+ ...facts,
1769
+ ...wait === void 0 ? {} : { retryAfterMs: wait }
1770
+ };
1771
+ if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return new MediaError(`The VibeDev account already runs as many ${failure.code.startsWith("VIDEO") ? "video" : "audio"} tasks at once as it may${failure.active === void 0 || failure.limit === void 0 ? "" : ` (${failure.active} of ${failure.limit})`}. Wait for one of them to finish (media_tasks lists them), then submit again; nothing was charged.`, failure.code, {
1772
+ ...details,
1773
+ retryable: true
1774
+ });
1775
+ if (status === 402) return new MediaError(`The VibeDev account balance is not enough for this request${(failure.estimatedCny === void 0 ? "" : `: this task is estimated at ¥${failure.estimatedCny}${failure.availableCny === void 0 ? "" : `, and ¥${failure.availableCny} is available`}${failure.pendingCny === void 0 || Number(failure.pendingCny) === 0 ? "" : ` (tasks in progress hold ¥${failure.pendingCny})`}`) || words}. Nothing was charged. Ask the user to top up their VibeDev balance${failure.rechargeUrl === void 0 ? "" : ` at ${failure.rechargeUrl}`}.`, "INSUFFICIENT_BALANCE", {
1776
+ ...details,
1777
+ retryable: false
1778
+ });
1779
+ if (status === 401) return new MediaError(`The VibeDev gateway rejected the sign-in${words}. Ask the user to sign in to VibeDev again.`, "SIGN_IN_REJECTED", {
1780
+ ...details,
1781
+ retryable: false
1782
+ });
1783
+ if (isBusy(status, failure, wait)) {
1784
+ const seconds = wait === void 0 ? void 0 : Math.ceil(wait / 1e3);
1785
+ return new MediaError(`The VibeDev gateway is busy${words}. ${seconds === void 0 ? "Try again shortly" : `Try again in about ${seconds} s`}; nothing was charged.`, failure.code ?? (status === 429 ? "RATE_LIMITED" : "GATEWAY_BUSY"), {
1786
+ ...details,
1787
+ retryable: true,
1788
+ busy: true
1789
+ });
1790
+ }
1791
+ return new MediaError(`The VibeDev gateway refused the request with HTTP ${status}${words}.`, failure.code ?? `HTTP_${status}`, details);
1792
+ }
1793
+ //#endregion
1794
+ //#region src/feedback/uploader.ts
1795
+ /**
1796
+ * Sends queued feedback to the gateway, one upload at a time, oldest first,
1797
+ * each only under the VibeDev account it belongs to (queue.ts, `FeedbackOwner`):
1798
+ * the account signed in when it was given; feedback given while signed out
1799
+ * goes with the next account that signs in. Feedback of another account waits
1800
+ * — within the queue's caps — until that account is back; it is never sent
1801
+ * under a different user. The credential is pinned for each request: a renewal
1802
+ * after a 401 is used only when it is still the same account.
1803
+ *
1804
+ * Every answer of the contract is handled:
1805
+ *
1806
+ * - 201 created, 200 the same id and content already received: done;
1807
+ * - 400 invalid, 403 not allowed, 409 id reused with other content, 415 not
1808
+ * JSON: dropped (sending it again cannot help);
1809
+ * - 401: the credential's owner renews it and the same body goes once more; a
1810
+ * second refusal waits for a sign-in or the next try;
1811
+ * - 413 too large: the attachment is halved, as a new body with a new id;
1812
+ * - 429 and 503: after `Retry-After` (else a back-off), the same body;
1813
+ * - 404 (an older gateway, or the feature not on yet): kept, tried again in hours;
1814
+ * - no answer, 5xx: a back-off with jitter, from 30 s up to an hour;
1815
+ * - any other answer: the back-off, and dropped after the fifth.
1816
+ *
1817
+ * A retry always resends the stored body byte for byte. Bodies are never logged.
1818
+ * @module dsh-vibedev/feedback/uploader
1819
+ */
1820
+ const BACKOFF_BASE_MS = 3e4;
1821
+ const BACKOFF_MAX_MS = 36e5;
1822
+ /** An older gateway, or the feature not switched on yet: look again in a few hours. */
1823
+ const NOT_AVAILABLE_MS = 216e5;
1824
+ const RATE_LIMIT_DEFAULT_MS = 6e4;
1825
+ const REQUEST_TIMEOUT_MS = 3e4;
1826
+ const DROP_STATUSES = /* @__PURE__ */ new Set([
1827
+ 400,
1828
+ 403,
1829
+ 409,
1830
+ 415
1831
+ ]);
1832
+ /** Attempts an answer outside the contract (another 4xx) gets before the item is dropped. */
1833
+ const UNKNOWN_STATUS_ATTEMPTS = 5;
1834
+ /** Signed in, but which account could not be read (the gateway unreachable): look again after this long. */
1835
+ const IDENTITY_RETRY_MS = 3e5;
1836
+ /** A refusal for good: its code, and the field and rule a validation refusal names (`metadata.field` / `metadata.rule`). */
1837
+ function dropped(error) {
1838
+ return {
1839
+ kind: "drop",
1840
+ code: error.code,
1841
+ ...error.details.field === void 0 ? {} : { field: error.details.field },
1842
+ ...error.details.rule === void 0 ? {} : { rule: error.details.rule }
1843
+ };
1844
+ }
1845
+ /** What a log line says about a refusal: the gateway's code, field and rule — names, never the report. */
1846
+ function refusalText(attempt) {
1847
+ const safe = (value) => value.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 128);
1848
+ return [
1849
+ safe(attempt.code),
1850
+ ...attempt.field === void 0 ? [] : [`field ${safe(attempt.field)}`],
1851
+ ...attempt.rule === void 0 ? [] : [`rule ${safe(attempt.rule)}`]
1852
+ ].join(", ");
1853
+ }
1854
+ /** A credential's identity in this process (its token hashed), never written anywhere. */
1855
+ const credentialRef = (credential) => createHash("sha256").update(credential.token).digest("hex");
1856
+ /** The feedback uploader. */
1857
+ var FeedbackUploader = class {
1858
+ options;
1859
+ flushing;
1860
+ again = false;
1861
+ timer;
1862
+ disposed = false;
1863
+ recording = Promise.resolve();
1864
+ waiters = /* @__PURE__ */ new Map();
1865
+ /** Feedback of an account not identified when it was given: the credential that gave it, in this run only. */
1866
+ bindings = /* @__PURE__ */ new Map();
1867
+ now;
1868
+ /**
1869
+ * @param options - the gateway, the queue, the client block, and who is signed in.
1870
+ */
1871
+ constructor(options) {
1872
+ this.options = options;
1873
+ this.now = options.now ?? Date.now;
1874
+ }
1875
+ /**
1876
+ * Queue one piece of feedback for the account signed in now, and try to send it.
1877
+ * @param draft - what it says.
1878
+ * @param locale - the locale the user chose it in, when known (the menu's dialog).
1879
+ * @returns the body id, or undefined when the draft says nothing the gateway takes.
1880
+ */
1881
+ async enqueue(draft, locale) {
1882
+ if (this.disposed || !isSendable(draft)) return void 0;
1883
+ const id = (this.options.newId ?? randomUUID)();
1884
+ await this.record(id, draft, locale);
1885
+ return id;
1886
+ }
1887
+ /**
1888
+ * Note who gave it and keep it. One at a time, so the queue keeps the order feedback was given in.
1889
+ */
1890
+ record(id, draft, locale) {
1891
+ const run = this.recording.then(async () => {
1892
+ let owner;
1893
+ try {
1894
+ const identity = await this.options.identity();
1895
+ owner = !identity.signedIn ? { kind: "signed-out" } : identity.userId !== void 0 ? {
1896
+ kind: "user",
1897
+ id: identity.userId
1898
+ } : { kind: "unidentified" };
1899
+ if (identity.signedIn && owner.kind === "unidentified") this.bindings.set(id, credentialRef(identity.credential));
1900
+ } catch {
1901
+ owner = { kind: "unidentified" };
1902
+ }
1903
+ const client = this.options.client();
1904
+ await this.options.queue.add(feedbackBody(id, draft, locale === void 0 ? client : {
1905
+ ...client,
1906
+ locale
1907
+ }), owner);
1908
+ });
1909
+ this.recording = run.catch(() => void 0);
1910
+ return run.then(() => {
1911
+ this.flush();
1912
+ });
1913
+ }
1914
+ /**
1915
+ * Queue feedback from the dialog (for the account signed in now) and say what became of it: sent, kept for later,
1916
+ * or refused.
1917
+ * @param draft - what it says.
1918
+ * @param locale - the dialog's locale.
1919
+ * @param waitMs - how long to wait for the first answer before calling it kept.
1920
+ * @returns the outcome.
1921
+ */
1922
+ submit(draft, locale, waitMs = 2e4) {
1923
+ if (this.disposed || !isSendable(draft)) return Promise.resolve({
1924
+ status: "rejected",
1925
+ code: "FEEDBACK_EMPTY"
1926
+ });
1927
+ const id = (this.options.newId ?? randomUUID)();
1928
+ return new Promise((resolve) => {
1929
+ const finish = (outcome) => {
1930
+ if (this.waiters.get(id) === finish) this.waiters.delete(id);
1931
+ for (const [key, waiter] of this.waiters) if (waiter === finish) this.waiters.delete(key);
1932
+ this.cancel(guard);
1933
+ resolve(outcome);
1934
+ };
1935
+ const guard = this.schedule(() => {
1936
+ finish({
1937
+ status: "queued",
1938
+ reason: "later"
1939
+ });
1940
+ }, waitMs);
1941
+ this.waiters.set(id, finish);
1942
+ this.record(id, draft, locale).catch(() => {
1943
+ finish({
1944
+ status: "rejected",
1945
+ code: "FEEDBACK_NOT_SAVED"
1946
+ });
1947
+ });
1948
+ });
1949
+ }
1950
+ /** The account changed (a sign-in, a sign-out, a renewal): its feedback, and what waited on a refused renewal, goes now. */
1951
+ credentialChanged() {
1952
+ (async () => {
1953
+ await this.options.queue.load();
1954
+ for (const item of this.options.queue.items()) if (item.last === "401" && item.nextAt > this.now()) await this.options.queue.update(item.body.id, {
1955
+ attempts: item.attempts,
1956
+ nextAt: 0,
1957
+ last: "401"
1958
+ });
1959
+ await this.flush();
1960
+ })().catch(() => void 0);
1961
+ }
1962
+ /**
1963
+ * Send what is due for the account signed in now, one at a time; a call while sending makes the loop look once
1964
+ * more when it ends.
1965
+ * @returns once nothing more can be sent now.
1966
+ */
1967
+ flush() {
1968
+ if (this.disposed) return Promise.resolve();
1969
+ if (this.flushing !== void 0) {
1970
+ this.again = true;
1971
+ return this.flushing;
1972
+ }
1973
+ const run = (async () => {
1974
+ try {
1975
+ do {
1976
+ this.again = false;
1977
+ await this.drain();
1978
+ } while (this.again && !this.disposed);
1979
+ } catch (error) {
1980
+ this.options.log?.(`dsh-vibedev: feedback upload stopped: ${error instanceof Error ? error.message : String(error)}`);
1981
+ } finally {
1982
+ this.flushing = void 0;
1983
+ }
1984
+ })();
1985
+ this.flushing = run;
1986
+ return run;
1987
+ }
1988
+ /** Stop: no new attempt starts and the timer is cleared (the queue stays on disk). */
1989
+ dispose() {
1990
+ this.disposed = true;
1991
+ this.cancel(this.timer);
1992
+ this.timer = void 0;
1993
+ for (const [id, settle] of [...this.waiters]) {
1994
+ this.waiters.delete(id);
1995
+ settle({
1996
+ status: "queued",
1997
+ reason: "later"
1998
+ });
1999
+ }
2000
+ }
2001
+ /** Whether an item may go out under this account. */
2002
+ sendable(item, identity) {
2003
+ switch (item.owner.kind) {
2004
+ case "user": return identity.userId === item.owner.id;
2005
+ case "signed-out": return identity.userId !== void 0;
2006
+ case "unidentified": return this.bindings.get(item.body.id) === credentialRef(identity.credential);
772
2007
  }
2008
+ }
2009
+ async identity() {
773
2010
  try {
774
- await (await open(path, "wx")).close();
2011
+ return await this.options.identity();
2012
+ } catch {
2013
+ return { signedIn: false };
2014
+ }
2015
+ }
2016
+ async drain() {
2017
+ await this.options.queue.load();
2018
+ for (;;) {
2019
+ if (this.disposed || this.options.queue.items().length === 0) return;
2020
+ const identity = await this.identity();
2021
+ if (!identity.signedIn) {
2022
+ this.release("signed-out");
2023
+ return;
2024
+ }
2025
+ const next = this.options.queue.items().find((item) => this.sendable(item, identity));
2026
+ if (next === void 0) {
2027
+ if (identity.userId === void 0) this.park(this.jitter(IDENTITY_RETRY_MS), "later");
2028
+ else this.release("later");
2029
+ return;
2030
+ }
2031
+ const wait = next.nextAt - this.now();
2032
+ if (wait > 0) {
2033
+ this.park(wait, "later");
2034
+ return;
2035
+ }
2036
+ const item = await this.claim(next, identity);
2037
+ const attempt = await this.attempt(item, identity);
2038
+ switch (attempt.kind) {
2039
+ case "done":
2040
+ await this.options.queue.remove(item.body.id);
2041
+ this.settle(item.body.id, { status: "sent" });
2042
+ break;
2043
+ case "drop":
2044
+ this.options.log?.(`dsh-vibedev: feedback ${item.body.id} refused by the gateway (${refusalText(attempt)}); dropped`);
2045
+ await this.options.queue.remove(item.body.id);
2046
+ this.settle(item.body.id, {
2047
+ status: "rejected",
2048
+ code: attempt.code
2049
+ });
2050
+ break;
2051
+ case "shrink": {
2052
+ const smaller = halveAttachment(item.body, (this.options.newId ?? randomUUID)());
2053
+ if (smaller === void 0) {
2054
+ await this.options.queue.remove(item.body.id);
2055
+ this.settle(item.body.id, {
2056
+ status: "rejected",
2057
+ code: "FEEDBACK_BODY_TOO_LARGE"
2058
+ });
2059
+ break;
2060
+ }
2061
+ await this.options.queue.replace(item.body.id, smaller);
2062
+ const binding = this.bindings.get(item.body.id);
2063
+ if (binding !== void 0) this.bindings.set(smaller.id, binding);
2064
+ const waiter = this.waiters.get(item.body.id);
2065
+ if (waiter !== void 0) {
2066
+ this.waiters.delete(item.body.id);
2067
+ this.waiters.set(smaller.id, waiter);
2068
+ }
2069
+ break;
2070
+ }
2071
+ case "wait":
2072
+ await this.options.queue.update(item.body.id, {
2073
+ attempts: item.attempts + 1,
2074
+ nextAt: this.now() + attempt.ms,
2075
+ last: attempt.last
2076
+ });
2077
+ this.park(attempt.ms, attempt.reason);
2078
+ return;
2079
+ case "signed-out":
2080
+ this.release("signed-out");
2081
+ return;
2082
+ case "other-account":
2083
+ this.release("later");
2084
+ return;
2085
+ }
2086
+ }
2087
+ }
2088
+ /**
2089
+ * Feedback given signed out (or by an account not identified then) belongs, from its first attempt under a known
2090
+ * account on, to that account, so a retry never changes hands.
2091
+ */
2092
+ async claim(item, identity) {
2093
+ if (item.owner.kind === "user" || identity.userId === void 0) return item;
2094
+ const owner = {
2095
+ kind: "user",
2096
+ id: identity.userId
2097
+ };
2098
+ await this.options.queue.bind(item.body.id, owner);
2099
+ this.bindings.delete(item.body.id);
2100
+ return {
2101
+ ...item,
2102
+ owner
2103
+ };
2104
+ }
2105
+ /** One POST of the stored body with the account's credential, its answer mapped onto the contract. */
2106
+ async attempt(item, identity) {
2107
+ let current = identity.credential;
2108
+ let renewal = "none";
2109
+ const http = new GatewayHttp({
2110
+ ...this.options.gateway,
2111
+ resolveCredential: () => Promise.resolve(current),
2112
+ rejectToken: async (rejected) => {
2113
+ await this.options.rejectCredential(rejected).catch(() => void 0);
2114
+ const renewed = await this.identity();
2115
+ if (!renewed.signedIn) {
2116
+ current = void 0;
2117
+ renewal = "none";
2118
+ return;
2119
+ }
2120
+ if (item.owner.kind === "unidentified" && renewed.credential.kind === rejected.kind) this.bindings.set(item.body.id, credentialRef(renewed.credential));
2121
+ if (this.sendable(item, renewed)) {
2122
+ current = renewed.credential;
2123
+ renewal = "same";
2124
+ return;
2125
+ }
2126
+ current = void 0;
2127
+ renewal = renewed.userId === void 0 && item.owner.kind === "user" ? "unknown" : "other";
2128
+ }
2129
+ });
2130
+ try {
2131
+ const response = await http.send(FEEDBACK_PATH, {
2132
+ method: "POST",
2133
+ json: item.body,
2134
+ busyRetries: 0,
2135
+ timeoutMs: REQUEST_TIMEOUT_MS
2136
+ });
2137
+ await response.body?.cancel();
2138
+ return {
2139
+ kind: "done",
2140
+ status: response.status
2141
+ };
775
2142
  } catch (error) {
776
- if (error.code === "EEXIST") continue;
777
- throw error;
2143
+ if (!(error instanceof MediaError)) return {
2144
+ kind: "wait",
2145
+ ms: this.backoff(item.attempts),
2146
+ last: "ERROR",
2147
+ reason: "offline"
2148
+ };
2149
+ if (error.code === "NOT_SIGNED_IN") {
2150
+ const renewed = renewal;
2151
+ if (renewed === "other") return { kind: "other-account" };
2152
+ if (renewed === "unknown") return {
2153
+ kind: "wait",
2154
+ ms: this.backoff(item.attempts),
2155
+ last: "401",
2156
+ reason: "later"
2157
+ };
2158
+ return { kind: "signed-out" };
2159
+ }
2160
+ const status = error.details.status;
2161
+ if (status === void 0) return {
2162
+ kind: "wait",
2163
+ ms: this.backoff(item.attempts),
2164
+ last: error.code,
2165
+ reason: "offline"
2166
+ };
2167
+ if (DROP_STATUSES.has(status)) return dropped(error);
2168
+ if (status === 413) return { kind: "shrink" };
2169
+ if (status === 429) return {
2170
+ kind: "wait",
2171
+ ms: error.details.retryAfterMs ?? RATE_LIMIT_DEFAULT_MS,
2172
+ last: "429",
2173
+ reason: "later"
2174
+ };
2175
+ if (status === 503) return {
2176
+ kind: "wait",
2177
+ ms: error.details.retryAfterMs ?? this.backoff(item.attempts),
2178
+ last: "503",
2179
+ reason: "later"
2180
+ };
2181
+ if (status === 404) return {
2182
+ kind: "wait",
2183
+ ms: this.jitter(NOT_AVAILABLE_MS),
2184
+ last: "404",
2185
+ reason: "later"
2186
+ };
2187
+ if (status === 401) return {
2188
+ kind: "wait",
2189
+ ms: this.backoff(item.attempts),
2190
+ last: "401",
2191
+ reason: "later"
2192
+ };
2193
+ if (status >= 500) return {
2194
+ kind: "wait",
2195
+ ms: this.backoff(item.attempts),
2196
+ last: String(status),
2197
+ reason: "later"
2198
+ };
2199
+ if (item.attempts + 1 >= UNKNOWN_STATUS_ATTEMPTS) return dropped(error);
2200
+ return {
2201
+ kind: "wait",
2202
+ ms: this.backoff(item.attempts),
2203
+ last: String(status),
2204
+ reason: "later"
2205
+ };
778
2206
  }
779
- await renameWithRetry(temporary, path);
780
- return path;
781
2207
  }
782
- throw new MediaError(`Could not find a free file name for "${stem}.${extension}" in ${dir}.`, "OUTPUT_NAME_EXHAUSTED");
783
- }
784
- /**
785
- * Save bytes under the first free name `dir/stem.ext`.
786
- * @param dir - the destination directory.
787
- * @param stem - the file-name stem.
788
- * @param extension - the extension, without a dot.
789
- * @param data - the content.
790
- * @returns the final path.
791
- */
792
- async function saveNewFile(dir, stem, extension, data) {
793
- await mkdir(dir, { recursive: true });
794
- const temporary = join(dir, `.dsh-media-${randomUUID()}.part`);
795
- try {
796
- await writeFile(temporary, data);
797
- return await placeFile(temporary, dir, stem, extension);
798
- } finally {
799
- await rm(temporary, { force: true });
2208
+ /** 30 s doubling per attempt up to an hour, times a jitter of 0.5–1.5. */
2209
+ backoff(attempts) {
2210
+ return this.jitter(Math.min(BACKOFF_BASE_MS * 2 ** Math.min(attempts, 20), BACKOFF_MAX_MS));
800
2211
  }
801
- }
802
- /**
803
- * Write bytes atomically, replacing the file.
804
- * @param path - the final path.
805
- * @param data - the content.
806
- * @param options - `mode` for a file only its owner may read.
807
- */
808
- async function writeFileAtomic(path, data, options = {}) {
809
- await mkdir(dirname(path), { recursive: true });
810
- const temporary = join(dirname(path), `.${randomUUID()}.part`);
811
- try {
812
- await writeFile(temporary, data, options.mode === void 0 ? {} : { mode: options.mode });
813
- await renameWithRetry(temporary, path);
814
- } catch (error) {
815
- await rm(temporary, { force: true });
816
- throw error;
2212
+ jitter(ms) {
2213
+ return Math.round(ms * (.5 + (this.options.random ?? Math.random)()));
817
2214
  }
818
- }
819
- /**
820
- * Stream a response body into a temporary file, replacing what was there.
821
- * @param response - a successful response whose body is unread.
822
- * @param temporary - where to write; the caller moves it into place when this resolves.
823
- * @param maxBytes - the largest accepted body.
824
- * @param signal - cancels the download.
825
- * @returns the number of bytes written.
826
- */
827
- async function downloadTo(response, temporary, maxBytes, signal) {
828
- const declared = Number(response.headers.get("content-length"));
829
- if (Number.isFinite(declared) && declared > maxBytes) {
830
- await response.body?.cancel().catch(() => void 0);
831
- throw new MediaError(`The generated file is ${(declared / 1048576).toFixed(1)} MiB, more than the ${(maxBytes / 1048576).toFixed(0)} MiB this plugin downloads.`, "OUTPUT_TOO_LARGE");
2215
+ /** What this account can send waits `ms` (its first item's turn); whoever waits on an answer hears it is kept. */
2216
+ park(ms, reason) {
2217
+ this.cancel(this.timer);
2218
+ this.timer = this.schedule(() => {
2219
+ this.timer = void 0;
2220
+ this.flush();
2221
+ }, ms);
2222
+ this.release(reason);
2223
+ }
2224
+ release(reason) {
2225
+ for (const [id, settle] of [...this.waiters]) {
2226
+ this.waiters.delete(id);
2227
+ settle({
2228
+ status: "queued",
2229
+ reason
2230
+ });
2231
+ }
832
2232
  }
833
- await mkdir(dirname(temporary), { recursive: true });
834
- await rm(temporary, { force: true });
835
- if (response.body === null) {
836
- const data = new Uint8Array(await response.arrayBuffer());
837
- if (data.byteLength > maxBytes) throw new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE");
838
- await writeFile(temporary, data);
839
- return data.byteLength;
2233
+ settle(id, outcome) {
2234
+ const settle = this.waiters.get(id);
2235
+ if (settle === void 0) return;
2236
+ this.waiters.delete(id);
2237
+ settle(outcome);
840
2238
  }
841
- let total = 0;
842
- const limit = new Transform({ transform(chunk, _encoding, callback) {
843
- total += chunk.byteLength;
844
- if (total > maxBytes) callback(new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE"));
845
- else callback(null, chunk);
846
- } });
847
- try {
848
- await pipeline(Readable.fromWeb(response.body), limit, createWriteStream(temporary), signal === void 0 ? {} : { signal });
849
- return total;
850
- } catch (error) {
851
- await rm(temporary, { force: true }).catch(() => void 0);
852
- throw error;
2239
+ schedule(callback, ms) {
2240
+ if (this.options.setTimeout !== void 0) return this.options.setTimeout(callback, ms);
2241
+ const handle = globalThis.setTimeout(callback, Math.min(ms, 2147483647));
2242
+ handle.unref?.();
2243
+ return handle;
2244
+ }
2245
+ cancel(handle) {
2246
+ if (handle === void 0) return;
2247
+ if (this.options.clearTimeout !== void 0) this.options.clearTimeout(handle);
2248
+ else globalThis.clearTimeout(handle);
853
2249
  }
2250
+ };
2251
+ //#endregion
2252
+ //#region src/feedback/index.ts
2253
+ /**
2254
+ * User feedback that reaches VibeDev. VibeDev turns off DeepSeek Harness's own
2255
+ * feedback upload (session-telemetry-otel), so a rating or a `/feedback`
2256
+ * stayed in the local session log; this uploads them to the gateway
2257
+ * (`POST /v1/account/feedback`) with the VibeDev account they were given
2258
+ * under, plus feedback given through the account menu's dialog. See observe.ts
2259
+ * for what counts as new feedback, uploader.ts for the answers and the account
2260
+ * rule, queue.ts for what is kept.
2261
+ * @module dsh-vibedev/feedback
2262
+ */
2263
+ /**
2264
+ * Install the feedback upload: listen for new feedback and recent failures, serve the dialog's routes, and send what
2265
+ * the queue holds.
2266
+ * @param ctx - the plugin context.
2267
+ * @param options - the gateway, the state directory, who is signed in, and the sign-in hooks.
2268
+ * @returns the uploader and the recent errors (for tests and other parts of the plugin).
2269
+ */
2270
+ function installFeedback(ctx, options) {
2271
+ const queue = new FeedbackQueue(join(options.gatewayDir, "feedback-queue.json"));
2272
+ let client;
2273
+ const uploader = new FeedbackUploader({
2274
+ gateway: options.gateway,
2275
+ queue,
2276
+ log: options.log,
2277
+ identity: options.identity,
2278
+ rejectCredential: options.rejectCredential,
2279
+ client: () => client ??= clientInfo(hostFacts(), options.pluginVersion)
2280
+ });
2281
+ const errors = new RecentErrors();
2282
+ const enqueue = (draft) => {
2283
+ if (draft === void 0) return;
2284
+ uploader.enqueue(draft).catch((error) => {
2285
+ options.log(`dsh-vibedev: feedback could not be queued: ${error instanceof Error ? error.message : String(error)}`);
2286
+ });
2287
+ };
2288
+ ctx.on("session/event", (session, event) => {
2289
+ errors.observe(session, event);
2290
+ enqueue(draftFromEvent(session, event));
2291
+ });
2292
+ ctx.on("feedback/committed", (inspection) => {
2293
+ enqueue(draftFromCommitted(inspection));
2294
+ });
2295
+ const hasCredential = async () => (await options.identity().catch(() => ({ signedIn: false }))).signedIn;
2296
+ ctx.inject(["connection"], (scoped) => {
2297
+ for (const route of feedbackRoutes({
2298
+ submit: (draft, locale) => uploader.submit(draft, locale),
2299
+ errors,
2300
+ hasCredential
2301
+ })) scoped.effect(() => scoped.connection.fetch.register(route), `dsh-vibedev: ${route.path}`);
2302
+ });
2303
+ ctx.effect(() => {
2304
+ uploader.flush();
2305
+ const unsubscribe = options.onCredentialChange(() => {
2306
+ uploader.credentialChanged();
2307
+ });
2308
+ return () => {
2309
+ unsubscribe();
2310
+ uploader.dispose();
2311
+ };
2312
+ }, "dsh-vibedev: feedback upload");
2313
+ return {
2314
+ uploader,
2315
+ errors
2316
+ };
854
2317
  }
855
2318
  //#endregion
856
2319
  //#region src/gateway/origin.ts
@@ -2463,7 +3926,7 @@ function isContextOverflow(message, contextWindow) {
2463
3926
  }
2464
3927
  //#endregion
2465
3928
  //#region node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
2466
- const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-KOS0z8Fy.js").then((n) => n.t));
3929
+ const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-BgIfgjNt.js").then((n) => n.t));
2467
3930
  //#endregion
2468
3931
  //#region node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
2469
3932
  const openAICompletionsApi = () => lazyApi(() => import("./openai-completions-DqTCiqpS.js"));
@@ -2953,7 +4416,7 @@ const SIGN_IN_REQUIRED_CODE = "VIBEDEV_SIGN_IN_REQUIRED";
2953
4416
  /** Failure code for a used-up balance; not the Harness's `ACCOUNT_QUOTA`, which opens the DeepSeek top-up. */
2954
4417
  const INSUFFICIENT_BALANCE_CODE = "VIBEDEV_INSUFFICIENT_BALANCE";
2955
4418
  /** What a person reads when a VibeDev model is used before signing in. */
2956
- const SIGN_IN_MESSAGE$1 = "请先登录 VibeDev:在侧边栏底部「登录 VibeDev」或「设置 → VibeDev 账号」中登录后即可使用这些模型。 Sign in to VibeDev (sidebar, or Settings → VibeDev account) to use these models.";
4419
+ const SIGN_IN_MESSAGE = "请先登录 VibeDev:在侧边栏底部「登录 VibeDev」或「设置 → VibeDev 账号」中登录后即可使用这些模型。 Sign in to VibeDev (sidebar, or Settings → VibeDev account) to use these models.";
2957
4420
  /** What a person reads when the gateway ended the sign-in and a refresh could not renew it. */
2958
4421
  const SESSION_ENDED_MESSAGE = "VibeDev 登录已失效,请重新登录(侧边栏底部或「设置 → VibeDev 账号」)。 Your VibeDev sign-in has ended; sign in again.";
2959
4422
  /**
@@ -3031,7 +4494,7 @@ var GatewayAdapter = class extends LlmAdapter {
3031
4494
  }
3032
4495
  modelOf(snapshot, provider, id) {
3033
4496
  this.assertOwned(provider);
3034
- if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE$1, SIGN_IN_REQUIRED_CODE);
4497
+ if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
3035
4498
  const catalog = snapshot.byId.get(id);
3036
4499
  const model = snapshot.models.getModel(provider, id);
3037
4500
  if (catalog === void 0 || model === void 0) throw new LlmError(`VibeDev has no model "${id}"`, "UNKNOWN_MODEL");
@@ -3091,7 +4554,7 @@ var GatewayAdapter = class extends LlmAdapter {
3091
4554
  const starting = startingReasoning(catalog);
3092
4555
  const reasoning = resolveReasoningLevel(model, options.reasoningEffort ?? (starting === void 0 ? void 0 : effortOf(starting)));
3093
4556
  let credential = await this.config.resolveCredential();
3094
- if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE$1, SIGN_IN_REQUIRED_CODE);
4557
+ if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
3095
4558
  const sessionId = options.sessionId === void 0 ? void 0 : String(options.sessionId);
3096
4559
  const deviceId = model.api === "anthropic-messages" && sessionId !== void 0 ? await this.config.deviceId?.() : void 0;
3097
4560
  const consumer = new AbortController();
@@ -3503,10 +4966,31 @@ function installGatewayModels(ctx, options) {
3503
4966
  * the returned upload headers when an upload is needed, `POST /{id}/complete`.
3504
4967
  * An asset the library already holds is read back through `/refresh`, which
3505
4968
  * also carries its measured duration.
4969
+ *
4970
+ * The gateway keeps one asset per account, purpose and digest
4971
+ * (media/service.go CreateUpload): every upload of the same bytes is handed the
4972
+ * same pending asset, the first PUT claims it, and the others are answered
4973
+ * 409 `MEDIA_ASSET_NOT_READY` ("media upload is unavailable" on the PUT,
4974
+ * "media upload is already in progress" on a later `uploads`). So inside the
4975
+ * Host one upload of a file serves every caller that wants it at the same time
4976
+ * (by purpose and digest), and a 409 from another process — or the coming
4977
+ * `MEDIA_ASSET_UPLOAD_IN_PROGRESS` — means another upload of the same bytes is
4978
+ * under way: the library waits for it (Retry-After, else 1 s doubling to 10 s,
4979
+ * two minutes at most) by asking `uploads` again, which hands back the asset
4980
+ * once it is ready, still answers 409 while it is not, and hands out a fresh
4981
+ * upload when the other one ended without the file (failed or expired) — the
4982
+ * library then uploads once more itself. `/refresh` cannot tell those apart (it
4983
+ * answers 409 for a failed asset too).
3506
4984
  * @module dsh-vibedev/gateway/assets
3507
4985
  */
3508
4986
  /** How long before expiry a cached asset is refreshed instead of reused. */
3509
4987
  const EXPIRY_MARGIN_MS = 6e5;
4988
+ /** How long to wait for another upload of the same file, in all. */
4989
+ const OTHER_UPLOAD_WAIT_MS = 12e4;
4990
+ const FIRST_LOOK_MS = 1e3;
4991
+ const LOOK_STEP_MAX_MS = 1e4;
4992
+ /** Uploads this library starts for one file: its own, and one more after another upload of the file ended without it. */
4993
+ const OWN_UPLOADS = 2;
3510
4994
  const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3511
4995
  const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
3512
4996
  const httpUrl$1 = (value) => {
@@ -3536,39 +5020,140 @@ function parseAsset(body, fallbackType) {
3536
5020
  ...typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? { durationMs: duration } : {}
3537
5021
  };
3538
5022
  }
5023
+ /**
5024
+ * Whether a media-asset answer means another upload of the same bytes is under way: 409 `MEDIA_ASSET_NOT_READY`
5025
+ * (on `uploads`, the PUT or `complete`), or `MEDIA_ASSET_UPLOAD_IN_PROGRESS`.
5026
+ */
5027
+ function otherUpload(error) {
5028
+ return error instanceof MediaError && (error.code === "MEDIA_ASSET_UPLOAD_IN_PROGRESS" || error.code === "MEDIA_ASSET_NOT_READY" && error.details.status === 409);
5029
+ }
3539
5030
  /** Uploads references and remembers them for the life of the plugin. */
3540
5031
  var MediaLibrary = class {
3541
5032
  http;
3542
5033
  now;
5034
+ options;
3543
5035
  cache = /* @__PURE__ */ new Map();
5036
+ flights = /* @__PURE__ */ new Map();
5037
+ /** Bumped by {@link clear}: an upload of the previous account does not land in the cache. */
5038
+ generation = 0;
3544
5039
  /**
3545
5040
  * @param http - the gateway client.
3546
- * @param now - clock, for expiry checks.
5041
+ * @param now - clock, for expiry checks and the wait for another upload.
5042
+ * @param options - the sleep (a test seam).
3547
5043
  */
3548
- constructor(http, now = Date.now) {
5044
+ constructor(http, now = Date.now, options = {}) {
3549
5045
  this.http = http;
3550
5046
  this.now = now;
5047
+ this.options = options;
3551
5048
  }
3552
5049
  /** Forget every remembered asset, as after an account change: assets belong to the account that uploaded them. */
3553
5050
  clear() {
5051
+ this.generation++;
3554
5052
  this.cache.clear();
5053
+ this.flights.clear();
3555
5054
  }
3556
5055
  /**
3557
- * Upload one loaded input, or reuse the asset the library already holds.
5056
+ * Upload one loaded input, or reuse the asset the library already holds. Callers that ask for the same file
5057
+ * (purpose and digest) at the same time share one upload; one that gives up leaves it running for the others.
3558
5058
  * @param media - the loaded input.
3559
5059
  * @param purpose - the asset purpose.
3560
- * @param signal - cancels the upload.
5060
+ * @param signal - cancels this caller's wait (and the upload, once no caller waits on it).
3561
5061
  * @returns the asset.
3562
5062
  */
3563
5063
  async upload(media, purpose, signal) {
5064
+ if (signal?.aborted === true) throw abortError(signal);
3564
5065
  const sha256 = createHash("sha256").update(media.data).digest("hex");
3565
5066
  const key = `${purpose}:${sha256}`;
3566
5067
  const cached = this.cache.get(key);
3567
5068
  if (cached !== void 0 && !this.expiring(cached)) return cached;
5069
+ let flight = this.flights.get(key);
5070
+ if (flight === void 0) {
5071
+ const controller = new AbortController();
5072
+ const generation = this.generation;
5073
+ const created = {
5074
+ promise: this.resolve(media, purpose, sha256, controller.signal).then((asset) => {
5075
+ if (generation === this.generation) this.cache.set(key, asset);
5076
+ return asset;
5077
+ }).finally(() => {
5078
+ if (this.flights.get(key) === created) this.flights.delete(key);
5079
+ }),
5080
+ controller,
5081
+ callers: 0
5082
+ };
5083
+ flight = created;
5084
+ this.flights.set(key, created);
5085
+ }
5086
+ return this.join(key, flight, signal);
5087
+ }
5088
+ /** Wait on a shared upload; giving up answers this caller at once and stops the upload when nobody else waits. */
5089
+ join(key, flight, signal) {
5090
+ flight.callers++;
5091
+ return new Promise((resolve, reject) => {
5092
+ let done = false;
5093
+ const leave = () => {
5094
+ done = true;
5095
+ flight.callers--;
5096
+ signal?.removeEventListener("abort", onAbort);
5097
+ };
5098
+ const onAbort = () => {
5099
+ if (done) return;
5100
+ leave();
5101
+ if (flight.callers === 0) {
5102
+ if (this.flights.get(key) === flight) this.flights.delete(key);
5103
+ flight.controller.abort(signal?.reason);
5104
+ }
5105
+ reject(abortError(signal));
5106
+ };
5107
+ signal?.addEventListener("abort", onAbort, { once: true });
5108
+ flight.promise.then((asset) => {
5109
+ if (!done) {
5110
+ leave();
5111
+ resolve(asset);
5112
+ }
5113
+ }, (error) => {
5114
+ if (!done) {
5115
+ leave();
5116
+ reject(error);
5117
+ }
5118
+ });
5119
+ });
5120
+ }
5121
+ /** Refresh a remembered asset about to expire, else upload the file — waiting for another upload of it when one is under way. */
5122
+ async resolve(media, purpose, sha256, signal) {
5123
+ const cached = this.cache.get(`${purpose}:${sha256}`);
3568
5124
  if (cached !== void 0) {
3569
5125
  const refreshed = await this.refresh(cached, signal).catch(() => void 0);
3570
- if (refreshed !== void 0) return this.remember(key, refreshed);
5126
+ if (refreshed !== void 0) return refreshed;
5127
+ }
5128
+ let own = 0;
5129
+ let waitingSince;
5130
+ let step = FIRST_LOOK_MS;
5131
+ for (;;) {
5132
+ let other;
5133
+ try {
5134
+ const created = await this.declare(media, purpose, sha256, signal);
5135
+ if (created.kind === "ready") return created.asset;
5136
+ if (own >= OWN_UPLOADS) throw new MediaError(`The upload of "${media.source}" to the VibeDev media library did not finish, here or in another upload of the same file. Try again in a minute.`, "ASSET_UPLOAD_FAILED", { retryable: true });
5137
+ own++;
5138
+ return await this.put(media, sha256, created.assetId, created.answer, signal);
5139
+ } catch (error) {
5140
+ if (!otherUpload(error)) throw error;
5141
+ other = error;
5142
+ }
5143
+ waitingSince ??= this.now();
5144
+ const left = waitingSince + OTHER_UPLOAD_WAIT_MS - this.now();
5145
+ if (left <= 0) throw new MediaError(`"${media.source}" is still being uploaded to the VibeDev media library by another upload of the same file on this account. Try again in a minute.`, "ASSET_UPLOAD_IN_PROGRESS", {
5146
+ status: 409,
5147
+ retryable: true,
5148
+ ...other.details.assetId === void 0 ? {} : { assetId: other.details.assetId }
5149
+ });
5150
+ await (this.options.sleep ?? delay$1)(Math.min(other.details.retryAfterMs ?? step, left), signal);
5151
+ if (signal.aborted) throw abortError(signal);
5152
+ step = Math.min(step * 2, LOOK_STEP_MAX_MS);
3571
5153
  }
5154
+ }
5155
+ /** `POST /uploads`: the asset when the library already holds the file, else the upload it hands out. */
5156
+ async declare(media, purpose, sha256, signal) {
3572
5157
  const created = record$4(await this.http.json("/v1/media-assets/uploads", {
3573
5158
  method: "POST",
3574
5159
  json: {
@@ -3578,20 +5163,31 @@ var MediaLibrary = class {
3578
5163
  sha256,
3579
5164
  purpose
3580
5165
  },
3581
- ...signal === void 0 ? {} : { signal }
5166
+ signal
3582
5167
  }));
3583
5168
  const assetId = text$5(created?.asset_id);
3584
5169
  if (created === void 0 || assetId === void 0) throw new MediaError(`The VibeDev gateway did not accept the upload of "${media.source}".`, "ASSET_UPLOAD_REFUSED");
3585
- if (created.upload_required === false) {
3586
- const known = parseAsset(created, media.mime);
3587
- const facts = await this.read(assetId, "refresh", media.mime, signal).catch(() => void 0) ?? known;
3588
- if (facts === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}".`, "ASSET_REFERENCE_MISSING");
3589
- return this.remember(key, {
5170
+ if (created.upload_required !== false) return {
5171
+ kind: "upload",
5172
+ assetId,
5173
+ answer: created
5174
+ };
5175
+ const known = parseAsset(created, media.mime);
5176
+ const facts = await this.read(assetId, "refresh", media.mime, signal).catch((error) => {
5177
+ if (signal.aborted) throw error;
5178
+ }) ?? known;
5179
+ if (facts === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}".`, "ASSET_REFERENCE_MISSING");
5180
+ return {
5181
+ kind: "ready",
5182
+ asset: {
3590
5183
  ...facts,
3591
5184
  sha256,
3592
5185
  bytes: media.data.byteLength
3593
- });
3594
- }
5186
+ }
5187
+ };
5188
+ }
5189
+ /** PUT the bytes where `uploads` said, then `complete`. */
5190
+ async put(media, sha256, assetId, created, signal) {
3595
5191
  const uploadUrl = httpUrl$1(created.upload_url) ?? (text$5(created.upload_url)?.startsWith("/") === true ? this.http.url(text$5(created.upload_url)) : void 0);
3596
5192
  if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
3597
5193
  const headers = { "content-type": media.mime };
@@ -3603,25 +5199,21 @@ var MediaLibrary = class {
3603
5199
  anonymous: true,
3604
5200
  timeoutMs: 6e5,
3605
5201
  busyRetries: 1,
3606
- ...signal === void 0 ? {} : { signal }
5202
+ signal
3607
5203
  });
3608
5204
  const completed = await this.read(assetId, "complete", media.mime, signal);
3609
5205
  if (completed === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}" after the upload.`, "ASSET_REFERENCE_MISSING");
3610
- return this.remember(key, {
5206
+ return {
3611
5207
  ...completed,
3612
5208
  sha256,
3613
5209
  bytes: media.data.byteLength
3614
- });
5210
+ };
3615
5211
  }
3616
5212
  expiring(asset) {
3617
5213
  if (asset.expiresAt === void 0) return false;
3618
5214
  const at = Date.parse(asset.expiresAt);
3619
5215
  return Number.isFinite(at) && at - this.now() < EXPIRY_MARGIN_MS;
3620
5216
  }
3621
- remember(key, asset) {
3622
- this.cache.set(key, asset);
3623
- return asset;
3624
- }
3625
5217
  async refresh(asset, signal) {
3626
5218
  const facts = await this.read(asset.assetId, "refresh", asset.contentType, signal);
3627
5219
  return facts === void 0 ? void 0 : {
@@ -3638,218 +5230,6 @@ var MediaLibrary = class {
3638
5230
  }
3639
5231
  };
3640
5232
  //#endregion
3641
- //#region src/gateway/http.ts
3642
- /**
3643
- * HTTP client for the VibeDev gateway. Every gateway call goes through here so
3644
- * authentication, refresh after a 401, balance refusals, busy back-off and
3645
- * idempotency are handled once.
3646
- *
3647
- * The credential is attached only to requests on the gateway origin: upload
3648
- * URLs and third-party links never see it.
3649
- * @module dsh-vibedev/gateway/http
3650
- */
3651
- /** Error codes the gateway uses for "full right now, nothing was charged". */
3652
- const BUSY_CODES = /* @__PURE__ */ new Set([
3653
- "APP_TOKEN_UNAVAILABLE",
3654
- "PROVIDER_CAPACITY_BUSY",
3655
- "upstream_capacity_busy",
3656
- "AUDIO_CAPACITY_BUSY",
3657
- "AUDIO_NO_AVAILABLE_ACCOUNT",
3658
- "WEB_SEARCH_BUSY",
3659
- "WEB_SEARCH_RATE_LIMITED"
3660
- ]);
3661
- /**
3662
- * The account already runs as many video or audio tasks as it may (HTTP 429).
3663
- * Not retried here: a slot frees only when one of the user's tasks finishes.
3664
- */
3665
- const TASK_LIMIT_CODES = /* @__PURE__ */ new Set(["VIDEO_TASK_LIMIT_REACHED", "AUDIO_TASK_LIMIT_REACHED"]);
3666
- const DEFAULT_TIMEOUT_MS = 6e4;
3667
- const DEFAULT_BUSY_WAIT_MS = 2e3;
3668
- /** The message for a call made while nobody is signed in. */
3669
- const SIGN_IN_MESSAGE = "VibeDev media generation needs a signed-in VibeDev account. Call media_account with action \"sign_in\": it opens the VibeDev sign-in page in the user's browser, where new users can also register. In the VibeDev app, the account signed in to the app is used automatically.";
3670
- /** Read through a call so a check made before an `await` is not taken as still true after it. */
3671
- function isAborted(signal) {
3672
- return signal?.aborted === true;
3673
- }
3674
- function delay$1(ms, signal) {
3675
- return new Promise((resolve, reject) => {
3676
- if (isAborted(signal)) {
3677
- reject(abortError(signal));
3678
- return;
3679
- }
3680
- const timer = setTimeout(() => {
3681
- signal?.removeEventListener("abort", onAbort);
3682
- resolve();
3683
- }, ms);
3684
- const onAbort = () => {
3685
- clearTimeout(timer);
3686
- reject(abortError(signal));
3687
- };
3688
- signal?.addEventListener("abort", onAbort, { once: true });
3689
- });
3690
- }
3691
- function abortError(signal) {
3692
- return new MediaError("The media request was cancelled.", "ABORTED", { retryable: true }, { cause: signal?.reason });
3693
- }
3694
- /** Gateway HTTP client. */
3695
- var GatewayHttp = class {
3696
- options;
3697
- origin;
3698
- /**
3699
- * @param options - origin, credential plane, user agent and test seams.
3700
- */
3701
- constructor(options) {
3702
- this.options = options;
3703
- this.origin = options.origin.trim().replace(/\/+$/, "");
3704
- }
3705
- /** Absolute URL for a gateway path, or the URL itself when already absolute. */
3706
- url(path) {
3707
- return /^https?:\/\//i.test(path) ? path : `${this.origin}${path.startsWith("/") ? "" : "/"}${path}`;
3708
- }
3709
- /** Whether a URL is on the gateway origin, and so may carry the credential. */
3710
- isGatewayUrl(url) {
3711
- try {
3712
- return new URL(url).origin === new URL(this.origin).origin;
3713
- } catch {
3714
- return false;
3715
- }
3716
- }
3717
- /**
3718
- * Send one request and return the successful response.
3719
- * @param path - gateway path, or an absolute URL.
3720
- * @param request - method, body, headers and retry policy.
3721
- * @returns the 2xx response, body unread.
3722
- * @throws {@link MediaError} for every refusal, with the gateway's code.
3723
- */
3724
- async send(path, request = {}) {
3725
- const url = this.url(path);
3726
- const authenticate = request.anonymous !== true && this.isGatewayUrl(url);
3727
- let credential = authenticate ? await this.credential() : void 0;
3728
- let refreshed = false;
3729
- let busyRetries = request.busyRetries ?? 2;
3730
- for (;;) {
3731
- const response = await this.attempt(url, request, credential);
3732
- if (response.ok) {
3733
- if (authenticate) try {
3734
- this.options.onAccepted?.({
3735
- method: request.method ?? "GET",
3736
- path: new URL(url).pathname
3737
- });
3738
- } catch {}
3739
- return response;
3740
- }
3741
- const failure = parseGatewayFailure(await response.clone().json().catch(() => void 0));
3742
- if (response.status === 401 && credential !== void 0 && credential.kind !== "key" && !refreshed) {
3743
- refreshed = true;
3744
- await this.options.rejectToken?.(credential);
3745
- credential = await this.credential();
3746
- continue;
3747
- }
3748
- const wait = retryAfterMs(response.headers.get("retry-after"));
3749
- if (isBusy(response.status, failure, wait) && busyRetries > 0 && (wait ?? DEFAULT_BUSY_WAIT_MS) <= (request.maxBusyWaitMs ?? 15e3)) {
3750
- busyRetries--;
3751
- await (this.options.sleep ?? delay$1)(wait ?? DEFAULT_BUSY_WAIT_MS, request.signal);
3752
- continue;
3753
- }
3754
- throw failureError$1(response.status, failure, wait);
3755
- }
3756
- }
3757
- /**
3758
- * Send one request and parse its JSON body.
3759
- * @param path - gateway path, or an absolute URL.
3760
- * @param request - method, body, headers and retry policy.
3761
- * @returns the parsed body.
3762
- */
3763
- async json(path, request = {}) {
3764
- const response = await this.send(path, request);
3765
- try {
3766
- return await response.json();
3767
- } catch (error) {
3768
- throw new MediaError(`The VibeDev gateway returned an unreadable answer for ${path}.`, "GATEWAY_BAD_RESPONSE", { status: response.status }, { cause: error });
3769
- }
3770
- }
3771
- async credential() {
3772
- const credential = await this.options.resolveCredential();
3773
- if (credential === void 0) throw new MediaError(SIGN_IN_MESSAGE, "NOT_SIGNED_IN");
3774
- return credential;
3775
- }
3776
- async attempt(url, request, credential) {
3777
- if (isAborted(request.signal)) throw abortError(request.signal);
3778
- const headers = {
3779
- accept: "application/json",
3780
- "user-agent": this.options.userAgent,
3781
- ...request.headers
3782
- };
3783
- if (credential !== void 0) headers.authorization = `Bearer ${credential.token}`;
3784
- if (request.idempotencyKey !== void 0) headers["idempotency-key"] = request.idempotencyKey;
3785
- let body = request.body;
3786
- if (request.json !== void 0) {
3787
- body = JSON.stringify(request.json);
3788
- headers["content-type"] = "application/json";
3789
- }
3790
- const timeout = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS);
3791
- const signal = request.signal === void 0 ? timeout : AbortSignal.any([request.signal, timeout]);
3792
- try {
3793
- return await (this.options.fetch ?? globalThis.fetch)(url, {
3794
- method: request.method ?? (body === void 0 ? "GET" : "POST"),
3795
- headers,
3796
- ...body === void 0 ? {} : { body },
3797
- redirect: "error",
3798
- signal
3799
- });
3800
- } catch (error) {
3801
- if (isAborted(request.signal)) throw abortError(request.signal);
3802
- if (timeout.aborted) throw new MediaError(`The VibeDev gateway did not answer within ${Math.round((request.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3)} s.`, "GATEWAY_TIMEOUT", { retryable: true });
3803
- throw new MediaError(`Could not reach the VibeDev gateway (${error instanceof Error ? error.message : String(error)}). Ask the user to check the network connection.`, "GATEWAY_UNREACHABLE", { retryable: true });
3804
- }
3805
- }
3806
- };
3807
- /**
3808
- * Whether an answer means "full right now, nothing was charged": any 429 but a
3809
- * task limit, or a 503 with a busy code or `Retry-After`. A bare 503 is an outage.
3810
- */
3811
- function isBusy(status, failure, wait) {
3812
- if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return false;
3813
- return status === 429 || status === 503 && (failure.code !== void 0 && BUSY_CODES.has(failure.code) || wait !== void 0);
3814
- }
3815
- /**
3816
- * The error for an answer the client does not retry, worded for the model.
3817
- * @param status - HTTP status.
3818
- * @param failure - the parsed error body.
3819
- * @param wait - Retry-After in milliseconds, when given.
3820
- * @returns the error to throw.
3821
- */
3822
- function failureError$1(status, failure, wait) {
3823
- const words = gatewayWords(failure);
3824
- const { code: _code, message: _message, ...facts } = failure;
3825
- const details = {
3826
- status,
3827
- ...facts,
3828
- ...wait === void 0 ? {} : { retryAfterMs: wait }
3829
- };
3830
- if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return new MediaError(`The VibeDev account already runs as many ${failure.code.startsWith("VIDEO") ? "video" : "audio"} tasks at once as it may${failure.active === void 0 || failure.limit === void 0 ? "" : ` (${failure.active} of ${failure.limit})`}. Wait for one of them to finish (media_tasks lists them), then submit again; nothing was charged.`, failure.code, {
3831
- ...details,
3832
- retryable: true
3833
- });
3834
- if (status === 402) return new MediaError(`The VibeDev account balance is not enough for this request${(failure.estimatedCny === void 0 ? "" : `: this task is estimated at ¥${failure.estimatedCny}${failure.availableCny === void 0 ? "" : `, and ¥${failure.availableCny} is available`}${failure.pendingCny === void 0 || Number(failure.pendingCny) === 0 ? "" : ` (tasks in progress hold ¥${failure.pendingCny})`}`) || words}. Nothing was charged. Ask the user to top up their VibeDev balance${failure.rechargeUrl === void 0 ? "" : ` at ${failure.rechargeUrl}`}.`, "INSUFFICIENT_BALANCE", {
3835
- ...details,
3836
- retryable: false
3837
- });
3838
- if (status === 401) return new MediaError(`The VibeDev gateway rejected the sign-in${words}. Ask the user to sign in to VibeDev again.`, "SIGN_IN_REJECTED", {
3839
- ...details,
3840
- retryable: false
3841
- });
3842
- if (isBusy(status, failure, wait)) {
3843
- const seconds = wait === void 0 ? void 0 : Math.ceil(wait / 1e3);
3844
- return new MediaError(`The VibeDev gateway is busy${words}. ${seconds === void 0 ? "Try again shortly" : `Try again in about ${seconds} s`}; nothing was charged.`, failure.code ?? (status === 429 ? "RATE_LIMITED" : "GATEWAY_BUSY"), {
3845
- ...details,
3846
- retryable: true,
3847
- busy: true
3848
- });
3849
- }
3850
- return new MediaError(`The VibeDev gateway refused the request with HTTP ${status}${words}.`, failure.code ?? `HTTP_${status}`, details);
3851
- }
3852
- //#endregion
3853
5233
  //#region src/gateway/catalog.ts
3854
5234
  /** The video generation modes of catalog schema v1, under their wire names. */
3855
5235
  const VIDEO_MODES = [
@@ -4128,14 +5508,15 @@ function stringChoices(raw) {
4128
5508
  }
4129
5509
  return Object.keys(out).length === 0 ? void 0 : out;
4130
5510
  }
4131
- function parseReferenceLimits(raw) {
5511
+ function parseReferenceLimits(raw, form) {
4132
5512
  if (raw === void 0) return void 0;
4133
5513
  const max = count(field(raw, "max_count")) ?? count(raw.max);
4134
5514
  if (max === void 0 || max === 0) return void 0;
4135
5515
  const min = count(field(raw, "min_count")) ?? count(raw.min) ?? 0;
4136
5516
  const limits = {
4137
5517
  min: Math.min(min, max),
4138
- max
5518
+ max,
5519
+ form
4139
5520
  };
4140
5521
  for (const [key, ...names] of [
4141
5522
  [
@@ -4167,13 +5548,31 @@ function parseReferenceLimits(raw) {
4167
5548
  return limits;
4168
5549
  }
4169
5550
  /**
5551
+ * Seed's reference audio, as the gateway declares it (catalog/audio.go AudioCapabilities): flat flags and limits for
5552
+ * each input of its union rather than a `references` object — `reference_audio_input`, `max_reference_audios`,
5553
+ * `max_reference_audio_duration_seconds`, `max_reference_audio_bytes`.
5554
+ */
5555
+ function seedReferenceLimits(raw) {
5556
+ const max = count(field(raw, "max_reference_audios"));
5557
+ if (bool(raw, "reference_audio_input") !== true || max === void 0 || max === 0) return void 0;
5558
+ const maxBytes = positive(field(raw, "max_reference_audio_bytes"));
5559
+ const maxSeconds = positive(field(raw, "max_reference_audio_duration_seconds"));
5560
+ return {
5561
+ min: 0,
5562
+ max,
5563
+ form: "object",
5564
+ ...maxBytes === void 0 ? {} : { maxBytes },
5565
+ ...maxSeconds === void 0 ? {} : { maxSeconds }
5566
+ };
5567
+ }
5568
+ /**
4170
5569
  * The output formats, in either declared shape: `output_formats: [{format, sample_rates}]`,
4171
5570
  * or `output_formats: ['wav','mp3']` with `sample_rates: {wav: [...], mp3: [...]}`.
4172
5571
  */
4173
5572
  function parseOutputFormats(raw) {
4174
5573
  const declared = field(raw, "output_formats");
4175
5574
  if (!Array.isArray(declared)) return void 0;
4176
- const rates = record$3(field(raw, "sample_rates"));
5575
+ const rates = record$3(field(raw, "sample_rates")) ?? record$3(field(raw, "output_sample_rates"));
4177
5576
  const formats = [];
4178
5577
  for (const item of declared) {
4179
5578
  const entry = record$3(item);
@@ -4202,10 +5601,16 @@ function parseAudioCapabilities(raw) {
4202
5601
  const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
4203
5602
  const promptField = text$4(field(raw, "prompt_field"));
4204
5603
  const requestFields = list(raw, "request_fields") ?? [];
4205
- const references = parseReferenceLimits(record$3(field(raw, "references")) ?? record$3(field(raw, "reference_audio")));
5604
+ const union = [
5605
+ "reference_audio_input",
5606
+ "reference_image_input",
5607
+ "speaker_input"
5608
+ ].some((name) => bool(raw, name) !== void 0);
5609
+ const references = parseReferenceLimits(record$3(field(raw, "references")) ?? record$3(field(raw, "reference_audio")), union ? "object" : "url") ?? seedReferenceLimits(raw);
4206
5610
  const outputFormats = parseOutputFormats(raw);
4207
5611
  const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
4208
5612
  const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
5613
+ const watermarkFields = list(raw, "watermark_fields");
4209
5614
  const result = { requestFields };
4210
5615
  if (generationKind !== void 0) result.generationKind = generationKind;
4211
5616
  if (promptField !== void 0) result.promptField = promptField;
@@ -4214,11 +5619,13 @@ function parseAudioCapabilities(raw) {
4214
5619
  if (outputFormats !== void 0) result.outputFormats = outputFormats;
4215
5620
  if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
4216
5621
  if (choices !== void 0) result.choices = choices;
5622
+ if (watermarkFields !== void 0 && watermarkFields.length > 0) result.watermarkFields = watermarkFields;
4217
5623
  for (const [key, ...names] of [
4218
5624
  [
4219
5625
  "maxPromptChars",
4220
5626
  "max_prompt_chars",
4221
- "max_text_chars"
5627
+ "max_text_chars",
5628
+ "max_prompt_characters"
4222
5629
  ],
4223
5630
  [
4224
5631
  "maxInputBytes",
@@ -5858,6 +7265,11 @@ function quotedCny(quote) {
5858
7265
  * | podcast | model, prompt, source_url |
5859
7266
  * | speech | as declared; Seed: model, text_prompt, references, audio_config, watermark |
5860
7267
  *
7268
+ * Seed (`seed-audio-1.0`) parses its body strictly: each reference is an object
7269
+ * naming its input (`{"audio_url": "<url>"}`) and the watermark an object
7270
+ * (`{"aigc_watermark": true}`); the model's declaration says so (the inputs of
7271
+ * its reference union, `watermark_fields`), and only such a model gets them.
7272
+ *
5861
7273
  * The main text goes in the model's `prompt_field`. A field the model does not
5862
7274
  * declare in `request_fields` is refused before anything is uploaded or charged;
5863
7275
  * music and podcasts never take speech references, output formats, sample rates
@@ -6004,7 +7416,10 @@ function audioRequestBody(model, request) {
6004
7416
  }
6005
7417
  if (request.watermark !== void 0) {
6006
7418
  if (!takes("watermark")) refuse(`${model.id} does not take watermark.`, "watermark");
6007
- body.watermark = request.watermark;
7419
+ const fields = audio?.watermarkFields;
7420
+ if (fields === void 0) body.watermark = request.watermark;
7421
+ else if (fields.includes("aigc_watermark")) body.watermark = { aigc_watermark: request.watermark };
7422
+ else refuse(`${model.id} declares its watermark as ${fields.join(", ")}, without a switch to turn it on or off.`, "watermark");
6008
7423
  }
6009
7424
  if (request.format !== void 0 || request.sampleRate !== void 0 || takes("audio_config")) {
6010
7425
  if (!takes("audio_config")) refuse(`${model.id} does not take an output format or sample rate.`, "format");
@@ -6078,7 +7493,7 @@ async function prepareAudioTask(runtime, call, request, save) {
6078
7493
  const kind = audioKindOf(model);
6079
7494
  const body = audioRequestBody(model, request);
6080
7495
  const references = request.references ?? [];
6081
- if (references.length > 0) body.references = (await uploadReferences(runtime, call, model, references, body)).map((item) => item.asset.referenceUrl);
7496
+ if (references.length > 0) body.references = (await uploadReferences(runtime, call, model, references, body)).map((item) => model.audio?.references?.form === "object" ? { audio_url: item.asset.referenceUrl } : item.asset.referenceUrl);
6082
7497
  else if ((model.audio?.references?.min ?? 0) > 0) refuse(`${model.id} needs at least ${model.audio?.references?.min} reference audio file(s).`, "references");
6083
7498
  const quote = quoteAudio(model);
6084
7499
  const what = {
@@ -6747,7 +8162,13 @@ function describeVideoModel(model) {
6747
8162
  return `${MODE_LABEL[mode]}: ${describeInputs(constraint)}${options === "" ? "" : `; ${options}`}`;
6748
8163
  });
6749
8164
  const limits = [];
6750
- if (video.minReferenceVideoSeconds !== void 0 || video.maxReferenceVideoSeconds !== void 0) limits.push(`each reference video ${video.minReferenceVideoSeconds ?? 0}-${video.maxReferenceVideoSeconds ?? "∞"} s`);
8165
+ if (video.maxReferenceVideoSeconds !== void 0) limits.push(`each reference video ${video.minReferenceVideoSeconds ?? 0}-${video.maxReferenceVideoSeconds} s`);
8166
+ else {
8167
+ const derived = [...new Set(VIDEO_MODES.filter((mode) => (modes[mode]?.inputs.referenceVideos?.max ?? 0) > 0).flatMap((mode) => referenceVideoLimit(model, modes[mode])?.seconds ?? []))];
8168
+ const at = video.minReferenceVideoSeconds === void 0 ? "at most " : `${video.minReferenceVideoSeconds}-`;
8169
+ if (derived.length > 0) limits.push(`each reference video ${at}${derived.join("/")} s (the longest video it makes${derived.length > 1 ? " in each mode" : ""}; the catalog declares no limit)`);
8170
+ else if (video.minReferenceVideoSeconds !== void 0) limits.push(`each reference video at least ${video.minReferenceVideoSeconds} s`);
8171
+ }
6751
8172
  if (video.maxTotalReferenceVideoSeconds !== void 0) limits.push(`reference videos at most ${video.maxTotalReferenceVideoSeconds} s in total`);
6752
8173
  if (video.minReferenceAudioSeconds !== void 0 || video.maxReferenceAudioSeconds !== void 0) limits.push(`each reference audio ${video.minReferenceAudioSeconds ?? 0}-${video.maxReferenceAudioSeconds ?? "∞"} s`);
6753
8174
  if (video.combinations !== void 0) limits.push(`allowed combinations: ${video.combinations.map((c) => [
@@ -6907,16 +8328,45 @@ function referenceByteLimit(model, input) {
6907
8328
  return Math.min(kindMax ?? Infinity, video.maxAssetBytes ?? Infinity, MEDIA_LIBRARY_MAX_BYTES);
6908
8329
  }
6909
8330
  /**
8331
+ * The longest a reference video may be in a mode: the limit the catalog declares, else the longest video the model
8332
+ * makes in that mode (from its durations). The production lanes declare no per-clip limit (0), and their providers
8333
+ * refuse a reference clip longer than the longest output, so a 15.2 s clip on a 15 s lane would fail upstream.
8334
+ * @param model - the video model.
8335
+ * @param constraint - the chosen mode's declaration, whose durations come before the model's.
8336
+ * @returns the limit and whether the catalog declared it, or undefined when nothing bounds the clips.
8337
+ */
8338
+ function referenceVideoLimit(model, constraint) {
8339
+ const video = model.video ?? {};
8340
+ if (video.maxReferenceVideoSeconds !== void 0) return {
8341
+ seconds: video.maxReferenceVideoSeconds,
8342
+ declared: true
8343
+ };
8344
+ const durations = constraint?.durations ?? video.durations ?? (video.combinations ?? []).flatMap((combo) => combo.duration === void 0 ? [] : [combo.duration]);
8345
+ return durations.length === 0 ? void 0 : {
8346
+ seconds: Math.max(...durations),
8347
+ declared: false
8348
+ };
8349
+ }
8350
+ /** A measured length for a message: two decimals, or three when two would not show it is over the limit. */
8351
+ function lengthText(durationMs, limitSeconds) {
8352
+ const two = (durationMs / 1e3).toFixed(2);
8353
+ return limitSeconds !== void 0 && durationMs > limitSeconds * 1e3 && Number(two) <= limitSeconds ? (durationMs / 1e3).toFixed(3) : two;
8354
+ }
8355
+ /**
6910
8356
  * Check the measured lengths of the reference media once the gateway has
6911
8357
  * measured them. A reference's OWN length is what is checked — never the
6912
- * requested output duration — and only against the limits that model declares.
8358
+ * requested output duration — against the limits that model declares; a
8359
+ * reference video on a model that declares no per-clip limit is held to the
8360
+ * longest video the model makes in the chosen mode ({@link referenceVideoLimit}).
6913
8361
  * @param model - the video model.
6914
8362
  * @param videos - the uploaded reference videos, in order.
6915
8363
  * @param audios - the uploaded reference audios, in order.
8364
+ * @param plan - the checked plan: its mode decides the limit a model without a declared one gets.
6916
8365
  * @throws {@link MediaError} when a clip or the total is outside the model's limits.
6917
8366
  */
6918
- function checkReferenceDurations(model, videos, audios = []) {
8367
+ function checkReferenceDurations(model, videos, audios = [], plan) {
6919
8368
  const video = model.video ?? {};
8369
+ const limit = referenceVideoLimit(model, plan?.constraint);
6920
8370
  let totalMs = 0;
6921
8371
  for (const [index, clip] of videos.entries()) {
6922
8372
  if (clip.durationMs === void 0) {
@@ -6925,7 +8375,10 @@ function checkReferenceDurations(model, videos, audios = []) {
6925
8375
  }
6926
8376
  const seconds = clip.durationMs / 1e3;
6927
8377
  if (video.minReferenceVideoSeconds !== void 0 && seconds < video.minReferenceVideoSeconds) throw new MediaError(`Reference video ${index + 1} ("${clip.source}") is ${seconds.toFixed(2)} s; ${model.id} needs at least ${video.minReferenceVideoSeconds} s per clip.`, "REFERENCE_TOO_SHORT", { field: "reference_videos" });
6928
- if (video.maxReferenceVideoSeconds !== void 0 && seconds > video.maxReferenceVideoSeconds) throw new MediaError(`Reference video ${index + 1} ("${clip.source}") is ${seconds.toFixed(2)} s; ${model.id} takes at most ${video.maxReferenceVideoSeconds} s per clip. Trim it first.`, "REFERENCE_TOO_LONG", { field: "reference_videos" });
8378
+ if (limit !== void 0 && seconds > limit.seconds) {
8379
+ const what = limit.declared ? `takes at most ${limit.seconds} s per clip` : `takes reference videos of at most ${limit.seconds} s${plan === void 0 ? "" : ` in the ${plan.mode} mode`} (the longest video it makes${plan === void 0 ? "" : " there"}; the catalog declares no limit)`;
8380
+ throw new MediaError(`Reference video ${index + 1} ("${clip.source}") is ${lengthText(clip.durationMs, limit.seconds)} s; ${model.id} ${what}. Trim it to ${limit.seconds} s or less.`, "REFERENCE_TOO_LONG", { field: "reference_videos" });
8381
+ }
6929
8382
  totalMs += clip.durationMs;
6930
8383
  }
6931
8384
  if (video.maxTotalReferenceVideoSeconds !== void 0 && totalMs / 1e3 > video.maxTotalReferenceVideoSeconds) throw new MediaError(`The reference videos add up to ${(totalMs / 1e3).toFixed(2)} s; ${model.id} takes at most ${video.maxTotalReferenceVideoSeconds} s in total.`, "REFERENCE_TOTAL_TOO_LONG", { field: "reference_videos" });
@@ -7095,7 +8548,7 @@ async function prepareVideoTask(runtime, call, request, save) {
7095
8548
  bytes: item.media.data.byteLength,
7096
8549
  ...assets[index]?.durationMs === void 0 ? {} : { durationMs: assets[index]?.durationMs }
7097
8550
  }] : []);
7098
- checkReferenceDurations(model, videos, audios);
8551
+ checkReferenceDurations(model, videos, audios, plan);
7099
8552
  const urls = {};
7100
8553
  for (const [index, item] of loaded.entries()) {
7101
8554
  const asset = assets[index];
@@ -7208,7 +8661,7 @@ function videoGenerateTool(runtime) {
7208
8661
  reference_videos: {
7209
8662
  type: "array",
7210
8663
  items: { type: "string" },
7211
- description: `Reference videos for motion, camera work or effects (omni_reference; MP4 or MOV). Each is ${SOURCE_HELP}.`
8664
+ description: `Reference videos for motion, camera work or effects (omni_reference; MP4 or MOV). Each clip may be at most as long as media_models says for the model — where the catalog declares no limit, the longest video the model makes in that mode (15 s on a 4–15 s model) — so trim longer clips first. Each is ${SOURCE_HELP}.`
7212
8665
  },
7213
8666
  reference_audios: {
7214
8667
  type: "array",
@@ -9423,7 +10876,7 @@ const Config = Schema.object({
9423
10876
  displayName: "模型选择器里显示的名称",
9424
10877
  preferredModels: "排在最前的 VibeDev 模型(按顺序,留空按网关顺序)",
9425
10878
  openBrowserOnSignIn: "登录时自动打开系统浏览器",
9426
- catalogRefreshMinutes: "模型目录刷新间隔(分钟)",
10879
+ catalogRefreshMinutes: "模型目录定时刷新间隔(分钟;没人打开余额卡片、账号菜单或设置时的兜底)",
9427
10880
  confirmSpending: "每次付费生成前先询问(默认关闭)",
9428
10881
  outputDir: "保存目录(相对于工作区)",
9429
10882
  imageModel: "默认生图模型(留空由 Agent 按目录选择)",
@@ -9442,7 +10895,7 @@ const Config = Schema.object({
9442
10895
  displayName: "Name the model pickers show",
9443
10896
  preferredModels: "VibeDev models listed first, in this order (empty: the gateway's order)",
9444
10897
  openBrowserOnSignIn: "Open the system browser when signing in",
9445
- catalogRefreshMinutes: "Model catalog refresh interval (minutes)",
10898
+ catalogRefreshMinutes: "Model catalog refresh interval in minutes (the fallback when nobody opens the balance card, the account menu or Settings)",
9446
10899
  confirmSpending: "Ask before each paid generation (off by default)",
9447
10900
  outputDir: "Output folder (relative to the workspace)",
9448
10901
  imageModel: "Default image model (empty: the agent chooses from the catalog)",
@@ -9589,7 +11042,8 @@ function apply(ctx, config) {
9589
11042
  models: () => ({
9590
11043
  count: route?.models().length ?? 0,
9591
11044
  ...route?.hidden() === void 0 ? {} : { hidden: route.hidden() }
9592
- })
11045
+ }),
11046
+ refreshCatalog: () => route?.refresh() ?? Promise.resolve()
9593
11047
  });
9594
11048
  account = accountService;
9595
11049
  const latency = new LatencyProbe({
@@ -9599,6 +11053,18 @@ function apply(ctx, config) {
9599
11053
  ctx.inject(["connection"], (scoped) => {
9600
11054
  for (const accountRoute of [...accountRoutes(accountService), ...latencyRoutes(latency)]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
9601
11055
  });
11056
+ const feedback = installFeedback(ctx, {
11057
+ gateway: {
11058
+ origin,
11059
+ userAgent
11060
+ },
11061
+ gatewayDir: gatewayStateDirectory(stateDir, origin),
11062
+ pluginVersion: version,
11063
+ log: warn,
11064
+ identity: () => accountService.identity(),
11065
+ rejectCredential: (credential) => chain.reject(credential),
11066
+ onCredentialChange: (listener) => login.onChange(listener)
11067
+ });
9602
11068
  ctx.effect(() => {
9603
11069
  tracker.resume().catch((error) => {
9604
11070
  warn(`dsh-vibedev: resuming tasks failed: ${String(error)}`);
@@ -9622,6 +11088,7 @@ function apply(ctx, config) {
9622
11088
  for await (const _view of accountCtx.deepseekAccount.watch(controller.signal)) {
9623
11089
  runtime.invalidateCatalog();
9624
11090
  accountService.credentialChanged();
11091
+ feedback.uploader.credentialChanged();
9625
11092
  }
9626
11093
  } catch {}
9627
11094
  })();
@@ -9632,6 +11099,6 @@ function apply(ctx, config) {
9632
11099
  });
9633
11100
  }
9634
11101
  //#endregion
9635
- export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, version };
11102
+ export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, FEEDBACK_ATTACHMENT_ROUTE, FEEDBACK_ROUTE, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, version };
9636
11103
 
9637
11104
  //# sourceMappingURL=index.js.map