@vibedev-si/dsh-vibedev 0.3.4 → 0.3.6

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,8 +41,27 @@ 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
+ const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
44
45
  const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
46
+ /**
47
+ * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
48
+ * writes with an exponent are spelled out), a string as sent; anything else, or text that is not a plain decimal, is
49
+ * no amount at all.
50
+ */
51
+ function amountOf(value) {
52
+ let raw;
53
+ if (typeof value === "number") {
54
+ if (!Number.isFinite(value)) return void 0;
55
+ raw = String(value);
56
+ if (raw.includes("e")) raw = Math.abs(value) >= 1 ? BigInt(value).toString() : value.toFixed(20).replace(/0+$/, "").replace(/\.$/, "");
57
+ } else raw = text$8(value);
58
+ return raw !== void 0 && /^-?\d+(\.\d+)?$/.test(raw) ? raw : void 0;
59
+ }
60
+ /** What a read showed, for telling whether the next one changed anything (when it was read is not a change). */
61
+ const seenOf = (read) => JSON.stringify({
62
+ balance: read.balance,
63
+ user: read.user
64
+ });
45
65
  /** The account state behind the pages. */
46
66
  var AccountService = class {
47
67
  options;
@@ -58,6 +78,10 @@ var AccountService = class {
58
78
  epoch = 0;
59
79
  /** When the last read after a charge started, to space them out. */
60
80
  lastSpendReadAt = Number.NEGATIVE_INFINITY;
81
+ /** The last read that succeeded, kept for the pages while a later read fails. */
82
+ lastGood;
83
+ /** The latest read failed, after the last one that succeeded. */
84
+ failure;
61
85
  /**
62
86
  * @param options - origin, credential chain, the plugin's sign-in and the route's model state.
63
87
  */
@@ -90,6 +114,8 @@ var AccountService = class {
90
114
  this.balanceCache = void 0;
91
115
  this.revalidating = void 0;
92
116
  this.lastSeen = void 0;
117
+ this.lastGood = void 0;
118
+ this.failure = void 0;
93
119
  this.changed();
94
120
  }
95
121
  /**
@@ -163,16 +189,39 @@ var AccountService = class {
163
189
  ...base,
164
190
  revision: this.revision
165
191
  };
166
- const [grantUser, me] = await Promise.all([credential.kind === "plugin" ? this.options.login.user().catch(() => void 0) : Promise.resolve(void 0), this.me(credential.token, fresh)]);
192
+ 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)]);
193
+ const good = this.lastGood?.token === credential.token ? this.lastGood.read : void 0;
194
+ const me = read.balance === void 0 && good !== void 0 ? good : read;
167
195
  const user = me.user ?? userOf(grantUser);
196
+ const failedAt = this.failure?.token === credential.token ? this.failure.at : void 0;
168
197
  return {
169
198
  ...base,
170
199
  ...user === void 0 ? {} : { user },
171
200
  ...me.balance === void 0 ? {} : { balance: me.balance },
201
+ ...me.readAt === void 0 ? {} : { readAt: me.readAt },
202
+ ...failedAt === void 0 ? {} : { readFailedAt: failedAt },
172
203
  revision: this.revision
173
204
  };
174
205
  }
175
206
  /**
207
+ * Who is signed in now, with the VibeDev user id when it can be known (a recent `/auth/me` read is reused, as for
208
+ * the pages).
209
+ * @returns the identity.
210
+ */
211
+ async identity() {
212
+ const credential = await this.options.chain.resolve().catch(() => void 0);
213
+ if (credential === void 0) return { signedIn: false };
214
+ const read = await this.me(credential.token, false);
215
+ const good = this.lastGood?.token === credential.token ? this.lastGood.read : void 0;
216
+ let userId = read.user?.id ?? good?.user?.id;
217
+ if (userId === void 0 && credential.kind === "plugin") userId = (await this.options.login.user().catch(() => void 0))?.id;
218
+ return {
219
+ signedIn: true,
220
+ credential,
221
+ userId
222
+ };
223
+ }
224
+ /**
176
225
  * `GET /v1/account/auth/me` for one token. A read younger than the TTL is
177
226
  * reused; an older one is answered at once while a new read runs behind it.
178
227
  */
@@ -204,10 +253,11 @@ var AccountService = class {
204
253
  redirect: "error"
205
254
  });
206
255
  if (!response.ok) return {};
207
- const body = record$8(await response.json().catch(() => void 0));
208
- const data = record$8(body?.data) ?? body;
209
- const balance = typeof data?.balance === "number" && Number.isFinite(data.balance) ? String(data.balance) : text$8(data?.balance);
256
+ const body = record$9(await response.json().catch(() => void 0));
257
+ const data = record$9(body?.data) ?? body;
258
+ const balance = amountOf(data?.balance);
210
259
  const currency = text$8(data?.currency) ?? "CNY";
260
+ const frozen = amountOf(data?.frozen_balance);
211
261
  const id = typeof data?.id === "number" ? String(data.id) : text$8(data?.id);
212
262
  const nickname = text$8(data?.nickname) ?? text$8(data?.username);
213
263
  const email = text$8(data?.email);
@@ -217,10 +267,14 @@ var AccountService = class {
217
267
  ...nickname === void 0 ? {} : { nickname }
218
268
  };
219
269
  return {
220
- ...balance === void 0 || !/^-?\d+(\.\d+)?$/.test(balance) ? {} : { balance: {
221
- amount: balance,
222
- currency
223
- } },
270
+ ...balance === void 0 ? {} : {
271
+ balance: {
272
+ amount: balance,
273
+ currency,
274
+ ...frozen === void 0 ? {} : { frozen }
275
+ },
276
+ readAt: this.now()
277
+ },
224
278
  ...user === void 0 ? {} : { user }
225
279
  };
226
280
  } catch {
@@ -237,6 +291,10 @@ var AccountService = class {
237
291
  if (epoch !== this.epoch) return;
238
292
  if (read.balance === void 0) {
239
293
  if (this.balanceCache?.value === value) this.balanceCache = void 0;
294
+ this.failure = {
295
+ token,
296
+ at: this.now()
297
+ };
240
298
  return;
241
299
  }
242
300
  this.balanceCache = {
@@ -244,7 +302,12 @@ var AccountService = class {
244
302
  at: this.now(),
245
303
  value
246
304
  };
247
- const seen = JSON.stringify(read);
305
+ this.lastGood = {
306
+ token,
307
+ read
308
+ };
309
+ this.failure = void 0;
310
+ const seen = seenOf(read);
248
311
  if (this.lastSeen !== void 0 && this.lastSeen !== seen) {
249
312
  this.lastSeen = seen;
250
313
  this.changed();
@@ -298,7 +361,7 @@ function userOf(user) {
298
361
  ...nickname === void 0 ? {} : { nickname }
299
362
  };
300
363
  }
301
- function json(status, body) {
364
+ function json$2(status, body) {
302
365
  return new Response(JSON.stringify(body), {
303
366
  status,
304
367
  headers: {
@@ -308,9 +371,9 @@ function json(status, body) {
308
371
  });
309
372
  }
310
373
  function failure(error) {
311
- const candidate = record$8(error)?.code;
374
+ const candidate = record$9(error)?.code;
312
375
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
313
- return json(500, { error: {
376
+ return json$2(500, { error: {
314
377
  code,
315
378
  message: code === "SIGN_IN_CANCELLED" ? "Sign-in was cancelled. 登录已取消。" : code === "SIGN_IN_TIMEOUT" ? "Sign-in expired. 登录已超时,请重新登录。" : "The account request could not be completed. 账号请求未完成,请查看登录诊断后重试。"
316
379
  } });
@@ -331,7 +394,7 @@ function accountRoutes(account) {
331
394
  const query = new URL(request.url, "http://host").searchParams;
332
395
  const since = query.get("since");
333
396
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
334
- return json(200, await account.view(query.get("fresh") === "1"));
397
+ return json$2(200, await account.view(query.get("fresh") === "1"));
335
398
  } catch (error) {
336
399
  return failure(error);
337
400
  }
@@ -343,8 +406,8 @@ function accountRoutes(account) {
343
406
  requestBody: "buffered",
344
407
  fetch: async (request) => {
345
408
  try {
346
- const body = record$8(await request.json().catch(() => void 0));
347
- return json(200, await account.signIn(body?.open !== false));
409
+ const body = record$9(await request.json().catch(() => void 0));
410
+ return json$2(200, await account.signIn(body?.open !== false));
348
411
  } catch (error) {
349
412
  return failure(error);
350
413
  }
@@ -356,7 +419,7 @@ function accountRoutes(account) {
356
419
  requestBody: "buffered",
357
420
  fetch: () => {
358
421
  account.cancel();
359
- return Promise.resolve(json(200, { ok: true }));
422
+ return Promise.resolve(json$2(200, { ok: true }));
360
423
  }
361
424
  },
362
425
  {
@@ -365,7 +428,7 @@ function accountRoutes(account) {
365
428
  requestBody: "buffered",
366
429
  fetch: async () => {
367
430
  try {
368
- return await account.signOut() ? json(200, { ok: true }) : json(409, { error: {
431
+ return await account.signOut() ? json$2(200, { ok: true }) : json$2(409, { error: {
369
432
  code: "SIGNED_IN_BY_APP",
370
433
  message: "The VibeDev account is the app's sign-in; sign out in the app."
371
434
  } });
@@ -377,6 +440,479 @@ function accountRoutes(account) {
377
440
  ];
378
441
  }
379
442
  //#endregion
443
+ //#region src/account/latency.ts
444
+ /** Path of the latency route. */
445
+ const LATENCY_ROUTE = "/api/dsh-vibedev/latency";
446
+ /** Timed requests after the first one. */
447
+ const TIMED_REQUESTS = 4;
448
+ /** Each request gets this long, its body included. */
449
+ const REQUEST_TIMEOUT_MS$1 = 5e3;
450
+ /** A result is answered again for this long; `fresh` measures anyway. */
451
+ const RESULT_TTL_MS = 6e4;
452
+ /** One turn of the event loop, after which the previous request's connection is back in the pool. */
453
+ const pauseBriefly = () => new Promise((resolve) => {
454
+ setTimeout(resolve, 0);
455
+ });
456
+ var StatusError = class extends Error {
457
+ status;
458
+ constructor(status) {
459
+ super(`HTTP ${status}`);
460
+ this.status = status;
461
+ }
462
+ };
463
+ /**
464
+ * What stopped a request.
465
+ * @param error - what the request threw.
466
+ * @returns the error kind (and the status, for an HTTP answer).
467
+ */
468
+ function errorOf$1(error) {
469
+ if (error instanceof StatusError) return {
470
+ kind: "http",
471
+ status: error.status
472
+ };
473
+ const name = error?.name;
474
+ const code = error?.cause?.code;
475
+ if (name === "TimeoutError" || name === "AbortError" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "UND_ERR_HEADERS_TIMEOUT" || code === "UND_ERR_BODY_TIMEOUT" || code === "ETIMEDOUT") return { kind: "timeout" };
476
+ return { kind: "network" };
477
+ }
478
+ /** The middle value; for an even count, the mean of the two middle ones. */
479
+ function median(values) {
480
+ const sorted = [...values].sort((a, b) => a - b);
481
+ const upper = sorted[Math.floor(sorted.length / 2)] ?? 0;
482
+ return sorted.length % 2 === 1 ? upper : ((sorted[sorted.length / 2 - 1] ?? upper) + upper) / 2;
483
+ }
484
+ /** Measures the network latency to the gateway. */
485
+ var LatencyProbe = class {
486
+ options;
487
+ last;
488
+ running;
489
+ now;
490
+ clock;
491
+ /**
492
+ * @param options - the gateway origin, the plugin's user agent, and the fetch and clock seams.
493
+ */
494
+ constructor(options) {
495
+ this.options = options;
496
+ this.now = options.now ?? Date.now;
497
+ this.clock = options.clock ?? (() => performance.now());
498
+ }
499
+ /**
500
+ * The latency, measured now or within the last minute. One measurement runs at a time: a call while one runs
501
+ * shares it.
502
+ * @param fresh - measure again even when the last result is younger than a minute.
503
+ * @returns the result (a failure is a result too, with its error).
504
+ */
505
+ measure(fresh = false) {
506
+ if (this.running !== void 0) return this.running;
507
+ const last = this.last;
508
+ if (!fresh && last !== void 0 && this.now() - last.measuredAt < RESULT_TTL_MS) return Promise.resolve(last);
509
+ const running = this.run().then((result) => {
510
+ this.last = result;
511
+ return result;
512
+ }).finally(() => {
513
+ this.running = void 0;
514
+ });
515
+ this.running = running;
516
+ return running;
517
+ }
518
+ async run() {
519
+ const samples = [];
520
+ let warmup;
521
+ try {
522
+ warmup = await this.once();
523
+ for (let index = 0; index < TIMED_REQUESTS; index++) {
524
+ await (this.options.pause ?? pauseBriefly)();
525
+ samples.push(await this.once());
526
+ }
527
+ } catch (error) {
528
+ return {
529
+ samplesMs: samples,
530
+ ...warmup === void 0 ? {} : { warmupMs: warmup },
531
+ measuredAt: this.now(),
532
+ error: errorOf$1(error)
533
+ };
534
+ }
535
+ return {
536
+ medianMs: Math.round(median(samples)),
537
+ samplesMs: samples,
538
+ warmupMs: warmup,
539
+ measuredAt: this.now()
540
+ };
541
+ }
542
+ /** One `GET /health`, timed until its body has been read (which also lets the connection be reused). */
543
+ async once() {
544
+ const init = {
545
+ method: "GET",
546
+ headers: {
547
+ accept: "application/json",
548
+ "user-agent": this.options.userAgent
549
+ },
550
+ cache: "no-store",
551
+ redirect: "error",
552
+ signal: (this.options.timeout ?? ((ms) => AbortSignal.timeout(ms)))(REQUEST_TIMEOUT_MS$1)
553
+ };
554
+ const started = this.clock();
555
+ const response = await (this.options.fetch ?? globalThis.fetch)(`${this.options.origin}/health`, init);
556
+ await response.arrayBuffer();
557
+ const elapsed = Math.round(this.clock() - started);
558
+ if (!response.ok) throw new StatusError(response.status);
559
+ return elapsed;
560
+ }
561
+ };
562
+ function json$1(status, body) {
563
+ return new Response(JSON.stringify(body), {
564
+ status,
565
+ headers: {
566
+ "content-type": "application/json; charset=utf-8",
567
+ "cache-control": "no-store"
568
+ }
569
+ });
570
+ }
571
+ /**
572
+ * The latency route.
573
+ * @param probe - the probe.
574
+ * @returns routes for the client connection.
575
+ */
576
+ function latencyRoutes(probe) {
577
+ return [{
578
+ path: LATENCY_ROUTE,
579
+ methods: ["POST"],
580
+ requestBody: "buffered",
581
+ fetch: async (request) => {
582
+ try {
583
+ return json$1(200, await probe.measure(new URL(request.url, "http://host").searchParams.get("fresh") === "1"));
584
+ } catch {
585
+ return json$1(500, { error: {
586
+ code: "INTERNAL",
587
+ message: "The latency could not be measured. 网络延迟没有测成,请稍后重试。"
588
+ } });
589
+ }
590
+ }
591
+ }];
592
+ }
593
+ //#endregion
594
+ //#region src/feedback/wire.ts
595
+ /**
596
+ * The feedback upload contract: `POST {origin}/v1/account/feedback` with the
597
+ * account's credential (the one `GET /v1/account/auth/me` carries) and a
598
+ * strict JSON body — the gateway refuses unknown fields, so a body holds
599
+ * nothing else. Limits: text at most 4,000 code points, an attachment at most
600
+ * 256 KiB of UTF-8, the whole body at most 300 KiB; short fields carry no
601
+ * control characters. Text and attachments are measured as the gateway stores
602
+ * them, with U+0000 as U+FFFD.
603
+ * @module dsh-vibedev/feedback/wire
604
+ */
605
+ /** Gateway path of the upload. */
606
+ const FEEDBACK_PATH = "/v1/account/feedback";
607
+ /** The categories DeepSeek Harness files feedback under (`FEEDBACK_CATEGORIES` in @deepseek-ai/dsh-command-feedback). */
608
+ const FEEDBACK_CATEGORIES = [
609
+ "task-result",
610
+ "instruction-following",
611
+ "product-interaction",
612
+ "service-stability",
613
+ "resource-cost",
614
+ "security-privacy-permission",
615
+ "other"
616
+ ];
617
+ const MAX_TEXT_CODE_POINTS = 4e3;
618
+ const MAX_ATTACHMENT_BYTES = 262144;
619
+ const MAX_BODY_BYTES = 307200;
620
+ /** Control characters: C0, DEL and C1. */
621
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g;
622
+ /**
623
+ * Free text as the gateway stores and measures it: U+0000 becomes U+FFFD (PostgreSQL text cannot hold it), three bytes
624
+ * instead of one, before any limit is checked (submission.go sanitizeFreeText, then the size checks). Measuring the
625
+ * text as stored keeps an attachment near 256 KiB with NULs in it from being refused as too large.
626
+ * @param value - the text.
627
+ * @returns the text as it will be stored.
628
+ */
629
+ function asStored(value) {
630
+ return value.replaceAll("\0", "�");
631
+ }
632
+ /**
633
+ * A short field as the gateway accepts it: no control characters, trimmed, at most `max` code points.
634
+ * @param value - anything.
635
+ * @param max - the longest value, in code points.
636
+ * @returns the field, or undefined when nothing is left.
637
+ */
638
+ function shortField(value, max) {
639
+ if (typeof value !== "string") return void 0;
640
+ const cut = [...value.replace(CONTROL, "").trim()].slice(0, max).join("");
641
+ return cut === "" ? void 0 : cut;
642
+ }
643
+ /**
644
+ * Free text as the gateway accepts it: line breaks and tabs kept, U+0000 as the U+FFFD the gateway stores, other
645
+ * control characters dropped, trimmed, at most 4,000 code points.
646
+ * @param value - anything.
647
+ * @returns the text, or undefined when blank.
648
+ */
649
+ function feedbackText(value) {
650
+ if (typeof value !== "string") return void 0;
651
+ const cleaned = asStored(value).replace(/[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "").trim();
652
+ if (cleaned === "") return void 0;
653
+ return [...cleaned].slice(0, MAX_TEXT_CODE_POINTS).join("");
654
+ }
655
+ /** The number of code points, the unit the gateway counts text in. */
656
+ function codePoints(text) {
657
+ let count = 0;
658
+ for (const _ of text) count++;
659
+ return count;
660
+ }
661
+ /**
662
+ * Whether a value is one of the feedback categories.
663
+ * @param value - anything.
664
+ * @returns true for a category.
665
+ */
666
+ function isCategory(value) {
667
+ return typeof value === "string" && FEEDBACK_CATEGORIES.includes(value);
668
+ }
669
+ const TRUNCATED = "\n…[truncated]";
670
+ /**
671
+ * Text cut to at most `maxBytes` of UTF-8 on a code-point boundary, with a marker when anything was cut.
672
+ * @param content - the text.
673
+ * @param maxBytes - the budget.
674
+ * @returns the text, unchanged when it fits.
675
+ */
676
+ function fitUtf8(content, maxBytes) {
677
+ if (Buffer$1.byteLength(content, "utf8") <= maxBytes) return content;
678
+ const budget = Math.max(0, maxBytes - Buffer$1.byteLength(TRUNCATED, "utf8"));
679
+ let used = 0;
680
+ let end = 0;
681
+ for (const character of content) {
682
+ const size = Buffer$1.byteLength(character, "utf8");
683
+ if (used + size > budget) break;
684
+ used += size;
685
+ end += character.length;
686
+ }
687
+ return `${content.slice(0, end)}${TRUNCATED}`;
688
+ }
689
+ /**
690
+ * Whether a draft says anything the gateway accepts: text, a rating or a category.
691
+ * @param draft - the draft.
692
+ * @returns true when it can be sent.
693
+ */
694
+ function isSendable(draft) {
695
+ return draft.text !== void 0 || draft.rating !== void 0 || draft.category !== void 0;
696
+ }
697
+ /**
698
+ * The body for a draft: only the fields the contract names, none of them empty; the attachment cut to its limit and
699
+ * then, if need be, to what the whole body allows.
700
+ * @param id - the idempotency key.
701
+ * @param draft - what the feedback says.
702
+ * @param client - which app sent it.
703
+ * @returns the body.
704
+ */
705
+ function feedbackBody(id, draft, client) {
706
+ const sessionRef = shortField(draft.context?.sessionRef, 128);
707
+ const messageRef = shortField(draft.context?.messageRef, 128);
708
+ const text = feedbackText(draft.text);
709
+ const base = {
710
+ id,
711
+ source: draft.source,
712
+ ...draft.rating === void 0 ? {} : { rating: draft.rating },
713
+ ...draft.category === void 0 ? {} : { category: draft.category },
714
+ ...text === void 0 ? {} : { text },
715
+ client,
716
+ ...sessionRef === void 0 && messageRef === void 0 ? {} : { context: {
717
+ ...sessionRef === void 0 ? {} : { sessionRef },
718
+ ...messageRef === void 0 ? {} : { messageRef }
719
+ } }
720
+ };
721
+ const attachment = draft.attachment;
722
+ if (attachment === void 0 || attachment.content === "") return base;
723
+ let content = fitUtf8(asStored(attachment.content), MAX_ATTACHMENT_BYTES);
724
+ let body = {
725
+ ...base,
726
+ attachment: {
727
+ kind: attachment.kind,
728
+ consent: true,
729
+ content
730
+ }
731
+ };
732
+ for (let over = bodyBytes(body) - MAX_BODY_BYTES; over > 0; over = bodyBytes(body) - MAX_BODY_BYTES) {
733
+ content = fitUtf8(content, Buffer$1.byteLength(content, "utf8") - over - 64);
734
+ body = {
735
+ ...base,
736
+ attachment: {
737
+ kind: attachment.kind,
738
+ consent: true,
739
+ content
740
+ }
741
+ };
742
+ }
743
+ return body;
744
+ }
745
+ /**
746
+ * The same draft with its attachment cut to half (after the gateway refused the body as too large).
747
+ * @param body - the refused body.
748
+ * @param id - the new body's id (a changed body is a new upload).
749
+ * @returns the smaller body, or undefined when there is no attachment left to cut.
750
+ */
751
+ function halveAttachment(body, id) {
752
+ const attachment = body.attachment;
753
+ if (attachment === void 0) return void 0;
754
+ const stored = asStored(attachment.content);
755
+ const bytes = Buffer$1.byteLength(stored, "utf8");
756
+ if (bytes <= 1024) {
757
+ const { attachment: _dropped, ...rest } = body;
758
+ return {
759
+ ...rest,
760
+ id
761
+ };
762
+ }
763
+ return {
764
+ ...body,
765
+ id,
766
+ attachment: {
767
+ ...attachment,
768
+ content: fitUtf8(stored, Math.floor(bytes / 2))
769
+ }
770
+ };
771
+ }
772
+ /** The size of a body on the wire. */
773
+ function bodyBytes(body) {
774
+ return Buffer$1.byteLength(JSON.stringify(body), "utf8");
775
+ }
776
+ //#endregion
777
+ //#region src/feedback/client-info.ts
778
+ /**
779
+ * The `client` block of a feedback upload: which VibeDev app the Host serves,
780
+ * its version, the DeepSeek Harness and plugin versions, the operating system
781
+ * and the locale.
782
+ * @module dsh-vibedev/feedback/client-info
783
+ */
784
+ /**
785
+ * This process's facts.
786
+ * @returns the facts.
787
+ */
788
+ function hostFacts() {
789
+ let locale;
790
+ try {
791
+ locale = Intl.DateTimeFormat().resolvedOptions().locale;
792
+ } catch {
793
+ locale = void 0;
794
+ }
795
+ return {
796
+ versions: process.versions,
797
+ hasIpc: typeof process.send === "function",
798
+ execPath: process.execPath,
799
+ platform: process.platform,
800
+ arch: process.arch,
801
+ osRelease: release(),
802
+ locale
803
+ };
804
+ }
805
+ /**
806
+ * Which app the Host serves. The VibeDev desktop app starts its Host from the window process on its own executable in
807
+ * Electron's Node mode, with an IPC channel back (apps/desktop/src/host-process.ts: `spawn(process.execPath, …,
808
+ * { stdio: [..., 'ipc'] })`); in that mode `process.versions.electron` is still set. `vibedev-app web` runs the same
809
+ * executable from a terminal, without that channel, and a DeepSeek Harness install runs on Node: both serve the
810
+ * browser. (Checked against VibeDev 0.2.1-rc.2.20261019.3: Electron 44.7.0, `process.send` present only with IPC.)
811
+ * @param facts - the process facts.
812
+ * @returns `vibedev-desktop` or `vibedev-web`.
813
+ */
814
+ function hostApp(facts) {
815
+ return typeof facts.versions.electron === "string" && facts.hasIpc ? "vibedev-desktop" : "vibedev-web";
816
+ }
817
+ /**
818
+ * The desktop app's own version, from its manifest beside the executable (`resources/app.asar/package.json`; on macOS
819
+ * `Contents/Resources`), which Electron's Node mode reads like any file.
820
+ * @param facts - the process facts.
821
+ * @param read - reads a file as text (a test seam).
822
+ * @returns the version, or undefined when there is no manifest to read.
823
+ */
824
+ function desktopAppVersion(facts, read = (path) => readFileSync(path, "utf8")) {
825
+ const base = dirname(facts.execPath);
826
+ for (const manifest of [join(base, "resources", "app.asar", "package.json"), join(base, "..", "Resources", "app.asar", "package.json")]) try {
827
+ const version = JSON.parse(read(manifest)).version;
828
+ if (typeof version === "string" && version !== "") return version;
829
+ } catch {}
830
+ }
831
+ /**
832
+ * The client block for this Host.
833
+ * @param facts - the process facts.
834
+ * @param pluginVersion - this plugin's version.
835
+ * @param dshVersion - DeepSeek Harness's version (the LLM runtime's own manifest, as its User-Agent reports).
836
+ * @param read - reads the desktop manifest (a test seam).
837
+ * @returns the block, every field within the contract's limits.
838
+ */
839
+ function clientInfo(facts, pluginVersion, dshVersion = APP_IDENTITY.version, read) {
840
+ const app = hostApp(facts);
841
+ const appVersion = typeof facts.versions.electron === "string" ? shortField(desktopAppVersion(facts, read), 64) : void 0;
842
+ const platform = shortField(facts.platform, 32);
843
+ const osVersion = shortField(facts.osRelease, 128);
844
+ const arch = shortField(facts.arch, 32);
845
+ const locale = shortField(facts.locale, 64);
846
+ const dsh = shortField(dshVersion, 64);
847
+ const plugin = shortField(pluginVersion, 64);
848
+ return {
849
+ app,
850
+ ...appVersion === void 0 ? {} : { appVersion },
851
+ ...dsh === void 0 ? {} : { dshVersion: dsh },
852
+ ...plugin === void 0 ? {} : { pluginVersion: plugin },
853
+ ...platform === void 0 || osVersion === void 0 || arch === void 0 ? {} : { os: {
854
+ platform,
855
+ version: osVersion,
856
+ arch
857
+ } },
858
+ ...locale === void 0 ? {} : { locale }
859
+ };
860
+ }
861
+ //#endregion
862
+ //#region src/feedback/observe.ts
863
+ /**
864
+ * The feedback one newly appended event carries.
865
+ * @param owner - the Session the event was appended to.
866
+ * @param event - the event.
867
+ * @returns the draft, or undefined for anything else (another event, a deletion, inherited or empty feedback).
868
+ */
869
+ function draftFromEvent(owner, event) {
870
+ if (event.seq < owner.inheritedEventCount) return void 0;
871
+ let draft;
872
+ switch (event.type) {
873
+ case "feedback/record": {
874
+ const { text, category } = event.data;
875
+ draft = {
876
+ source: "command",
877
+ ...text === void 0 ? {} : { text },
878
+ ...isCategory(category) ? { category } : {},
879
+ context: { sessionRef: owner.id }
880
+ };
881
+ break;
882
+ }
883
+ case "feedback/message-put": {
884
+ if (event.data.sessionId !== owner.id) return void 0;
885
+ const { messageId, rating, note, category } = event.data.item;
886
+ draft = {
887
+ source: "message",
888
+ rating: rating === "positive" ? "up" : "down",
889
+ ...isCategory(category) ? { category } : {},
890
+ ...note === void 0 ? {} : { text: note },
891
+ context: {
892
+ sessionRef: event.data.sessionId,
893
+ messageRef: messageId
894
+ }
895
+ };
896
+ break;
897
+ }
898
+ default: return;
899
+ }
900
+ return isSendable(draft) ? draft : void 0;
901
+ }
902
+ /**
903
+ * The feedback a committed write to a Session that is not open carries: the inspection's last event.
904
+ * @param inspection - the committed log, the feedback last.
905
+ * @returns the draft, or undefined.
906
+ */
907
+ function draftFromCommitted(inspection) {
908
+ const last = inspection.events.at(-1);
909
+ if (last === void 0) return void 0;
910
+ return draftFromEvent({
911
+ id: inspection.meta.id,
912
+ inheritedEventCount: inspection.inheritedEventCount
913
+ }, last);
914
+ }
915
+ //#endregion
380
916
  //#region src/gateway/errors.ts
381
917
  /**
382
918
  * Failures the plugin reports to the model: a gateway refusal, or a request the
@@ -403,7 +939,7 @@ var MediaError = class extends HarnessError {
403
939
  this.details = details;
404
940
  }
405
941
  };
406
- function record$7(value) {
942
+ function record$8(value) {
407
943
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
408
944
  }
409
945
  function text$7(value) {
@@ -421,19 +957,22 @@ function amount$1(value) {
421
957
  /**
422
958
  * Read a gateway error body. The gateway answers in several shapes: OpenAI's
423
959
  * `{error:{code,message,type}}`, its own `{error:{code,message,retryable,field}}`,
424
- * the account API's `{code,message,reason}`, and a top-level `recharge_url` on
425
- * balance refusals. Media admission refusals add `active`/`limit` (task limit)
426
- * or `estimated_cny`/`available_cny`/`pending_cny` (balance).
960
+ * the account API's `{code,message,reason,metadata}` (a validation refusal names
961
+ * the field and the rule there: `metadata: {field, rule}`), and a top-level
962
+ * `recharge_url` on balance refusals. Media admission refusals add
963
+ * `active`/`limit` (task limit) or `estimated_cny`/`available_cny`/`pending_cny` (balance).
427
964
  * @param body - the parsed JSON body, or undefined when it was not JSON.
428
965
  * @returns the fields found.
429
966
  */
430
967
  function parseGatewayFailure(body) {
431
- const root = record$7(body);
968
+ const root = record$8(body);
432
969
  if (root === void 0) return {};
433
- const source = record$7(root.error) ?? root;
970
+ const source = record$8(root.error) ?? root;
971
+ const metadata = record$8(source.metadata) ?? record$8(root.metadata);
434
972
  const code = text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
435
973
  const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
436
- const field = text$7(source.field);
974
+ const field = text$7(source.field) ?? text$7(metadata?.field);
975
+ const rule = text$7(source.rule) ?? text$7(metadata?.rule);
437
976
  const rechargeUrl = text$7(source.recharge_url) ?? text$7(root.recharge_url);
438
977
  const numbers = {
439
978
  active: count$1(source.active),
@@ -446,14 +985,17 @@ function parseGatewayFailure(body) {
446
985
  };
447
986
  const submissionState = text$7(source.submission_state) ?? text$7(root.submission_state);
448
987
  const retryAction = text$7(source.retry_action) ?? text$7(root.retry_action);
988
+ const assetId = text$7(source.asset_id) ?? text$7(root.asset_id);
449
989
  return {
450
990
  ...code === void 0 ? {} : { code },
451
991
  ...message === void 0 ? {} : { message },
452
992
  ...field === void 0 ? {} : { field },
993
+ ...rule === void 0 ? {} : { rule },
453
994
  ...typeof source.retryable === "boolean" ? { retryable: source.retryable } : {},
454
995
  ...submissionState === void 0 ? {} : { submissionState: submissionState.toLowerCase() },
455
996
  ...retryAction === void 0 ? {} : { retryAction: retryAction.toLowerCase() },
456
997
  ...rechargeUrl === void 0 ? {} : { rechargeUrl },
998
+ ...assetId === void 0 ? {} : { assetId },
457
999
  ...Object.fromEntries(Object.entries({
458
1000
  ...numbers,
459
1001
  ...amounts
@@ -553,109 +1095,1195 @@ async function renameWithRetry(from, to) {
553
1095
  await new Promise((resolve) => setTimeout(resolve, 50 * 2 ** attempt));
554
1096
  }
555
1097
  }
556
- /**
557
- * Move a complete temporary file to the first free name `dir/stem.ext`
558
- * (then `stem-2.ext`, ...), never replacing an existing file.
559
- * @param temporary - the complete file.
560
- * @param dir - the destination directory, created when missing.
561
- * @param stem - the file-name stem.
562
- * @param extension - the extension, without a dot.
563
- * @returns the final path.
564
- */
565
- async function placeFile(temporary, dir, stem, extension) {
566
- await mkdir(dir, { recursive: true });
567
- let linkable = true;
568
- for (let attempt = 1; attempt < 1e3; attempt++) {
569
- const path = join(dir, `${attempt === 1 ? stem : `${stem}-${attempt}`}.${extension}`);
570
- if (linkable) try {
571
- await link(temporary, path);
572
- await rm(temporary, { force: true });
573
- return path;
574
- } catch (error) {
575
- if (error.code === "EEXIST") continue;
576
- linkable = false;
1098
+ /**
1099
+ * Move a complete temporary file to the first free name `dir/stem.ext`
1100
+ * (then `stem-2.ext`, ...), never replacing an existing file.
1101
+ * @param temporary - the complete file.
1102
+ * @param dir - the destination directory, created when missing.
1103
+ * @param stem - the file-name stem.
1104
+ * @param extension - the extension, without a dot.
1105
+ * @returns the final path.
1106
+ */
1107
+ async function placeFile(temporary, dir, stem, extension) {
1108
+ await mkdir(dir, { recursive: true });
1109
+ let linkable = true;
1110
+ for (let attempt = 1; attempt < 1e3; attempt++) {
1111
+ const path = join(dir, `${attempt === 1 ? stem : `${stem}-${attempt}`}.${extension}`);
1112
+ if (linkable) try {
1113
+ await link(temporary, path);
1114
+ await rm(temporary, { force: true });
1115
+ return path;
1116
+ } catch (error) {
1117
+ if (error.code === "EEXIST") continue;
1118
+ linkable = false;
1119
+ }
1120
+ try {
1121
+ await (await open(path, "wx")).close();
1122
+ } catch (error) {
1123
+ if (error.code === "EEXIST") continue;
1124
+ throw error;
1125
+ }
1126
+ await renameWithRetry(temporary, path);
1127
+ return path;
1128
+ }
1129
+ throw new MediaError(`Could not find a free file name for "${stem}.${extension}" in ${dir}.`, "OUTPUT_NAME_EXHAUSTED");
1130
+ }
1131
+ /**
1132
+ * Save bytes under the first free name `dir/stem.ext`.
1133
+ * @param dir - the destination directory.
1134
+ * @param stem - the file-name stem.
1135
+ * @param extension - the extension, without a dot.
1136
+ * @param data - the content.
1137
+ * @returns the final path.
1138
+ */
1139
+ async function saveNewFile(dir, stem, extension, data) {
1140
+ await mkdir(dir, { recursive: true });
1141
+ const temporary = join(dir, `.dsh-media-${randomUUID()}.part`);
1142
+ try {
1143
+ await writeFile(temporary, data);
1144
+ return await placeFile(temporary, dir, stem, extension);
1145
+ } finally {
1146
+ await rm(temporary, { force: true });
1147
+ }
1148
+ }
1149
+ /**
1150
+ * Write bytes atomically, replacing the file.
1151
+ * @param path - the final path.
1152
+ * @param data - the content.
1153
+ * @param options - `mode` for a file only its owner may read.
1154
+ */
1155
+ async function writeFileAtomic(path, data, options = {}) {
1156
+ await mkdir(dirname(path), { recursive: true });
1157
+ const temporary = join(dirname(path), `.${randomUUID()}.part`);
1158
+ try {
1159
+ await writeFile(temporary, data, options.mode === void 0 ? {} : { mode: options.mode });
1160
+ await renameWithRetry(temporary, path);
1161
+ } catch (error) {
1162
+ await rm(temporary, { force: true });
1163
+ throw error;
1164
+ }
1165
+ }
1166
+ /**
1167
+ * Stream a response body into a temporary file, replacing what was there.
1168
+ * @param response - a successful response whose body is unread.
1169
+ * @param temporary - where to write; the caller moves it into place when this resolves.
1170
+ * @param maxBytes - the largest accepted body.
1171
+ * @param signal - cancels the download.
1172
+ * @returns the number of bytes written.
1173
+ */
1174
+ async function downloadTo(response, temporary, maxBytes, signal) {
1175
+ const declared = Number(response.headers.get("content-length"));
1176
+ if (Number.isFinite(declared) && declared > maxBytes) {
1177
+ await response.body?.cancel().catch(() => void 0);
1178
+ 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");
1179
+ }
1180
+ await mkdir(dirname(temporary), { recursive: true });
1181
+ await rm(temporary, { force: true });
1182
+ if (response.body === null) {
1183
+ const data = new Uint8Array(await response.arrayBuffer());
1184
+ if (data.byteLength > maxBytes) throw new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE");
1185
+ await writeFile(temporary, data);
1186
+ return data.byteLength;
1187
+ }
1188
+ let total = 0;
1189
+ const limit = new Transform({ transform(chunk, _encoding, callback) {
1190
+ total += chunk.byteLength;
1191
+ if (total > maxBytes) callback(new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE"));
1192
+ else callback(null, chunk);
1193
+ } });
1194
+ try {
1195
+ await pipeline(Readable.fromWeb(response.body), limit, createWriteStream(temporary), signal === void 0 ? {} : { signal });
1196
+ return total;
1197
+ } catch (error) {
1198
+ await rm(temporary, { force: true }).catch(() => void 0);
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ const SOURCES = /* @__PURE__ */ new Set([
1203
+ "message",
1204
+ "command",
1205
+ "menu"
1206
+ ]);
1207
+ /** Whether something read from disk names an owner this version knows. */
1208
+ function isOwner(value) {
1209
+ const owner = value;
1210
+ if (typeof owner !== "object" || owner === null) return false;
1211
+ return owner.kind === "user" ? typeof owner.id === "string" && owner.id !== "" : owner.kind === "signed-out" || owner.kind === "unidentified";
1212
+ }
1213
+ /** Whether something read from disk is an item this version can send (an item without an owner is never sent). */
1214
+ function isItem(value) {
1215
+ const item = value;
1216
+ const body = item?.body;
1217
+ 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";
1218
+ }
1219
+ /** The persistent queue. All changes are serialized; reads see the latest state. */
1220
+ var FeedbackQueue = class {
1221
+ file;
1222
+ options;
1223
+ state = [];
1224
+ loading;
1225
+ writing = Promise.resolve();
1226
+ now;
1227
+ /**
1228
+ * @param file - the queue file.
1229
+ * @param options - caps and the clock (test seams).
1230
+ */
1231
+ constructor(file, options = {}) {
1232
+ this.file = file;
1233
+ this.options = options;
1234
+ this.now = options.now ?? Date.now;
1235
+ }
1236
+ /** Read the file once; a missing or unreadable file is an empty queue (and is replaced on the next change). */
1237
+ load() {
1238
+ this.loading ??= (async () => {
1239
+ let parsed;
1240
+ try {
1241
+ parsed = JSON.parse(await readFile(this.file, "utf8"));
1242
+ } catch {
1243
+ parsed = void 0;
1244
+ }
1245
+ const items = parsed?.items;
1246
+ this.state = Array.isArray(items) ? items.filter(isItem) : [];
1247
+ if (this.prune()) await this.save();
1248
+ })();
1249
+ return this.loading;
1250
+ }
1251
+ /** The waiting items, oldest first. */
1252
+ items() {
1253
+ return this.state;
1254
+ }
1255
+ /**
1256
+ * Queue one body at the end.
1257
+ * @param body - the exact body to send.
1258
+ * @param owner - the VibeDev account it belongs to.
1259
+ */
1260
+ async add(body, owner) {
1261
+ await this.load();
1262
+ const before = this.state;
1263
+ this.state = [...this.state, {
1264
+ body,
1265
+ owner,
1266
+ enqueuedAt: this.now(),
1267
+ attempts: 0,
1268
+ nextAt: 0
1269
+ }];
1270
+ this.prune();
1271
+ try {
1272
+ await this.save();
1273
+ } catch (error) {
1274
+ this.state = before;
1275
+ throw error;
1276
+ }
1277
+ }
1278
+ /**
1279
+ * Record how an attempt ended without a final answer.
1280
+ * @param id - the item's body id.
1281
+ * @param change - the attempt count, when to try next, and what it ended with.
1282
+ */
1283
+ async update(id, change) {
1284
+ await this.load();
1285
+ this.state = this.state.map((item) => item.body.id === id ? {
1286
+ ...item,
1287
+ ...change
1288
+ } : item);
1289
+ await this.save();
1290
+ }
1291
+ /**
1292
+ * Give an item to an account (feedback given signed out, or by an account not identified then, on its first
1293
+ * attempt): from now on it goes out under that account only.
1294
+ * @param id - the item's body id.
1295
+ * @param owner - the account.
1296
+ */
1297
+ async bind(id, owner) {
1298
+ await this.load();
1299
+ this.state = this.state.map((item) => item.body.id === id ? {
1300
+ ...item,
1301
+ owner
1302
+ } : item);
1303
+ await this.save();
1304
+ }
1305
+ /**
1306
+ * Put a new body in an item's place (the gateway asked for a smaller one): same position and owner, attempts start
1307
+ * over.
1308
+ * @param id - the item's current body id.
1309
+ * @param body - the new body.
1310
+ */
1311
+ async replace(id, body) {
1312
+ await this.load();
1313
+ this.state = this.state.map((item) => item.body.id === id ? {
1314
+ body,
1315
+ owner: item.owner,
1316
+ enqueuedAt: item.enqueuedAt,
1317
+ attempts: 0,
1318
+ nextAt: 0
1319
+ } : item);
1320
+ await this.save();
1321
+ }
1322
+ /**
1323
+ * Take an item out (sent, or refused for good).
1324
+ * @param id - the item's body id.
1325
+ */
1326
+ async remove(id) {
1327
+ await this.load();
1328
+ this.state = this.state.filter((item) => item.body.id !== id);
1329
+ await this.save();
1330
+ }
1331
+ /**
1332
+ * Apply the caps: too old first, then the oldest past the count, then the oldest past the size.
1333
+ * @returns whether anything was dropped.
1334
+ */
1335
+ prune() {
1336
+ const before = this.state.length;
1337
+ const maxAge = this.options.maxAgeMs ?? 2592e6;
1338
+ const now = this.now();
1339
+ let items = this.state.filter((item) => now - item.enqueuedAt <= maxAge);
1340
+ const maxItems = this.options.maxItems ?? 200;
1341
+ if (items.length > maxItems) items = items.slice(items.length - maxItems);
1342
+ const maxBytes = this.options.maxBytes ?? 4194304;
1343
+ let total = items.reduce((sum, item) => sum + bodyBytes(item.body), 0);
1344
+ while (items.length > 1 && total > maxBytes) {
1345
+ total -= bodyBytes(items[0].body);
1346
+ items = items.slice(1);
1347
+ }
1348
+ this.state = items;
1349
+ return items.length !== before;
1350
+ }
1351
+ /** Write the current state; owner-only from creation, replaced atomically, one write at a time. */
1352
+ save() {
1353
+ const snapshot = {
1354
+ version: 1,
1355
+ items: this.state
1356
+ };
1357
+ const write = this.writing.then(() => writeFileAtomic(this.file, new TextEncoder().encode(JSON.stringify(snapshot)), { mode: 384 }));
1358
+ this.writing = write.catch(() => void 0);
1359
+ return write;
1360
+ }
1361
+ };
1362
+ //#endregion
1363
+ //#region src/feedback/recent-errors.ts
1364
+ const MAX_ENTRIES = 50;
1365
+ const MAX_MESSAGE = 500;
1366
+ /** Tool names remembered for calls whose result has not come back yet. */
1367
+ const MAX_PENDING_CALLS = 256;
1368
+ const oneLine = (text, max = MAX_MESSAGE) => {
1369
+ const flat = text.replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ").replace(/\s+/g, " ").trim();
1370
+ const characters = [...flat];
1371
+ return characters.length <= max ? flat : `${characters.slice(0, max).join("")}…`;
1372
+ };
1373
+ /** The last failures this Host saw. */
1374
+ var RecentErrors = class {
1375
+ entries = [];
1376
+ toolNames = /* @__PURE__ */ new Map();
1377
+ now;
1378
+ max;
1379
+ /**
1380
+ * @param options - how many failures to keep, and the clock (test seams).
1381
+ */
1382
+ constructor(options = {}) {
1383
+ this.max = options.max ?? MAX_ENTRIES;
1384
+ this.now = options.now ?? Date.now;
1385
+ }
1386
+ /**
1387
+ * Note one appended event.
1388
+ * @param session - the Session it was appended to.
1389
+ * @param event - the event.
1390
+ */
1391
+ observe(session, event) {
1392
+ switch (event.type) {
1393
+ case "tool/call":
1394
+ this.toolNames.delete(event.data.callId);
1395
+ this.toolNames.set(event.data.callId, event.data.name);
1396
+ if (this.toolNames.size > MAX_PENDING_CALLS) this.toolNames.delete(this.toolNames.keys().next().value);
1397
+ break;
1398
+ case "tool/result": {
1399
+ const { message, error } = event.data;
1400
+ const tool = this.toolNames.get(message.toolCallId);
1401
+ this.toolNames.delete(message.toolCallId);
1402
+ if (message.isError !== true) break;
1403
+ const said = message.content.flatMap((block) => block.type === "text" ? [block.text] : []).join(" ");
1404
+ this.push({
1405
+ at: this.now(),
1406
+ sessionRef: session.id,
1407
+ kind: "tool",
1408
+ tool: tool ?? "unknown tool",
1409
+ ...error?.code === void 0 ? {} : { code: error.code },
1410
+ message: oneLine(error?.reason ?? (said || error?.name || "failed"))
1411
+ });
1412
+ break;
1413
+ }
1414
+ case "turn/end": {
1415
+ const reason = event.data.reason;
1416
+ if (reason.kind !== "error") break;
1417
+ this.push({
1418
+ at: this.now(),
1419
+ sessionRef: session.id,
1420
+ kind: "model",
1421
+ code: reason.error.code,
1422
+ ...reason.error.status === void 0 ? {} : { status: reason.error.status },
1423
+ message: oneLine(reason.error.message)
1424
+ });
1425
+ break;
1426
+ }
1427
+ }
1428
+ }
1429
+ push(entry) {
1430
+ this.entries.push(entry);
1431
+ if (this.entries.length > this.max) this.entries.splice(0, this.entries.length - this.max);
1432
+ }
1433
+ /** The kept failures, newest first. */
1434
+ list() {
1435
+ return [...this.entries].reverse();
1436
+ }
1437
+ /**
1438
+ * The attachment text: a header, then one line per failure, newest first, cut to the attachment limit (so what
1439
+ * gives way first is the oldest).
1440
+ * @returns the text, its line count and its size; empty when nothing failed.
1441
+ */
1442
+ attachment() {
1443
+ const list = this.list();
1444
+ if (list.length === 0) return {
1445
+ content: "",
1446
+ entries: 0,
1447
+ bytes: 0
1448
+ };
1449
+ const lines = list.map((entry) => {
1450
+ const what = entry.kind === "tool" ? `tool ${oneLine(entry.tool ?? "", 80)}` : "model";
1451
+ const code = [entry.code, entry.status === void 0 ? void 0 : `HTTP ${entry.status}`].filter(Boolean).join(" ");
1452
+ return `${new Date(entry.at).toISOString()} session ${entry.sessionRef} ${what}${code === "" ? "" : ` [${code}]`} ${entry.message}`;
1453
+ });
1454
+ const content = fitUtf8(`Recent errors in VibeDev (newest first, ${list.length})\n${lines.join("\n")}`, MAX_ATTACHMENT_BYTES);
1455
+ return {
1456
+ content,
1457
+ entries: list.length,
1458
+ bytes: Buffer$1.byteLength(content, "utf8")
1459
+ };
1460
+ }
1461
+ };
1462
+ //#endregion
1463
+ //#region src/feedback/routes.ts
1464
+ /**
1465
+ * The feedback dialog's Host routes (answers are never cached):
1466
+ *
1467
+ * - `GET /api/dsh-vibedev/feedback/attachment` — the exact text the "attach
1468
+ * recent errors" box would send, its line count and size;
1469
+ * - `POST /api/dsh-vibedev/feedback` — `{ category?, text?, attachment?:
1470
+ * { content }, locale? }`: queued as `source: 'menu'` (an attachment only as
1471
+ * an `error-log` the user consented to by ticking the box) and sent at once
1472
+ * when it can be; answers `sent`, `queued` (with why) or `rejected`. Nothing
1473
+ * is queued while nobody is signed in: feedback goes with the VibeDev
1474
+ * account, never anonymously.
1475
+ * @module dsh-vibedev/feedback/routes
1476
+ */
1477
+ const FEEDBACK_ROUTE = "/api/dsh-vibedev/feedback";
1478
+ const FEEDBACK_ATTACHMENT_ROUTE = "/api/dsh-vibedev/feedback/attachment";
1479
+ function json(status, body) {
1480
+ return new Response(JSON.stringify(body), {
1481
+ status,
1482
+ headers: {
1483
+ "content-type": "application/json; charset=utf-8",
1484
+ "cache-control": "no-store"
1485
+ }
1486
+ });
1487
+ }
1488
+ const invalid = (field) => json(400, { error: {
1489
+ code: "FEEDBACK_INVALID",
1490
+ field
1491
+ } });
1492
+ const record$7 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1493
+ /**
1494
+ * The feedback routes.
1495
+ * @param options - the uploader's submit, the recent errors and the credential check.
1496
+ * @returns routes for the client connection.
1497
+ */
1498
+ function feedbackRoutes(options) {
1499
+ return [{
1500
+ path: FEEDBACK_ATTACHMENT_ROUTE,
1501
+ methods: ["GET"],
1502
+ requestBody: "buffered",
1503
+ fetch: () => Promise.resolve(json(200, options.errors.attachment()))
1504
+ }, {
1505
+ path: FEEDBACK_ROUTE,
1506
+ methods: ["POST"],
1507
+ requestBody: "buffered",
1508
+ fetch: async (request) => {
1509
+ try {
1510
+ const body = record$7(await request.json().catch(() => void 0));
1511
+ if (body === void 0) return invalid("body");
1512
+ if (body.category !== void 0 && body.category !== null && !isCategory(body.category)) return invalid("category");
1513
+ if (body.text !== void 0 && typeof body.text !== "string") return invalid("text");
1514
+ if (typeof body.text === "string" && codePoints(body.text.trim()) > 4e3) return invalid("text");
1515
+ const text = feedbackText(body.text);
1516
+ const category = isCategory(body.category) ? body.category : void 0;
1517
+ if (text === void 0 && category === void 0) return invalid("text");
1518
+ let content;
1519
+ if (body.attachment !== void 0 && body.attachment !== null) {
1520
+ const given = record$7(body.attachment)?.content;
1521
+ if (typeof given !== "string" || given === "" || Buffer$1.byteLength(given, "utf8") > 262144) return invalid("attachment");
1522
+ content = given;
1523
+ }
1524
+ if (!await options.hasCredential()) return json(409, { error: { code: "SIGNED_OUT" } });
1525
+ return json(200, await options.submit({
1526
+ source: "menu",
1527
+ ...category === void 0 ? {} : { category },
1528
+ ...text === void 0 ? {} : { text },
1529
+ ...content === void 0 ? {} : { attachment: {
1530
+ kind: "error-log",
1531
+ consent: true,
1532
+ content
1533
+ } }
1534
+ }, shortField(body.locale, 64)));
1535
+ } catch {
1536
+ return json(500, { error: { code: "INTERNAL" } });
1537
+ }
1538
+ }
1539
+ }];
1540
+ }
1541
+ //#endregion
1542
+ //#region src/gateway/http.ts
1543
+ /**
1544
+ * HTTP client for the VibeDev gateway. Every gateway call goes through here so
1545
+ * authentication, refresh after a 401, balance refusals, busy back-off and
1546
+ * idempotency are handled once.
1547
+ *
1548
+ * The credential is attached only to requests on the gateway origin: upload
1549
+ * URLs and third-party links never see it.
1550
+ * @module dsh-vibedev/gateway/http
1551
+ */
1552
+ /** Error codes the gateway uses for "full right now, nothing was charged". */
1553
+ const BUSY_CODES = /* @__PURE__ */ new Set([
1554
+ "APP_TOKEN_UNAVAILABLE",
1555
+ "PROVIDER_CAPACITY_BUSY",
1556
+ "upstream_capacity_busy",
1557
+ "AUDIO_CAPACITY_BUSY",
1558
+ "AUDIO_NO_AVAILABLE_ACCOUNT",
1559
+ "WEB_SEARCH_BUSY",
1560
+ "WEB_SEARCH_RATE_LIMITED"
1561
+ ]);
1562
+ /**
1563
+ * The account already runs as many video or audio tasks as it may (HTTP 429).
1564
+ * Not retried here: a slot frees only when one of the user's tasks finishes.
1565
+ */
1566
+ const TASK_LIMIT_CODES = /* @__PURE__ */ new Set(["VIDEO_TASK_LIMIT_REACHED", "AUDIO_TASK_LIMIT_REACHED"]);
1567
+ const DEFAULT_TIMEOUT_MS = 6e4;
1568
+ const DEFAULT_BUSY_WAIT_MS = 2e3;
1569
+ /** The message for a call made while nobody is signed in. */
1570
+ 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.";
1571
+ /** Read through a call so a check made before an `await` is not taken as still true after it. */
1572
+ function isAborted(signal) {
1573
+ return signal?.aborted === true;
1574
+ }
1575
+ /**
1576
+ * Wait, ending early (with {@link abortError}) when the signal aborts.
1577
+ * @param ms - how long.
1578
+ * @param signal - cancels the wait.
1579
+ */
1580
+ function delay$1(ms, signal) {
1581
+ return new Promise((resolve, reject) => {
1582
+ if (isAborted(signal)) {
1583
+ reject(abortError(signal));
1584
+ return;
1585
+ }
1586
+ const timer = setTimeout(() => {
1587
+ signal?.removeEventListener("abort", onAbort);
1588
+ resolve();
1589
+ }, ms);
1590
+ const onAbort = () => {
1591
+ clearTimeout(timer);
1592
+ reject(abortError(signal));
1593
+ };
1594
+ signal?.addEventListener("abort", onAbort, { once: true });
1595
+ });
1596
+ }
1597
+ /**
1598
+ * The error a cancelled media request ends with.
1599
+ * @param signal - the signal that aborted; its reason is the cause.
1600
+ * @returns the error (`ABORTED`).
1601
+ */
1602
+ function abortError(signal) {
1603
+ return new MediaError("The media request was cancelled.", "ABORTED", { retryable: true }, { cause: signal?.reason });
1604
+ }
1605
+ /** Gateway HTTP client. */
1606
+ var GatewayHttp = class {
1607
+ options;
1608
+ origin;
1609
+ /**
1610
+ * @param options - origin, credential plane, user agent and test seams.
1611
+ */
1612
+ constructor(options) {
1613
+ this.options = options;
1614
+ this.origin = options.origin.trim().replace(/\/+$/, "");
1615
+ }
1616
+ /** Absolute URL for a gateway path, or the URL itself when already absolute. */
1617
+ url(path) {
1618
+ return /^https?:\/\//i.test(path) ? path : `${this.origin}${path.startsWith("/") ? "" : "/"}${path}`;
1619
+ }
1620
+ /** Whether a URL is on the gateway origin, and so may carry the credential. */
1621
+ isGatewayUrl(url) {
1622
+ try {
1623
+ return new URL(url).origin === new URL(this.origin).origin;
1624
+ } catch {
1625
+ return false;
1626
+ }
1627
+ }
1628
+ /**
1629
+ * Send one request and return the successful response.
1630
+ * @param path - gateway path, or an absolute URL.
1631
+ * @param request - method, body, headers and retry policy.
1632
+ * @returns the 2xx response, body unread.
1633
+ * @throws {@link MediaError} for every refusal, with the gateway's code.
1634
+ */
1635
+ async send(path, request = {}) {
1636
+ const url = this.url(path);
1637
+ const authenticate = request.anonymous !== true && this.isGatewayUrl(url);
1638
+ let credential = authenticate ? await this.credential() : void 0;
1639
+ let refreshed = false;
1640
+ let busyRetries = request.busyRetries ?? 2;
1641
+ for (;;) {
1642
+ const response = await this.attempt(url, request, credential);
1643
+ if (response.ok) {
1644
+ if (authenticate) try {
1645
+ this.options.onAccepted?.({
1646
+ method: request.method ?? "GET",
1647
+ path: new URL(url).pathname
1648
+ });
1649
+ } catch {}
1650
+ return response;
1651
+ }
1652
+ const failure = parseGatewayFailure(await response.clone().json().catch(() => void 0));
1653
+ if (response.status === 401 && credential !== void 0 && credential.kind !== "key" && !refreshed) {
1654
+ refreshed = true;
1655
+ await this.options.rejectToken?.(credential);
1656
+ credential = await this.credential();
1657
+ continue;
1658
+ }
1659
+ const wait = retryAfterMs(response.headers.get("retry-after"));
1660
+ if (isBusy(response.status, failure, wait) && busyRetries > 0 && (wait ?? DEFAULT_BUSY_WAIT_MS) <= (request.maxBusyWaitMs ?? 15e3)) {
1661
+ busyRetries--;
1662
+ await (this.options.sleep ?? delay$1)(wait ?? DEFAULT_BUSY_WAIT_MS, request.signal);
1663
+ continue;
1664
+ }
1665
+ throw failureError$1(response.status, failure, wait);
1666
+ }
1667
+ }
1668
+ /**
1669
+ * Send one request and parse its JSON body.
1670
+ * @param path - gateway path, or an absolute URL.
1671
+ * @param request - method, body, headers and retry policy.
1672
+ * @returns the parsed body.
1673
+ */
1674
+ async json(path, request = {}) {
1675
+ const response = await this.send(path, request);
1676
+ try {
1677
+ return await response.json();
1678
+ } catch (error) {
1679
+ throw new MediaError(`The VibeDev gateway returned an unreadable answer for ${path}.`, "GATEWAY_BAD_RESPONSE", { status: response.status }, { cause: error });
1680
+ }
1681
+ }
1682
+ async credential() {
1683
+ const credential = await this.options.resolveCredential();
1684
+ if (credential === void 0) throw new MediaError(SIGN_IN_MESSAGE$1, "NOT_SIGNED_IN");
1685
+ return credential;
1686
+ }
1687
+ async attempt(url, request, credential) {
1688
+ if (isAborted(request.signal)) throw abortError(request.signal);
1689
+ const headers = {
1690
+ accept: "application/json",
1691
+ "user-agent": this.options.userAgent,
1692
+ ...request.headers
1693
+ };
1694
+ if (credential !== void 0) headers.authorization = `Bearer ${credential.token}`;
1695
+ if (request.idempotencyKey !== void 0) headers["idempotency-key"] = request.idempotencyKey;
1696
+ let body = request.body;
1697
+ if (request.json !== void 0) {
1698
+ body = JSON.stringify(request.json);
1699
+ headers["content-type"] = "application/json";
1700
+ }
1701
+ const timeout = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS);
1702
+ const signal = request.signal === void 0 ? timeout : AbortSignal.any([request.signal, timeout]);
1703
+ try {
1704
+ return await (this.options.fetch ?? globalThis.fetch)(url, {
1705
+ method: request.method ?? (body === void 0 ? "GET" : "POST"),
1706
+ headers,
1707
+ ...body === void 0 ? {} : { body },
1708
+ redirect: "error",
1709
+ signal
1710
+ });
1711
+ } catch (error) {
1712
+ if (isAborted(request.signal)) throw abortError(request.signal);
1713
+ 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 });
1714
+ 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 });
1715
+ }
1716
+ }
1717
+ };
1718
+ /**
1719
+ * Whether an answer means "full right now, nothing was charged": any 429 but a
1720
+ * task limit, or a 503 with a busy code or `Retry-After`. A bare 503 is an outage.
1721
+ */
1722
+ function isBusy(status, failure, wait) {
1723
+ if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return false;
1724
+ return status === 429 || status === 503 && (failure.code !== void 0 && BUSY_CODES.has(failure.code) || wait !== void 0);
1725
+ }
1726
+ /**
1727
+ * The error for an answer the client does not retry, worded for the model.
1728
+ * @param status - HTTP status.
1729
+ * @param failure - the parsed error body.
1730
+ * @param wait - Retry-After in milliseconds, when given.
1731
+ * @returns the error to throw.
1732
+ */
1733
+ function failureError$1(status, failure, wait) {
1734
+ const words = gatewayWords(failure);
1735
+ const { code: _code, message: _message, ...facts } = failure;
1736
+ const details = {
1737
+ status,
1738
+ ...facts,
1739
+ ...wait === void 0 ? {} : { retryAfterMs: wait }
1740
+ };
1741
+ 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, {
1742
+ ...details,
1743
+ retryable: true
1744
+ });
1745
+ 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", {
1746
+ ...details,
1747
+ retryable: false
1748
+ });
1749
+ 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", {
1750
+ ...details,
1751
+ retryable: false
1752
+ });
1753
+ if (isBusy(status, failure, wait)) {
1754
+ const seconds = wait === void 0 ? void 0 : Math.ceil(wait / 1e3);
1755
+ 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"), {
1756
+ ...details,
1757
+ retryable: true,
1758
+ busy: true
1759
+ });
1760
+ }
1761
+ return new MediaError(`The VibeDev gateway refused the request with HTTP ${status}${words}.`, failure.code ?? `HTTP_${status}`, details);
1762
+ }
1763
+ //#endregion
1764
+ //#region src/feedback/uploader.ts
1765
+ /**
1766
+ * Sends queued feedback to the gateway, one upload at a time, oldest first,
1767
+ * each only under the VibeDev account it belongs to (queue.ts, `FeedbackOwner`):
1768
+ * the account signed in when it was given; feedback given while signed out
1769
+ * goes with the next account that signs in. Feedback of another account waits
1770
+ * — within the queue's caps — until that account is back; it is never sent
1771
+ * under a different user. The credential is pinned for each request: a renewal
1772
+ * after a 401 is used only when it is still the same account.
1773
+ *
1774
+ * Every answer of the contract is handled:
1775
+ *
1776
+ * - 201 created, 200 the same id and content already received: done;
1777
+ * - 400 invalid, 403 not allowed, 409 id reused with other content, 415 not
1778
+ * JSON: dropped (sending it again cannot help);
1779
+ * - 401: the credential's owner renews it and the same body goes once more; a
1780
+ * second refusal waits for a sign-in or the next try;
1781
+ * - 413 too large: the attachment is halved, as a new body with a new id;
1782
+ * - 429 and 503: after `Retry-After` (else a back-off), the same body;
1783
+ * - 404 (an older gateway, or the feature not on yet): kept, tried again in hours;
1784
+ * - no answer, 5xx: a back-off with jitter, from 30 s up to an hour;
1785
+ * - any other answer: the back-off, and dropped after the fifth.
1786
+ *
1787
+ * A retry always resends the stored body byte for byte. Bodies are never logged.
1788
+ * @module dsh-vibedev/feedback/uploader
1789
+ */
1790
+ const BACKOFF_BASE_MS = 3e4;
1791
+ const BACKOFF_MAX_MS = 36e5;
1792
+ /** An older gateway, or the feature not switched on yet: look again in a few hours. */
1793
+ const NOT_AVAILABLE_MS = 216e5;
1794
+ const RATE_LIMIT_DEFAULT_MS = 6e4;
1795
+ const REQUEST_TIMEOUT_MS = 3e4;
1796
+ const DROP_STATUSES = /* @__PURE__ */ new Set([
1797
+ 400,
1798
+ 403,
1799
+ 409,
1800
+ 415
1801
+ ]);
1802
+ /** Attempts an answer outside the contract (another 4xx) gets before the item is dropped. */
1803
+ const UNKNOWN_STATUS_ATTEMPTS = 5;
1804
+ /** Signed in, but which account could not be read (the gateway unreachable): look again after this long. */
1805
+ const IDENTITY_RETRY_MS = 3e5;
1806
+ /** A refusal for good: its code, and the field and rule a validation refusal names (`metadata.field` / `metadata.rule`). */
1807
+ function dropped(error) {
1808
+ return {
1809
+ kind: "drop",
1810
+ code: error.code,
1811
+ ...error.details.field === void 0 ? {} : { field: error.details.field },
1812
+ ...error.details.rule === void 0 ? {} : { rule: error.details.rule }
1813
+ };
1814
+ }
1815
+ /** What a log line says about a refusal: the gateway's code, field and rule — names, never the report. */
1816
+ function refusalText(attempt) {
1817
+ const safe = (value) => value.replace(/[\u0000-\u001f\u007f-\u009f]/g, " ").slice(0, 128);
1818
+ return [
1819
+ safe(attempt.code),
1820
+ ...attempt.field === void 0 ? [] : [`field ${safe(attempt.field)}`],
1821
+ ...attempt.rule === void 0 ? [] : [`rule ${safe(attempt.rule)}`]
1822
+ ].join(", ");
1823
+ }
1824
+ /** A credential's identity in this process (its token hashed), never written anywhere. */
1825
+ const credentialRef = (credential) => createHash("sha256").update(credential.token).digest("hex");
1826
+ /** The feedback uploader. */
1827
+ var FeedbackUploader = class {
1828
+ options;
1829
+ flushing;
1830
+ again = false;
1831
+ timer;
1832
+ disposed = false;
1833
+ recording = Promise.resolve();
1834
+ waiters = /* @__PURE__ */ new Map();
1835
+ /** Feedback of an account not identified when it was given: the credential that gave it, in this run only. */
1836
+ bindings = /* @__PURE__ */ new Map();
1837
+ now;
1838
+ /**
1839
+ * @param options - the gateway, the queue, the client block, and who is signed in.
1840
+ */
1841
+ constructor(options) {
1842
+ this.options = options;
1843
+ this.now = options.now ?? Date.now;
1844
+ }
1845
+ /**
1846
+ * Queue one piece of feedback for the account signed in now, and try to send it.
1847
+ * @param draft - what it says.
1848
+ * @param locale - the locale the user chose it in, when known (the menu's dialog).
1849
+ * @returns the body id, or undefined when the draft says nothing the gateway takes.
1850
+ */
1851
+ async enqueue(draft, locale) {
1852
+ if (this.disposed || !isSendable(draft)) return void 0;
1853
+ const id = (this.options.newId ?? randomUUID)();
1854
+ await this.record(id, draft, locale);
1855
+ return id;
1856
+ }
1857
+ /**
1858
+ * Note who gave it and keep it. One at a time, so the queue keeps the order feedback was given in.
1859
+ */
1860
+ record(id, draft, locale) {
1861
+ const run = this.recording.then(async () => {
1862
+ let owner;
1863
+ try {
1864
+ const identity = await this.options.identity();
1865
+ owner = !identity.signedIn ? { kind: "signed-out" } : identity.userId !== void 0 ? {
1866
+ kind: "user",
1867
+ id: identity.userId
1868
+ } : { kind: "unidentified" };
1869
+ if (identity.signedIn && owner.kind === "unidentified") this.bindings.set(id, credentialRef(identity.credential));
1870
+ } catch {
1871
+ owner = { kind: "unidentified" };
1872
+ }
1873
+ const client = this.options.client();
1874
+ await this.options.queue.add(feedbackBody(id, draft, locale === void 0 ? client : {
1875
+ ...client,
1876
+ locale
1877
+ }), owner);
1878
+ });
1879
+ this.recording = run.catch(() => void 0);
1880
+ return run.then(() => {
1881
+ this.flush();
1882
+ });
1883
+ }
1884
+ /**
1885
+ * Queue feedback from the dialog (for the account signed in now) and say what became of it: sent, kept for later,
1886
+ * or refused.
1887
+ * @param draft - what it says.
1888
+ * @param locale - the dialog's locale.
1889
+ * @param waitMs - how long to wait for the first answer before calling it kept.
1890
+ * @returns the outcome.
1891
+ */
1892
+ submit(draft, locale, waitMs = 2e4) {
1893
+ if (this.disposed || !isSendable(draft)) return Promise.resolve({
1894
+ status: "rejected",
1895
+ code: "FEEDBACK_EMPTY"
1896
+ });
1897
+ const id = (this.options.newId ?? randomUUID)();
1898
+ return new Promise((resolve) => {
1899
+ const finish = (outcome) => {
1900
+ if (this.waiters.get(id) === finish) this.waiters.delete(id);
1901
+ for (const [key, waiter] of this.waiters) if (waiter === finish) this.waiters.delete(key);
1902
+ this.cancel(guard);
1903
+ resolve(outcome);
1904
+ };
1905
+ const guard = this.schedule(() => {
1906
+ finish({
1907
+ status: "queued",
1908
+ reason: "later"
1909
+ });
1910
+ }, waitMs);
1911
+ this.waiters.set(id, finish);
1912
+ this.record(id, draft, locale).catch(() => {
1913
+ finish({
1914
+ status: "rejected",
1915
+ code: "FEEDBACK_NOT_SAVED"
1916
+ });
1917
+ });
1918
+ });
1919
+ }
1920
+ /** The account changed (a sign-in, a sign-out, a renewal): its feedback, and what waited on a refused renewal, goes now. */
1921
+ credentialChanged() {
1922
+ (async () => {
1923
+ await this.options.queue.load();
1924
+ for (const item of this.options.queue.items()) if (item.last === "401" && item.nextAt > this.now()) await this.options.queue.update(item.body.id, {
1925
+ attempts: item.attempts,
1926
+ nextAt: 0,
1927
+ last: "401"
1928
+ });
1929
+ await this.flush();
1930
+ })().catch(() => void 0);
1931
+ }
1932
+ /**
1933
+ * Send what is due for the account signed in now, one at a time; a call while sending makes the loop look once
1934
+ * more when it ends.
1935
+ * @returns once nothing more can be sent now.
1936
+ */
1937
+ flush() {
1938
+ if (this.disposed) return Promise.resolve();
1939
+ if (this.flushing !== void 0) {
1940
+ this.again = true;
1941
+ return this.flushing;
1942
+ }
1943
+ const run = (async () => {
1944
+ try {
1945
+ do {
1946
+ this.again = false;
1947
+ await this.drain();
1948
+ } while (this.again && !this.disposed);
1949
+ } catch (error) {
1950
+ this.options.log?.(`dsh-vibedev: feedback upload stopped: ${error instanceof Error ? error.message : String(error)}`);
1951
+ } finally {
1952
+ this.flushing = void 0;
1953
+ }
1954
+ })();
1955
+ this.flushing = run;
1956
+ return run;
1957
+ }
1958
+ /** Stop: no new attempt starts and the timer is cleared (the queue stays on disk). */
1959
+ dispose() {
1960
+ this.disposed = true;
1961
+ this.cancel(this.timer);
1962
+ this.timer = void 0;
1963
+ for (const [id, settle] of [...this.waiters]) {
1964
+ this.waiters.delete(id);
1965
+ settle({
1966
+ status: "queued",
1967
+ reason: "later"
1968
+ });
1969
+ }
1970
+ }
1971
+ /** Whether an item may go out under this account. */
1972
+ sendable(item, identity) {
1973
+ switch (item.owner.kind) {
1974
+ case "user": return identity.userId === item.owner.id;
1975
+ case "signed-out": return identity.userId !== void 0;
1976
+ case "unidentified": return this.bindings.get(item.body.id) === credentialRef(identity.credential);
577
1977
  }
1978
+ }
1979
+ async identity() {
578
1980
  try {
579
- await (await open(path, "wx")).close();
1981
+ return await this.options.identity();
1982
+ } catch {
1983
+ return { signedIn: false };
1984
+ }
1985
+ }
1986
+ async drain() {
1987
+ await this.options.queue.load();
1988
+ for (;;) {
1989
+ if (this.disposed || this.options.queue.items().length === 0) return;
1990
+ const identity = await this.identity();
1991
+ if (!identity.signedIn) {
1992
+ this.release("signed-out");
1993
+ return;
1994
+ }
1995
+ const next = this.options.queue.items().find((item) => this.sendable(item, identity));
1996
+ if (next === void 0) {
1997
+ if (identity.userId === void 0) this.park(this.jitter(IDENTITY_RETRY_MS), "later");
1998
+ else this.release("later");
1999
+ return;
2000
+ }
2001
+ const wait = next.nextAt - this.now();
2002
+ if (wait > 0) {
2003
+ this.park(wait, "later");
2004
+ return;
2005
+ }
2006
+ const item = await this.claim(next, identity);
2007
+ const attempt = await this.attempt(item, identity);
2008
+ switch (attempt.kind) {
2009
+ case "done":
2010
+ await this.options.queue.remove(item.body.id);
2011
+ this.settle(item.body.id, { status: "sent" });
2012
+ break;
2013
+ case "drop":
2014
+ this.options.log?.(`dsh-vibedev: feedback ${item.body.id} refused by the gateway (${refusalText(attempt)}); dropped`);
2015
+ await this.options.queue.remove(item.body.id);
2016
+ this.settle(item.body.id, {
2017
+ status: "rejected",
2018
+ code: attempt.code
2019
+ });
2020
+ break;
2021
+ case "shrink": {
2022
+ const smaller = halveAttachment(item.body, (this.options.newId ?? randomUUID)());
2023
+ if (smaller === void 0) {
2024
+ await this.options.queue.remove(item.body.id);
2025
+ this.settle(item.body.id, {
2026
+ status: "rejected",
2027
+ code: "FEEDBACK_BODY_TOO_LARGE"
2028
+ });
2029
+ break;
2030
+ }
2031
+ await this.options.queue.replace(item.body.id, smaller);
2032
+ const binding = this.bindings.get(item.body.id);
2033
+ if (binding !== void 0) this.bindings.set(smaller.id, binding);
2034
+ const waiter = this.waiters.get(item.body.id);
2035
+ if (waiter !== void 0) {
2036
+ this.waiters.delete(item.body.id);
2037
+ this.waiters.set(smaller.id, waiter);
2038
+ }
2039
+ break;
2040
+ }
2041
+ case "wait":
2042
+ await this.options.queue.update(item.body.id, {
2043
+ attempts: item.attempts + 1,
2044
+ nextAt: this.now() + attempt.ms,
2045
+ last: attempt.last
2046
+ });
2047
+ this.park(attempt.ms, attempt.reason);
2048
+ return;
2049
+ case "signed-out":
2050
+ this.release("signed-out");
2051
+ return;
2052
+ case "other-account":
2053
+ this.release("later");
2054
+ return;
2055
+ }
2056
+ }
2057
+ }
2058
+ /**
2059
+ * Feedback given signed out (or by an account not identified then) belongs, from its first attempt under a known
2060
+ * account on, to that account, so a retry never changes hands.
2061
+ */
2062
+ async claim(item, identity) {
2063
+ if (item.owner.kind === "user" || identity.userId === void 0) return item;
2064
+ const owner = {
2065
+ kind: "user",
2066
+ id: identity.userId
2067
+ };
2068
+ await this.options.queue.bind(item.body.id, owner);
2069
+ this.bindings.delete(item.body.id);
2070
+ return {
2071
+ ...item,
2072
+ owner
2073
+ };
2074
+ }
2075
+ /** One POST of the stored body with the account's credential, its answer mapped onto the contract. */
2076
+ async attempt(item, identity) {
2077
+ let current = identity.credential;
2078
+ let renewal = "none";
2079
+ const http = new GatewayHttp({
2080
+ ...this.options.gateway,
2081
+ resolveCredential: () => Promise.resolve(current),
2082
+ rejectToken: async (rejected) => {
2083
+ await this.options.rejectCredential(rejected).catch(() => void 0);
2084
+ const renewed = await this.identity();
2085
+ if (!renewed.signedIn) {
2086
+ current = void 0;
2087
+ renewal = "none";
2088
+ return;
2089
+ }
2090
+ if (item.owner.kind === "unidentified" && renewed.credential.kind === rejected.kind) this.bindings.set(item.body.id, credentialRef(renewed.credential));
2091
+ if (this.sendable(item, renewed)) {
2092
+ current = renewed.credential;
2093
+ renewal = "same";
2094
+ return;
2095
+ }
2096
+ current = void 0;
2097
+ renewal = renewed.userId === void 0 && item.owner.kind === "user" ? "unknown" : "other";
2098
+ }
2099
+ });
2100
+ try {
2101
+ const response = await http.send(FEEDBACK_PATH, {
2102
+ method: "POST",
2103
+ json: item.body,
2104
+ busyRetries: 0,
2105
+ timeoutMs: REQUEST_TIMEOUT_MS
2106
+ });
2107
+ await response.body?.cancel();
2108
+ return {
2109
+ kind: "done",
2110
+ status: response.status
2111
+ };
580
2112
  } catch (error) {
581
- if (error.code === "EEXIST") continue;
582
- throw error;
2113
+ if (!(error instanceof MediaError)) return {
2114
+ kind: "wait",
2115
+ ms: this.backoff(item.attempts),
2116
+ last: "ERROR",
2117
+ reason: "offline"
2118
+ };
2119
+ if (error.code === "NOT_SIGNED_IN") {
2120
+ const renewed = renewal;
2121
+ if (renewed === "other") return { kind: "other-account" };
2122
+ if (renewed === "unknown") return {
2123
+ kind: "wait",
2124
+ ms: this.backoff(item.attempts),
2125
+ last: "401",
2126
+ reason: "later"
2127
+ };
2128
+ return { kind: "signed-out" };
2129
+ }
2130
+ const status = error.details.status;
2131
+ if (status === void 0) return {
2132
+ kind: "wait",
2133
+ ms: this.backoff(item.attempts),
2134
+ last: error.code,
2135
+ reason: "offline"
2136
+ };
2137
+ if (DROP_STATUSES.has(status)) return dropped(error);
2138
+ if (status === 413) return { kind: "shrink" };
2139
+ if (status === 429) return {
2140
+ kind: "wait",
2141
+ ms: error.details.retryAfterMs ?? RATE_LIMIT_DEFAULT_MS,
2142
+ last: "429",
2143
+ reason: "later"
2144
+ };
2145
+ if (status === 503) return {
2146
+ kind: "wait",
2147
+ ms: error.details.retryAfterMs ?? this.backoff(item.attempts),
2148
+ last: "503",
2149
+ reason: "later"
2150
+ };
2151
+ if (status === 404) return {
2152
+ kind: "wait",
2153
+ ms: this.jitter(NOT_AVAILABLE_MS),
2154
+ last: "404",
2155
+ reason: "later"
2156
+ };
2157
+ if (status === 401) return {
2158
+ kind: "wait",
2159
+ ms: this.backoff(item.attempts),
2160
+ last: "401",
2161
+ reason: "later"
2162
+ };
2163
+ if (status >= 500) return {
2164
+ kind: "wait",
2165
+ ms: this.backoff(item.attempts),
2166
+ last: String(status),
2167
+ reason: "later"
2168
+ };
2169
+ if (item.attempts + 1 >= UNKNOWN_STATUS_ATTEMPTS) return dropped(error);
2170
+ return {
2171
+ kind: "wait",
2172
+ ms: this.backoff(item.attempts),
2173
+ last: String(status),
2174
+ reason: "later"
2175
+ };
583
2176
  }
584
- await renameWithRetry(temporary, path);
585
- return path;
586
2177
  }
587
- throw new MediaError(`Could not find a free file name for "${stem}.${extension}" in ${dir}.`, "OUTPUT_NAME_EXHAUSTED");
588
- }
589
- /**
590
- * Save bytes under the first free name `dir/stem.ext`.
591
- * @param dir - the destination directory.
592
- * @param stem - the file-name stem.
593
- * @param extension - the extension, without a dot.
594
- * @param data - the content.
595
- * @returns the final path.
596
- */
597
- async function saveNewFile(dir, stem, extension, data) {
598
- await mkdir(dir, { recursive: true });
599
- const temporary = join(dir, `.dsh-media-${randomUUID()}.part`);
600
- try {
601
- await writeFile(temporary, data);
602
- return await placeFile(temporary, dir, stem, extension);
603
- } finally {
604
- await rm(temporary, { force: true });
2178
+ /** 30 s doubling per attempt up to an hour, times a jitter of 0.5–1.5. */
2179
+ backoff(attempts) {
2180
+ return this.jitter(Math.min(BACKOFF_BASE_MS * 2 ** Math.min(attempts, 20), BACKOFF_MAX_MS));
605
2181
  }
606
- }
607
- /**
608
- * Write bytes atomically, replacing the file.
609
- * @param path - the final path.
610
- * @param data - the content.
611
- * @param options - `mode` for a file only its owner may read.
612
- */
613
- async function writeFileAtomic(path, data, options = {}) {
614
- await mkdir(dirname(path), { recursive: true });
615
- const temporary = join(dirname(path), `.${randomUUID()}.part`);
616
- try {
617
- await writeFile(temporary, data, options.mode === void 0 ? {} : { mode: options.mode });
618
- await renameWithRetry(temporary, path);
619
- } catch (error) {
620
- await rm(temporary, { force: true });
621
- throw error;
2182
+ jitter(ms) {
2183
+ return Math.round(ms * (.5 + (this.options.random ?? Math.random)()));
622
2184
  }
623
- }
624
- /**
625
- * Stream a response body into a temporary file, replacing what was there.
626
- * @param response - a successful response whose body is unread.
627
- * @param temporary - where to write; the caller moves it into place when this resolves.
628
- * @param maxBytes - the largest accepted body.
629
- * @param signal - cancels the download.
630
- * @returns the number of bytes written.
631
- */
632
- async function downloadTo(response, temporary, maxBytes, signal) {
633
- const declared = Number(response.headers.get("content-length"));
634
- if (Number.isFinite(declared) && declared > maxBytes) {
635
- await response.body?.cancel().catch(() => void 0);
636
- 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");
2185
+ /** What this account can send waits `ms` (its first item's turn); whoever waits on an answer hears it is kept. */
2186
+ park(ms, reason) {
2187
+ this.cancel(this.timer);
2188
+ this.timer = this.schedule(() => {
2189
+ this.timer = void 0;
2190
+ this.flush();
2191
+ }, ms);
2192
+ this.release(reason);
2193
+ }
2194
+ release(reason) {
2195
+ for (const [id, settle] of [...this.waiters]) {
2196
+ this.waiters.delete(id);
2197
+ settle({
2198
+ status: "queued",
2199
+ reason
2200
+ });
2201
+ }
637
2202
  }
638
- await mkdir(dirname(temporary), { recursive: true });
639
- await rm(temporary, { force: true });
640
- if (response.body === null) {
641
- const data = new Uint8Array(await response.arrayBuffer());
642
- if (data.byteLength > maxBytes) throw new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE");
643
- await writeFile(temporary, data);
644
- return data.byteLength;
2203
+ settle(id, outcome) {
2204
+ const settle = this.waiters.get(id);
2205
+ if (settle === void 0) return;
2206
+ this.waiters.delete(id);
2207
+ settle(outcome);
645
2208
  }
646
- let total = 0;
647
- const limit = new Transform({ transform(chunk, _encoding, callback) {
648
- total += chunk.byteLength;
649
- if (total > maxBytes) callback(new MediaError("The generated file is larger than this plugin downloads.", "OUTPUT_TOO_LARGE"));
650
- else callback(null, chunk);
651
- } });
652
- try {
653
- await pipeline(Readable.fromWeb(response.body), limit, createWriteStream(temporary), signal === void 0 ? {} : { signal });
654
- return total;
655
- } catch (error) {
656
- await rm(temporary, { force: true }).catch(() => void 0);
657
- throw error;
2209
+ schedule(callback, ms) {
2210
+ if (this.options.setTimeout !== void 0) return this.options.setTimeout(callback, ms);
2211
+ const handle = globalThis.setTimeout(callback, Math.min(ms, 2147483647));
2212
+ handle.unref?.();
2213
+ return handle;
2214
+ }
2215
+ cancel(handle) {
2216
+ if (handle === void 0) return;
2217
+ if (this.options.clearTimeout !== void 0) this.options.clearTimeout(handle);
2218
+ else globalThis.clearTimeout(handle);
658
2219
  }
2220
+ };
2221
+ //#endregion
2222
+ //#region src/feedback/index.ts
2223
+ /**
2224
+ * User feedback that reaches VibeDev. VibeDev turns off DeepSeek Harness's own
2225
+ * feedback upload (session-telemetry-otel), so a rating or a `/feedback`
2226
+ * stayed in the local session log; this uploads them to the gateway
2227
+ * (`POST /v1/account/feedback`) with the VibeDev account they were given
2228
+ * under, plus feedback given through the account menu's dialog. See observe.ts
2229
+ * for what counts as new feedback, uploader.ts for the answers and the account
2230
+ * rule, queue.ts for what is kept.
2231
+ * @module dsh-vibedev/feedback
2232
+ */
2233
+ /**
2234
+ * Install the feedback upload: listen for new feedback and recent failures, serve the dialog's routes, and send what
2235
+ * the queue holds.
2236
+ * @param ctx - the plugin context.
2237
+ * @param options - the gateway, the state directory, who is signed in, and the sign-in hooks.
2238
+ * @returns the uploader and the recent errors (for tests and other parts of the plugin).
2239
+ */
2240
+ function installFeedback(ctx, options) {
2241
+ const queue = new FeedbackQueue(join(options.gatewayDir, "feedback-queue.json"));
2242
+ let client;
2243
+ const uploader = new FeedbackUploader({
2244
+ gateway: options.gateway,
2245
+ queue,
2246
+ log: options.log,
2247
+ identity: options.identity,
2248
+ rejectCredential: options.rejectCredential,
2249
+ client: () => client ??= clientInfo(hostFacts(), options.pluginVersion)
2250
+ });
2251
+ const errors = new RecentErrors();
2252
+ const enqueue = (draft) => {
2253
+ if (draft === void 0) return;
2254
+ uploader.enqueue(draft).catch((error) => {
2255
+ options.log(`dsh-vibedev: feedback could not be queued: ${error instanceof Error ? error.message : String(error)}`);
2256
+ });
2257
+ };
2258
+ ctx.on("session/event", (session, event) => {
2259
+ errors.observe(session, event);
2260
+ enqueue(draftFromEvent(session, event));
2261
+ });
2262
+ ctx.on("feedback/committed", (inspection) => {
2263
+ enqueue(draftFromCommitted(inspection));
2264
+ });
2265
+ const hasCredential = async () => (await options.identity().catch(() => ({ signedIn: false }))).signedIn;
2266
+ ctx.inject(["connection"], (scoped) => {
2267
+ for (const route of feedbackRoutes({
2268
+ submit: (draft, locale) => uploader.submit(draft, locale),
2269
+ errors,
2270
+ hasCredential
2271
+ })) scoped.effect(() => scoped.connection.fetch.register(route), `dsh-vibedev: ${route.path}`);
2272
+ });
2273
+ ctx.effect(() => {
2274
+ uploader.flush();
2275
+ const unsubscribe = options.onCredentialChange(() => {
2276
+ uploader.credentialChanged();
2277
+ });
2278
+ return () => {
2279
+ unsubscribe();
2280
+ uploader.dispose();
2281
+ };
2282
+ }, "dsh-vibedev: feedback upload");
2283
+ return {
2284
+ uploader,
2285
+ errors
2286
+ };
659
2287
  }
660
2288
  //#endregion
661
2289
  //#region src/gateway/origin.ts
@@ -2268,7 +3896,7 @@ function isContextOverflow(message, contextWindow) {
2268
3896
  }
2269
3897
  //#endregion
2270
3898
  //#region node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
2271
- const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-KOS0z8Fy.js").then((n) => n.t));
3899
+ const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-BgIfgjNt.js").then((n) => n.t));
2272
3900
  //#endregion
2273
3901
  //#region node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
2274
3902
  const openAICompletionsApi = () => lazyApi(() => import("./openai-completions-DqTCiqpS.js"));
@@ -2758,7 +4386,7 @@ const SIGN_IN_REQUIRED_CODE = "VIBEDEV_SIGN_IN_REQUIRED";
2758
4386
  /** Failure code for a used-up balance; not the Harness's `ACCOUNT_QUOTA`, which opens the DeepSeek top-up. */
2759
4387
  const INSUFFICIENT_BALANCE_CODE = "VIBEDEV_INSUFFICIENT_BALANCE";
2760
4388
  /** What a person reads when a VibeDev model is used before signing in. */
2761
- const SIGN_IN_MESSAGE$1 = "请先登录 VibeDev:在侧边栏底部「登录 VibeDev」或「设置 → VibeDev 账号」中登录后即可使用这些模型。 Sign in to VibeDev (sidebar, or Settings → VibeDev account) to use these models.";
4389
+ const SIGN_IN_MESSAGE = "请先登录 VibeDev:在侧边栏底部「登录 VibeDev」或「设置 → VibeDev 账号」中登录后即可使用这些模型。 Sign in to VibeDev (sidebar, or Settings → VibeDev account) to use these models.";
2762
4390
  /** What a person reads when the gateway ended the sign-in and a refresh could not renew it. */
2763
4391
  const SESSION_ENDED_MESSAGE = "VibeDev 登录已失效,请重新登录(侧边栏底部或「设置 → VibeDev 账号」)。 Your VibeDev sign-in has ended; sign in again.";
2764
4392
  /**
@@ -2836,7 +4464,7 @@ var GatewayAdapter = class extends LlmAdapter {
2836
4464
  }
2837
4465
  modelOf(snapshot, provider, id) {
2838
4466
  this.assertOwned(provider);
2839
- if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE$1, SIGN_IN_REQUIRED_CODE);
4467
+ if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
2840
4468
  const catalog = snapshot.byId.get(id);
2841
4469
  const model = snapshot.models.getModel(provider, id);
2842
4470
  if (catalog === void 0 || model === void 0) throw new LlmError(`VibeDev has no model "${id}"`, "UNKNOWN_MODEL");
@@ -2896,7 +4524,7 @@ var GatewayAdapter = class extends LlmAdapter {
2896
4524
  const starting = startingReasoning(catalog);
2897
4525
  const reasoning = resolveReasoningLevel(model, options.reasoningEffort ?? (starting === void 0 ? void 0 : effortOf(starting)));
2898
4526
  let credential = await this.config.resolveCredential();
2899
- if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE$1, SIGN_IN_REQUIRED_CODE);
4527
+ if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
2900
4528
  const sessionId = options.sessionId === void 0 ? void 0 : String(options.sessionId);
2901
4529
  const deviceId = model.api === "anthropic-messages" && sessionId !== void 0 ? await this.config.deviceId?.() : void 0;
2902
4530
  const consumer = new AbortController();
@@ -3308,10 +4936,31 @@ function installGatewayModels(ctx, options) {
3308
4936
  * the returned upload headers when an upload is needed, `POST /{id}/complete`.
3309
4937
  * An asset the library already holds is read back through `/refresh`, which
3310
4938
  * also carries its measured duration.
4939
+ *
4940
+ * The gateway keeps one asset per account, purpose and digest
4941
+ * (media/service.go CreateUpload): every upload of the same bytes is handed the
4942
+ * same pending asset, the first PUT claims it, and the others are answered
4943
+ * 409 `MEDIA_ASSET_NOT_READY` ("media upload is unavailable" on the PUT,
4944
+ * "media upload is already in progress" on a later `uploads`). So inside the
4945
+ * Host one upload of a file serves every caller that wants it at the same time
4946
+ * (by purpose and digest), and a 409 from another process — or the coming
4947
+ * `MEDIA_ASSET_UPLOAD_IN_PROGRESS` — means another upload of the same bytes is
4948
+ * under way: the library waits for it (Retry-After, else 1 s doubling to 10 s,
4949
+ * two minutes at most) by asking `uploads` again, which hands back the asset
4950
+ * once it is ready, still answers 409 while it is not, and hands out a fresh
4951
+ * upload when the other one ended without the file (failed or expired) — the
4952
+ * library then uploads once more itself. `/refresh` cannot tell those apart (it
4953
+ * answers 409 for a failed asset too).
3311
4954
  * @module dsh-vibedev/gateway/assets
3312
4955
  */
3313
4956
  /** How long before expiry a cached asset is refreshed instead of reused. */
3314
4957
  const EXPIRY_MARGIN_MS = 6e5;
4958
+ /** How long to wait for another upload of the same file, in all. */
4959
+ const OTHER_UPLOAD_WAIT_MS = 12e4;
4960
+ const FIRST_LOOK_MS = 1e3;
4961
+ const LOOK_STEP_MAX_MS = 1e4;
4962
+ /** Uploads this library starts for one file: its own, and one more after another upload of the file ended without it. */
4963
+ const OWN_UPLOADS = 2;
3315
4964
  const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3316
4965
  const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
3317
4966
  const httpUrl$1 = (value) => {
@@ -3341,39 +4990,140 @@ function parseAsset(body, fallbackType) {
3341
4990
  ...typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? { durationMs: duration } : {}
3342
4991
  };
3343
4992
  }
4993
+ /**
4994
+ * Whether a media-asset answer means another upload of the same bytes is under way: 409 `MEDIA_ASSET_NOT_READY`
4995
+ * (on `uploads`, the PUT or `complete`), or `MEDIA_ASSET_UPLOAD_IN_PROGRESS`.
4996
+ */
4997
+ function otherUpload(error) {
4998
+ return error instanceof MediaError && (error.code === "MEDIA_ASSET_UPLOAD_IN_PROGRESS" || error.code === "MEDIA_ASSET_NOT_READY" && error.details.status === 409);
4999
+ }
3344
5000
  /** Uploads references and remembers them for the life of the plugin. */
3345
5001
  var MediaLibrary = class {
3346
5002
  http;
3347
5003
  now;
5004
+ options;
3348
5005
  cache = /* @__PURE__ */ new Map();
5006
+ flights = /* @__PURE__ */ new Map();
5007
+ /** Bumped by {@link clear}: an upload of the previous account does not land in the cache. */
5008
+ generation = 0;
3349
5009
  /**
3350
5010
  * @param http - the gateway client.
3351
- * @param now - clock, for expiry checks.
5011
+ * @param now - clock, for expiry checks and the wait for another upload.
5012
+ * @param options - the sleep (a test seam).
3352
5013
  */
3353
- constructor(http, now = Date.now) {
5014
+ constructor(http, now = Date.now, options = {}) {
3354
5015
  this.http = http;
3355
5016
  this.now = now;
5017
+ this.options = options;
3356
5018
  }
3357
5019
  /** Forget every remembered asset, as after an account change: assets belong to the account that uploaded them. */
3358
5020
  clear() {
5021
+ this.generation++;
3359
5022
  this.cache.clear();
5023
+ this.flights.clear();
3360
5024
  }
3361
5025
  /**
3362
- * Upload one loaded input, or reuse the asset the library already holds.
5026
+ * Upload one loaded input, or reuse the asset the library already holds. Callers that ask for the same file
5027
+ * (purpose and digest) at the same time share one upload; one that gives up leaves it running for the others.
3363
5028
  * @param media - the loaded input.
3364
5029
  * @param purpose - the asset purpose.
3365
- * @param signal - cancels the upload.
5030
+ * @param signal - cancels this caller's wait (and the upload, once no caller waits on it).
3366
5031
  * @returns the asset.
3367
5032
  */
3368
5033
  async upload(media, purpose, signal) {
5034
+ if (signal?.aborted === true) throw abortError(signal);
3369
5035
  const sha256 = createHash("sha256").update(media.data).digest("hex");
3370
5036
  const key = `${purpose}:${sha256}`;
3371
5037
  const cached = this.cache.get(key);
3372
5038
  if (cached !== void 0 && !this.expiring(cached)) return cached;
5039
+ let flight = this.flights.get(key);
5040
+ if (flight === void 0) {
5041
+ const controller = new AbortController();
5042
+ const generation = this.generation;
5043
+ const created = {
5044
+ promise: this.resolve(media, purpose, sha256, controller.signal).then((asset) => {
5045
+ if (generation === this.generation) this.cache.set(key, asset);
5046
+ return asset;
5047
+ }).finally(() => {
5048
+ if (this.flights.get(key) === created) this.flights.delete(key);
5049
+ }),
5050
+ controller,
5051
+ callers: 0
5052
+ };
5053
+ flight = created;
5054
+ this.flights.set(key, created);
5055
+ }
5056
+ return this.join(key, flight, signal);
5057
+ }
5058
+ /** Wait on a shared upload; giving up answers this caller at once and stops the upload when nobody else waits. */
5059
+ join(key, flight, signal) {
5060
+ flight.callers++;
5061
+ return new Promise((resolve, reject) => {
5062
+ let done = false;
5063
+ const leave = () => {
5064
+ done = true;
5065
+ flight.callers--;
5066
+ signal?.removeEventListener("abort", onAbort);
5067
+ };
5068
+ const onAbort = () => {
5069
+ if (done) return;
5070
+ leave();
5071
+ if (flight.callers === 0) {
5072
+ if (this.flights.get(key) === flight) this.flights.delete(key);
5073
+ flight.controller.abort(signal?.reason);
5074
+ }
5075
+ reject(abortError(signal));
5076
+ };
5077
+ signal?.addEventListener("abort", onAbort, { once: true });
5078
+ flight.promise.then((asset) => {
5079
+ if (!done) {
5080
+ leave();
5081
+ resolve(asset);
5082
+ }
5083
+ }, (error) => {
5084
+ if (!done) {
5085
+ leave();
5086
+ reject(error);
5087
+ }
5088
+ });
5089
+ });
5090
+ }
5091
+ /** Refresh a remembered asset about to expire, else upload the file — waiting for another upload of it when one is under way. */
5092
+ async resolve(media, purpose, sha256, signal) {
5093
+ const cached = this.cache.get(`${purpose}:${sha256}`);
3373
5094
  if (cached !== void 0) {
3374
5095
  const refreshed = await this.refresh(cached, signal).catch(() => void 0);
3375
- if (refreshed !== void 0) return this.remember(key, refreshed);
5096
+ if (refreshed !== void 0) return refreshed;
5097
+ }
5098
+ let own = 0;
5099
+ let waitingSince;
5100
+ let step = FIRST_LOOK_MS;
5101
+ for (;;) {
5102
+ let other;
5103
+ try {
5104
+ const created = await this.declare(media, purpose, sha256, signal);
5105
+ if (created.kind === "ready") return created.asset;
5106
+ 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 });
5107
+ own++;
5108
+ return await this.put(media, sha256, created.assetId, created.answer, signal);
5109
+ } catch (error) {
5110
+ if (!otherUpload(error)) throw error;
5111
+ other = error;
5112
+ }
5113
+ waitingSince ??= this.now();
5114
+ const left = waitingSince + OTHER_UPLOAD_WAIT_MS - this.now();
5115
+ 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", {
5116
+ status: 409,
5117
+ retryable: true,
5118
+ ...other.details.assetId === void 0 ? {} : { assetId: other.details.assetId }
5119
+ });
5120
+ await (this.options.sleep ?? delay$1)(Math.min(other.details.retryAfterMs ?? step, left), signal);
5121
+ if (signal.aborted) throw abortError(signal);
5122
+ step = Math.min(step * 2, LOOK_STEP_MAX_MS);
3376
5123
  }
5124
+ }
5125
+ /** `POST /uploads`: the asset when the library already holds the file, else the upload it hands out. */
5126
+ async declare(media, purpose, sha256, signal) {
3377
5127
  const created = record$4(await this.http.json("/v1/media-assets/uploads", {
3378
5128
  method: "POST",
3379
5129
  json: {
@@ -3383,20 +5133,31 @@ var MediaLibrary = class {
3383
5133
  sha256,
3384
5134
  purpose
3385
5135
  },
3386
- ...signal === void 0 ? {} : { signal }
5136
+ signal
3387
5137
  }));
3388
5138
  const assetId = text$5(created?.asset_id);
3389
5139
  if (created === void 0 || assetId === void 0) throw new MediaError(`The VibeDev gateway did not accept the upload of "${media.source}".`, "ASSET_UPLOAD_REFUSED");
3390
- if (created.upload_required === false) {
3391
- const known = parseAsset(created, media.mime);
3392
- const facts = await this.read(assetId, "refresh", media.mime, signal).catch(() => void 0) ?? known;
3393
- if (facts === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}".`, "ASSET_REFERENCE_MISSING");
3394
- return this.remember(key, {
5140
+ if (created.upload_required !== false) return {
5141
+ kind: "upload",
5142
+ assetId,
5143
+ answer: created
5144
+ };
5145
+ const known = parseAsset(created, media.mime);
5146
+ const facts = await this.read(assetId, "refresh", media.mime, signal).catch((error) => {
5147
+ if (signal.aborted) throw error;
5148
+ }) ?? known;
5149
+ if (facts === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}".`, "ASSET_REFERENCE_MISSING");
5150
+ return {
5151
+ kind: "ready",
5152
+ asset: {
3395
5153
  ...facts,
3396
5154
  sha256,
3397
5155
  bytes: media.data.byteLength
3398
- });
3399
- }
5156
+ }
5157
+ };
5158
+ }
5159
+ /** PUT the bytes where `uploads` said, then `complete`. */
5160
+ async put(media, sha256, assetId, created, signal) {
3400
5161
  const uploadUrl = httpUrl$1(created.upload_url) ?? (text$5(created.upload_url)?.startsWith("/") === true ? this.http.url(text$5(created.upload_url)) : void 0);
3401
5162
  if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
3402
5163
  const headers = { "content-type": media.mime };
@@ -3408,25 +5169,21 @@ var MediaLibrary = class {
3408
5169
  anonymous: true,
3409
5170
  timeoutMs: 6e5,
3410
5171
  busyRetries: 1,
3411
- ...signal === void 0 ? {} : { signal }
5172
+ signal
3412
5173
  });
3413
5174
  const completed = await this.read(assetId, "complete", media.mime, signal);
3414
5175
  if (completed === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}" after the upload.`, "ASSET_REFERENCE_MISSING");
3415
- return this.remember(key, {
5176
+ return {
3416
5177
  ...completed,
3417
5178
  sha256,
3418
5179
  bytes: media.data.byteLength
3419
- });
5180
+ };
3420
5181
  }
3421
5182
  expiring(asset) {
3422
5183
  if (asset.expiresAt === void 0) return false;
3423
5184
  const at = Date.parse(asset.expiresAt);
3424
5185
  return Number.isFinite(at) && at - this.now() < EXPIRY_MARGIN_MS;
3425
5186
  }
3426
- remember(key, asset) {
3427
- this.cache.set(key, asset);
3428
- return asset;
3429
- }
3430
5187
  async refresh(asset, signal) {
3431
5188
  const facts = await this.read(asset.assetId, "refresh", asset.contentType, signal);
3432
5189
  return facts === void 0 ? void 0 : {
@@ -3443,218 +5200,6 @@ var MediaLibrary = class {
3443
5200
  }
3444
5201
  };
3445
5202
  //#endregion
3446
- //#region src/gateway/http.ts
3447
- /**
3448
- * HTTP client for the VibeDev gateway. Every gateway call goes through here so
3449
- * authentication, refresh after a 401, balance refusals, busy back-off and
3450
- * idempotency are handled once.
3451
- *
3452
- * The credential is attached only to requests on the gateway origin: upload
3453
- * URLs and third-party links never see it.
3454
- * @module dsh-vibedev/gateway/http
3455
- */
3456
- /** Error codes the gateway uses for "full right now, nothing was charged". */
3457
- const BUSY_CODES = /* @__PURE__ */ new Set([
3458
- "APP_TOKEN_UNAVAILABLE",
3459
- "PROVIDER_CAPACITY_BUSY",
3460
- "upstream_capacity_busy",
3461
- "AUDIO_CAPACITY_BUSY",
3462
- "AUDIO_NO_AVAILABLE_ACCOUNT",
3463
- "WEB_SEARCH_BUSY",
3464
- "WEB_SEARCH_RATE_LIMITED"
3465
- ]);
3466
- /**
3467
- * The account already runs as many video or audio tasks as it may (HTTP 429).
3468
- * Not retried here: a slot frees only when one of the user's tasks finishes.
3469
- */
3470
- const TASK_LIMIT_CODES = /* @__PURE__ */ new Set(["VIDEO_TASK_LIMIT_REACHED", "AUDIO_TASK_LIMIT_REACHED"]);
3471
- const DEFAULT_TIMEOUT_MS = 6e4;
3472
- const DEFAULT_BUSY_WAIT_MS = 2e3;
3473
- /** The message for a call made while nobody is signed in. */
3474
- 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.";
3475
- /** Read through a call so a check made before an `await` is not taken as still true after it. */
3476
- function isAborted(signal) {
3477
- return signal?.aborted === true;
3478
- }
3479
- function delay$1(ms, signal) {
3480
- return new Promise((resolve, reject) => {
3481
- if (isAborted(signal)) {
3482
- reject(abortError(signal));
3483
- return;
3484
- }
3485
- const timer = setTimeout(() => {
3486
- signal?.removeEventListener("abort", onAbort);
3487
- resolve();
3488
- }, ms);
3489
- const onAbort = () => {
3490
- clearTimeout(timer);
3491
- reject(abortError(signal));
3492
- };
3493
- signal?.addEventListener("abort", onAbort, { once: true });
3494
- });
3495
- }
3496
- function abortError(signal) {
3497
- return new MediaError("The media request was cancelled.", "ABORTED", { retryable: true }, { cause: signal?.reason });
3498
- }
3499
- /** Gateway HTTP client. */
3500
- var GatewayHttp = class {
3501
- options;
3502
- origin;
3503
- /**
3504
- * @param options - origin, credential plane, user agent and test seams.
3505
- */
3506
- constructor(options) {
3507
- this.options = options;
3508
- this.origin = options.origin.trim().replace(/\/+$/, "");
3509
- }
3510
- /** Absolute URL for a gateway path, or the URL itself when already absolute. */
3511
- url(path) {
3512
- return /^https?:\/\//i.test(path) ? path : `${this.origin}${path.startsWith("/") ? "" : "/"}${path}`;
3513
- }
3514
- /** Whether a URL is on the gateway origin, and so may carry the credential. */
3515
- isGatewayUrl(url) {
3516
- try {
3517
- return new URL(url).origin === new URL(this.origin).origin;
3518
- } catch {
3519
- return false;
3520
- }
3521
- }
3522
- /**
3523
- * Send one request and return the successful response.
3524
- * @param path - gateway path, or an absolute URL.
3525
- * @param request - method, body, headers and retry policy.
3526
- * @returns the 2xx response, body unread.
3527
- * @throws {@link MediaError} for every refusal, with the gateway's code.
3528
- */
3529
- async send(path, request = {}) {
3530
- const url = this.url(path);
3531
- const authenticate = request.anonymous !== true && this.isGatewayUrl(url);
3532
- let credential = authenticate ? await this.credential() : void 0;
3533
- let refreshed = false;
3534
- let busyRetries = request.busyRetries ?? 2;
3535
- for (;;) {
3536
- const response = await this.attempt(url, request, credential);
3537
- if (response.ok) {
3538
- if (authenticate) try {
3539
- this.options.onAccepted?.({
3540
- method: request.method ?? "GET",
3541
- path: new URL(url).pathname
3542
- });
3543
- } catch {}
3544
- return response;
3545
- }
3546
- const failure = parseGatewayFailure(await response.clone().json().catch(() => void 0));
3547
- if (response.status === 401 && credential !== void 0 && credential.kind !== "key" && !refreshed) {
3548
- refreshed = true;
3549
- await this.options.rejectToken?.(credential);
3550
- credential = await this.credential();
3551
- continue;
3552
- }
3553
- const wait = retryAfterMs(response.headers.get("retry-after"));
3554
- if (isBusy(response.status, failure, wait) && busyRetries > 0 && (wait ?? DEFAULT_BUSY_WAIT_MS) <= (request.maxBusyWaitMs ?? 15e3)) {
3555
- busyRetries--;
3556
- await (this.options.sleep ?? delay$1)(wait ?? DEFAULT_BUSY_WAIT_MS, request.signal);
3557
- continue;
3558
- }
3559
- throw failureError$1(response.status, failure, wait);
3560
- }
3561
- }
3562
- /**
3563
- * Send one request and parse its JSON body.
3564
- * @param path - gateway path, or an absolute URL.
3565
- * @param request - method, body, headers and retry policy.
3566
- * @returns the parsed body.
3567
- */
3568
- async json(path, request = {}) {
3569
- const response = await this.send(path, request);
3570
- try {
3571
- return await response.json();
3572
- } catch (error) {
3573
- throw new MediaError(`The VibeDev gateway returned an unreadable answer for ${path}.`, "GATEWAY_BAD_RESPONSE", { status: response.status }, { cause: error });
3574
- }
3575
- }
3576
- async credential() {
3577
- const credential = await this.options.resolveCredential();
3578
- if (credential === void 0) throw new MediaError(SIGN_IN_MESSAGE, "NOT_SIGNED_IN");
3579
- return credential;
3580
- }
3581
- async attempt(url, request, credential) {
3582
- if (isAborted(request.signal)) throw abortError(request.signal);
3583
- const headers = {
3584
- accept: "application/json",
3585
- "user-agent": this.options.userAgent,
3586
- ...request.headers
3587
- };
3588
- if (credential !== void 0) headers.authorization = `Bearer ${credential.token}`;
3589
- if (request.idempotencyKey !== void 0) headers["idempotency-key"] = request.idempotencyKey;
3590
- let body = request.body;
3591
- if (request.json !== void 0) {
3592
- body = JSON.stringify(request.json);
3593
- headers["content-type"] = "application/json";
3594
- }
3595
- const timeout = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS);
3596
- const signal = request.signal === void 0 ? timeout : AbortSignal.any([request.signal, timeout]);
3597
- try {
3598
- return await (this.options.fetch ?? globalThis.fetch)(url, {
3599
- method: request.method ?? (body === void 0 ? "GET" : "POST"),
3600
- headers,
3601
- ...body === void 0 ? {} : { body },
3602
- redirect: "error",
3603
- signal
3604
- });
3605
- } catch (error) {
3606
- if (isAborted(request.signal)) throw abortError(request.signal);
3607
- 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 });
3608
- 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 });
3609
- }
3610
- }
3611
- };
3612
- /**
3613
- * Whether an answer means "full right now, nothing was charged": any 429 but a
3614
- * task limit, or a 503 with a busy code or `Retry-After`. A bare 503 is an outage.
3615
- */
3616
- function isBusy(status, failure, wait) {
3617
- if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return false;
3618
- return status === 429 || status === 503 && (failure.code !== void 0 && BUSY_CODES.has(failure.code) || wait !== void 0);
3619
- }
3620
- /**
3621
- * The error for an answer the client does not retry, worded for the model.
3622
- * @param status - HTTP status.
3623
- * @param failure - the parsed error body.
3624
- * @param wait - Retry-After in milliseconds, when given.
3625
- * @returns the error to throw.
3626
- */
3627
- function failureError$1(status, failure, wait) {
3628
- const words = gatewayWords(failure);
3629
- const { code: _code, message: _message, ...facts } = failure;
3630
- const details = {
3631
- status,
3632
- ...facts,
3633
- ...wait === void 0 ? {} : { retryAfterMs: wait }
3634
- };
3635
- 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, {
3636
- ...details,
3637
- retryable: true
3638
- });
3639
- 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", {
3640
- ...details,
3641
- retryable: false
3642
- });
3643
- 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", {
3644
- ...details,
3645
- retryable: false
3646
- });
3647
- if (isBusy(status, failure, wait)) {
3648
- const seconds = wait === void 0 ? void 0 : Math.ceil(wait / 1e3);
3649
- 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"), {
3650
- ...details,
3651
- retryable: true,
3652
- busy: true
3653
- });
3654
- }
3655
- return new MediaError(`The VibeDev gateway refused the request with HTTP ${status}${words}.`, failure.code ?? `HTTP_${status}`, details);
3656
- }
3657
- //#endregion
3658
5203
  //#region src/gateway/catalog.ts
3659
5204
  /** The video generation modes of catalog schema v1, under their wire names. */
3660
5205
  const VIDEO_MODES = [
@@ -3933,14 +5478,15 @@ function stringChoices(raw) {
3933
5478
  }
3934
5479
  return Object.keys(out).length === 0 ? void 0 : out;
3935
5480
  }
3936
- function parseReferenceLimits(raw) {
5481
+ function parseReferenceLimits(raw, form) {
3937
5482
  if (raw === void 0) return void 0;
3938
5483
  const max = count(field(raw, "max_count")) ?? count(raw.max);
3939
5484
  if (max === void 0 || max === 0) return void 0;
3940
5485
  const min = count(field(raw, "min_count")) ?? count(raw.min) ?? 0;
3941
5486
  const limits = {
3942
5487
  min: Math.min(min, max),
3943
- max
5488
+ max,
5489
+ form
3944
5490
  };
3945
5491
  for (const [key, ...names] of [
3946
5492
  [
@@ -3972,13 +5518,31 @@ function parseReferenceLimits(raw) {
3972
5518
  return limits;
3973
5519
  }
3974
5520
  /**
5521
+ * Seed's reference audio, as the gateway declares it (catalog/audio.go AudioCapabilities): flat flags and limits for
5522
+ * each input of its union rather than a `references` object — `reference_audio_input`, `max_reference_audios`,
5523
+ * `max_reference_audio_duration_seconds`, `max_reference_audio_bytes`.
5524
+ */
5525
+ function seedReferenceLimits(raw) {
5526
+ const max = count(field(raw, "max_reference_audios"));
5527
+ if (bool(raw, "reference_audio_input") !== true || max === void 0 || max === 0) return void 0;
5528
+ const maxBytes = positive(field(raw, "max_reference_audio_bytes"));
5529
+ const maxSeconds = positive(field(raw, "max_reference_audio_duration_seconds"));
5530
+ return {
5531
+ min: 0,
5532
+ max,
5533
+ form: "object",
5534
+ ...maxBytes === void 0 ? {} : { maxBytes },
5535
+ ...maxSeconds === void 0 ? {} : { maxSeconds }
5536
+ };
5537
+ }
5538
+ /**
3975
5539
  * The output formats, in either declared shape: `output_formats: [{format, sample_rates}]`,
3976
5540
  * or `output_formats: ['wav','mp3']` with `sample_rates: {wav: [...], mp3: [...]}`.
3977
5541
  */
3978
5542
  function parseOutputFormats(raw) {
3979
5543
  const declared = field(raw, "output_formats");
3980
5544
  if (!Array.isArray(declared)) return void 0;
3981
- const rates = record$3(field(raw, "sample_rates"));
5545
+ const rates = record$3(field(raw, "sample_rates")) ?? record$3(field(raw, "output_sample_rates"));
3982
5546
  const formats = [];
3983
5547
  for (const item of declared) {
3984
5548
  const entry = record$3(item);
@@ -4007,10 +5571,16 @@ function parseAudioCapabilities(raw) {
4007
5571
  const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
4008
5572
  const promptField = text$4(field(raw, "prompt_field"));
4009
5573
  const requestFields = list(raw, "request_fields") ?? [];
4010
- const references = parseReferenceLimits(record$3(field(raw, "references")) ?? record$3(field(raw, "reference_audio")));
5574
+ const union = [
5575
+ "reference_audio_input",
5576
+ "reference_image_input",
5577
+ "speaker_input"
5578
+ ].some((name) => bool(raw, name) !== void 0);
5579
+ const references = parseReferenceLimits(record$3(field(raw, "references")) ?? record$3(field(raw, "reference_audio")), union ? "object" : "url") ?? seedReferenceLimits(raw);
4011
5580
  const outputFormats = parseOutputFormats(raw);
4012
5581
  const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
4013
5582
  const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
5583
+ const watermarkFields = list(raw, "watermark_fields");
4014
5584
  const result = { requestFields };
4015
5585
  if (generationKind !== void 0) result.generationKind = generationKind;
4016
5586
  if (promptField !== void 0) result.promptField = promptField;
@@ -4019,11 +5589,13 @@ function parseAudioCapabilities(raw) {
4019
5589
  if (outputFormats !== void 0) result.outputFormats = outputFormats;
4020
5590
  if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
4021
5591
  if (choices !== void 0) result.choices = choices;
5592
+ if (watermarkFields !== void 0 && watermarkFields.length > 0) result.watermarkFields = watermarkFields;
4022
5593
  for (const [key, ...names] of [
4023
5594
  [
4024
5595
  "maxPromptChars",
4025
5596
  "max_prompt_chars",
4026
- "max_text_chars"
5597
+ "max_text_chars",
5598
+ "max_prompt_characters"
4027
5599
  ],
4028
5600
  [
4029
5601
  "maxInputBytes",
@@ -5663,6 +7235,11 @@ function quotedCny(quote) {
5663
7235
  * | podcast | model, prompt, source_url |
5664
7236
  * | speech | as declared; Seed: model, text_prompt, references, audio_config, watermark |
5665
7237
  *
7238
+ * Seed (`seed-audio-1.0`) parses its body strictly: each reference is an object
7239
+ * naming its input (`{"audio_url": "<url>"}`) and the watermark an object
7240
+ * (`{"aigc_watermark": true}`); the model's declaration says so (the inputs of
7241
+ * its reference union, `watermark_fields`), and only such a model gets them.
7242
+ *
5666
7243
  * The main text goes in the model's `prompt_field`. A field the model does not
5667
7244
  * declare in `request_fields` is refused before anything is uploaded or charged;
5668
7245
  * music and podcasts never take speech references, output formats, sample rates
@@ -5809,7 +7386,10 @@ function audioRequestBody(model, request) {
5809
7386
  }
5810
7387
  if (request.watermark !== void 0) {
5811
7388
  if (!takes("watermark")) refuse(`${model.id} does not take watermark.`, "watermark");
5812
- body.watermark = request.watermark;
7389
+ const fields = audio?.watermarkFields;
7390
+ if (fields === void 0) body.watermark = request.watermark;
7391
+ else if (fields.includes("aigc_watermark")) body.watermark = { aigc_watermark: request.watermark };
7392
+ else refuse(`${model.id} declares its watermark as ${fields.join(", ")}, without a switch to turn it on or off.`, "watermark");
5813
7393
  }
5814
7394
  if (request.format !== void 0 || request.sampleRate !== void 0 || takes("audio_config")) {
5815
7395
  if (!takes("audio_config")) refuse(`${model.id} does not take an output format or sample rate.`, "format");
@@ -5883,7 +7463,7 @@ async function prepareAudioTask(runtime, call, request, save) {
5883
7463
  const kind = audioKindOf(model);
5884
7464
  const body = audioRequestBody(model, request);
5885
7465
  const references = request.references ?? [];
5886
- if (references.length > 0) body.references = (await uploadReferences(runtime, call, model, references, body)).map((item) => item.asset.referenceUrl);
7466
+ 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);
5887
7467
  else if ((model.audio?.references?.min ?? 0) > 0) refuse(`${model.id} needs at least ${model.audio?.references?.min} reference audio file(s).`, "references");
5888
7468
  const quote = quoteAudio(model);
5889
7469
  const what = {
@@ -6552,7 +8132,13 @@ function describeVideoModel(model) {
6552
8132
  return `${MODE_LABEL[mode]}: ${describeInputs(constraint)}${options === "" ? "" : `; ${options}`}`;
6553
8133
  });
6554
8134
  const limits = [];
6555
- if (video.minReferenceVideoSeconds !== void 0 || video.maxReferenceVideoSeconds !== void 0) limits.push(`each reference video ${video.minReferenceVideoSeconds ?? 0}-${video.maxReferenceVideoSeconds ?? "∞"} s`);
8135
+ if (video.maxReferenceVideoSeconds !== void 0) limits.push(`each reference video ${video.minReferenceVideoSeconds ?? 0}-${video.maxReferenceVideoSeconds} s`);
8136
+ else {
8137
+ const derived = [...new Set(VIDEO_MODES.filter((mode) => (modes[mode]?.inputs.referenceVideos?.max ?? 0) > 0).flatMap((mode) => referenceVideoLimit(model, modes[mode])?.seconds ?? []))];
8138
+ const at = video.minReferenceVideoSeconds === void 0 ? "at most " : `${video.minReferenceVideoSeconds}-`;
8139
+ 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)`);
8140
+ else if (video.minReferenceVideoSeconds !== void 0) limits.push(`each reference video at least ${video.minReferenceVideoSeconds} s`);
8141
+ }
6556
8142
  if (video.maxTotalReferenceVideoSeconds !== void 0) limits.push(`reference videos at most ${video.maxTotalReferenceVideoSeconds} s in total`);
6557
8143
  if (video.minReferenceAudioSeconds !== void 0 || video.maxReferenceAudioSeconds !== void 0) limits.push(`each reference audio ${video.minReferenceAudioSeconds ?? 0}-${video.maxReferenceAudioSeconds ?? "∞"} s`);
6558
8144
  if (video.combinations !== void 0) limits.push(`allowed combinations: ${video.combinations.map((c) => [
@@ -6712,16 +8298,45 @@ function referenceByteLimit(model, input) {
6712
8298
  return Math.min(kindMax ?? Infinity, video.maxAssetBytes ?? Infinity, MEDIA_LIBRARY_MAX_BYTES);
6713
8299
  }
6714
8300
  /**
8301
+ * The longest a reference video may be in a mode: the limit the catalog declares, else the longest video the model
8302
+ * makes in that mode (from its durations). The production lanes declare no per-clip limit (0), and their providers
8303
+ * refuse a reference clip longer than the longest output, so a 15.2 s clip on a 15 s lane would fail upstream.
8304
+ * @param model - the video model.
8305
+ * @param constraint - the chosen mode's declaration, whose durations come before the model's.
8306
+ * @returns the limit and whether the catalog declared it, or undefined when nothing bounds the clips.
8307
+ */
8308
+ function referenceVideoLimit(model, constraint) {
8309
+ const video = model.video ?? {};
8310
+ if (video.maxReferenceVideoSeconds !== void 0) return {
8311
+ seconds: video.maxReferenceVideoSeconds,
8312
+ declared: true
8313
+ };
8314
+ const durations = constraint?.durations ?? video.durations ?? (video.combinations ?? []).flatMap((combo) => combo.duration === void 0 ? [] : [combo.duration]);
8315
+ return durations.length === 0 ? void 0 : {
8316
+ seconds: Math.max(...durations),
8317
+ declared: false
8318
+ };
8319
+ }
8320
+ /** A measured length for a message: two decimals, or three when two would not show it is over the limit. */
8321
+ function lengthText(durationMs, limitSeconds) {
8322
+ const two = (durationMs / 1e3).toFixed(2);
8323
+ return limitSeconds !== void 0 && durationMs > limitSeconds * 1e3 && Number(two) <= limitSeconds ? (durationMs / 1e3).toFixed(3) : two;
8324
+ }
8325
+ /**
6715
8326
  * Check the measured lengths of the reference media once the gateway has
6716
8327
  * measured them. A reference's OWN length is what is checked — never the
6717
- * requested output duration — and only against the limits that model declares.
8328
+ * requested output duration — against the limits that model declares; a
8329
+ * reference video on a model that declares no per-clip limit is held to the
8330
+ * longest video the model makes in the chosen mode ({@link referenceVideoLimit}).
6718
8331
  * @param model - the video model.
6719
8332
  * @param videos - the uploaded reference videos, in order.
6720
8333
  * @param audios - the uploaded reference audios, in order.
8334
+ * @param plan - the checked plan: its mode decides the limit a model without a declared one gets.
6721
8335
  * @throws {@link MediaError} when a clip or the total is outside the model's limits.
6722
8336
  */
6723
- function checkReferenceDurations(model, videos, audios = []) {
8337
+ function checkReferenceDurations(model, videos, audios = [], plan) {
6724
8338
  const video = model.video ?? {};
8339
+ const limit = referenceVideoLimit(model, plan?.constraint);
6725
8340
  let totalMs = 0;
6726
8341
  for (const [index, clip] of videos.entries()) {
6727
8342
  if (clip.durationMs === void 0) {
@@ -6730,7 +8345,10 @@ function checkReferenceDurations(model, videos, audios = []) {
6730
8345
  }
6731
8346
  const seconds = clip.durationMs / 1e3;
6732
8347
  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" });
6733
- 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" });
8348
+ if (limit !== void 0 && seconds > limit.seconds) {
8349
+ 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)`;
8350
+ 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" });
8351
+ }
6734
8352
  totalMs += clip.durationMs;
6735
8353
  }
6736
8354
  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" });
@@ -6900,7 +8518,7 @@ async function prepareVideoTask(runtime, call, request, save) {
6900
8518
  bytes: item.media.data.byteLength,
6901
8519
  ...assets[index]?.durationMs === void 0 ? {} : { durationMs: assets[index]?.durationMs }
6902
8520
  }] : []);
6903
- checkReferenceDurations(model, videos, audios);
8521
+ checkReferenceDurations(model, videos, audios, plan);
6904
8522
  const urls = {};
6905
8523
  for (const [index, item] of loaded.entries()) {
6906
8524
  const asset = assets[index];
@@ -7013,7 +8631,7 @@ function videoGenerateTool(runtime) {
7013
8631
  reference_videos: {
7014
8632
  type: "array",
7015
8633
  items: { type: "string" },
7016
- description: `Reference videos for motion, camera work or effects (omni_reference; MP4 or MOV). Each is ${SOURCE_HELP}.`
8634
+ 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}.`
7017
8635
  },
7018
8636
  reference_audios: {
7019
8637
  type: "array",
@@ -9397,8 +11015,24 @@ function apply(ctx, config) {
9397
11015
  })
9398
11016
  });
9399
11017
  account = accountService;
11018
+ const latency = new LatencyProbe({
11019
+ origin,
11020
+ userAgent
11021
+ });
9400
11022
  ctx.inject(["connection"], (scoped) => {
9401
- for (const accountRoute of accountRoutes(accountService)) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
11023
+ for (const accountRoute of [...accountRoutes(accountService), ...latencyRoutes(latency)]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
11024
+ });
11025
+ const feedback = installFeedback(ctx, {
11026
+ gateway: {
11027
+ origin,
11028
+ userAgent
11029
+ },
11030
+ gatewayDir: gatewayStateDirectory(stateDir, origin),
11031
+ pluginVersion: version,
11032
+ log: warn,
11033
+ identity: () => accountService.identity(),
11034
+ rejectCredential: (credential) => chain.reject(credential),
11035
+ onCredentialChange: (listener) => login.onChange(listener)
9402
11036
  });
9403
11037
  ctx.effect(() => {
9404
11038
  tracker.resume().catch((error) => {
@@ -9423,6 +11057,7 @@ function apply(ctx, config) {
9423
11057
  for await (const _view of accountCtx.deepseekAccount.watch(controller.signal)) {
9424
11058
  runtime.invalidateCatalog();
9425
11059
  accountService.credentialChanged();
11060
+ feedback.uploader.credentialChanged();
9426
11061
  }
9427
11062
  } catch {}
9428
11063
  })();
@@ -9433,6 +11068,6 @@ function apply(ctx, config) {
9433
11068
  });
9434
11069
  }
9435
11070
  //#endregion
9436
- export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, INSUFFICIENT_BALANCE_CODE, MediaError, MediaHostService, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, version };
11071
+ 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 };
9437
11072
 
9438
11073
  //# sourceMappingURL=index.js.map