@vibedev-si/dsh-vibedev 0.3.5 → 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/README.md +31 -3
- package/THIRD-PARTY-NOTICES.txt +1 -1
- package/client/client.js +619 -13
- package/lib/account/index.d.ts +19 -0
- package/lib/{anthropic-messages-KOS0z8Fy.js → anthropic-messages-BgIfgjNt.js} +11 -11
- package/lib/audio/request.d.ts +5 -0
- package/lib/feedback/client-info.d.ts +51 -0
- package/lib/feedback/index.d.ts +46 -0
- package/lib/feedback/observe.d.ts +43 -0
- package/lib/feedback/queue.d.ts +110 -0
- package/lib/feedback/recent-errors.d.ts +59 -0
- package/lib/feedback/routes.d.ts +31 -0
- package/lib/feedback/uploader.d.ts +131 -0
- package/lib/feedback/wire.d.ts +128 -0
- package/lib/gateway/assets.d.ts +38 -5
- package/lib/gateway/catalog.d.ts +11 -0
- package/lib/gateway/errors.d.ts +10 -3
- package/lib/gateway/http.d.ts +12 -0
- package/lib/index.d.ts +1 -0
- package/lib/index.js +1806 -370
- package/lib/{node-vkDR3GtK.js → node-Br-0fshF.js} +2 -2
- package/lib/{node-Cujw_a4_.js → node-D58f7Ea6.js} +5 -5
- package/lib/video/plan.d.ts +17 -2
- package/package.json +4 -1
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 {
|
|
12
|
+
import { credentialKey } from "@deepseek-ai/dsh-credentials";
|
|
12
13
|
import { spawn } from "node:child_process";
|
|
13
14
|
import { createServer } from "node:http";
|
|
14
15
|
import { idleWatchdog, timeoutOf } from "@deepseek-ai/dsh-timeout";
|
|
@@ -40,7 +41,7 @@ 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$
|
|
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;
|
|
45
46
|
/**
|
|
46
47
|
* A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
|
|
@@ -203,6 +204,24 @@ var AccountService = class {
|
|
|
203
204
|
};
|
|
204
205
|
}
|
|
205
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
|
+
/**
|
|
206
225
|
* `GET /v1/account/auth/me` for one token. A read younger than the TTL is
|
|
207
226
|
* reused; an older one is answered at once while a new read runs behind it.
|
|
208
227
|
*/
|
|
@@ -234,8 +253,8 @@ var AccountService = class {
|
|
|
234
253
|
redirect: "error"
|
|
235
254
|
});
|
|
236
255
|
if (!response.ok) return {};
|
|
237
|
-
const body = record$
|
|
238
|
-
const data = record$
|
|
256
|
+
const body = record$9(await response.json().catch(() => void 0));
|
|
257
|
+
const data = record$9(body?.data) ?? body;
|
|
239
258
|
const balance = amountOf(data?.balance);
|
|
240
259
|
const currency = text$8(data?.currency) ?? "CNY";
|
|
241
260
|
const frozen = amountOf(data?.frozen_balance);
|
|
@@ -342,7 +361,7 @@ function userOf(user) {
|
|
|
342
361
|
...nickname === void 0 ? {} : { nickname }
|
|
343
362
|
};
|
|
344
363
|
}
|
|
345
|
-
function json$
|
|
364
|
+
function json$2(status, body) {
|
|
346
365
|
return new Response(JSON.stringify(body), {
|
|
347
366
|
status,
|
|
348
367
|
headers: {
|
|
@@ -352,9 +371,9 @@ function json$1(status, body) {
|
|
|
352
371
|
});
|
|
353
372
|
}
|
|
354
373
|
function failure(error) {
|
|
355
|
-
const candidate = record$
|
|
374
|
+
const candidate = record$9(error)?.code;
|
|
356
375
|
const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
|
|
357
|
-
return json$
|
|
376
|
+
return json$2(500, { error: {
|
|
358
377
|
code,
|
|
359
378
|
message: code === "SIGN_IN_CANCELLED" ? "Sign-in was cancelled. 登录已取消。" : code === "SIGN_IN_TIMEOUT" ? "Sign-in expired. 登录已超时,请重新登录。" : "The account request could not be completed. 账号请求未完成,请查看登录诊断后重试。"
|
|
360
379
|
} });
|
|
@@ -375,7 +394,7 @@ function accountRoutes(account) {
|
|
|
375
394
|
const query = new URL(request.url, "http://host").searchParams;
|
|
376
395
|
const since = query.get("since");
|
|
377
396
|
if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
|
|
378
|
-
return json$
|
|
397
|
+
return json$2(200, await account.view(query.get("fresh") === "1"));
|
|
379
398
|
} catch (error) {
|
|
380
399
|
return failure(error);
|
|
381
400
|
}
|
|
@@ -387,8 +406,8 @@ function accountRoutes(account) {
|
|
|
387
406
|
requestBody: "buffered",
|
|
388
407
|
fetch: async (request) => {
|
|
389
408
|
try {
|
|
390
|
-
const body = record$
|
|
391
|
-
return json$
|
|
409
|
+
const body = record$9(await request.json().catch(() => void 0));
|
|
410
|
+
return json$2(200, await account.signIn(body?.open !== false));
|
|
392
411
|
} catch (error) {
|
|
393
412
|
return failure(error);
|
|
394
413
|
}
|
|
@@ -400,7 +419,7 @@ function accountRoutes(account) {
|
|
|
400
419
|
requestBody: "buffered",
|
|
401
420
|
fetch: () => {
|
|
402
421
|
account.cancel();
|
|
403
|
-
return Promise.resolve(json$
|
|
422
|
+
return Promise.resolve(json$2(200, { ok: true }));
|
|
404
423
|
}
|
|
405
424
|
},
|
|
406
425
|
{
|
|
@@ -409,7 +428,7 @@ function accountRoutes(account) {
|
|
|
409
428
|
requestBody: "buffered",
|
|
410
429
|
fetch: async () => {
|
|
411
430
|
try {
|
|
412
|
-
return await account.signOut() ? json$
|
|
431
|
+
return await account.signOut() ? json$2(200, { ok: true }) : json$2(409, { error: {
|
|
413
432
|
code: "SIGNED_IN_BY_APP",
|
|
414
433
|
message: "The VibeDev account is the app's sign-in; sign out in the app."
|
|
415
434
|
} });
|
|
@@ -427,7 +446,7 @@ const LATENCY_ROUTE = "/api/dsh-vibedev/latency";
|
|
|
427
446
|
/** Timed requests after the first one. */
|
|
428
447
|
const TIMED_REQUESTS = 4;
|
|
429
448
|
/** Each request gets this long, its body included. */
|
|
430
|
-
const REQUEST_TIMEOUT_MS = 5e3;
|
|
449
|
+
const REQUEST_TIMEOUT_MS$1 = 5e3;
|
|
431
450
|
/** A result is answered again for this long; `fresh` measures anyway. */
|
|
432
451
|
const RESULT_TTL_MS = 6e4;
|
|
433
452
|
/** One turn of the event loop, after which the previous request's connection is back in the pool. */
|
|
@@ -530,7 +549,7 @@ var LatencyProbe = class {
|
|
|
530
549
|
},
|
|
531
550
|
cache: "no-store",
|
|
532
551
|
redirect: "error",
|
|
533
|
-
signal: (this.options.timeout ?? ((ms) => AbortSignal.timeout(ms)))(REQUEST_TIMEOUT_MS)
|
|
552
|
+
signal: (this.options.timeout ?? ((ms) => AbortSignal.timeout(ms)))(REQUEST_TIMEOUT_MS$1)
|
|
534
553
|
};
|
|
535
554
|
const started = this.clock();
|
|
536
555
|
const response = await (this.options.fetch ?? globalThis.fetch)(`${this.options.origin}/health`, init);
|
|
@@ -540,7 +559,7 @@ var LatencyProbe = class {
|
|
|
540
559
|
return elapsed;
|
|
541
560
|
}
|
|
542
561
|
};
|
|
543
|
-
function json(status, body) {
|
|
562
|
+
function json$1(status, body) {
|
|
544
563
|
return new Response(JSON.stringify(body), {
|
|
545
564
|
status,
|
|
546
565
|
headers: {
|
|
@@ -561,9 +580,9 @@ function latencyRoutes(probe) {
|
|
|
561
580
|
requestBody: "buffered",
|
|
562
581
|
fetch: async (request) => {
|
|
563
582
|
try {
|
|
564
|
-
return json(200, await probe.measure(new URL(request.url, "http://host").searchParams.get("fresh") === "1"));
|
|
583
|
+
return json$1(200, await probe.measure(new URL(request.url, "http://host").searchParams.get("fresh") === "1"));
|
|
565
584
|
} catch {
|
|
566
|
-
return json(500, { error: {
|
|
585
|
+
return json$1(500, { error: {
|
|
567
586
|
code: "INTERNAL",
|
|
568
587
|
message: "The latency could not be measured. 网络延迟没有测成,请稍后重试。"
|
|
569
588
|
} });
|
|
@@ -572,6 +591,328 @@ function latencyRoutes(probe) {
|
|
|
572
591
|
}];
|
|
573
592
|
}
|
|
574
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
|
|
575
916
|
//#region src/gateway/errors.ts
|
|
576
917
|
/**
|
|
577
918
|
* Failures the plugin reports to the model: a gateway refusal, or a request the
|
|
@@ -598,7 +939,7 @@ var MediaError = class extends HarnessError {
|
|
|
598
939
|
this.details = details;
|
|
599
940
|
}
|
|
600
941
|
};
|
|
601
|
-
function record$
|
|
942
|
+
function record$8(value) {
|
|
602
943
|
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
603
944
|
}
|
|
604
945
|
function text$7(value) {
|
|
@@ -616,19 +957,22 @@ function amount$1(value) {
|
|
|
616
957
|
/**
|
|
617
958
|
* Read a gateway error body. The gateway answers in several shapes: OpenAI's
|
|
618
959
|
* `{error:{code,message,type}}`, its own `{error:{code,message,retryable,field}}`,
|
|
619
|
-
* the account API's `{code,message,reason}
|
|
620
|
-
*
|
|
621
|
-
*
|
|
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).
|
|
622
964
|
* @param body - the parsed JSON body, or undefined when it was not JSON.
|
|
623
965
|
* @returns the fields found.
|
|
624
966
|
*/
|
|
625
967
|
function parseGatewayFailure(body) {
|
|
626
|
-
const root = record$
|
|
968
|
+
const root = record$8(body);
|
|
627
969
|
if (root === void 0) return {};
|
|
628
|
-
const source = record$
|
|
970
|
+
const source = record$8(root.error) ?? root;
|
|
971
|
+
const metadata = record$8(source.metadata) ?? record$8(root.metadata);
|
|
629
972
|
const code = text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
|
|
630
973
|
const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
|
|
631
|
-
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);
|
|
632
976
|
const rechargeUrl = text$7(source.recharge_url) ?? text$7(root.recharge_url);
|
|
633
977
|
const numbers = {
|
|
634
978
|
active: count$1(source.active),
|
|
@@ -641,14 +985,17 @@ function parseGatewayFailure(body) {
|
|
|
641
985
|
};
|
|
642
986
|
const submissionState = text$7(source.submission_state) ?? text$7(root.submission_state);
|
|
643
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);
|
|
644
989
|
return {
|
|
645
990
|
...code === void 0 ? {} : { code },
|
|
646
991
|
...message === void 0 ? {} : { message },
|
|
647
992
|
...field === void 0 ? {} : { field },
|
|
993
|
+
...rule === void 0 ? {} : { rule },
|
|
648
994
|
...typeof source.retryable === "boolean" ? { retryable: source.retryable } : {},
|
|
649
995
|
...submissionState === void 0 ? {} : { submissionState: submissionState.toLowerCase() },
|
|
650
996
|
...retryAction === void 0 ? {} : { retryAction: retryAction.toLowerCase() },
|
|
651
997
|
...rechargeUrl === void 0 ? {} : { rechargeUrl },
|
|
998
|
+
...assetId === void 0 ? {} : { assetId },
|
|
652
999
|
...Object.fromEntries(Object.entries({
|
|
653
1000
|
...numbers,
|
|
654
1001
|
...amounts
|
|
@@ -748,109 +1095,1195 @@ async function renameWithRetry(from, to) {
|
|
|
748
1095
|
await new Promise((resolve) => setTimeout(resolve, 50 * 2 ** attempt));
|
|
749
1096
|
}
|
|
750
1097
|
}
|
|
751
|
-
/**
|
|
752
|
-
* Move a complete temporary file to the first free name `dir/stem.ext`
|
|
753
|
-
* (then `stem-2.ext`, ...), never replacing an existing file.
|
|
754
|
-
* @param temporary - the complete file.
|
|
755
|
-
* @param dir - the destination directory, created when missing.
|
|
756
|
-
* @param stem - the file-name stem.
|
|
757
|
-
* @param extension - the extension, without a dot.
|
|
758
|
-
* @returns the final path.
|
|
759
|
-
*/
|
|
760
|
-
async function placeFile(temporary, dir, stem, extension) {
|
|
761
|
-
await mkdir(dir, { recursive: true });
|
|
762
|
-
let linkable = true;
|
|
763
|
-
for (let attempt = 1; attempt < 1e3; attempt++) {
|
|
764
|
-
const path = join(dir, `${attempt === 1 ? stem : `${stem}-${attempt}`}.${extension}`);
|
|
765
|
-
if (linkable) try {
|
|
766
|
-
await link(temporary, path);
|
|
767
|
-
await rm(temporary, { force: true });
|
|
768
|
-
return path;
|
|
769
|
-
} catch (error) {
|
|
770
|
-
if (error.code === "EEXIST") continue;
|
|
771
|
-
linkable = false;
|
|
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);
|
|
772
1977
|
}
|
|
1978
|
+
}
|
|
1979
|
+
async identity() {
|
|
773
1980
|
try {
|
|
774
|
-
|
|
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
|
+
};
|
|
775
2112
|
} catch (error) {
|
|
776
|
-
if (error
|
|
777
|
-
|
|
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
|
+
};
|
|
778
2176
|
}
|
|
779
|
-
await renameWithRetry(temporary, path);
|
|
780
|
-
return path;
|
|
781
2177
|
}
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
* Save bytes under the first free name `dir/stem.ext`.
|
|
786
|
-
* @param dir - the destination directory.
|
|
787
|
-
* @param stem - the file-name stem.
|
|
788
|
-
* @param extension - the extension, without a dot.
|
|
789
|
-
* @param data - the content.
|
|
790
|
-
* @returns the final path.
|
|
791
|
-
*/
|
|
792
|
-
async function saveNewFile(dir, stem, extension, data) {
|
|
793
|
-
await mkdir(dir, { recursive: true });
|
|
794
|
-
const temporary = join(dir, `.dsh-media-${randomUUID()}.part`);
|
|
795
|
-
try {
|
|
796
|
-
await writeFile(temporary, data);
|
|
797
|
-
return await placeFile(temporary, dir, stem, extension);
|
|
798
|
-
} finally {
|
|
799
|
-
await rm(temporary, { force: true });
|
|
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));
|
|
800
2181
|
}
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
* Write bytes atomically, replacing the file.
|
|
804
|
-
* @param path - the final path.
|
|
805
|
-
* @param data - the content.
|
|
806
|
-
* @param options - `mode` for a file only its owner may read.
|
|
807
|
-
*/
|
|
808
|
-
async function writeFileAtomic(path, data, options = {}) {
|
|
809
|
-
await mkdir(dirname(path), { recursive: true });
|
|
810
|
-
const temporary = join(dirname(path), `.${randomUUID()}.part`);
|
|
811
|
-
try {
|
|
812
|
-
await writeFile(temporary, data, options.mode === void 0 ? {} : { mode: options.mode });
|
|
813
|
-
await renameWithRetry(temporary, path);
|
|
814
|
-
} catch (error) {
|
|
815
|
-
await rm(temporary, { force: true });
|
|
816
|
-
throw error;
|
|
2182
|
+
jitter(ms) {
|
|
2183
|
+
return Math.round(ms * (.5 + (this.options.random ?? Math.random)()));
|
|
817
2184
|
}
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
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
|
+
}
|
|
832
2202
|
}
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
await writeFile(temporary, data);
|
|
839
|
-
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);
|
|
840
2208
|
}
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
await rm(temporary, { force: true }).catch(() => void 0);
|
|
852
|
-
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);
|
|
853
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
|
+
};
|
|
854
2287
|
}
|
|
855
2288
|
//#endregion
|
|
856
2289
|
//#region src/gateway/origin.ts
|
|
@@ -2463,7 +3896,7 @@ function isContextOverflow(message, contextWindow) {
|
|
|
2463
3896
|
}
|
|
2464
3897
|
//#endregion
|
|
2465
3898
|
//#region node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
|
|
2466
|
-
const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-
|
|
3899
|
+
const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-BgIfgjNt.js").then((n) => n.t));
|
|
2467
3900
|
//#endregion
|
|
2468
3901
|
//#region node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
|
|
2469
3902
|
const openAICompletionsApi = () => lazyApi(() => import("./openai-completions-DqTCiqpS.js"));
|
|
@@ -2953,7 +4386,7 @@ const SIGN_IN_REQUIRED_CODE = "VIBEDEV_SIGN_IN_REQUIRED";
|
|
|
2953
4386
|
/** Failure code for a used-up balance; not the Harness's `ACCOUNT_QUOTA`, which opens the DeepSeek top-up. */
|
|
2954
4387
|
const INSUFFICIENT_BALANCE_CODE = "VIBEDEV_INSUFFICIENT_BALANCE";
|
|
2955
4388
|
/** What a person reads when a VibeDev model is used before signing in. */
|
|
2956
|
-
const SIGN_IN_MESSAGE
|
|
4389
|
+
const SIGN_IN_MESSAGE = "请先登录 VibeDev:在侧边栏底部「登录 VibeDev」或「设置 → VibeDev 账号」中登录后即可使用这些模型。 Sign in to VibeDev (sidebar, or Settings → VibeDev account) to use these models.";
|
|
2957
4390
|
/** What a person reads when the gateway ended the sign-in and a refresh could not renew it. */
|
|
2958
4391
|
const SESSION_ENDED_MESSAGE = "VibeDev 登录已失效,请重新登录(侧边栏底部或「设置 → VibeDev 账号」)。 Your VibeDev sign-in has ended; sign in again.";
|
|
2959
4392
|
/**
|
|
@@ -3031,7 +4464,7 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
3031
4464
|
}
|
|
3032
4465
|
modelOf(snapshot, provider, id) {
|
|
3033
4466
|
this.assertOwned(provider);
|
|
3034
|
-
if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE
|
|
4467
|
+
if (snapshot.catalog.length === 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
|
|
3035
4468
|
const catalog = snapshot.byId.get(id);
|
|
3036
4469
|
const model = snapshot.models.getModel(provider, id);
|
|
3037
4470
|
if (catalog === void 0 || model === void 0) throw new LlmError(`VibeDev has no model "${id}"`, "UNKNOWN_MODEL");
|
|
@@ -3091,7 +4524,7 @@ var GatewayAdapter = class extends LlmAdapter {
|
|
|
3091
4524
|
const starting = startingReasoning(catalog);
|
|
3092
4525
|
const reasoning = resolveReasoningLevel(model, options.reasoningEffort ?? (starting === void 0 ? void 0 : effortOf(starting)));
|
|
3093
4526
|
let credential = await this.config.resolveCredential();
|
|
3094
|
-
if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE
|
|
4527
|
+
if (credential === void 0) throw new LlmError(SIGN_IN_MESSAGE, SIGN_IN_REQUIRED_CODE);
|
|
3095
4528
|
const sessionId = options.sessionId === void 0 ? void 0 : String(options.sessionId);
|
|
3096
4529
|
const deviceId = model.api === "anthropic-messages" && sessionId !== void 0 ? await this.config.deviceId?.() : void 0;
|
|
3097
4530
|
const consumer = new AbortController();
|
|
@@ -3503,10 +4936,31 @@ function installGatewayModels(ctx, options) {
|
|
|
3503
4936
|
* the returned upload headers when an upload is needed, `POST /{id}/complete`.
|
|
3504
4937
|
* An asset the library already holds is read back through `/refresh`, which
|
|
3505
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).
|
|
3506
4954
|
* @module dsh-vibedev/gateway/assets
|
|
3507
4955
|
*/
|
|
3508
4956
|
/** How long before expiry a cached asset is refreshed instead of reused. */
|
|
3509
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;
|
|
3510
4964
|
const record$4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
3511
4965
|
const text$5 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
|
|
3512
4966
|
const httpUrl$1 = (value) => {
|
|
@@ -3536,39 +4990,140 @@ function parseAsset(body, fallbackType) {
|
|
|
3536
4990
|
...typeof duration === "number" && Number.isFinite(duration) && duration > 0 ? { durationMs: duration } : {}
|
|
3537
4991
|
};
|
|
3538
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
|
+
}
|
|
3539
5000
|
/** Uploads references and remembers them for the life of the plugin. */
|
|
3540
5001
|
var MediaLibrary = class {
|
|
3541
5002
|
http;
|
|
3542
5003
|
now;
|
|
5004
|
+
options;
|
|
3543
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;
|
|
3544
5009
|
/**
|
|
3545
5010
|
* @param http - the gateway client.
|
|
3546
|
-
* @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).
|
|
3547
5013
|
*/
|
|
3548
|
-
constructor(http, now = Date.now) {
|
|
5014
|
+
constructor(http, now = Date.now, options = {}) {
|
|
3549
5015
|
this.http = http;
|
|
3550
5016
|
this.now = now;
|
|
5017
|
+
this.options = options;
|
|
3551
5018
|
}
|
|
3552
5019
|
/** Forget every remembered asset, as after an account change: assets belong to the account that uploaded them. */
|
|
3553
5020
|
clear() {
|
|
5021
|
+
this.generation++;
|
|
3554
5022
|
this.cache.clear();
|
|
5023
|
+
this.flights.clear();
|
|
3555
5024
|
}
|
|
3556
5025
|
/**
|
|
3557
|
-
* 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.
|
|
3558
5028
|
* @param media - the loaded input.
|
|
3559
5029
|
* @param purpose - the asset purpose.
|
|
3560
|
-
* @param signal - cancels the upload.
|
|
5030
|
+
* @param signal - cancels this caller's wait (and the upload, once no caller waits on it).
|
|
3561
5031
|
* @returns the asset.
|
|
3562
5032
|
*/
|
|
3563
5033
|
async upload(media, purpose, signal) {
|
|
5034
|
+
if (signal?.aborted === true) throw abortError(signal);
|
|
3564
5035
|
const sha256 = createHash("sha256").update(media.data).digest("hex");
|
|
3565
5036
|
const key = `${purpose}:${sha256}`;
|
|
3566
5037
|
const cached = this.cache.get(key);
|
|
3567
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}`);
|
|
3568
5094
|
if (cached !== void 0) {
|
|
3569
5095
|
const refreshed = await this.refresh(cached, signal).catch(() => void 0);
|
|
3570
|
-
if (refreshed !== void 0) return
|
|
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);
|
|
3571
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) {
|
|
3572
5127
|
const created = record$4(await this.http.json("/v1/media-assets/uploads", {
|
|
3573
5128
|
method: "POST",
|
|
3574
5129
|
json: {
|
|
@@ -3578,20 +5133,31 @@ var MediaLibrary = class {
|
|
|
3578
5133
|
sha256,
|
|
3579
5134
|
purpose
|
|
3580
5135
|
},
|
|
3581
|
-
|
|
5136
|
+
signal
|
|
3582
5137
|
}));
|
|
3583
5138
|
const assetId = text$5(created?.asset_id);
|
|
3584
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");
|
|
3585
|
-
if (created.upload_required
|
|
3586
|
-
|
|
3587
|
-
|
|
3588
|
-
|
|
3589
|
-
|
|
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: {
|
|
3590
5153
|
...facts,
|
|
3591
5154
|
sha256,
|
|
3592
5155
|
bytes: media.data.byteLength
|
|
3593
|
-
}
|
|
3594
|
-
}
|
|
5156
|
+
}
|
|
5157
|
+
};
|
|
5158
|
+
}
|
|
5159
|
+
/** PUT the bytes where `uploads` said, then `complete`. */
|
|
5160
|
+
async put(media, sha256, assetId, created, signal) {
|
|
3595
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);
|
|
3596
5162
|
if (uploadUrl === void 0) throw new MediaError(`The VibeDev gateway returned no upload address for "${media.source}".`, "ASSET_UPLOAD_URL_MISSING");
|
|
3597
5163
|
const headers = { "content-type": media.mime };
|
|
@@ -3603,25 +5169,21 @@ var MediaLibrary = class {
|
|
|
3603
5169
|
anonymous: true,
|
|
3604
5170
|
timeoutMs: 6e5,
|
|
3605
5171
|
busyRetries: 1,
|
|
3606
|
-
|
|
5172
|
+
signal
|
|
3607
5173
|
});
|
|
3608
5174
|
const completed = await this.read(assetId, "complete", media.mime, signal);
|
|
3609
5175
|
if (completed === void 0) throw new MediaError(`The VibeDev gateway returned no address for "${media.source}" after the upload.`, "ASSET_REFERENCE_MISSING");
|
|
3610
|
-
return
|
|
5176
|
+
return {
|
|
3611
5177
|
...completed,
|
|
3612
5178
|
sha256,
|
|
3613
5179
|
bytes: media.data.byteLength
|
|
3614
|
-
}
|
|
5180
|
+
};
|
|
3615
5181
|
}
|
|
3616
5182
|
expiring(asset) {
|
|
3617
5183
|
if (asset.expiresAt === void 0) return false;
|
|
3618
5184
|
const at = Date.parse(asset.expiresAt);
|
|
3619
5185
|
return Number.isFinite(at) && at - this.now() < EXPIRY_MARGIN_MS;
|
|
3620
5186
|
}
|
|
3621
|
-
remember(key, asset) {
|
|
3622
|
-
this.cache.set(key, asset);
|
|
3623
|
-
return asset;
|
|
3624
|
-
}
|
|
3625
5187
|
async refresh(asset, signal) {
|
|
3626
5188
|
const facts = await this.read(asset.assetId, "refresh", asset.contentType, signal);
|
|
3627
5189
|
return facts === void 0 ? void 0 : {
|
|
@@ -3638,218 +5200,6 @@ var MediaLibrary = class {
|
|
|
3638
5200
|
}
|
|
3639
5201
|
};
|
|
3640
5202
|
//#endregion
|
|
3641
|
-
//#region src/gateway/http.ts
|
|
3642
|
-
/**
|
|
3643
|
-
* HTTP client for the VibeDev gateway. Every gateway call goes through here so
|
|
3644
|
-
* authentication, refresh after a 401, balance refusals, busy back-off and
|
|
3645
|
-
* idempotency are handled once.
|
|
3646
|
-
*
|
|
3647
|
-
* The credential is attached only to requests on the gateway origin: upload
|
|
3648
|
-
* URLs and third-party links never see it.
|
|
3649
|
-
* @module dsh-vibedev/gateway/http
|
|
3650
|
-
*/
|
|
3651
|
-
/** Error codes the gateway uses for "full right now, nothing was charged". */
|
|
3652
|
-
const BUSY_CODES = /* @__PURE__ */ new Set([
|
|
3653
|
-
"APP_TOKEN_UNAVAILABLE",
|
|
3654
|
-
"PROVIDER_CAPACITY_BUSY",
|
|
3655
|
-
"upstream_capacity_busy",
|
|
3656
|
-
"AUDIO_CAPACITY_BUSY",
|
|
3657
|
-
"AUDIO_NO_AVAILABLE_ACCOUNT",
|
|
3658
|
-
"WEB_SEARCH_BUSY",
|
|
3659
|
-
"WEB_SEARCH_RATE_LIMITED"
|
|
3660
|
-
]);
|
|
3661
|
-
/**
|
|
3662
|
-
* The account already runs as many video or audio tasks as it may (HTTP 429).
|
|
3663
|
-
* Not retried here: a slot frees only when one of the user's tasks finishes.
|
|
3664
|
-
*/
|
|
3665
|
-
const TASK_LIMIT_CODES = /* @__PURE__ */ new Set(["VIDEO_TASK_LIMIT_REACHED", "AUDIO_TASK_LIMIT_REACHED"]);
|
|
3666
|
-
const DEFAULT_TIMEOUT_MS = 6e4;
|
|
3667
|
-
const DEFAULT_BUSY_WAIT_MS = 2e3;
|
|
3668
|
-
/** The message for a call made while nobody is signed in. */
|
|
3669
|
-
const SIGN_IN_MESSAGE = "VibeDev media generation needs a signed-in VibeDev account. Call media_account with action \"sign_in\": it opens the VibeDev sign-in page in the user's browser, where new users can also register. In the VibeDev app, the account signed in to the app is used automatically.";
|
|
3670
|
-
/** Read through a call so a check made before an `await` is not taken as still true after it. */
|
|
3671
|
-
function isAborted(signal) {
|
|
3672
|
-
return signal?.aborted === true;
|
|
3673
|
-
}
|
|
3674
|
-
function delay$1(ms, signal) {
|
|
3675
|
-
return new Promise((resolve, reject) => {
|
|
3676
|
-
if (isAborted(signal)) {
|
|
3677
|
-
reject(abortError(signal));
|
|
3678
|
-
return;
|
|
3679
|
-
}
|
|
3680
|
-
const timer = setTimeout(() => {
|
|
3681
|
-
signal?.removeEventListener("abort", onAbort);
|
|
3682
|
-
resolve();
|
|
3683
|
-
}, ms);
|
|
3684
|
-
const onAbort = () => {
|
|
3685
|
-
clearTimeout(timer);
|
|
3686
|
-
reject(abortError(signal));
|
|
3687
|
-
};
|
|
3688
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
3689
|
-
});
|
|
3690
|
-
}
|
|
3691
|
-
function abortError(signal) {
|
|
3692
|
-
return new MediaError("The media request was cancelled.", "ABORTED", { retryable: true }, { cause: signal?.reason });
|
|
3693
|
-
}
|
|
3694
|
-
/** Gateway HTTP client. */
|
|
3695
|
-
var GatewayHttp = class {
|
|
3696
|
-
options;
|
|
3697
|
-
origin;
|
|
3698
|
-
/**
|
|
3699
|
-
* @param options - origin, credential plane, user agent and test seams.
|
|
3700
|
-
*/
|
|
3701
|
-
constructor(options) {
|
|
3702
|
-
this.options = options;
|
|
3703
|
-
this.origin = options.origin.trim().replace(/\/+$/, "");
|
|
3704
|
-
}
|
|
3705
|
-
/** Absolute URL for a gateway path, or the URL itself when already absolute. */
|
|
3706
|
-
url(path) {
|
|
3707
|
-
return /^https?:\/\//i.test(path) ? path : `${this.origin}${path.startsWith("/") ? "" : "/"}${path}`;
|
|
3708
|
-
}
|
|
3709
|
-
/** Whether a URL is on the gateway origin, and so may carry the credential. */
|
|
3710
|
-
isGatewayUrl(url) {
|
|
3711
|
-
try {
|
|
3712
|
-
return new URL(url).origin === new URL(this.origin).origin;
|
|
3713
|
-
} catch {
|
|
3714
|
-
return false;
|
|
3715
|
-
}
|
|
3716
|
-
}
|
|
3717
|
-
/**
|
|
3718
|
-
* Send one request and return the successful response.
|
|
3719
|
-
* @param path - gateway path, or an absolute URL.
|
|
3720
|
-
* @param request - method, body, headers and retry policy.
|
|
3721
|
-
* @returns the 2xx response, body unread.
|
|
3722
|
-
* @throws {@link MediaError} for every refusal, with the gateway's code.
|
|
3723
|
-
*/
|
|
3724
|
-
async send(path, request = {}) {
|
|
3725
|
-
const url = this.url(path);
|
|
3726
|
-
const authenticate = request.anonymous !== true && this.isGatewayUrl(url);
|
|
3727
|
-
let credential = authenticate ? await this.credential() : void 0;
|
|
3728
|
-
let refreshed = false;
|
|
3729
|
-
let busyRetries = request.busyRetries ?? 2;
|
|
3730
|
-
for (;;) {
|
|
3731
|
-
const response = await this.attempt(url, request, credential);
|
|
3732
|
-
if (response.ok) {
|
|
3733
|
-
if (authenticate) try {
|
|
3734
|
-
this.options.onAccepted?.({
|
|
3735
|
-
method: request.method ?? "GET",
|
|
3736
|
-
path: new URL(url).pathname
|
|
3737
|
-
});
|
|
3738
|
-
} catch {}
|
|
3739
|
-
return response;
|
|
3740
|
-
}
|
|
3741
|
-
const failure = parseGatewayFailure(await response.clone().json().catch(() => void 0));
|
|
3742
|
-
if (response.status === 401 && credential !== void 0 && credential.kind !== "key" && !refreshed) {
|
|
3743
|
-
refreshed = true;
|
|
3744
|
-
await this.options.rejectToken?.(credential);
|
|
3745
|
-
credential = await this.credential();
|
|
3746
|
-
continue;
|
|
3747
|
-
}
|
|
3748
|
-
const wait = retryAfterMs(response.headers.get("retry-after"));
|
|
3749
|
-
if (isBusy(response.status, failure, wait) && busyRetries > 0 && (wait ?? DEFAULT_BUSY_WAIT_MS) <= (request.maxBusyWaitMs ?? 15e3)) {
|
|
3750
|
-
busyRetries--;
|
|
3751
|
-
await (this.options.sleep ?? delay$1)(wait ?? DEFAULT_BUSY_WAIT_MS, request.signal);
|
|
3752
|
-
continue;
|
|
3753
|
-
}
|
|
3754
|
-
throw failureError$1(response.status, failure, wait);
|
|
3755
|
-
}
|
|
3756
|
-
}
|
|
3757
|
-
/**
|
|
3758
|
-
* Send one request and parse its JSON body.
|
|
3759
|
-
* @param path - gateway path, or an absolute URL.
|
|
3760
|
-
* @param request - method, body, headers and retry policy.
|
|
3761
|
-
* @returns the parsed body.
|
|
3762
|
-
*/
|
|
3763
|
-
async json(path, request = {}) {
|
|
3764
|
-
const response = await this.send(path, request);
|
|
3765
|
-
try {
|
|
3766
|
-
return await response.json();
|
|
3767
|
-
} catch (error) {
|
|
3768
|
-
throw new MediaError(`The VibeDev gateway returned an unreadable answer for ${path}.`, "GATEWAY_BAD_RESPONSE", { status: response.status }, { cause: error });
|
|
3769
|
-
}
|
|
3770
|
-
}
|
|
3771
|
-
async credential() {
|
|
3772
|
-
const credential = await this.options.resolveCredential();
|
|
3773
|
-
if (credential === void 0) throw new MediaError(SIGN_IN_MESSAGE, "NOT_SIGNED_IN");
|
|
3774
|
-
return credential;
|
|
3775
|
-
}
|
|
3776
|
-
async attempt(url, request, credential) {
|
|
3777
|
-
if (isAborted(request.signal)) throw abortError(request.signal);
|
|
3778
|
-
const headers = {
|
|
3779
|
-
accept: "application/json",
|
|
3780
|
-
"user-agent": this.options.userAgent,
|
|
3781
|
-
...request.headers
|
|
3782
|
-
};
|
|
3783
|
-
if (credential !== void 0) headers.authorization = `Bearer ${credential.token}`;
|
|
3784
|
-
if (request.idempotencyKey !== void 0) headers["idempotency-key"] = request.idempotencyKey;
|
|
3785
|
-
let body = request.body;
|
|
3786
|
-
if (request.json !== void 0) {
|
|
3787
|
-
body = JSON.stringify(request.json);
|
|
3788
|
-
headers["content-type"] = "application/json";
|
|
3789
|
-
}
|
|
3790
|
-
const timeout = AbortSignal.timeout(request.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
|
3791
|
-
const signal = request.signal === void 0 ? timeout : AbortSignal.any([request.signal, timeout]);
|
|
3792
|
-
try {
|
|
3793
|
-
return await (this.options.fetch ?? globalThis.fetch)(url, {
|
|
3794
|
-
method: request.method ?? (body === void 0 ? "GET" : "POST"),
|
|
3795
|
-
headers,
|
|
3796
|
-
...body === void 0 ? {} : { body },
|
|
3797
|
-
redirect: "error",
|
|
3798
|
-
signal
|
|
3799
|
-
});
|
|
3800
|
-
} catch (error) {
|
|
3801
|
-
if (isAborted(request.signal)) throw abortError(request.signal);
|
|
3802
|
-
if (timeout.aborted) throw new MediaError(`The VibeDev gateway did not answer within ${Math.round((request.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3)} s.`, "GATEWAY_TIMEOUT", { retryable: true });
|
|
3803
|
-
throw new MediaError(`Could not reach the VibeDev gateway (${error instanceof Error ? error.message : String(error)}). Ask the user to check the network connection.`, "GATEWAY_UNREACHABLE", { retryable: true });
|
|
3804
|
-
}
|
|
3805
|
-
}
|
|
3806
|
-
};
|
|
3807
|
-
/**
|
|
3808
|
-
* Whether an answer means "full right now, nothing was charged": any 429 but a
|
|
3809
|
-
* task limit, or a 503 with a busy code or `Retry-After`. A bare 503 is an outage.
|
|
3810
|
-
*/
|
|
3811
|
-
function isBusy(status, failure, wait) {
|
|
3812
|
-
if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return false;
|
|
3813
|
-
return status === 429 || status === 503 && (failure.code !== void 0 && BUSY_CODES.has(failure.code) || wait !== void 0);
|
|
3814
|
-
}
|
|
3815
|
-
/**
|
|
3816
|
-
* The error for an answer the client does not retry, worded for the model.
|
|
3817
|
-
* @param status - HTTP status.
|
|
3818
|
-
* @param failure - the parsed error body.
|
|
3819
|
-
* @param wait - Retry-After in milliseconds, when given.
|
|
3820
|
-
* @returns the error to throw.
|
|
3821
|
-
*/
|
|
3822
|
-
function failureError$1(status, failure, wait) {
|
|
3823
|
-
const words = gatewayWords(failure);
|
|
3824
|
-
const { code: _code, message: _message, ...facts } = failure;
|
|
3825
|
-
const details = {
|
|
3826
|
-
status,
|
|
3827
|
-
...facts,
|
|
3828
|
-
...wait === void 0 ? {} : { retryAfterMs: wait }
|
|
3829
|
-
};
|
|
3830
|
-
if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return new MediaError(`The VibeDev account already runs as many ${failure.code.startsWith("VIDEO") ? "video" : "audio"} tasks at once as it may${failure.active === void 0 || failure.limit === void 0 ? "" : ` (${failure.active} of ${failure.limit})`}. Wait for one of them to finish (media_tasks lists them), then submit again; nothing was charged.`, failure.code, {
|
|
3831
|
-
...details,
|
|
3832
|
-
retryable: true
|
|
3833
|
-
});
|
|
3834
|
-
if (status === 402) return new MediaError(`The VibeDev account balance is not enough for this request${(failure.estimatedCny === void 0 ? "" : `: this task is estimated at ¥${failure.estimatedCny}${failure.availableCny === void 0 ? "" : `, and ¥${failure.availableCny} is available`}${failure.pendingCny === void 0 || Number(failure.pendingCny) === 0 ? "" : ` (tasks in progress hold ¥${failure.pendingCny})`}`) || words}. Nothing was charged. Ask the user to top up their VibeDev balance${failure.rechargeUrl === void 0 ? "" : ` at ${failure.rechargeUrl}`}.`, "INSUFFICIENT_BALANCE", {
|
|
3835
|
-
...details,
|
|
3836
|
-
retryable: false
|
|
3837
|
-
});
|
|
3838
|
-
if (status === 401) return new MediaError(`The VibeDev gateway rejected the sign-in${words}. Ask the user to sign in to VibeDev again.`, "SIGN_IN_REJECTED", {
|
|
3839
|
-
...details,
|
|
3840
|
-
retryable: false
|
|
3841
|
-
});
|
|
3842
|
-
if (isBusy(status, failure, wait)) {
|
|
3843
|
-
const seconds = wait === void 0 ? void 0 : Math.ceil(wait / 1e3);
|
|
3844
|
-
return new MediaError(`The VibeDev gateway is busy${words}. ${seconds === void 0 ? "Try again shortly" : `Try again in about ${seconds} s`}; nothing was charged.`, failure.code ?? (status === 429 ? "RATE_LIMITED" : "GATEWAY_BUSY"), {
|
|
3845
|
-
...details,
|
|
3846
|
-
retryable: true,
|
|
3847
|
-
busy: true
|
|
3848
|
-
});
|
|
3849
|
-
}
|
|
3850
|
-
return new MediaError(`The VibeDev gateway refused the request with HTTP ${status}${words}.`, failure.code ?? `HTTP_${status}`, details);
|
|
3851
|
-
}
|
|
3852
|
-
//#endregion
|
|
3853
5203
|
//#region src/gateway/catalog.ts
|
|
3854
5204
|
/** The video generation modes of catalog schema v1, under their wire names. */
|
|
3855
5205
|
const VIDEO_MODES = [
|
|
@@ -4128,14 +5478,15 @@ function stringChoices(raw) {
|
|
|
4128
5478
|
}
|
|
4129
5479
|
return Object.keys(out).length === 0 ? void 0 : out;
|
|
4130
5480
|
}
|
|
4131
|
-
function parseReferenceLimits(raw) {
|
|
5481
|
+
function parseReferenceLimits(raw, form) {
|
|
4132
5482
|
if (raw === void 0) return void 0;
|
|
4133
5483
|
const max = count(field(raw, "max_count")) ?? count(raw.max);
|
|
4134
5484
|
if (max === void 0 || max === 0) return void 0;
|
|
4135
5485
|
const min = count(field(raw, "min_count")) ?? count(raw.min) ?? 0;
|
|
4136
5486
|
const limits = {
|
|
4137
5487
|
min: Math.min(min, max),
|
|
4138
|
-
max
|
|
5488
|
+
max,
|
|
5489
|
+
form
|
|
4139
5490
|
};
|
|
4140
5491
|
for (const [key, ...names] of [
|
|
4141
5492
|
[
|
|
@@ -4167,13 +5518,31 @@ function parseReferenceLimits(raw) {
|
|
|
4167
5518
|
return limits;
|
|
4168
5519
|
}
|
|
4169
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
|
+
/**
|
|
4170
5539
|
* The output formats, in either declared shape: `output_formats: [{format, sample_rates}]`,
|
|
4171
5540
|
* or `output_formats: ['wav','mp3']` with `sample_rates: {wav: [...], mp3: [...]}`.
|
|
4172
5541
|
*/
|
|
4173
5542
|
function parseOutputFormats(raw) {
|
|
4174
5543
|
const declared = field(raw, "output_formats");
|
|
4175
5544
|
if (!Array.isArray(declared)) return void 0;
|
|
4176
|
-
const rates = record$3(field(raw, "sample_rates"));
|
|
5545
|
+
const rates = record$3(field(raw, "sample_rates")) ?? record$3(field(raw, "output_sample_rates"));
|
|
4177
5546
|
const formats = [];
|
|
4178
5547
|
for (const item of declared) {
|
|
4179
5548
|
const entry = record$3(item);
|
|
@@ -4202,10 +5571,16 @@ function parseAudioCapabilities(raw) {
|
|
|
4202
5571
|
const billingUnit = billingRaw === "generation" || billingRaw === "original_second" || billingRaw === "minute" ? billingRaw : void 0;
|
|
4203
5572
|
const promptField = text$4(field(raw, "prompt_field"));
|
|
4204
5573
|
const requestFields = list(raw, "request_fields") ?? [];
|
|
4205
|
-
const
|
|
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);
|
|
4206
5580
|
const outputFormats = parseOutputFormats(raw);
|
|
4207
5581
|
const defaultFormat = text$4(field(raw, "default_format"))?.toLowerCase();
|
|
4208
5582
|
const choices = stringChoices(field(raw, "choices") ?? field(raw, "field_options"));
|
|
5583
|
+
const watermarkFields = list(raw, "watermark_fields");
|
|
4209
5584
|
const result = { requestFields };
|
|
4210
5585
|
if (generationKind !== void 0) result.generationKind = generationKind;
|
|
4211
5586
|
if (promptField !== void 0) result.promptField = promptField;
|
|
@@ -4214,11 +5589,13 @@ function parseAudioCapabilities(raw) {
|
|
|
4214
5589
|
if (outputFormats !== void 0) result.outputFormats = outputFormats;
|
|
4215
5590
|
if (defaultFormat !== void 0 && outputFormats?.some((format) => format.format === defaultFormat) === true) result.defaultFormat = defaultFormat;
|
|
4216
5591
|
if (choices !== void 0) result.choices = choices;
|
|
5592
|
+
if (watermarkFields !== void 0 && watermarkFields.length > 0) result.watermarkFields = watermarkFields;
|
|
4217
5593
|
for (const [key, ...names] of [
|
|
4218
5594
|
[
|
|
4219
5595
|
"maxPromptChars",
|
|
4220
5596
|
"max_prompt_chars",
|
|
4221
|
-
"max_text_chars"
|
|
5597
|
+
"max_text_chars",
|
|
5598
|
+
"max_prompt_characters"
|
|
4222
5599
|
],
|
|
4223
5600
|
[
|
|
4224
5601
|
"maxInputBytes",
|
|
@@ -5858,6 +7235,11 @@ function quotedCny(quote) {
|
|
|
5858
7235
|
* | podcast | model, prompt, source_url |
|
|
5859
7236
|
* | speech | as declared; Seed: model, text_prompt, references, audio_config, watermark |
|
|
5860
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
|
+
*
|
|
5861
7243
|
* The main text goes in the model's `prompt_field`. A field the model does not
|
|
5862
7244
|
* declare in `request_fields` is refused before anything is uploaded or charged;
|
|
5863
7245
|
* music and podcasts never take speech references, output formats, sample rates
|
|
@@ -6004,7 +7386,10 @@ function audioRequestBody(model, request) {
|
|
|
6004
7386
|
}
|
|
6005
7387
|
if (request.watermark !== void 0) {
|
|
6006
7388
|
if (!takes("watermark")) refuse(`${model.id} does not take watermark.`, "watermark");
|
|
6007
|
-
|
|
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");
|
|
6008
7393
|
}
|
|
6009
7394
|
if (request.format !== void 0 || request.sampleRate !== void 0 || takes("audio_config")) {
|
|
6010
7395
|
if (!takes("audio_config")) refuse(`${model.id} does not take an output format or sample rate.`, "format");
|
|
@@ -6078,7 +7463,7 @@ async function prepareAudioTask(runtime, call, request, save) {
|
|
|
6078
7463
|
const kind = audioKindOf(model);
|
|
6079
7464
|
const body = audioRequestBody(model, request);
|
|
6080
7465
|
const references = request.references ?? [];
|
|
6081
|
-
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);
|
|
6082
7467
|
else if ((model.audio?.references?.min ?? 0) > 0) refuse(`${model.id} needs at least ${model.audio?.references?.min} reference audio file(s).`, "references");
|
|
6083
7468
|
const quote = quoteAudio(model);
|
|
6084
7469
|
const what = {
|
|
@@ -6747,7 +8132,13 @@ function describeVideoModel(model) {
|
|
|
6747
8132
|
return `${MODE_LABEL[mode]}: ${describeInputs(constraint)}${options === "" ? "" : `; ${options}`}`;
|
|
6748
8133
|
});
|
|
6749
8134
|
const limits = [];
|
|
6750
|
-
if (video.
|
|
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
|
+
}
|
|
6751
8142
|
if (video.maxTotalReferenceVideoSeconds !== void 0) limits.push(`reference videos at most ${video.maxTotalReferenceVideoSeconds} s in total`);
|
|
6752
8143
|
if (video.minReferenceAudioSeconds !== void 0 || video.maxReferenceAudioSeconds !== void 0) limits.push(`each reference audio ${video.minReferenceAudioSeconds ?? 0}-${video.maxReferenceAudioSeconds ?? "∞"} s`);
|
|
6753
8144
|
if (video.combinations !== void 0) limits.push(`allowed combinations: ${video.combinations.map((c) => [
|
|
@@ -6907,16 +8298,45 @@ function referenceByteLimit(model, input) {
|
|
|
6907
8298
|
return Math.min(kindMax ?? Infinity, video.maxAssetBytes ?? Infinity, MEDIA_LIBRARY_MAX_BYTES);
|
|
6908
8299
|
}
|
|
6909
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
|
+
/**
|
|
6910
8326
|
* Check the measured lengths of the reference media once the gateway has
|
|
6911
8327
|
* measured them. A reference's OWN length is what is checked — never the
|
|
6912
|
-
* requested output duration —
|
|
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}).
|
|
6913
8331
|
* @param model - the video model.
|
|
6914
8332
|
* @param videos - the uploaded reference videos, in order.
|
|
6915
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.
|
|
6916
8335
|
* @throws {@link MediaError} when a clip or the total is outside the model's limits.
|
|
6917
8336
|
*/
|
|
6918
|
-
function checkReferenceDurations(model, videos, audios = []) {
|
|
8337
|
+
function checkReferenceDurations(model, videos, audios = [], plan) {
|
|
6919
8338
|
const video = model.video ?? {};
|
|
8339
|
+
const limit = referenceVideoLimit(model, plan?.constraint);
|
|
6920
8340
|
let totalMs = 0;
|
|
6921
8341
|
for (const [index, clip] of videos.entries()) {
|
|
6922
8342
|
if (clip.durationMs === void 0) {
|
|
@@ -6925,7 +8345,10 @@ function checkReferenceDurations(model, videos, audios = []) {
|
|
|
6925
8345
|
}
|
|
6926
8346
|
const seconds = clip.durationMs / 1e3;
|
|
6927
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" });
|
|
6928
|
-
if (
|
|
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
|
+
}
|
|
6929
8352
|
totalMs += clip.durationMs;
|
|
6930
8353
|
}
|
|
6931
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" });
|
|
@@ -7095,7 +8518,7 @@ async function prepareVideoTask(runtime, call, request, save) {
|
|
|
7095
8518
|
bytes: item.media.data.byteLength,
|
|
7096
8519
|
...assets[index]?.durationMs === void 0 ? {} : { durationMs: assets[index]?.durationMs }
|
|
7097
8520
|
}] : []);
|
|
7098
|
-
checkReferenceDurations(model, videos, audios);
|
|
8521
|
+
checkReferenceDurations(model, videos, audios, plan);
|
|
7099
8522
|
const urls = {};
|
|
7100
8523
|
for (const [index, item] of loaded.entries()) {
|
|
7101
8524
|
const asset = assets[index];
|
|
@@ -7208,7 +8631,7 @@ function videoGenerateTool(runtime) {
|
|
|
7208
8631
|
reference_videos: {
|
|
7209
8632
|
type: "array",
|
|
7210
8633
|
items: { type: "string" },
|
|
7211
|
-
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}.`
|
|
7212
8635
|
},
|
|
7213
8636
|
reference_audios: {
|
|
7214
8637
|
type: "array",
|
|
@@ -9599,6 +11022,18 @@ function apply(ctx, config) {
|
|
|
9599
11022
|
ctx.inject(["connection"], (scoped) => {
|
|
9600
11023
|
for (const accountRoute of [...accountRoutes(accountService), ...latencyRoutes(latency)]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
|
|
9601
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)
|
|
11036
|
+
});
|
|
9602
11037
|
ctx.effect(() => {
|
|
9603
11038
|
tracker.resume().catch((error) => {
|
|
9604
11039
|
warn(`dsh-vibedev: resuming tasks failed: ${String(error)}`);
|
|
@@ -9622,6 +11057,7 @@ function apply(ctx, config) {
|
|
|
9622
11057
|
for await (const _view of accountCtx.deepseekAccount.watch(controller.signal)) {
|
|
9623
11058
|
runtime.invalidateCatalog();
|
|
9624
11059
|
accountService.credentialChanged();
|
|
11060
|
+
feedback.uploader.credentialChanged();
|
|
9625
11061
|
}
|
|
9626
11062
|
} catch {}
|
|
9627
11063
|
})();
|
|
@@ -9632,6 +11068,6 @@ function apply(ctx, config) {
|
|
|
9632
11068
|
});
|
|
9633
11069
|
}
|
|
9634
11070
|
//#endregion
|
|
9635
|
-
export { ACCOUNT_ROUTE_PREFIX, AccountService, Config, INSUFFICIENT_BALANCE_CODE, LATENCY_ROUTE, MediaError, MediaHostService, GATEWAY_SEARCH_PROVIDER_ID as SEARCH_PROVIDER_ID, SIGN_IN_REQUIRED_CODE, VIBEDEV_ROUTE, apply, inject, name, parseMediaCatalog, version };
|
|
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 };
|
|
9636
11072
|
|
|
9637
11073
|
//# sourceMappingURL=index.js.map
|