@vibedev-si/dsh-vibedev 0.3.11 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +122 -7
  2. package/THIRD-PARTY-NOTICES.txt +1 -1
  3. package/client/client.account-center.js +13151 -0
  4. package/client/client.js +3417 -878
  5. package/cordis.patch.yml +5 -0
  6. package/lib/account/center-business-contract.d.ts +22 -0
  7. package/lib/account/center-business.d.ts +6 -0
  8. package/lib/account/center-contract.d.ts +12 -0
  9. package/lib/account/center-monitor-contract.d.ts +10 -0
  10. package/lib/account/center-price-contract.d.ts +5 -0
  11. package/lib/account/center.d.ts +7 -0
  12. package/lib/account/index.d.ts +14 -0
  13. package/lib/{anthropic-messages-BgIfgjNt.js → anthropic-messages-QcnVMGaA.js} +11 -11
  14. package/lib/contract-v1.types.d.ts +134 -0
  15. package/lib/contracts.d.ts +34 -0
  16. package/lib/gateway/errors.d.ts +29 -1
  17. package/lib/gateway/http.d.ts +6 -0
  18. package/lib/host-locales.d.ts +4 -0
  19. package/lib/index.d.ts +13 -0
  20. package/lib/index.js +2808 -412
  21. package/lib/{node-D58f7Ea6.js → node-CcLPV4RA.js} +4 -4
  22. package/lib/{node-Br-0fshF.js → node-vkDR3GtK.js} +2 -2
  23. package/lib/pricing.d.ts +21 -1
  24. package/lib/service.d.ts +36 -9
  25. package/lib/tasks/remote.d.ts +4 -4
  26. package/lib/tasks/store.d.ts +54 -9
  27. package/lib/tasks/tracker.d.ts +45 -45
  28. package/lib/tools/image.d.ts +1 -0
  29. package/lib/tools/video.d.ts +3 -0
  30. package/lib/util/files.d.ts +2 -0
  31. package/locale/en.json +13 -0
  32. package/locale/zh.json +13 -0
  33. package/node_modules/@vibedev-si/dsh-ecosystem/LICENSE +22 -0
  34. package/node_modules/@vibedev-si/dsh-ecosystem/README.md +154 -0
  35. package/node_modules/@vibedev-si/dsh-ecosystem/catalog/catalog.json +167 -0
  36. package/node_modules/@vibedev-si/dsh-ecosystem/catalog-updates.js +326 -0
  37. package/node_modules/@vibedev-si/dsh-ecosystem/catalog-validator.js +263 -0
  38. package/node_modules/@vibedev-si/dsh-ecosystem/client.js +2816 -0
  39. package/node_modules/@vibedev-si/dsh-ecosystem/cordis.patch.yml +5 -0
  40. package/node_modules/@vibedev-si/dsh-ecosystem/icon.svg +5 -0
  41. package/node_modules/@vibedev-si/dsh-ecosystem/index.js +169 -0
  42. package/node_modules/@vibedev-si/dsh-ecosystem/locale/en.json +6 -0
  43. package/node_modules/@vibedev-si/dsh-ecosystem/locale/zh.json +6 -0
  44. package/node_modules/@vibedev-si/dsh-ecosystem/package.json +75 -0
  45. package/node_modules/@vibedev-si/dsh-ecosystem/remote-catalog.js +212 -0
  46. package/package.json +12 -1
package/lib/index.js CHANGED
@@ -1,12 +1,12 @@
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 { 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";
4
6
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
5
7
  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
8
  import { Buffer as Buffer$1 } from "node:buffer";
8
9
  import { link, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
9
- import { createHash, randomBytes, randomUUID } from "node:crypto";
10
10
  import { Readable, Transform } from "node:stream";
11
11
  import { pipeline } from "node:stream/promises";
12
12
  import { credentialKey } from "@deepseek-ai/dsh-credentials";
@@ -16,6 +16,7 @@ import { idleWatchdog, timeoutOf } from "@deepseek-ai/dsh-timeout";
16
16
  import { brandString } from "@deepseek-ai/dsh-brand";
17
17
  import { requestImageDimensions } from "@deepseek-ai/dsh-attachment";
18
18
  import { WebError } from "@deepseek-ai/dsh-web";
19
+ import { AsyncLocalStorage } from "node:async_hooks";
19
20
  import { defineTool } from "@deepseek-ai/dsh-tools";
20
21
  //#region src/account/index.ts
21
22
  /** Path prefix of the plugin's Host routes. */
@@ -48,7 +49,7 @@ const MIN_READ_SPACING_MS = 5e3;
48
49
  * current when nobody opens anything.
49
50
  */
50
51
  const CATALOG_REFRESH_GAP_MS = 6e4;
51
- const record$10 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
52
+ const record$12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
52
53
  const text$8 = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
53
54
  /**
54
55
  * A gateway amount as plain decimal text: a number as JavaScript writes it (`99976091.91426945`; the few numbers it
@@ -72,6 +73,23 @@ const seenOf = (read) => JSON.stringify({
72
73
  /** The account state behind the pages. */
73
74
  var AccountService = class {
74
75
  options;
76
+ announcedUserId;
77
+ navigation;
78
+ openAccountCenter(page = "dashboard") {
79
+ this.navigation = {
80
+ id: randomUUID(),
81
+ page,
82
+ revision: this.revision + 1,
83
+ expiresAt: this.now() + 1e4
84
+ };
85
+ this.changed();
86
+ }
87
+ consumeNavigation(id) {
88
+ if (this.navigation?.id !== id || this.navigation.expiresAt <= this.now()) return false;
89
+ this.navigation = void 0;
90
+ this.changed();
91
+ return true;
92
+ }
75
93
  balanceCache;
76
94
  /** A background read of a stale balance, so only one runs at a time. */
77
95
  revalidating;
@@ -120,6 +138,8 @@ var AccountService = class {
120
138
  }
121
139
  /** The account changed hands (sign-in, sign-out, switch): forget the balance and tell the pages. */
122
140
  credentialChanged() {
141
+ this.options.identityInvalidated?.();
142
+ this.announcedUserId = void 0;
123
143
  this.epoch++;
124
144
  this.balanceCache = void 0;
125
145
  this.revalidating = void 0;
@@ -210,6 +230,7 @@ var AccountService = class {
210
230
  source,
211
231
  links: this.links(),
212
232
  primary: this.options.primary === true,
233
+ ...this.navigation === void 0 || this.navigation.expiresAt <= this.now() ? {} : { accountCenter: this.navigation },
213
234
  ...pending === void 0 ? {} : { pending },
214
235
  ...attempt === void 0 ? {} : { attempt }
215
236
  };
@@ -283,8 +304,8 @@ var AccountService = class {
283
304
  redirect: "error"
284
305
  });
285
306
  if (!response.ok) return {};
286
- const body = record$10(await response.json().catch(() => void 0));
287
- const data = record$10(body?.data) ?? body;
307
+ const body = record$12(await response.json().catch(() => void 0));
308
+ const data = record$12(body?.data) ?? body;
288
309
  const balance = amountOf(data?.balance);
289
310
  const currency = text$8(data?.currency) ?? "CNY";
290
311
  const frozen = amountOf(data?.frozen_balance);
@@ -319,6 +340,10 @@ var AccountService = class {
319
340
  };
320
341
  value.then((read) => {
321
342
  if (epoch !== this.epoch) return;
343
+ if (read.user?.id !== void 0 && read.user.id !== this.announcedUserId) {
344
+ this.announcedUserId = read.user.id;
345
+ this.options.identityAvailable?.(read.user.id);
346
+ }
322
347
  if (read.balance === void 0) {
323
348
  if (this.balanceCache?.value === value) this.balanceCache = void 0;
324
349
  this.failure = {
@@ -400,8 +425,8 @@ function json$2(status, body) {
400
425
  }
401
426
  });
402
427
  }
403
- function failure(error) {
404
- const candidate = record$10(error)?.code;
428
+ function failure$1(error) {
429
+ const candidate = record$12(error)?.code;
405
430
  const code = candidate === "SIGN_IN_REFUSED" || candidate === "SIGN_IN_TIMEOUT" || candidate === "SIGN_IN_CANCELLED" ? candidate : "INTERNAL";
406
431
  return json$2(500, { error: {
407
432
  code,
@@ -415,6 +440,15 @@ function failure(error) {
415
440
  */
416
441
  function accountRoutes(account) {
417
442
  return [
443
+ {
444
+ path: `${ACCOUNT_ROUTE_PREFIX}/navigation/consume`,
445
+ methods: ["POST"],
446
+ requestBody: "buffered",
447
+ fetch: async (request) => {
448
+ const body = record$12(await request.json().catch(() => void 0));
449
+ return json$2(200, { consumed: typeof body?.id === "string" && account.consumeNavigation(body.id) });
450
+ }
451
+ },
418
452
  {
419
453
  path: ACCOUNT_ROUTE_PREFIX,
420
454
  methods: ["GET"],
@@ -426,7 +460,7 @@ function accountRoutes(account) {
426
460
  if (since !== null && /^\d{1,15}$/.test(since)) await account.wait(Number(since), request.signal);
427
461
  return json$2(200, await account.view(query.get("fresh") === "1"));
428
462
  } catch (error) {
429
- return failure(error);
463
+ return failure$1(error);
430
464
  }
431
465
  }
432
466
  },
@@ -436,10 +470,10 @@ function accountRoutes(account) {
436
470
  requestBody: "buffered",
437
471
  fetch: async (request) => {
438
472
  try {
439
- const body = record$10(await request.json().catch(() => void 0));
473
+ const body = record$12(await request.json().catch(() => void 0));
440
474
  return json$2(200, await account.signIn(body?.open !== false));
441
475
  } catch (error) {
442
- return failure(error);
476
+ return failure$1(error);
443
477
  }
444
478
  }
445
479
  },
@@ -463,13 +497,1575 @@ function accountRoutes(account) {
463
497
  message: "The VibeDev account is the app's sign-in; sign out in the app."
464
498
  } });
465
499
  } catch (error) {
466
- return failure(error);
500
+ return failure$1(error);
467
501
  }
468
502
  }
469
503
  }
470
504
  ];
471
505
  }
472
506
  //#endregion
507
+ //#region src/gateway/errors.ts
508
+ /**
509
+ * Failures the plugin reports to the model: a gateway refusal, or a request the
510
+ * plugin refused before anything was sent or charged. Messages are written for
511
+ * the model to act on and relay to the user.
512
+ * @module dsh-vibedev/gateway/errors
513
+ */
514
+ /**
515
+ * One failure, with a stable `code` to route on and a message to show. It is a
516
+ * harness error, so a tool failure keeps the code in the durable tool result
517
+ * where a client can route on it (sign-in card, top-up link).
518
+ */
519
+ var MediaError = class extends HarnessError {
520
+ details;
521
+ /**
522
+ * @param message - what happened and what to do next.
523
+ * @param code - stable failure class, such as `INSUFFICIENT_BALANCE` or `VIDEO_MODE_UNSUPPORTED`.
524
+ * @param details - status, retry and field facts.
525
+ * @param options - the underlying cause, when there is one.
526
+ */
527
+ constructor(message, code, details = {}, options) {
528
+ super(message, code, options);
529
+ this.name = "MediaError";
530
+ this.details = {
531
+ ...details,
532
+ category: normalizeErrorCategory(details.category, code),
533
+ stage: normalizeErrorStage(details.stage)
534
+ };
535
+ }
536
+ };
537
+ /** Only for local validators executed before media creation; never wrap gateway or dispatch errors. */
538
+ function localInputError(message, code, details = {}) {
539
+ return new MediaError(message, code, {
540
+ ...details,
541
+ category: "invalid_input",
542
+ stage: "submit",
543
+ submissionState: "not_submitted",
544
+ billingState: "not_charged",
545
+ retryable: false,
546
+ retryAction: "modify_input"
547
+ });
548
+ }
549
+ /** Contract V1 words at the plugin boundary, including older deployed media gateways. */
550
+ const ERROR_CATEGORIES = /* @__PURE__ */ new Set([
551
+ "authentication",
552
+ "access_restricted",
553
+ "billing",
554
+ "model_unavailable",
555
+ "invalid_input",
556
+ "content_rejected",
557
+ "rate_limited",
558
+ "service_unavailable",
559
+ "submission_uncertain",
560
+ "internal_error"
561
+ ]);
562
+ const ERROR_STAGES = /* @__PURE__ */ new Set([
563
+ "auth",
564
+ "catalog",
565
+ "quote",
566
+ "upload",
567
+ "submit",
568
+ "poll",
569
+ "generation",
570
+ "download",
571
+ "settle"
572
+ ]);
573
+ const UNKNOWN_SUBMISSION_ERRORS = /* @__PURE__ */ new Set([
574
+ "VIDEO_SUBMISSION_AMBIGUOUS",
575
+ "SEED_AUDIO_SUBMISSION_UNKNOWN",
576
+ "MEDIA_SUBMISSION_UNKNOWN",
577
+ "SUBMISSION_UNCERTAIN"
578
+ ]);
579
+ const LEGACY_CATEGORIES = {
580
+ submission_unknown: "submission_uncertain",
581
+ request: "invalid_input",
582
+ content_policy: "content_rejected",
583
+ rate_limit: "rate_limited",
584
+ service: "service_unavailable",
585
+ timeout: "service_unavailable",
586
+ result: "service_unavailable",
587
+ conflict: "invalid_input",
588
+ auth: "authentication",
589
+ internal: "internal_error"
590
+ };
591
+ /** Unknown submission codes outrank weaker provider/service categories. */
592
+ function normalizeErrorCategory(value, code) {
593
+ if (UNKNOWN_SUBMISSION_ERRORS.has(code ?? "")) return "submission_uncertain";
594
+ if (value === void 0) return void 0;
595
+ const word = value.toLowerCase();
596
+ return ERROR_CATEGORIES.has(word) ? word : LEGACY_CATEGORIES[word] ?? "internal_error";
597
+ }
598
+ /** An unknown stage is omitted rather than exposing a provider's private vocabulary. */
599
+ function normalizeErrorStage(value) {
600
+ if (value === void 0) return void 0;
601
+ const word = value.toLowerCase();
602
+ return ERROR_STAGES.has(word) ? word : {
603
+ provider_submit: "submit",
604
+ gateway_timeout: "submit",
605
+ request: "submit"
606
+ }[word];
607
+ }
608
+ function record$11(value) {
609
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
610
+ }
611
+ function text$7(value) {
612
+ return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
613
+ }
614
+ function count$1(value) {
615
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
616
+ }
617
+ /** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
618
+ function amount$1(value) {
619
+ if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
620
+ const raw = text$7(value);
621
+ return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
622
+ }
623
+ /**
624
+ * Read a gateway error body. The gateway answers in several shapes: OpenAI's
625
+ * `{error:{code,message,type}}`, its own `{error:{code,message,retryable,field}}`,
626
+ * the account API's `{code,message,reason,metadata}` (a validation refusal names
627
+ * the field and the rule there: `metadata: {field, rule}`), and a top-level
628
+ * `recharge_url` on balance refusals. Media admission refusals add
629
+ * `active`/`limit` (task limit) or `estimated_cny`/`available_cny`/`pending_cny` (balance).
630
+ * @param body - the parsed JSON body, or undefined when it was not JSON.
631
+ * @returns the fields found.
632
+ */
633
+ function parseGatewayFailure(body) {
634
+ const root = record$11(body);
635
+ if (root === void 0) return {};
636
+ const source = record$11(root.error) ?? root;
637
+ const metadata = record$11(source.metadata) ?? record$11(root.metadata);
638
+ const gatewayCode = text$7(source.gateway_code) ?? text$7(root.gateway_code);
639
+ const code = gatewayCode ?? text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
640
+ const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
641
+ const field = text$7(source.field) ?? text$7(metadata?.field);
642
+ const rule = text$7(source.rule) ?? text$7(metadata?.rule);
643
+ const rechargeUrl = text$7(source.recharge_url) ?? text$7(root.recharge_url);
644
+ const numbers = {
645
+ active: count$1(source.active),
646
+ limit: count$1(source.limit)
647
+ };
648
+ const amounts = {
649
+ estimatedCny: amount$1(source.estimated_cny),
650
+ availableCny: amount$1(source.available_cny),
651
+ pendingCny: amount$1(source.pending_cny)
652
+ };
653
+ const submissionState = text$7(source.submission_state) ?? text$7(root.submission_state);
654
+ const retryAction = text$7(source.retry_action) ?? text$7(root.retry_action);
655
+ const assetId = text$7(source.asset_id) ?? text$7(root.asset_id);
656
+ return {
657
+ ...gatewayCode === void 0 ? {} : { gatewayCode },
658
+ ...Object.fromEntries(Object.entries({
659
+ category: normalizeErrorCategory(text$7(source.category) ?? text$7(root.category), code),
660
+ stage: normalizeErrorStage(text$7(source.stage) ?? text$7(root.stage)),
661
+ requestId: text$7(source.request_id) ?? text$7(root.request_id),
662
+ taskId: text$7(source.task_id) ?? text$7(root.task_id),
663
+ operationId: text$7(source.operation_id) ?? text$7(root.operation_id),
664
+ billingState: text$7(source.billing_state) ?? text$7(root.billing_state),
665
+ retryAt: text$7(source.retry_at) ?? text$7(root.retry_at),
666
+ retryAfterSeconds: count$1(source.retry_after_seconds) ?? count$1(root.retry_after_seconds)
667
+ }).filter(([, value]) => value !== void 0)),
668
+ ...code === void 0 ? {} : { code },
669
+ ...message === void 0 ? {} : { message },
670
+ ...field === void 0 ? {} : { field },
671
+ ...rule === void 0 ? {} : { rule },
672
+ ...typeof source.retryable === "boolean" ? { retryable: source.retryable } : {},
673
+ ...submissionState === void 0 ? {} : { submissionState: submissionState.toLowerCase() },
674
+ ...retryAction === void 0 ? {} : { retryAction: retryAction.toLowerCase() },
675
+ ...rechargeUrl === void 0 ? {} : { rechargeUrl },
676
+ ...assetId === void 0 ? {} : { assetId },
677
+ ...Object.fromEntries(Object.entries({
678
+ ...numbers,
679
+ ...amounts
680
+ }).filter(([, value]) => value !== void 0))
681
+ };
682
+ }
683
+ /**
684
+ * Milliseconds a `Retry-After` header asks for: delta seconds or an HTTP date.
685
+ * @param header - the header value, or null when absent.
686
+ * @param now - current epoch milliseconds, for an HTTP date.
687
+ * @returns the wait, or undefined when absent or unreadable.
688
+ */
689
+ function retryAfterMs(header, now = Date.now()) {
690
+ if (header === null || header.trim() === "") return void 0;
691
+ const seconds = Number(header.trim());
692
+ if (Number.isFinite(seconds)) return seconds < 0 ? void 0 : Math.round(seconds * 1e3);
693
+ const at = Date.parse(header);
694
+ return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
695
+ }
696
+ /** `(CODE: message)`, for appending the gateway's own words to a message. */
697
+ function gatewayWords(failure) {
698
+ const parts = [failure.code, safeGatewayMessage(failure)].filter((part) => part !== void 0);
699
+ return parts.length === 0 ? "" : ` (${parts.join(": ")})`;
700
+ }
701
+ /** One safe presentation for HTTP, SDK finishes and asynchronous task errors. */
702
+ function safeGatewayMessage(failure) {
703
+ const supplied = failure.message?.replace(/https?:\/\/[^\s<>"']+/gi, "[link removed]").replace(/\bBearer\s+[^\s,;]+/gi, "[credential removed]").replace(/\b(?:sk-|vdat_)[a-zA-Z0-9_-]+/g, "[credential removed]").replace(/\b(?:api[_-]?key|access[_-]?token|refresh[_-]?token|authorization)\s*[:=]\s*["']?[^\s,;"']+/gi, "[credential removed]").replace(/\b[A-Z]:\\[^\s<>"']+/gi, "[path removed]").replace(/[\u0000-\u001f\u007f]/g, " ").trim().slice(0, 600);
704
+ if (supplied) return supplied;
705
+ switch (failure.code) {
706
+ case "SUBSCRIPTION_QUOTA_EXHAUSTED": return "订阅额度已用完,请查看恢复时间或账户计费方式。";
707
+ case "MODEL_NOT_INCLUDED": return "当前订阅不包含此模型,请查看账户中的可用计费方式。";
708
+ case "BALANCE_INSUFFICIENT":
709
+ case "INSUFFICIENT_BALANCE": return "余额不足,请充值后继续。";
710
+ case "BILLING_SOURCE_UNAVAILABLE": return "这个模型暂时没有可用的计费方式。";
711
+ case "CONTENT_REJECTED":
712
+ case "MEDIA_REQUEST_REJECTED": return "提示词或参考素材未通过生成服务审核,请调整后重试。";
713
+ case "IDEMPOTENCY_CONFLICT": return "该操作编号已用于其他请求,请先核对原任务。";
714
+ }
715
+ switch (failure.category) {
716
+ case "authentication": return "VibeDev 登录已失效,请重新登录。";
717
+ case "access_restricted": return "账号访问受限,请查看账户说明。";
718
+ case "billing": return "当前计费方式无法承接请求,请查看账户。";
719
+ case "model_unavailable": return "模型暂时不可用,请刷新模型列表。";
720
+ case "invalid_input": return "参数或参考素材不符合要求,请检查后重试。";
721
+ case "content_rejected": return "提示词或参考素材未通过生成服务审核,请调整后重试。";
722
+ case "rate_limited": return "请求过于频繁,请稍后重试。";
723
+ case "service_unavailable": return failure.stage === "poll" ? "暂时无法获取进度,原任务已保留。" : failure.stage === "download" ? "生成结果已保留,请重试下载。" : "服务暂时不可用,请稍后再试。";
724
+ case "submission_uncertain": return "提交结果待确认,请核对原任务,勿重复生成。";
725
+ default: return "请求未完成,请使用请求编号查看诊断信息。";
726
+ }
727
+ }
728
+ function gatewayFailureWithHeaders(body, headers) {
729
+ const failure = parseGatewayFailure(body);
730
+ return {
731
+ ...failure,
732
+ code: failure.gatewayCode ?? text$7(headers.get("x-vibedev-error-code")) ?? failure.code,
733
+ category: normalizeErrorCategory(failure.category ?? text$7(headers.get("x-vibedev-error-category")), failure.gatewayCode ?? text$7(headers.get("x-vibedev-error-code")) ?? failure.code),
734
+ requestId: failure.requestId ?? text$7(headers.get("x-request-id")),
735
+ retryAction: failure.retryAction ?? text$7(headers.get("x-vibedev-retry-action")),
736
+ retryAt: failure.retryAt ?? text$7(headers.get("x-vibedev-retry-at"))
737
+ };
738
+ }
739
+ function isUserAuthenticationFailure(failure) {
740
+ return failure.category === "authentication" || failure.category === void 0 && /^(?:AUTHENTICATION_REQUIRED|APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|TOKEN_EXPIRED|TOKEN_INVALID|authentication_error)$/.test(failure.code ?? "");
741
+ }
742
+ function sdkGatewayFailure(message, headers = {}) {
743
+ const prefix = /\bvibedev:([A-Z][A-Z0-9_]{1,100}):/.exec(message)?.[1];
744
+ const legacy = /["'](?:gateway_code|code)["']\s*:\s*["'](APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)["']/.exec(message)?.[1];
745
+ const code = text$7(headers["x-vibedev-error-code"]) ?? prefix ?? legacy;
746
+ const category = text$7(headers["x-vibedev-error-category"]) ?? (code === void 0 ? void 0 : /^(?:APP_TOKEN_EXPIRED|APP_TOKEN_INVALID|INVALID_API_KEY|APP_SESSION_REVOKED|SESSION_REVOKED|AUTHENTICATION_REQUIRED)$/.test(code) ? "authentication" : /^(?:BALANCE_INSUFFICIENT|SUBSCRIPTION_QUOTA_EXHAUSTED|MODEL_NOT_INCLUDED|BILLING_SOURCE_UNAVAILABLE)$/.test(code) ? "billing" : code === "CONTENT_REJECTED" ? "content_rejected" : code === "SUBMISSION_UNCERTAIN" ? "submission_uncertain" : /^(?:UPSTREAM_UNAVAILABLE|TASK_QUERY_UNAVAILABLE|RESULT_DOWNLOAD_UNAVAILABLE)$/.test(code) ? "service_unavailable" : "internal_error");
747
+ if (code === void 0 && category === void 0) return void 0;
748
+ return {
749
+ code,
750
+ category: normalizeErrorCategory(category, code),
751
+ requestId: text$7(headers["x-request-id"]),
752
+ retryAction: text$7(headers["x-vibedev-retry-action"])
753
+ };
754
+ }
755
+ //#endregion
756
+ //#region src/account/center-price-contract.ts
757
+ const record$10 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
758
+ const keys = (value = "") => value.split(" ").filter(Boolean);
759
+ const scalar$1 = (value) => value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && value.length <= 1e3 && !/\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
760
+ /** Only public DNS HTTPS references become navigable links. No credentials, IPs or local hosts. */
761
+ function publicReferenceUrl(value) {
762
+ if (typeof value !== "string" || value.length > 2e3 || !value.startsWith("https://") || /[\u0000-\u0020\\]/.test(value)) return void 0;
763
+ try {
764
+ const url = new URL(value), host = url.hostname.toLowerCase().replace(/\.$/, ""), labels = host.split(".");
765
+ if (url.protocol !== "https:" || url.username || url.password || value.split(/[/?#]/)[2]?.includes("@") || url.hash || url.search || url.port && url.port !== "443") return void 0;
766
+ if (labels.length < 2 || labels.some((label) => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label)) || /^(?:[0-9]+|0x[0-9a-f]+)$/.test(labels.at(-1)) || /\.(?:localhost|local|internal|test|invalid|example)$/.test(host)) return void 0;
767
+ for (const [key, item] of url.searchParams) if (/token|secret|password|credential|signature|authorization|api[-_]?key|access[-_]?key|signed|x-(?:amz|tos|goog)-/i.test(key) || /\b(?:Bearer\s|vdat_|sk-)|eyJ[A-Za-z0-9_-]+\./i.test(item)) return void 0;
768
+ return url.href;
769
+ } catch {
770
+ return;
771
+ }
772
+ }
773
+ function project$1(value, shape) {
774
+ if (value === null) return null;
775
+ const source = record$10(value);
776
+ if (!source) return void 0;
777
+ const out = {};
778
+ for (const key of keys(shape.fields)) {
779
+ const item = scalar$1(source[key]);
780
+ if (item !== void 0) out[key] = item;
781
+ }
782
+ for (const key of keys(shape.urls)) {
783
+ const item = publicReferenceUrl(source[key]);
784
+ if (item !== void 0) out[key] = item;
785
+ else if (key === "source") {
786
+ const label = scalar$1(source[key]);
787
+ if (label !== void 0) out[key] = label;
788
+ }
789
+ }
790
+ for (const [key, child] of Object.entries(shape.objects ?? {})) {
791
+ const item = project$1(source[key], child);
792
+ if (item !== void 0) out[key] = item;
793
+ }
794
+ for (const [key, child] of Object.entries(shape.arrays ?? {})) {
795
+ if (source[key] === null) {
796
+ out[key] = null;
797
+ continue;
798
+ }
799
+ if (!Array.isArray(source[key])) continue;
800
+ out[key] = source[key].slice(0, key === "models" ? 48 : 1e3).map((item) => child === "scalar" ? scalar$1(item) : child === "matrix" ? Array.isArray(item) ? item.slice(0, 64).map(scalar$1).filter((v) => v !== void 0) : void 0 : project$1(item, child)).filter((item) => item !== void 0);
801
+ }
802
+ for (const [key, child] of Object.entries(shape.maps ?? {})) {
803
+ const map = record$10(source[key]);
804
+ if (!map) continue;
805
+ out[key] = Object.fromEntries(Object.entries(map).slice(0, 64).filter(([name, value]) => /^[a-z][a-z0-9_]{0,63}$/i.test(name) && !/secret|password|credential|api_key/i.test(name) && (key !== "reasoning_effort_multipliers" || [
806
+ "none",
807
+ "minimal",
808
+ "low",
809
+ "medium",
810
+ "high",
811
+ "xhigh",
812
+ "max"
813
+ ].includes(name) && typeof value === "number" && Number.isFinite(value) && value >= 0)).map(([name, value]) => [name, child === "scalar" ? scalar$1(value) : child === "numbers" ? Array.isArray(value) ? value.filter((item) => typeof item === "number" && Number.isFinite(item)).slice(0, 100) : void 0 : project$1(value, child)]).filter(([, value]) => value !== void 0));
814
+ }
815
+ return out;
816
+ }
817
+ const media = { fields: "currency unit amount free_count status expires_at" };
818
+ const reference = {
819
+ fields: "profile_id comparison_enabled status reason",
820
+ objects: {
821
+ profile: {
822
+ fields: "official_model_id provider kind currency unit verified_at expires_at max_age_days region region_label service_tier status cache_mode cache_write_ttl_seconds cache_write_long_ttl_seconds context_basis pricing_basis display_name model_version api_model_id availability comparison_scope billing_unit billing_duration token_usage_basis estimate_basis evidence_method mapping_requires_confirmation reference_video_minimum_tokens notes",
823
+ urls: "website source model_source",
824
+ arrays: {
825
+ tiers: {
826
+ fields: "label min_tokens max_tokens period resolution ratio pixel_size quality reference_video reference_audio reference_image generate_audio input output read write write1h output_tokens image_output_per_million text_input image_input text_cached image_cached text_input_per_million image_input_per_million text_output_per_million input_video_per_second input_image_per_image free_images units_per_second",
827
+ arrays: { cache_writes: { fields: "ttl_seconds amount" } }
828
+ },
829
+ requires: "scalar",
830
+ notices: "scalar"
831
+ },
832
+ maps: { media_input_prices: media },
833
+ objects: {
834
+ cache_storage: media,
835
+ credit_unit: { fields: "currency amount unit basis" },
836
+ promotion: { fields: "multiplier end_at checked_at description" },
837
+ time_pricing: {
838
+ fields: "timezone weekdays_only exclude_china_public_holidays",
839
+ arrays: { periods: { fields: "start_time end_time period" } }
840
+ }
841
+ }
842
+ },
843
+ binding: {
844
+ fields: "profile_id comparison_enabled status reason notice official_retirement_date channel_kind",
845
+ urls: "source",
846
+ objects: { sale_conditions: { fields: "region service_tier context_basis cache_write_ttl_seconds cache_write_long_ttl_seconds model_mapping_confirmed sku_confirmed" } }
847
+ }
848
+ }
849
+ };
850
+ const schedule = {
851
+ fields: "timezone weekdays_only",
852
+ arrays: {
853
+ excluded_dates: "scalar",
854
+ periods: { fields: "start_time end_time multiplier" }
855
+ }
856
+ };
857
+ const catalog = {
858
+ fields: "currency description catalog_version",
859
+ arrays: {
860
+ groups: { fields: "id name" },
861
+ models: {
862
+ fields: "id name description kind",
863
+ arrays: { aliases: "scalar" },
864
+ objects: {
865
+ capabilities: {
866
+ fields: "context_window max_input_tokens max_output_tokens reasoning_supported default_reasoning tools parallel_tools vision structured_output streaming fast interleaved_thinking adaptive_thinking",
867
+ arrays: {
868
+ image_sizes: "scalar",
869
+ image_ratios: "scalar",
870
+ input_modalities: "scalar",
871
+ output_modalities: "scalar",
872
+ reasoning_levels: "scalar"
873
+ },
874
+ objects: {
875
+ audio: {
876
+ fields: "default_format generation_kind prompt_field max_prompt_characters reference_audio_input max_reference_audios max_reference_audio_duration_seconds max_reference_audio_bytes reference_image_input max_reference_images max_reference_image_bytes reference_image_exclusive speaker_input subtitle watermark max_original_duration_seconds billing_unit async_create_poll_content gateway_relay_required",
877
+ arrays: {
878
+ request_fields: "scalar",
879
+ output_formats: "scalar",
880
+ sample_rates: "scalar",
881
+ config_fields: "scalar",
882
+ watermark_fields: "scalar"
883
+ },
884
+ maps: {
885
+ output_sample_rates: "numbers",
886
+ config_ranges: { fields: "min max" }
887
+ }
888
+ },
889
+ video: {
890
+ fields: "text_to_video image_to_video reference_image_input max_reference_images reference_video_input max_reference_videos reference_audio_input max_reference_audios max_reference_video_duration_seconds min_reference_video_duration_seconds max_total_reference_video_duration_seconds max_asset_bytes max_request_bytes max_reference_image_bytes max_reference_video_bytes max_reference_audio_bytes modes_schema_version native_audio_output native_sequence first_frame last_frame edit extend async_create_poll_content gateway_relay_required min_reference_audio_duration_seconds max_reference_audio_duration_seconds max_total_reference_audio_duration_seconds min_reference_image_width max_reference_image_width min_reference_image_height max_reference_image_height min_reference_image_aspect_ratio max_reference_image_aspect_ratio min_reference_image_pixels max_reference_image_pixels min_reference_video_width max_reference_video_width min_reference_video_height max_reference_video_height min_reference_video_aspect_ratio max_reference_video_aspect_ratio min_reference_video_pixels max_reference_video_pixels min_reference_video_fps max_reference_video_fps",
891
+ arrays: {
892
+ allowed_image_mimes: "scalar",
893
+ allowed_video_mimes: "scalar",
894
+ allowed_audio_mimes: "scalar",
895
+ allowed_extensions: "scalar",
896
+ durations_seconds: "scalar",
897
+ ratios: "scalar",
898
+ resolutions: "scalar",
899
+ combinations: { fields: "duration_seconds ratio resolution" }
900
+ },
901
+ maps: { modes: {
902
+ arrays: {
903
+ required_any_of: "matrix",
904
+ resolutions: "scalar",
905
+ ratios: "scalar",
906
+ durations_seconds: "scalar"
907
+ },
908
+ maps: { inputs: { fields: "min max source" } }
909
+ } }
910
+ }
911
+ }
912
+ },
913
+ pricing: {
914
+ fields: "status currency unit billing_mode input_per_million output_per_million cache_read_per_million cache_write_per_million cache_write_1h_per_million image_input_per_million image_output_per_million amount default_amount default_unit headline_tier long_context_basis fast_multiplier flex_multiplier",
915
+ arrays: { tiers: { fields: "unit label min_tokens max_tokens input_per_million output_per_million cache_read_per_million cache_write_per_million cache_write_1h_per_million amount" } },
916
+ maps: { reasoning_effort_multipliers: "scalar" },
917
+ objects: {
918
+ time_pricing: schedule,
919
+ group_peak_pricing: schedule,
920
+ video_pricing: {
921
+ fields: "schema_version currency final_basis estimate_basis estimate_only",
922
+ arrays: { rules: { fields: "resolution reference_video reference_audio reference_image price_per_million_tokens estimated_price_per_second" } }
923
+ }
924
+ }
925
+ },
926
+ reference_pricing: reference
927
+ }
928
+ }
929
+ },
930
+ objects: {
931
+ pagination: { fields: "page page_size total" },
932
+ price_context: { fields: "group_id group_name personalized quoted_at" },
933
+ reference_context: {
934
+ fields: "catalog_version quoted_at",
935
+ objects: { display_fx: {
936
+ fields: "base_currency quote_currency rate as_of",
937
+ urls: "source"
938
+ } },
939
+ arrays: { sources: {
940
+ fields: "id name currency region integration classification notes checked_at",
941
+ urls: "url website",
942
+ arrays: {
943
+ kinds: "scalar",
944
+ alternate_sources: {
945
+ fields: "label",
946
+ urls: "url"
947
+ }
948
+ }
949
+ } }
950
+ }
951
+ }
952
+ };
953
+ function projectModelPlaza(value) {
954
+ return project$1(value, catalog) ?? {};
955
+ }
956
+ /** Duplicate, unknown, identity and unbounded catalog filters fail closed. */
957
+ function validateModelPlazaQuery(params) {
958
+ const output = new URLSearchParams(), seen = /* @__PURE__ */ new Set();
959
+ for (const [key, value] of params) {
960
+ if (seen.has(key) || new TextEncoder().encode(value).length > 256 || /[\r\n\0]/.test(value)) return void 0;
961
+ seen.add(key);
962
+ const choices = {
963
+ scope: ["platform", "mine"],
964
+ period: [
965
+ "24h",
966
+ "7d",
967
+ "30d"
968
+ ],
969
+ sort: [
970
+ "recommended",
971
+ "usage",
972
+ "name"
973
+ ],
974
+ kind: [
975
+ "text",
976
+ "image",
977
+ "video",
978
+ "audio"
979
+ ]
980
+ };
981
+ if (Object.hasOwn(choices, key)) {
982
+ if (!choices[key].includes(value)) return void 0;
983
+ } else if (key === "page") {
984
+ if (!/^[1-9]\d{0,9}$/.test(value) || Number(value) > 2147483647) return void 0;
985
+ } else if (key === "page_size") {
986
+ if (!/^[1-9]\d?$/.test(value) || Number(value) > 48) return void 0;
987
+ } else if (key === "group_id") {
988
+ if (!/^[1-9]\d{0,18}$/.test(value) || BigInt(value) > 9223372036854775807n) return void 0;
989
+ } else if (key !== "search") return void 0;
990
+ output.set(key, value);
991
+ }
992
+ return output;
993
+ }
994
+ //#endregion
995
+ //#region src/account/center-monitor-contract.ts
996
+ /** Fixed, authenticated monitor reads. This projection also protects admin AppTokens. */
997
+ const MONITOR_READ_PATHS = [
998
+ "channel-monitor-v2/dimensions",
999
+ "channel-monitor-v2/snapshot",
1000
+ "channel-monitor-v2/models",
1001
+ "channel-monitor-v2/matrix",
1002
+ "channel-monitor-v2/errors",
1003
+ "channel-monitors/status",
1004
+ "channel-monitors/detail"
1005
+ ];
1006
+ const object$4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1007
+ const safeText = (value) => typeof value === "string" && value.length > 0 && value.length <= 160 && !/[\r\n\0]|\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
1008
+ const number = (max = Number.MAX_SAFE_INTEGER) => (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= max ? value : void 0;
1009
+ const nullable = (rule) => (value) => value === null ? null : rule(value);
1010
+ const bool$1 = (value) => typeof value === "boolean" ? value : void 0;
1011
+ const enumOf = (...values) => (value) => typeof value === "string" && values.includes(value) ? value : void 0;
1012
+ const time = (value) => typeof value === "string" && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/.test(value) && Number.isFinite(Date.parse(value)) ? value : void 0;
1013
+ const positiveId$1 = (value) => /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n;
1014
+ const id = (value) => typeof value === "string" && positiveId$1(value) || typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
1015
+ const fields$1 = (rules) => (value) => {
1016
+ const source = object$4(value), output = {};
1017
+ for (const [key, rule] of Object.entries(rules)) {
1018
+ const item = rule(source[key]);
1019
+ if (item !== void 0) output[key] = item;
1020
+ }
1021
+ return output;
1022
+ };
1023
+ const array = (rule, max = 1e3) => (value) => Array.isArray(value) ? value.slice(0, max).map(rule).filter((item) => item !== void 0) : void 0;
1024
+ const latency = fields$1({
1025
+ p50_ms: nullable(number()),
1026
+ p90_ms: nullable(number()),
1027
+ p95_ms: nullable(number()),
1028
+ avg_ms: nullable(number())
1029
+ });
1030
+ const metric = (value) => {
1031
+ const source = object$4(value);
1032
+ const output = fields$1({
1033
+ data_available: bool$1,
1034
+ cache_data_available: bool$1,
1035
+ throughput_hidden: bool$1,
1036
+ success_rate: number(1),
1037
+ error_rate: number(1),
1038
+ cache_rate: number(1),
1039
+ rpm: nullable(number()),
1040
+ tpm: nullable(number()),
1041
+ ttft: (value) => value === void 0 ? void 0 : latency(value),
1042
+ duration: (value) => value === void 0 ? void 0 : latency(value)
1043
+ })(value);
1044
+ if (source.throughput_hidden === true) {
1045
+ output.rpm = null;
1046
+ output.tpm = null;
1047
+ }
1048
+ return output;
1049
+ };
1050
+ const thresholds = fields$1(Object.fromEntries([
1051
+ "warning_error_rate",
1052
+ "critical_error_rate",
1053
+ "target_ttft_ms",
1054
+ "warning_ttft_ms",
1055
+ "critical_ttft_ms",
1056
+ "warning_cache_rate",
1057
+ "critical_cache_rate",
1058
+ "error_weight",
1059
+ "ttft_weight",
1060
+ "cache_weight"
1061
+ ].map((key) => [key, number()])));
1062
+ const health = fields$1({
1063
+ overall: enumOf("healthy", "warning", "critical", "unknown"),
1064
+ error_rate: enumOf("healthy", "warning", "critical", "unknown"),
1065
+ ttft: enumOf("healthy", "warning", "critical", "unknown"),
1066
+ cache: enumOf("healthy", "warning", "critical", "unknown"),
1067
+ score: nullable(number(100)),
1068
+ error_rate_score: nullable(number(100)),
1069
+ ttft_score: nullable(number(100)),
1070
+ cache_score: nullable(number(100)),
1071
+ thresholds: (value) => value === void 0 ? void 0 : thresholds(value)
1072
+ });
1073
+ const coverage = fields$1({
1074
+ requested_start: time,
1075
+ requested_end: time,
1076
+ coverage_start: time,
1077
+ data_through: time,
1078
+ computed_at: time,
1079
+ aggregation_lag_seconds: number(),
1080
+ coverage_complete: bool$1,
1081
+ bucket_seconds: number(),
1082
+ bootstrap: (value) => value === void 0 ? void 0 : fields$1({
1083
+ active: bool$1,
1084
+ progress_percent: number(100),
1085
+ covered_from: time,
1086
+ target_start: time
1087
+ })(value)
1088
+ });
1089
+ const trend = fields$1({
1090
+ bucket_start: time,
1091
+ metrics: (value) => value === void 0 ? void 0 : metric(value),
1092
+ health: (value) => value === void 0 ? void 0 : health(value)
1093
+ });
1094
+ const model = fields$1({
1095
+ platform: safeText,
1096
+ model: safeText,
1097
+ metrics: (value) => value === void 0 ? void 0 : metric(value),
1098
+ health: (value) => value === void 0 ? void 0 : health(value)
1099
+ });
1100
+ const matrix = fields$1({
1101
+ platform: safeText,
1102
+ group_id: id,
1103
+ group_name: safeText,
1104
+ model: safeText,
1105
+ metrics: (value) => value === void 0 ? void 0 : metric(value),
1106
+ health: (value) => value === void 0 ? void 0 : health(value),
1107
+ buckets: array(trend, 2e3)
1108
+ });
1109
+ const categories = [
1110
+ "content_policy",
1111
+ "authentication",
1112
+ "context_limit",
1113
+ "invalid_request",
1114
+ "model_unsupported",
1115
+ "group_access",
1116
+ "quota_or_balance",
1117
+ "account_pool_unavailable",
1118
+ "rate_or_capacity",
1119
+ "timeout",
1120
+ "transport_or_stream",
1121
+ "upstream_forbidden",
1122
+ "not_found",
1123
+ "client_cancelled",
1124
+ "upstream_5xx",
1125
+ "internal",
1126
+ "other"
1127
+ ];
1128
+ const error$1 = (value) => categories.includes(String(object$4(value).category)) ? fields$1({
1129
+ category: enumOf(...categories),
1130
+ rate: number(1),
1131
+ ignored: bool$1
1132
+ })(value) : void 0;
1133
+ const status = enumOf("operational", "degraded", "failed", "error", "unknown");
1134
+ const v1 = fields$1({
1135
+ id,
1136
+ name: safeText,
1137
+ group_name: safeText,
1138
+ primary_model: safeText,
1139
+ primary_status: status,
1140
+ primary_latency_ms: nullable(number()),
1141
+ primary_ping_latency_ms: nullable(number()),
1142
+ availability_7d: number(100),
1143
+ extra_models: array(fields$1({
1144
+ model: safeText,
1145
+ status,
1146
+ latency_ms: nullable(number())
1147
+ })),
1148
+ timeline: array(fields$1({
1149
+ status,
1150
+ checked_at: time,
1151
+ latency_ms: nullable(number()),
1152
+ ping_latency_ms: nullable(number())
1153
+ }), 2e3)
1154
+ });
1155
+ const v1Detail = fields$1({
1156
+ id,
1157
+ name: safeText,
1158
+ group_name: safeText,
1159
+ models: array(fields$1({
1160
+ model: safeText,
1161
+ latest_status: status,
1162
+ latest_latency_ms: nullable(number()),
1163
+ availability_7d: number(100),
1164
+ availability_15d: number(100),
1165
+ availability_30d: number(100),
1166
+ avg_latency_7d_ms: nullable(number())
1167
+ }))
1168
+ });
1169
+ const optional = (rule) => (value) => value === void 0 ? void 0 : rule(value);
1170
+ function projectMonitorRoute(path, value) {
1171
+ if (path === "channel-monitors/status") return fields$1({ items: array(v1) })(value);
1172
+ if (path === "channel-monitors/detail") return v1Detail(value);
1173
+ if (path === "channel-monitor-v2/dimensions") return fields$1({
1174
+ platforms: array(fields$1({
1175
+ value: safeText,
1176
+ label: safeText,
1177
+ platform: safeText
1178
+ })),
1179
+ groups: array(fields$1({
1180
+ id,
1181
+ name: safeText,
1182
+ platform: safeText
1183
+ })),
1184
+ models: array(fields$1({
1185
+ value: safeText,
1186
+ label: safeText,
1187
+ platform: safeText
1188
+ }))
1189
+ })(value);
1190
+ if (path === "channel-monitor-v2/snapshot") return fields$1({
1191
+ config: optional(fields$1({
1192
+ model_source: enumOf("vibedev_catalog", "manual"),
1193
+ catalog_version: number(),
1194
+ refresh_interval_seconds: (value) => value === 60 || value === 300 ? value : void 0
1195
+ })),
1196
+ coverage: optional(coverage),
1197
+ metrics: optional(metric),
1198
+ health: optional(health),
1199
+ trend: array(trend, 2e3)
1200
+ })(value);
1201
+ if (path === "channel-monitor-v2/models" || path === "channel-monitor-v2/errors") return fields$1({
1202
+ coverage: optional(coverage),
1203
+ items: array(path.endsWith("errors") ? error$1 : model)
1204
+ })(value);
1205
+ if (path === "channel-monitor-v2/matrix") return fields$1({
1206
+ group_by: enumOf("platform", "platform_group", "platform_model", "platform_group_model"),
1207
+ coverage: optional(coverage),
1208
+ items: array(matrix)
1209
+ })(value);
1210
+ return {};
1211
+ }
1212
+ /** Repeated dimensions are retained; scalar duplicates and caller-selected scopes fail closed. */
1213
+ function validateMonitorQuery(path, params) {
1214
+ if (!MONITOR_READ_PATHS.includes(path) || [...params].length > 128) return void 0;
1215
+ const v2 = path.startsWith("channel-monitor-v2/"), query = new URLSearchParams(), seen = /* @__PURE__ */ new Map();
1216
+ let fresh = false, detailId;
1217
+ for (const [key, value] of params) {
1218
+ const repeated = v2 && [
1219
+ "platform",
1220
+ "model",
1221
+ "group_id"
1222
+ ].includes(key), occurrences = (seen.get(key) ?? 0) + 1;
1223
+ seen.set(key, occurrences);
1224
+ if (occurrences > (repeated ? 40 : 1) || safeText(value) === void 0 || value.includes(",")) return void 0;
1225
+ if (key === "fresh") {
1226
+ if (value !== "1") return void 0;
1227
+ fresh = true;
1228
+ continue;
1229
+ }
1230
+ if (!v2) {
1231
+ if (path !== "channel-monitors/detail" || key !== "id" || !positiveId$1(value)) return void 0;
1232
+ detailId = value;
1233
+ continue;
1234
+ }
1235
+ if (key === "range") {
1236
+ if (![
1237
+ "90m",
1238
+ "24h",
1239
+ "7d",
1240
+ "30d"
1241
+ ].includes(value)) return void 0;
1242
+ } else if (key === "platform") {
1243
+ if (!/^[a-z][a-z0-9_-]{0,47}$/.test(value)) return void 0;
1244
+ } else if (key === "group_id") {
1245
+ if (!positiveId$1(value)) return void 0;
1246
+ } else if (key === "model") {
1247
+ if (value.trim() !== value) return void 0;
1248
+ } else if (key === "group_by") {
1249
+ if (path !== "channel-monitor-v2/matrix" || ![
1250
+ "platform",
1251
+ "platform_group",
1252
+ "platform_model",
1253
+ "platform_group_model"
1254
+ ].includes(value)) return void 0;
1255
+ } else return void 0;
1256
+ query.append(key, value);
1257
+ }
1258
+ if (path === "channel-monitors/detail" && detailId === void 0) return void 0;
1259
+ return {
1260
+ wire: detailId === void 0 ? path : `channel-monitors/${detailId}/status`,
1261
+ query,
1262
+ fresh
1263
+ };
1264
+ }
1265
+ //#endregion
1266
+ //#region src/account/center-business-contract.ts
1267
+ /** Fixed native account reads/actions; no renderer-selected URL or method. */
1268
+ const BUSINESS_READ_PATHS = [
1269
+ "payment/config",
1270
+ "payment/checkout-info",
1271
+ "payment/plans",
1272
+ "payment/limits",
1273
+ "payment/orders/my",
1274
+ "payment/orders/detail",
1275
+ "payment/orders/refund-eligible-providers",
1276
+ "redeem/history",
1277
+ "affiliate",
1278
+ "profile",
1279
+ "actions/status"
1280
+ ];
1281
+ const BUSINESS_ACTIONS = [
1282
+ "payment/create",
1283
+ "payment/cancel",
1284
+ "payment/refund",
1285
+ "payment/verify",
1286
+ "redeem/apply",
1287
+ "affiliate/refresh",
1288
+ "affiliate/transfer",
1289
+ "profile/update"
1290
+ ];
1291
+ const object$3 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1292
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
1293
+ const validOperationId = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{8,128}$/.test(value);
1294
+ const positiveId = (value) => typeof value === "string" && /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n;
1295
+ const cleanText = (value, max = 1e3) => typeof value === "string" && value.length <= max && !/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(value);
1296
+ const only = (value, fields) => Object.keys(value).every((key) => fields.split(" ").includes(key));
1297
+ const plain = (value) => value === null || typeof value === "boolean" || finite(value) || cleanText(value, 4096) ? value : void 0;
1298
+ const pick$1 = (value, fields) => {
1299
+ const source = object$3(value), out = {};
1300
+ if (source === void 0) return out;
1301
+ for (const field of fields.split(" ")) {
1302
+ const value = plain(source[field]);
1303
+ if (value !== void 0) out[field] = value;
1304
+ }
1305
+ return out;
1306
+ };
1307
+ const idFields = (value, fields) => {
1308
+ for (const field of fields.split(" ")) {
1309
+ const current = value[field];
1310
+ if (positiveId(current)) continue;
1311
+ if (finite(current) && Number.isSafeInteger(current) && current > 0) value[field] = String(current);
1312
+ else if (current !== null) delete value[field];
1313
+ }
1314
+ return value;
1315
+ };
1316
+ const paymentType = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,40}$/.test(value);
1317
+ /** HTTPS payment links are server-issued; QR payment schemes are never navigated automatically. */
1318
+ function safeBusinessUrl(value, qr = false) {
1319
+ if (!cleanText(value, 8192) || /[\r\n\s]/.test(value)) return void 0;
1320
+ try {
1321
+ const url = new URL(value);
1322
+ if (url.username || url.password) return void 0;
1323
+ if (qr && [
1324
+ "weixin:",
1325
+ "alipays:",
1326
+ "alipay:"
1327
+ ].includes(url.protocol)) return value;
1328
+ const host = url.hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.+$/, "");
1329
+ if (url.protocol !== "https:" || url.port !== "" && url.port !== "443" || !host.includes(".") || /^[\d.]+$/.test(host) || host.includes(":") || /(?:^|\.)(?:localhost|local|internal)$/.test(host)) return void 0;
1330
+ for (const key of url.searchParams.keys()) if (/^(?:api[_-]?key|authorization|password|access_token|refresh_token)$/i.test(key)) return void 0;
1331
+ return value;
1332
+ } catch {
1333
+ return;
1334
+ }
1335
+ }
1336
+ function safeAvatarUrl(value) {
1337
+ if (!cleanText(value, 4096) || /[\r\n\s\\]/.test(value)) return void 0;
1338
+ try {
1339
+ const url = new URL(value), host = url.hostname.toLowerCase().replace(/\.$/, "");
1340
+ if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || !host.includes(".") || /^[\d.]+$/.test(host) || host.includes(":") || /(?:^|\.)(?:localhost|local|internal|home|lan)$/.test(host)) return void 0;
1341
+ return value;
1342
+ } catch {
1343
+ return;
1344
+ }
1345
+ }
1346
+ function businessQuery(path, params) {
1347
+ const query = new URLSearchParams(), seen = /* @__PURE__ */ new Set();
1348
+ let wire = path, fresh = false, detail;
1349
+ for (const [key, value] of params) {
1350
+ if (seen.has(key) || value.length > 160 || /[\r\n\0]/.test(value)) return void 0;
1351
+ seen.add(key);
1352
+ if (key === "fresh") {
1353
+ if (value !== "1") return void 0;
1354
+ fresh = true;
1355
+ continue;
1356
+ }
1357
+ if (path === "payment/orders/detail") {
1358
+ if (key !== "id" || !positiveId(value)) return void 0;
1359
+ detail = value;
1360
+ continue;
1361
+ }
1362
+ if (path === "actions/status") {
1363
+ if (key !== "operation_id" || !validOperationId(value)) return void 0;
1364
+ detail = value;
1365
+ continue;
1366
+ }
1367
+ if (path !== "payment/orders/my" && path !== "redeem/history") return void 0;
1368
+ if (key === "page") {
1369
+ if (!/^[1-9]\d{0,6}$/.test(value) || Number(value) > 1e6) return void 0;
1370
+ } else if (key === "page_size") {
1371
+ if (!/^[1-9]\d{0,2}$/.test(value) || Number(value) > 100) return void 0;
1372
+ } else if (path === "payment/orders/my" && key === "status") {
1373
+ if (![
1374
+ "PENDING",
1375
+ "PAID",
1376
+ "RECHARGING",
1377
+ "COMPLETED",
1378
+ "EXPIRED",
1379
+ "CANCELLED",
1380
+ "FAILED",
1381
+ "REFUND_REQUESTED",
1382
+ "REFUNDING",
1383
+ "REFUND_PENDING",
1384
+ "PARTIALLY_REFUNDED",
1385
+ "REFUNDED",
1386
+ "REFUND_FAILED"
1387
+ ].includes(value.toUpperCase())) return void 0;
1388
+ } else if (path === "payment/orders/my" && key === "order_type") {
1389
+ if (!["balance", "subscription"].includes(value)) return void 0;
1390
+ } else if (path === "payment/orders/my" && key === "payment_type") {
1391
+ if (!paymentType(value)) return void 0;
1392
+ } else return void 0;
1393
+ query.append(key, path === "payment/orders/my" && key === "status" ? value.toUpperCase() : value);
1394
+ }
1395
+ if (path === "payment/orders/detail" || path === "actions/status") {
1396
+ if (detail === void 0) return void 0;
1397
+ wire = path === "actions/status" ? `actions/${detail}` : `payment/orders/${detail}`;
1398
+ }
1399
+ return {
1400
+ wire,
1401
+ query,
1402
+ fresh
1403
+ };
1404
+ }
1405
+ function validateBusinessAction(kind, body) {
1406
+ const value = object$3(body);
1407
+ if (value === void 0) return void 0;
1408
+ let wire, method = "POST", payload = { ...value };
1409
+ if (kind === "payment/create") {
1410
+ if (!only(value, "amount payment_type order_type plan_id is_mobile") || !finite(value.amount) || value.amount < 0 || value.amount > 1e8 || !paymentType(value.payment_type)) return void 0;
1411
+ if (value.order_type !== void 0 && !["balance", "subscription"].includes(String(value.order_type))) return void 0;
1412
+ if (value.plan_id !== void 0 && (!finite(value.plan_id) || !Number.isSafeInteger(value.plan_id) || value.plan_id <= 0)) return void 0;
1413
+ if (value.amount === 0 && (value.order_type !== "subscription" || value.plan_id === void 0)) return void 0;
1414
+ if (value.is_mobile !== void 0 && typeof value.is_mobile !== "boolean") return void 0;
1415
+ wire = "payment/orders";
1416
+ } else if (kind === "payment/cancel" || kind === "payment/refund") {
1417
+ if (!only(value, kind === "payment/cancel" ? "id" : "id reason") || !positiveId(value.id)) return void 0;
1418
+ if (kind === "payment/refund" && (!cleanText(value.reason, 500) || value.reason.trim() === "")) return void 0;
1419
+ wire = `payment/orders/${value.id}/${kind === "payment/cancel" ? "cancel" : "refund-request"}`;
1420
+ const { id: _id, ...rest } = value;
1421
+ payload = rest;
1422
+ } else if (kind === "payment/verify") {
1423
+ if (!only(value, "out_trade_no") || !cleanText(value.out_trade_no, 128) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.out_trade_no)) return void 0;
1424
+ wire = "payment/orders/verify";
1425
+ } else if (kind === "redeem/apply") {
1426
+ if (!only(value, "code") || !cleanText(value.code, 256) || value.code.trim() === "" || /[\r\n]/.test(value.code)) return void 0;
1427
+ wire = "redeem";
1428
+ } else if (kind === "affiliate/refresh" || kind === "affiliate/transfer") {
1429
+ if (Object.keys(value).length !== 0) return void 0;
1430
+ wire = kind;
1431
+ } else if (kind === "profile/update") {
1432
+ if (!only(value, "username avatar_url balance_notify_enabled balance_notify_threshold") || Object.keys(value).length === 0) return void 0;
1433
+ if (value.username !== void 0 && (!cleanText(value.username, 256) || new TextEncoder().encode(value.username).length > 256)) return void 0;
1434
+ if (value.avatar_url !== void 0 && value.avatar_url !== "" && safeAvatarUrl(value.avatar_url) === void 0 && !(cleanText(value.avatar_url, 512e3) && /^data:image\/(?:png|jpeg|webp|gif);base64,[A-Za-z0-9+/=]+$/.test(value.avatar_url))) return void 0;
1435
+ if (value.balance_notify_enabled !== void 0 && typeof value.balance_notify_enabled !== "boolean") return void 0;
1436
+ if (value.balance_notify_threshold !== void 0 && (!finite(value.balance_notify_threshold) || Math.abs(value.balance_notify_threshold) > Number.MAX_SAFE_INTEGER)) return void 0;
1437
+ wire = "profile";
1438
+ method = "PUT";
1439
+ } else return void 0;
1440
+ return {
1441
+ wire,
1442
+ method,
1443
+ payload
1444
+ };
1445
+ }
1446
+ const profile = (value) => {
1447
+ const out = idFields(pick$1(value, "id username email avatar_url balance currency balance_notify_enabled balance_notify_threshold created_at status"), "id");
1448
+ if (out.avatar_url !== void 0 && out.avatar_url !== "") {
1449
+ const url = safeAvatarUrl(out.avatar_url);
1450
+ if (url !== void 0) out.avatar_url = url;
1451
+ else delete out.avatar_url;
1452
+ }
1453
+ return out;
1454
+ };
1455
+ const plan = (value) => {
1456
+ const source = object$3(value) ?? {}, out = idFields(pick$1(value, "id group_id group_name group_platform name description price original_price currency validity_days validity_unit duration_days duration_months sort_order product_name platform daily_limit_usd weekly_limit_usd monthly_limit_usd rate_multiplier peak_rate_enabled peak_start peak_end peak_rate_multiplier model_restriction_enabled for_sale"), "id group_id");
1457
+ for (const field of [
1458
+ "features",
1459
+ "allowed_models",
1460
+ "model_scopes",
1461
+ "supported_model_scopes"
1462
+ ]) {
1463
+ const sourceValue = typeof source[field] === "string" ? (() => {
1464
+ try {
1465
+ return JSON.parse(source[field]);
1466
+ } catch {
1467
+ return [source[field]];
1468
+ }
1469
+ })() : source[field];
1470
+ if (Array.isArray(sourceValue)) out[field] = sourceValue.slice(0, 200).filter((x) => cleanText(x, 300));
1471
+ }
1472
+ if (object$3(source.group)) out.group = idFields(pick$1(source.group, "id name description platform rate_multiplier subscription_type daily_limit_usd weekly_limit_usd monthly_limit_usd"), "id");
1473
+ return out;
1474
+ };
1475
+ const order = (value) => idFields(pick$1(value, "id amount pay_amount fee_rate bonus_amount currency balance_currency payment_type out_trade_no status order_type created_at expires_at paid_at completed_at refunded_at refund_at refund_requested_at refund_amount refund_reason refund_request_reason refund_status refund_reject_reason plan_id provider_instance_id refundable"), "id plan_id");
1476
+ const redeemed = (value) => idFields(pick$1(value, "id type value status used_at created_at expires_at group_id validity_days description"), "id group_id");
1477
+ const affiliate = (value) => {
1478
+ const source = object$3(value) ?? {}, out = pick$1(value, "aff_code aff_count aff_quota aff_frozen_quota aff_history_quota effective_rebate_rate_percent");
1479
+ out.invitees = Array.isArray(source.invitees) ? source.invitees.slice(0, 100).map((item) => idFields(pick$1(item, "user_id email username created_at total_rebate"), "user_id")) : [];
1480
+ return out;
1481
+ };
1482
+ const paged = (value, row) => {
1483
+ if (Array.isArray(value)) return value.slice(0, 100).map(row);
1484
+ const source = object$3(value) ?? {}, out = pick$1(source, "total page page_size pages");
1485
+ out.items = Array.isArray(source.items) ? source.items.slice(0, 100).map(row) : [];
1486
+ return out;
1487
+ };
1488
+ const checkout = (value) => {
1489
+ const source = object$3(value) ?? {}, out = pick$1(value, "enabled balance_currency balance_disabled subscription_enabled min_amount max_amount global_min global_max daily_limit order_timeout_minutes max_pending_orders balance_recharge_multiplier subscription_usd_to_cny_rate recharge_fee_rate bonus_mode recharge_bonus_mode bonus_notice recharge_bonus_notice help_text");
1490
+ const methods = object$3(source.methods);
1491
+ if (methods !== void 0) out.methods = Object.fromEntries(Object.entries(methods).filter(([key]) => paymentType(key)).slice(0, 32).map(([key, item]) => [key, pick$1(item, "currency display_name daily_limit daily_used daily_remaining single_min single_max fee_rate available")]));
1492
+ for (const field of ["bonus_tiers", "recharge_bonus_tiers"]) if (Array.isArray(source[field])) out[field] = source[field].slice(0, 100).map((item) => pick$1(item, "min_amount amount bonus_rate bonus_percent bonus_amount rate threshold"));
1493
+ if (Array.isArray(source.plans)) out.plans = source.plans.slice(0, 200).map(plan);
1494
+ const image = safeBusinessUrl(source.help_image_url);
1495
+ if (image !== void 0) out.help_image_url = image;
1496
+ return out;
1497
+ };
1498
+ const checkoutResult = (value) => {
1499
+ const source = object$3(value) ?? {}, out = {
1500
+ ...order(value),
1501
+ ...pick$1(value, "order_id message payment_mode payment_type result_type expires_in")
1502
+ };
1503
+ idFields(out, "id order_id plan_id");
1504
+ if (object$3(source.order)) out.order = order(source.order);
1505
+ for (const field of [
1506
+ "pay_url",
1507
+ "payment_url",
1508
+ "qr_code_url",
1509
+ "qr_code"
1510
+ ]) {
1511
+ const url = safeBusinessUrl(source[field], field === "qr_code_url" || field === "qr_code");
1512
+ if (url !== void 0) out[field] = url;
1513
+ }
1514
+ return out;
1515
+ };
1516
+ function projectBusinessRead(path, value) {
1517
+ if (path === "actions/status") return projectBusinessReceipt(value);
1518
+ if (path === "profile") return profile(value);
1519
+ if (path === "affiliate") return affiliate(value);
1520
+ if (path === "redeem/history") return paged(value, redeemed);
1521
+ if (path === "payment/orders/my") return paged(value, order);
1522
+ if (path === "payment/orders/detail") return order(value);
1523
+ if (path === "payment/plans") return Array.isArray(value) ? value.slice(0, 200).map(plan) : [];
1524
+ if (path === "payment/orders/refund-eligible-providers") {
1525
+ const source = object$3(value);
1526
+ return { provider_instance_ids: Array.isArray(source?.provider_instance_ids) ? source.provider_instance_ids.slice(0, 200).filter((x) => cleanText(x, 128) && /^[A-Za-z0-9_-]+$/.test(x) || finite(x) && Number.isSafeInteger(x)).map(String) : [] };
1527
+ }
1528
+ return checkout(value);
1529
+ }
1530
+ const ACTION_NAMES = {
1531
+ "payment.create": "payment/create",
1532
+ "payment.cancel": "payment/cancel",
1533
+ "payment.refund": "payment/refund",
1534
+ "payment.verify": "payment/verify",
1535
+ redeem: "redeem/apply",
1536
+ "affiliate.refresh": "affiliate/refresh",
1537
+ "affiliate.transfer": "affiliate/transfer",
1538
+ "profile.update": "profile/update"
1539
+ };
1540
+ function projectBusinessReceipt(value) {
1541
+ const source = object$3(value);
1542
+ if (source === void 0 || !validOperationId(source.operation_id) || typeof source.action !== "string" || !Object.hasOwn(ACTION_NAMES, source.action) || ![
1543
+ "processing",
1544
+ "succeeded",
1545
+ "rejected",
1546
+ "unknown"
1547
+ ].includes(String(source.state))) return void 0;
1548
+ const out = pick$1(source, "operation_id action state response_status");
1549
+ if (source.result !== void 0) out.result = source.action === "profile.update" ? profile(source.result) : source.action === "redeem" ? redeemed(source.result) : source.action === "affiliate.refresh" ? affiliate(source.result) : source.action === "affiliate.transfer" ? pick$1(source.result, "transferred_quota balance") : checkoutResult(source.result);
1550
+ if (object$3(source.error)) {
1551
+ const error = pick$1(source.error, "code category message");
1552
+ if (source.action === "redeem") delete error.message;
1553
+ if (typeof error.message === "string") error.message = error.message.replace(/https?:\/\/\S+|Bearer\s+\S+|\b(?:sk-|vdat_)[A-Za-z0-9_.-]+/gi, "[…]").slice(0, 500);
1554
+ out.error = error;
1555
+ }
1556
+ return out;
1557
+ }
1558
+ //#endregion
1559
+ //#region src/account/center-contract.ts
1560
+ /** Exact, read-only account-page schemas. No caller-selected URL or object shape. */
1561
+ const record$9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1562
+ const fields = (text) => text.split(" ");
1563
+ const scalar = (value) => value === null || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && value.length <= 1e3 && !/\b(?:Bearer\s|vdat_|sk-)|https?:\/\/|eyJ[A-Za-z0-9_-]+\./i.test(value) ? value : void 0;
1564
+ function project(value, shape) {
1565
+ const source = record$9(value);
1566
+ if (source === void 0) return void 0;
1567
+ if (shape === imageSizes) return Object.fromEntries(Object.entries(source).filter(([key, item]) => {
1568
+ const kilo = /^(\d{1,2}(?:\.\d{1,3})?)K$/.exec(key), dimensions = /^(\d{1,5})x(\d{1,5})$/.exec(key);
1569
+ return (kilo !== null ? Number(kilo[1]) >= 1 && Number(kilo[1]) <= 16 : dimensions !== null && dimensions.slice(1).every((part) => Number(part) >= 1 && Number(part) <= 16384)) && typeof item === "number" && Number.isSafeInteger(item) && item >= 0;
1570
+ }).slice(0, 32));
1571
+ const result = {};
1572
+ for (const key of shape.fields) {
1573
+ const item = scalar(source[key]);
1574
+ if ([
1575
+ "inbound_endpoint",
1576
+ "upstream_endpoint",
1577
+ "endpoint"
1578
+ ].includes(key) && (typeof item !== "string" || !SAFE_ENDPOINTS.has(item))) continue;
1579
+ if (item !== void 0) result[key] = item;
1580
+ }
1581
+ for (const [key, child] of Object.entries(shape.objects ?? {})) {
1582
+ const item = project(source[key], child);
1583
+ if (item !== void 0) result[key] = item;
1584
+ }
1585
+ for (const [key, child] of Object.entries(shape.arrays ?? {})) if (Array.isArray(source[key])) result[key] = source[key].slice(0, 1e3).map((item) => child === "scalar" ? scalar(item) : project(item, child)).filter((item) => item !== void 0);
1586
+ return result;
1587
+ }
1588
+ const SAFE_ENDPOINTS = new Set(fields("/v1/systemone /v1/completions /v1/alpha/search /v1/responses/compact /v1/responses/input_tokens /v1/images/tasks /v1/videos/generations /v1/videos/edits /v1/videos/extensions /v1beta/models /v1beta/cachedContents /v1internal:streamGenerateContent /v1/messages /v1/messages/count_tokens /v1/chat/completions /v1/responses /v1/embeddings /v1/images/generations /v1/images/edits /v1/videos /v1/audio/speech /v1/audio/transcriptions /v1/audio/translations /v1/realtime /messages /messages/count_tokens /chat/completions /responses /embeddings /images/generations /images/edits /videos /tts /stt /realtime /alpha/search /v3/contents/generations/tasks /api/v3/contents/generations/tasks /v1/contents/generations/tasks"));
1589
+ const imageSizes = { fields: [] };
1590
+ const group = { fields: fields("id name platform description status subscription_type rate_multiplier peak_rate_enabled peak_start peak_end peak_rate_multiplier") };
1591
+ const window = { fields: fields("state remaining_percent resets_at") };
1592
+ const windows = {
1593
+ fields: [],
1594
+ objects: {
1595
+ five_hour: window,
1596
+ seven_day: window
1597
+ }
1598
+ };
1599
+ const reason = { fields: fields("code window retry_at") };
1600
+ const subscription = {
1601
+ fields: fields("id subscription_id group_id name group_name status starts_at expires_at created_at updated_at revoked_at legacy_constraints_present usable allow_balance_fallback priority"),
1602
+ objects: {
1603
+ group,
1604
+ windows
1605
+ },
1606
+ arrays: {
1607
+ model_ids: "scalar",
1608
+ blocking_reasons: reason
1609
+ }
1610
+ };
1611
+ const metadata = {
1612
+ fields: fields("id group_id name status starts_at expires_at created_at updated_at revoked_at legacy_constraints_present"),
1613
+ objects: { group }
1614
+ };
1615
+ const progress = {
1616
+ fields: ["id", "usable"],
1617
+ objects: { windows: {
1618
+ fields: [],
1619
+ objects: { seven_day: window }
1620
+ } },
1621
+ arrays: { blocking_reasons: reason }
1622
+ };
1623
+ const usage = {
1624
+ fields: fields("id model request_id created_at reasoning_effort service_tier inbound_endpoint upstream_endpoint ip_address user_agent group_id subscription_id input_tokens output_tokens cache_read_tokens cache_creation_tokens cache_creation_5m_tokens cache_creation_1h_tokens total_tokens input_cost output_cost cache_read_cost cache_creation_cost actual_cost total_cost currency rate_multiplier long_context_billing_applied duration_ms first_token_ms request_type stream openai_ws_mode native_compaction_v2 billing_type billing_mode image_count image_size image_input_size image_output_size image_size_source image_input_tokens image_input_cost image_output_tokens image_output_cost media_type cache_ttl_overridden"),
1625
+ objects: {
1626
+ group,
1627
+ image_size_breakdown: imageSizes
1628
+ }
1629
+ };
1630
+ const error = { fields: fields("code stage task_id operation_id id created_at request_id model inbound_endpoint status_code category platform client_ip group_name request_type stream user_agent upstream_status_code") };
1631
+ const aggregate = { fields: fields("date endpoint group_id group_name model requests count input_tokens output_tokens cache_creation_tokens cache_read_tokens total_tokens tokens cost actual_cost percentage currency") };
1632
+ const platform$1 = { fields: fields("platform total_requests total_tokens total_actual_cost today_requests today_tokens today_actual_cost") };
1633
+ const stats = {
1634
+ fields: fields("total_requests total_input_tokens total_output_tokens total_cache_tokens total_cache_read_tokens total_cache_creation_tokens total_actual_cost total_cost today_requests today_cost today_actual_cost today_input_tokens today_output_tokens today_cache_read_tokens today_cache_creation_tokens today_tokens total_tokens average_duration_ms rpm tpm currency period"),
1635
+ arrays: {
1636
+ by_platform: platform$1,
1637
+ endpoints: aggregate
1638
+ }
1639
+ };
1640
+ const list$1 = (item) => ({
1641
+ fields: fields("total page page_size pages"),
1642
+ arrays: { items: item }
1643
+ });
1644
+ const features = { fields: fields("available_channels channel_status model_prices recharge redeem affiliate profile error_requests api_key_management") };
1645
+ const entitlements = {
1646
+ fields: fields("contract_version revision server_time available_amount frozen_amount total_amount currency subscription_billing_enabled subscription_snapshot_available allow_balance_fallback"),
1647
+ objects: {
1648
+ features,
1649
+ balance: { fields: fields("currency available_amount frozen_amount total_amount") }
1650
+ },
1651
+ arrays: {
1652
+ capabilities: "scalar",
1653
+ model_ids: "scalar",
1654
+ subscriptions: subscription
1655
+ }
1656
+ };
1657
+ const quota = { fields: fields("platform daily_limit_usd daily_usage_usd weekly_limit_usd weekly_usage_usd monthly_limit_usd monthly_usage_usd daily_window_resets_at weekly_window_resets_at monthly_window_resets_at") };
1658
+ const CENTER_READ_PATHS = [
1659
+ "auth/me",
1660
+ "usage",
1661
+ "usage/dashboard/stats",
1662
+ "usage/dashboard/trend",
1663
+ "usage/dashboard/models",
1664
+ "subscriptions/summary",
1665
+ "entitlements",
1666
+ "usage/stats",
1667
+ "usage/details",
1668
+ "usage/errors",
1669
+ "usage/errors/detail",
1670
+ "usage/dashboard/snapshot-v2",
1671
+ "groups/available",
1672
+ "user/platform-quotas",
1673
+ "subscriptions",
1674
+ "subscriptions/progress",
1675
+ "model-plaza",
1676
+ ...MONITOR_READ_PATHS,
1677
+ ...BUSINESS_READ_PATHS
1678
+ ];
1679
+ const filters = fields("start_date end_date model group_id request_type stream native_compaction_v2 billing_type billing_mode timezone");
1680
+ const queries = {
1681
+ "auth/me": [],
1682
+ usage: [
1683
+ ...filters,
1684
+ "page",
1685
+ "page_size",
1686
+ "sort_by",
1687
+ "sort_order"
1688
+ ],
1689
+ "usage/dashboard/stats": [],
1690
+ "usage/dashboard/trend": [...filters, "granularity"],
1691
+ "usage/dashboard/models": [...filters, "model_source"],
1692
+ "subscriptions/summary": [],
1693
+ entitlements: ["fresh"],
1694
+ "usage/stats": [...filters, "period"],
1695
+ "usage/details": ["id"],
1696
+ "usage/errors": fields("page page_size start_date end_date timezone model category status_code sort_by sort_order"),
1697
+ "usage/errors/detail": ["id"],
1698
+ "usage/dashboard/snapshot-v2": [
1699
+ ...filters,
1700
+ "granularity",
1701
+ "include_trend",
1702
+ "include_model_stats",
1703
+ "include_group_stats"
1704
+ ],
1705
+ "groups/available": [],
1706
+ "user/platform-quotas": [],
1707
+ subscriptions: [],
1708
+ "subscriptions/progress": []
1709
+ };
1710
+ function positiveCenterId(value) {
1711
+ return /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n;
1712
+ }
1713
+ function validDate(value) {
1714
+ return /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
1715
+ }
1716
+ /** Returns undefined for any unsupported/duplicate/invalid parameter. */
1717
+ function centerQuery(path, params) {
1718
+ if (BUSINESS_READ_PATHS.includes(path)) return businessQuery(path, params);
1719
+ if (path === "model-plaza") {
1720
+ const query = validateModelPlazaQuery(params);
1721
+ return query === void 0 ? void 0 : {
1722
+ wire: path,
1723
+ query,
1724
+ fresh: false
1725
+ };
1726
+ }
1727
+ if (MONITOR_READ_PATHS.includes(path)) return validateMonitorQuery(path, params);
1728
+ const query = new URLSearchParams(), seen = /* @__PURE__ */ new Set();
1729
+ let id, fresh = false;
1730
+ for (const [key, value] of params) {
1731
+ if (seen.has(key) || !queries[path].includes(key) || value.length > 160 || /[\r\n\0]/.test(value)) return void 0;
1732
+ seen.add(key);
1733
+ if ((key === "id" || key === "group_id") && !positiveCenterId(value)) return void 0;
1734
+ if (key === "page" && (!/^\d{1,7}$/.test(value) || Number(value) < 1)) return void 0;
1735
+ if (key === "page_size" && (!/^\d{1,3}$/.test(value) || Number(value) < 1 || Number(value) > 100)) return void 0;
1736
+ if ((key === "start_date" || key === "end_date") && !validDate(value)) return void 0;
1737
+ if (key === "granularity" && !["hour", "day"].includes(value)) return void 0;
1738
+ if (key === "request_type" && ![
1739
+ "unknown",
1740
+ "sync",
1741
+ "stream",
1742
+ "ws_v2",
1743
+ "cyber",
1744
+ "live"
1745
+ ].includes(value)) return void 0;
1746
+ if ([
1747
+ "stream",
1748
+ "native_compaction_v2",
1749
+ "include_trend",
1750
+ "include_model_stats",
1751
+ "include_group_stats"
1752
+ ].includes(key) && !["true", "false"].includes(value)) return void 0;
1753
+ if (key === "billing_type" && !["0", "1"].includes(value)) return void 0;
1754
+ if (key === "billing_mode" && ![
1755
+ "token",
1756
+ "per_request",
1757
+ "image",
1758
+ "video",
1759
+ "video_token"
1760
+ ].includes(value)) return void 0;
1761
+ if (key === "sort_by" && !(path === "usage/errors" ? [
1762
+ "created_at",
1763
+ "model",
1764
+ "status_code"
1765
+ ] : ["created_at", "model"]).includes(value)) return void 0;
1766
+ if (key === "sort_order" && !["asc", "desc"].includes(value)) return void 0;
1767
+ if (key === "status_code" && !/^[1-5]\d{2}$/.test(value)) return void 0;
1768
+ if (key === "category" && ![
1769
+ "auth",
1770
+ "rate_limit",
1771
+ "quota",
1772
+ "invalid_request",
1773
+ "service_unavailable",
1774
+ "upstream",
1775
+ "internal",
1776
+ "cyber",
1777
+ "other"
1778
+ ].includes(value)) return void 0;
1779
+ if (key === "period" && ![
1780
+ "today",
1781
+ "week",
1782
+ "month",
1783
+ "year"
1784
+ ].includes(value)) return void 0;
1785
+ if (key === "model_source" && value !== "requested") return void 0;
1786
+ if (key === "timezone") try {
1787
+ new Intl.DateTimeFormat("en", { timeZone: value });
1788
+ } catch {
1789
+ return;
1790
+ }
1791
+ if (key === "fresh") {
1792
+ if (value !== "1") return void 0;
1793
+ fresh = true;
1794
+ continue;
1795
+ }
1796
+ if (key === "id") {
1797
+ id = value;
1798
+ continue;
1799
+ }
1800
+ query.set(key, value);
1801
+ }
1802
+ if (path.endsWith("/details") || path.endsWith("/detail")) {
1803
+ if (id === void 0) return void 0;
1804
+ return {
1805
+ wire: path === "usage/details" ? `usage/details/${id}` : `usage/errors/${id}`,
1806
+ query,
1807
+ fresh
1808
+ };
1809
+ }
1810
+ if (query.has("start_date") && query.has("end_date") && query.get("start_date") > query.get("end_date")) return void 0;
1811
+ return {
1812
+ wire: path,
1813
+ query,
1814
+ fresh
1815
+ };
1816
+ }
1817
+ /** Legacy summary only: monetary weekly fields become a percentage, never a five-hour window. */
1818
+ function projectAccountData(value) {
1819
+ const convert = (item) => {
1820
+ const output = project(item, subscription), source = record$9(item);
1821
+ if (output === void 0 || source === void 0) return void 0;
1822
+ const number = (n) => typeof n === "number" && Number.isFinite(n) ? n : typeof n === "string" && /^\d+(?:\.\d+)?$/.test(n) ? Number(n) : void 0;
1823
+ const used = number(source.weekly_used_usd), limit = number(source.weekly_limit_usd);
1824
+ if (limit !== void 0 && used !== void 0) output.windows = { seven_day: {
1825
+ state: limit === 0 ? "unlimited" : used >= limit ? "exhausted" : "available",
1826
+ remaining_percent: limit === 0 ? null : Math.max(0, Math.min(100, (limit - used) / limit * 100)),
1827
+ resets_at: null
1828
+ } };
1829
+ return output;
1830
+ };
1831
+ if (Array.isArray(value)) return value.slice(0, 1e3).map(convert).filter((item) => item !== void 0);
1832
+ const source = record$9(value);
1833
+ return source === void 0 ? {} : {
1834
+ ...project(source, { fields: ["active_count"] }),
1835
+ ...Array.isArray(source.subscriptions) ? { subscriptions: source.subscriptions.slice(0, 1e3).map(convert).filter((item) => item !== void 0) } : {}
1836
+ };
1837
+ }
1838
+ function projectCenterRoute(path, value) {
1839
+ if (BUSINESS_READ_PATHS.includes(path)) return projectBusinessRead(path, value);
1840
+ if (path === "model-plaza") return projectModelPlaza(value);
1841
+ if (MONITOR_READ_PATHS.includes(path)) return projectMonitorRoute(path, value);
1842
+ if (path === "subscriptions/summary") return projectAccountData(value);
1843
+ if (path === "subscriptions" || path === "subscriptions/progress" || path === "groups/available") return Array.isArray(value) ? value.slice(0, 1e3).map((item) => project(item, path === "groups/available" ? group : path === "subscriptions/progress" ? progress : metadata)).filter((item) => item !== void 0) : [];
1844
+ if (path === "usage") return project(value, list$1(usage)) ?? {};
1845
+ if (path === "usage/details") return project(value, usage) ?? {};
1846
+ if (path === "usage/errors") return project(value, list$1(error)) ?? {};
1847
+ if (path === "usage/errors/detail") return project(value, error) ?? {};
1848
+ if (path === "entitlements") return project(value, entitlements) ?? {};
1849
+ if (path === "usage/stats" || path === "usage/dashboard/stats") return project(value, stats) ?? {};
1850
+ if (path === "user/platform-quotas") return project(value, {
1851
+ fields: ["currency"],
1852
+ arrays: { platform_quotas: quota }
1853
+ }) ?? {};
1854
+ if (path === "auth/me") return project(value, { fields: fields("id email nickname username balance frozen_balance currency") }) ?? {};
1855
+ if (Array.isArray(value)) return value.slice(0, 1e3).map((item) => project(item, aggregate)).filter((item) => item !== void 0);
1856
+ return project(value, {
1857
+ fields: fields("generated_at start_date end_date granularity currency"),
1858
+ arrays: {
1859
+ trend: aggregate,
1860
+ models: aggregate,
1861
+ groups: aggregate
1862
+ }
1863
+ }) ?? {};
1864
+ }
1865
+ //#endregion
1866
+ //#region src/account/center-business.ts
1867
+ const object$2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1868
+ const answer$1 = (status, body) => new Response(JSON.stringify(body), {
1869
+ status,
1870
+ headers: {
1871
+ "content-type": "application/json; charset=utf-8",
1872
+ "cache-control": "private, no-store"
1873
+ }
1874
+ });
1875
+ const failure = (status, code, notSubmitted, extra = {}) => answer$1(status, {
1876
+ ...extra,
1877
+ ...notSubmitted ? { not_submitted: true } : {},
1878
+ error: {
1879
+ code,
1880
+ category: code === "INVALID_INPUT" ? "invalid_input" : code === "ACCOUNT_CHANGED" ? "access_restricted" : "service_unavailable"
1881
+ }
1882
+ });
1883
+ const sameAccount$1 = (a, b) => a.signedIn && b.signedIn && a.userId !== void 0 && a.userId === b.userId;
1884
+ /** The buffered wire body must be unambiguous before it is canonicalized and fingerprinted. */
1885
+ function uniqueBusinessJson(raw) {
1886
+ if (Buffer.byteLength(raw, "utf8") > 1 << 20) throw new Error("body too large");
1887
+ const tokens = raw.match(/"(?:\\[\s\S]|[^"\\])*"|[{}\[\]:,]/g) ?? [];
1888
+ const stack = [];
1889
+ for (let index = 0; index < tokens.length; index++) {
1890
+ const token = tokens[index];
1891
+ if (token === "{" || token === "[") {
1892
+ stack.push(token === "{" ? /* @__PURE__ */ new Set() : null);
1893
+ if (stack.length > 8) throw new Error("body nesting");
1894
+ continue;
1895
+ }
1896
+ if (token === "}" || token === "]") {
1897
+ stack.pop();
1898
+ continue;
1899
+ }
1900
+ const keys = stack.at(-1);
1901
+ if (token.startsWith("\"") && tokens[index + 1] === ":" && keys !== void 0 && keys !== null) {
1902
+ const key = JSON.parse(token);
1903
+ if (keys.has(key)) throw new Error("duplicate field");
1904
+ keys.add(key);
1905
+ }
1906
+ }
1907
+ return JSON.parse(raw);
1908
+ }
1909
+ function accountBusinessActionsRoutes(http, account) {
1910
+ return BUSINESS_ACTIONS.map((kind) => ({
1911
+ path: `/api/dsh-vibedev/account-center/${kind}`,
1912
+ methods: ["POST"],
1913
+ requestBody: "buffered",
1914
+ fetch: async (request) => {
1915
+ let before, dispatched = false;
1916
+ const stillCurrent = async () => {
1917
+ try {
1918
+ return before !== void 0 && sameAccount$1(before, await account.identity());
1919
+ } catch {
1920
+ return false;
1921
+ }
1922
+ };
1923
+ try {
1924
+ if (new URL(request.url, "http://host").search !== "") return failure(400, "INVALID_INPUT", true);
1925
+ let body;
1926
+ try {
1927
+ body = object$2(uniqueBusinessJson(await request.text()));
1928
+ } catch {
1929
+ return failure(400, "INVALID_INPUT", true);
1930
+ }
1931
+ if (body === void 0 || Object.keys(body).some((key) => ![
1932
+ "operation_id",
1933
+ "expected_user_id",
1934
+ "payload"
1935
+ ].includes(key)) || !validOperationId(body.operation_id) || typeof body.expected_user_id !== "string") return failure(400, "INVALID_INPUT", true);
1936
+ const parsed = validateBusinessAction(kind, body.payload);
1937
+ if (parsed === void 0) return failure(400, "INVALID_INPUT", true);
1938
+ before = await account.identity();
1939
+ if (!before.signedIn || before.userId === void 0) return failure(401, "ACCOUNT_UNAVAILABLE", true);
1940
+ if (before.userId !== body.expected_user_id) return failure(409, "ACCOUNT_CHANGED", true);
1941
+ dispatched = true;
1942
+ const raw = await http.json(`/v1/account/${parsed.wire}`, {
1943
+ method: parsed.method,
1944
+ json: parsed.payload,
1945
+ idempotencyKey: body.operation_id,
1946
+ signal: request.signal,
1947
+ timeoutMs: 45e3,
1948
+ busyRetries: 0,
1949
+ isCurrentAccount: stillCurrent
1950
+ });
1951
+ if (!await stillCurrent()) {
1952
+ http.invalidateAccountSnapshots();
1953
+ return failure(409, "ACCOUNT_CHANGED", false);
1954
+ }
1955
+ const receipt = object$2(projectBusinessReceipt(object$2(raw)?.data));
1956
+ const expectedAction = kind === "redeem/apply" ? "redeem" : kind.replace("/", ".");
1957
+ if (receipt === void 0 || receipt.operation_id !== body.operation_id || receipt.action !== expectedAction) return failure(502, "ACCOUNT_ACTION_UNKNOWN", false);
1958
+ if (receipt.state === "succeeded") http.invalidateAccountSnapshots();
1959
+ return answer$1(200, {
1960
+ code: 0,
1961
+ data: receipt
1962
+ });
1963
+ } catch (error) {
1964
+ if (before !== void 0 && !await stillCurrent()) {
1965
+ http.invalidateAccountSnapshots();
1966
+ return failure(409, "ACCOUNT_CHANGED", !dispatched);
1967
+ }
1968
+ if (error instanceof MediaError) {
1969
+ const status = error.details.status ?? 502;
1970
+ if (status === 404 || status === 405) return failure(200, "ACCOUNT_ACTION_UNSUPPORTED", true, { unsupported: true });
1971
+ const refused = [
1972
+ 400,
1973
+ 401,
1974
+ 403,
1975
+ 413,
1976
+ 422
1977
+ ].includes(status);
1978
+ return failure(status, refused ? error.code : "ACCOUNT_ACTION_UNKNOWN", refused);
1979
+ }
1980
+ return failure(502, "ACCOUNT_ACTION_UNKNOWN", !dispatched);
1981
+ }
1982
+ }
1983
+ }));
1984
+ }
1985
+ //#endregion
1986
+ //#region src/account/center.ts
1987
+ const CENTER_PREFIX = "/api/dsh-vibedev/account-center";
1988
+ const obj = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1989
+ function answer(status, body) {
1990
+ return new Response(JSON.stringify(body), {
1991
+ status,
1992
+ headers: {
1993
+ "content-type": "application/json; charset=utf-8",
1994
+ "cache-control": "private, no-store"
1995
+ }
1996
+ });
1997
+ }
1998
+ function sameAccount(before, after) {
1999
+ return before.signedIn && after.signedIn && before.userId === after.userId && (before.userId !== void 0 || before.credential.token === after.credential.token);
2000
+ }
2001
+ function accountCenterRoutes(http, account) {
2002
+ return [...CENTER_READ_PATHS.map((path) => ({
2003
+ path: `${CENTER_PREFIX}/${path}`,
2004
+ methods: ["GET"],
2005
+ requestBody: "buffered",
2006
+ fetch: async (request) => {
2007
+ let before;
2008
+ const changed = () => {
2009
+ http.invalidateAccountSnapshots();
2010
+ return answer(409, { error: {
2011
+ code: "ACCOUNT_CHANGED",
2012
+ message: "账号已切换,请刷新页面。"
2013
+ } });
2014
+ };
2015
+ try {
2016
+ const params = new URL(request.url, "http://host").searchParams;
2017
+ const parsed = centerQuery(path, params);
2018
+ if (parsed === void 0) return answer(400, { error: {
2019
+ code: "INVALID_INPUT",
2020
+ category: "invalid_input",
2021
+ message: "筛选参数不符合要求。"
2022
+ } });
2023
+ const { query, wire, fresh } = parsed;
2024
+ before = await account.identity();
2025
+ if (!before.signedIn) return answer(401, { error: {
2026
+ code: "AUTHENTICATION_REQUIRED",
2027
+ category: "authentication",
2028
+ message: "请先登录 VibeDev。"
2029
+ } });
2030
+ const expectedUser = request.headers.get("X-VibeDev-Expected-User");
2031
+ if (expectedUser !== null && expectedUser !== before.userId) return changed();
2032
+ const options = {
2033
+ timeoutMs: 3e4,
2034
+ signal: request.signal,
2035
+ busyRetries: 0,
2036
+ isCurrentAccount: async () => sameAccount(before, await account.identity())
2037
+ };
2038
+ const data = path === "entitlements" && before.userId !== void 0 && query.size === 0 ? await http.entitlements(`${http.origin}\nuser:${before.userId}`, options, fresh) : await http.json(`/v1/account/${wire}${query.size === 0 ? "" : `?${query}`}`, options);
2039
+ const after = await account.identity();
2040
+ if (!sameAccount(before, after)) return changed();
2041
+ const projected = projectCenterRoute(path, obj(data)?.data ?? data);
2042
+ if (projected === void 0) return answer(502, { error: {
2043
+ code: "ACCOUNT_READ_UNAVAILABLE",
2044
+ category: "service_unavailable"
2045
+ } });
2046
+ return answer(200, {
2047
+ code: 0,
2048
+ data: projected
2049
+ });
2050
+ } catch (error) {
2051
+ if (error instanceof MediaError && error.code === "ACCOUNT_CHANGED" || before !== void 0 && !sameAccount(before, await account.identity())) return changed();
2052
+ if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405)) return answer(200, { unsupported: true });
2053
+ if (error instanceof MediaError) return answer(error.details.status ?? 502, { error: {
2054
+ code: error.code,
2055
+ category: error.details.category,
2056
+ message: error.message,
2057
+ request_id: error.details.requestId
2058
+ } });
2059
+ return answer(502, { error: {
2060
+ code: "ACCOUNT_READ_UNAVAILABLE",
2061
+ category: "service_unavailable",
2062
+ message: "账户信息暂时无法获取,请稍后刷新。"
2063
+ } });
2064
+ }
2065
+ }
2066
+ })), ...accountBusinessActionsRoutes(http, account)];
2067
+ }
2068
+ //#endregion
473
2069
  //#region src/account/latency.ts
474
2070
  /** Path of the latency route. */
475
2071
  const LATENCY_ROUTE = "/api/dsh-vibedev/latency";
@@ -943,114 +2539,6 @@ function draftFromCommitted(inspection) {
943
2539
  }, last);
944
2540
  }
945
2541
  //#endregion
946
- //#region src/gateway/errors.ts
947
- /**
948
- * Failures the plugin reports to the model: a gateway refusal, or a request the
949
- * plugin refused before anything was sent or charged. Messages are written for
950
- * the model to act on and relay to the user.
951
- * @module dsh-vibedev/gateway/errors
952
- */
953
- /**
954
- * One failure, with a stable `code` to route on and a message to show. It is a
955
- * harness error, so a tool failure keeps the code in the durable tool result
956
- * where a client can route on it (sign-in card, top-up link).
957
- */
958
- var MediaError = class extends HarnessError {
959
- details;
960
- /**
961
- * @param message - what happened and what to do next.
962
- * @param code - stable failure class, such as `INSUFFICIENT_BALANCE` or `VIDEO_MODE_UNSUPPORTED`.
963
- * @param details - status, retry and field facts.
964
- * @param options - the underlying cause, when there is one.
965
- */
966
- constructor(message, code, details = {}, options) {
967
- super(message, code, options);
968
- this.name = "MediaError";
969
- this.details = details;
970
- }
971
- };
972
- function record$9(value) {
973
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
974
- }
975
- function text$7(value) {
976
- return typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
977
- }
978
- function count$1(value) {
979
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
980
- }
981
- /** A CNY amount the gateway sends as a two-decimal string (a number is accepted too). */
982
- function amount$1(value) {
983
- if (typeof value === "number" && Number.isFinite(value)) return value.toFixed(2);
984
- const raw = text$7(value);
985
- return raw !== void 0 && /^-?\d+(?:\.\d+)?$/.test(raw) ? raw : void 0;
986
- }
987
- /**
988
- * Read a gateway error body. The gateway answers in several shapes: OpenAI's
989
- * `{error:{code,message,type}}`, its own `{error:{code,message,retryable,field}}`,
990
- * the account API's `{code,message,reason,metadata}` (a validation refusal names
991
- * the field and the rule there: `metadata: {field, rule}`), and a top-level
992
- * `recharge_url` on balance refusals. Media admission refusals add
993
- * `active`/`limit` (task limit) or `estimated_cny`/`available_cny`/`pending_cny` (balance).
994
- * @param body - the parsed JSON body, or undefined when it was not JSON.
995
- * @returns the fields found.
996
- */
997
- function parseGatewayFailure(body) {
998
- const root = record$9(body);
999
- if (root === void 0) return {};
1000
- const source = record$9(root.error) ?? root;
1001
- const metadata = record$9(source.metadata) ?? record$9(root.metadata);
1002
- const code = text$7(source.code) ?? text$7(source.type) ?? text$7(root.reason);
1003
- const message = text$7(source.message) ?? (typeof root.error === "string" ? text$7(root.error) : void 0);
1004
- const field = text$7(source.field) ?? text$7(metadata?.field);
1005
- const rule = text$7(source.rule) ?? text$7(metadata?.rule);
1006
- const rechargeUrl = text$7(source.recharge_url) ?? text$7(root.recharge_url);
1007
- const numbers = {
1008
- active: count$1(source.active),
1009
- limit: count$1(source.limit)
1010
- };
1011
- const amounts = {
1012
- estimatedCny: amount$1(source.estimated_cny),
1013
- availableCny: amount$1(source.available_cny),
1014
- pendingCny: amount$1(source.pending_cny)
1015
- };
1016
- const submissionState = text$7(source.submission_state) ?? text$7(root.submission_state);
1017
- const retryAction = text$7(source.retry_action) ?? text$7(root.retry_action);
1018
- const assetId = text$7(source.asset_id) ?? text$7(root.asset_id);
1019
- return {
1020
- ...code === void 0 ? {} : { code },
1021
- ...message === void 0 ? {} : { message },
1022
- ...field === void 0 ? {} : { field },
1023
- ...rule === void 0 ? {} : { rule },
1024
- ...typeof source.retryable === "boolean" ? { retryable: source.retryable } : {},
1025
- ...submissionState === void 0 ? {} : { submissionState: submissionState.toLowerCase() },
1026
- ...retryAction === void 0 ? {} : { retryAction: retryAction.toLowerCase() },
1027
- ...rechargeUrl === void 0 ? {} : { rechargeUrl },
1028
- ...assetId === void 0 ? {} : { assetId },
1029
- ...Object.fromEntries(Object.entries({
1030
- ...numbers,
1031
- ...amounts
1032
- }).filter(([, value]) => value !== void 0))
1033
- };
1034
- }
1035
- /**
1036
- * Milliseconds a `Retry-After` header asks for: delta seconds or an HTTP date.
1037
- * @param header - the header value, or null when absent.
1038
- * @param now - current epoch milliseconds, for an HTTP date.
1039
- * @returns the wait, or undefined when absent or unreadable.
1040
- */
1041
- function retryAfterMs(header, now = Date.now()) {
1042
- if (header === null || header.trim() === "") return void 0;
1043
- const seconds = Number(header.trim());
1044
- if (Number.isFinite(seconds)) return seconds < 0 ? void 0 : Math.round(seconds * 1e3);
1045
- const at = Date.parse(header);
1046
- return Number.isNaN(at) ? void 0 : Math.max(0, at - now);
1047
- }
1048
- /** `(CODE: message)`, for appending the gateway's own words to a message. */
1049
- function gatewayWords(failure) {
1050
- const parts = [failure.code, failure.message].filter((part) => part !== void 0);
1051
- return parts.length === 0 ? "" : ` (${parts.join(": ")})`;
1052
- }
1053
- //#endregion
1054
2542
  //#region src/util/files.ts
1055
2543
  /**
1056
2544
  * Files the plugin writes: its state directory, output names in the
@@ -1059,6 +2547,10 @@ function gatewayWords(failure) {
1059
2547
  * never leaves a half-written or empty file under a final name.
1060
2548
  * @module dsh-vibedev/util/files
1061
2549
  */
2550
+ /** A remembered result is usable only while its nonempty file still exists. */
2551
+ async function savedFileExists(path) {
2552
+ return path === void 0 ? false : stat(path).then((info) => info.isFile() && info.size > 0, () => false);
2553
+ }
1062
2554
  function expandHome(path) {
1063
2555
  if (path === "~") return homedir();
1064
2556
  if (path.startsWith("~/") || path.startsWith("~\\")) return join(homedir(), path.slice(2));
@@ -1569,6 +3061,71 @@ function feedbackRoutes(options) {
1569
3061
  }];
1570
3062
  }
1571
3063
  //#endregion
3064
+ //#region locale/en.json
3065
+ var en_default = {
3066
+ meta: {
3067
+ "title": "VibeDev Account & Models",
3068
+ "description": "Sign in to VibeDev (next to the DeepSeek account) to use the VibeDev gateway's models (Claude, GPT and more) in the model picker, and let the agent generate images, videos, music and podcasts and transcribe speech; paid from your VibeDev balance."
3069
+ },
3070
+ mediaErrors: {
3071
+ "operationIdentifier": "The operation identifier must contain 8-80 letters, numbers, underscores or hyphens.",
3072
+ "quoteUnavailable": "The quote response could not be verified. Refresh the quote.",
3073
+ "quoteMismatch": "The quote does not match this operation or has expired. Request a new quote.",
3074
+ "accountChanged": "The account changed. The original task is preserved.",
3075
+ "imageUncertain": "The image submission outcome is unknown. Check the original operation before generating again.",
3076
+ "lookupUnavailable": "Local task records are temporarily unavailable. Keep the original operation identifier and retry the lookup.",
3077
+ "accountUnavailable": "Unable to confirm the VibeDev account. Refresh account information and try again; original tasks are preserved.",
3078
+ "pollBilling": "Progress is temporarily unavailable. Check account billing; the original task is preserved.",
3079
+ "pollUnavailable": "Progress is temporarily unavailable. The original task is preserved.",
3080
+ "downloadFailed": "Generation completed, but the result could not be downloaded. Retry the download without generating again.",
3081
+ "submissionUncertain": "This operation needs confirmation. Keep operation {operationId}. Only its original key and saved request are checked within a limited recovery budget; a new operation will not be created automatically. Check the original task or account usage before generating again."
3082
+ }
3083
+ };
3084
+ //#endregion
3085
+ //#region locale/zh.json
3086
+ var zh_default = {
3087
+ meta: {
3088
+ "title": "VibeDev 账号与模型",
3089
+ "description": "登录 VibeDev 账号(与 DeepSeek 账号并存),在模型选择器里使用 VibeDev 网关的模型(Claude、GPT 等),并让 Agent 生成图片、视频、音乐和播客、转写语音;费用从 VibeDev 余额扣除。"
3090
+ },
3091
+ mediaErrors: {
3092
+ "operationIdentifier": "操作编号须为8–80个字母、数字、下划线或连字符。",
3093
+ "quoteUnavailable": "报价响应无法确认,请刷新报价。",
3094
+ "quoteMismatch": "报价与当前操作不匹配或已过期,请重新询价。",
3095
+ "accountChanged": "账号已切换,原任务已保留。",
3096
+ "imageUncertain": "图片提交结果待确认,请核对原请求,勿重复生成。",
3097
+ "lookupUnavailable": "本地任务记录暂时无法读取,请保留原操作编号后重试。",
3098
+ "accountUnavailable": "暂时无法确认 VibeDev 账户,请刷新账户信息后再试;原任务已保留。",
3099
+ "pollBilling": "暂时无法获取进度,请查看账户计费状态;原任务已保留。",
3100
+ "pollUnavailable": "暂时无法获取进度,原任务已保留。",
3101
+ "downloadFailed": "生成已完成,但结果下载失败。请重试下载,勿重复生成。",
3102
+ "submissionUncertain": "此操作结果待确认,请保留原操作编号 {operationId}。插件只会在有限核对预算内使用原编号和已保存请求核对,不会自动创建新操作;请核对原任务或账户用量后再决定是否重新生成。"
3103
+ }
3104
+ };
3105
+ //#endregion
3106
+ //#region src/host-locales.ts
3107
+ /** Host callers do not carry the UI locale. Use English by default; both shipped dictionaries remain available. */
3108
+ function hostMessage(key, locale = "en") {
3109
+ return (locale === "zh" ? zh_default : en_default).mediaErrors[key];
3110
+ }
3111
+ //#endregion
3112
+ //#region src/contracts.ts
3113
+ /** CONTRACT-V1.md 1.0.0-rc.1. Capabilities describe implemented support, never authorization. */
3114
+ const CLIENT_CAPABILITIES = ["errors-v1", "media-quotes-v1"];
3115
+ const ACCOUNT_PAGES = [
3116
+ "dashboard",
3117
+ "usage",
3118
+ "subscriptions",
3119
+ "available_channels",
3120
+ "channel_status",
3121
+ "model_prices",
3122
+ "recharge",
3123
+ "orders",
3124
+ "redeem",
3125
+ "affiliate",
3126
+ "profile"
3127
+ ];
3128
+ //#endregion
1572
3129
  //#region src/gateway/http.ts
1573
3130
  /**
1574
3131
  * HTTP client for the VibeDev gateway. Every gateway call goes through here so
@@ -1579,7 +3136,7 @@ function feedbackRoutes(options) {
1579
3136
  * URLs and third-party links never see it.
1580
3137
  * @module dsh-vibedev/gateway/http
1581
3138
  */
1582
- /** Error codes the gateway uses for "full right now, nothing was charged". */
3139
+ /** Legacy capacity/backoff codes; none independently proves a billing outcome. */
1583
3140
  const BUSY_CODES = /* @__PURE__ */ new Set([
1584
3141
  "APP_TOKEN_UNAVAILABLE",
1585
3142
  "PROVIDER_CAPACITY_BUSY",
@@ -1636,6 +3193,33 @@ function abortError(signal) {
1636
3193
  var GatewayHttp = class {
1637
3194
  options;
1638
3195
  origin;
3196
+ snapshots = /* @__PURE__ */ new Map();
3197
+ invalidateAccountSnapshots() {
3198
+ this.snapshots.clear();
3199
+ }
3200
+ /** One Host-only capability snapshot shared by quotes and the account bridge. */
3201
+ entitlements(scope, request = {}, fresh = false) {
3202
+ const cached = this.snapshots.get(scope);
3203
+ if (cached !== void 0 && (cached.pending && (!fresh || cached.fresh) || !fresh && Date.now() - cached.at < 3e4)) return cached.value;
3204
+ const snapshot = {
3205
+ at: Date.now(),
3206
+ pending: true,
3207
+ fresh,
3208
+ value: void 0
3209
+ };
3210
+ const value = this.json("/v1/account/entitlements", {
3211
+ ...request,
3212
+ busyRetries: 0
3213
+ }).catch((error) => {
3214
+ if (this.snapshots.get(scope) === snapshot && (!(error instanceof MediaError) || ![404, 405].includes(error.details.status ?? 0))) this.snapshots.delete(scope);
3215
+ throw error;
3216
+ }).finally(() => {
3217
+ snapshot.pending = false;
3218
+ });
3219
+ snapshot.value = value;
3220
+ this.snapshots.set(scope, snapshot);
3221
+ return value;
3222
+ }
1639
3223
  /**
1640
3224
  * @param options - origin, credential plane, user agent and test seams.
1641
3225
  */
@@ -1668,8 +3252,17 @@ var GatewayHttp = class {
1668
3252
  let credential = authenticate ? await this.credential() : void 0;
1669
3253
  let refreshed = false;
1670
3254
  let busyRetries = request.busyRetries ?? 2;
3255
+ const imageCreation = /^\/v1\/images\/(generations|edits)$/.test(new URL(url).pathname) && (request.method ?? (request.json === void 0 && request.body === void 0 ? "GET" : "POST")) === "POST";
3256
+ if (imageCreation) busyRetries = 0;
1671
3257
  for (;;) {
1672
- const response = await this.attempt(url, request, credential);
3258
+ if (request.isCurrentAccount !== void 0 && !await request.isCurrentAccount()) throw new MediaError("The active VibeDev account changed. The original operation is preserved.", "ACCOUNT_CHANGED", { retryable: false });
3259
+ let response;
3260
+ try {
3261
+ response = await this.attempt(url, request, credential);
3262
+ } catch (error) {
3263
+ if (imageCreation) throw uncertainImage(request.idempotencyKey, error);
3264
+ throw error;
3265
+ }
1673
3266
  if (response.ok) {
1674
3267
  if (authenticate) try {
1675
3268
  this.options.onAccepted?.({
@@ -1679,20 +3272,36 @@ var GatewayHttp = class {
1679
3272
  } catch {}
1680
3273
  return response;
1681
3274
  }
1682
- const failure = parseGatewayFailure(await response.clone().json().catch(() => void 0));
1683
- if (response.status === 401 && credential !== void 0 && credential.kind !== "key" && !refreshed) {
3275
+ const failure = gatewayFailureWithHeaders(await response.clone().json().catch(() => void 0), response.headers);
3276
+ if (imageCreation && imageSubmissionUncertain(failure)) throw uncertainImage(request.idempotencyKey, void 0, response.status, failure);
3277
+ if (response.status === 401 && isUserAuthenticationFailure(failure) && credential !== void 0 && credential.kind !== "key" && !refreshed) {
1684
3278
  refreshed = true;
1685
3279
  await this.options.rejectToken?.(credential);
1686
3280
  credential = await this.credential();
1687
3281
  continue;
1688
3282
  }
3283
+ if (imageCreation && response.status >= 500 && failure.submissionState !== "not_submitted" && failure.submissionState !== "rejected") throw uncertainImage(request.idempotencyKey, void 0, response.status);
1689
3284
  const wait = retryAfterMs(response.headers.get("retry-after"));
1690
3285
  if (isBusy(response.status, failure, wait) && busyRetries > 0 && (wait ?? DEFAULT_BUSY_WAIT_MS) <= (request.maxBusyWaitMs ?? 15e3)) {
1691
3286
  busyRetries--;
1692
3287
  await (this.options.sleep ?? delay$1)(wait ?? DEFAULT_BUSY_WAIT_MS, request.signal);
1693
3288
  continue;
1694
3289
  }
1695
- throw failureError$1(response.status, failure, wait);
3290
+ const classified = imageCreation && [
3291
+ 400,
3292
+ 402,
3293
+ 413,
3294
+ 422
3295
+ ].includes(response.status) && failure.submissionState === void 0 && (failure.category === void 0 || [
3296
+ "invalid_input",
3297
+ "billing",
3298
+ "content_rejected",
3299
+ "request"
3300
+ ].includes(failure.category)) ? {
3301
+ ...failure,
3302
+ submissionState: "rejected"
3303
+ } : failure;
3304
+ throw failureError$1(response.status, classified, wait);
1696
3305
  }
1697
3306
  }
1698
3307
  /**
@@ -1717,6 +3326,7 @@ var GatewayHttp = class {
1717
3326
  async attempt(url, request, credential) {
1718
3327
  if (isAborted(request.signal)) throw abortError(request.signal);
1719
3328
  const headers = {
3329
+ ...this.isGatewayUrl(url) ? { "x-vibedev-capabilities": CLIENT_CAPABILITIES.join(",") } : {},
1720
3330
  accept: "application/json",
1721
3331
  "user-agent": this.options.userAgent,
1722
3332
  ...request.headers
@@ -1741,13 +3351,36 @@ var GatewayHttp = class {
1741
3351
  } catch (error) {
1742
3352
  if (isAborted(request.signal)) throw abortError(request.signal);
1743
3353
  if (timeout.aborted) throw new MediaError(`The VibeDev gateway did not answer within ${Math.round((request.timeoutMs ?? DEFAULT_TIMEOUT_MS) / 1e3)} s.`, "GATEWAY_TIMEOUT", { retryable: true });
1744
- throw new MediaError(`Could not reach the VibeDev gateway (${error instanceof Error ? error.message : String(error)}). Ask the user to check the network connection.`, "GATEWAY_UNREACHABLE", { retryable: true });
3354
+ throw new MediaError("Could not reach the VibeDev gateway. Ask the user to check the network connection.", "GATEWAY_UNREACHABLE", { retryable: true });
1745
3355
  }
1746
3356
  }
1747
3357
  };
1748
- /**
1749
- * Whether an answer means "full right now, nothing was charged": any 429 but a
1750
- * task limit, or a 503 with a busy code or `Retry-After`. A bare 503 is an outage.
3358
+ function imageSubmissionUncertain(failure) {
3359
+ return failure.category === "submission_uncertain" || [
3360
+ "VIDEO_SUBMISSION_AMBIGUOUS",
3361
+ "SEED_AUDIO_SUBMISSION_UNKNOWN",
3362
+ "SUBMISSION_UNCERTAIN"
3363
+ ].includes(failure.code ?? "") || [
3364
+ "unknown",
3365
+ "submitting",
3366
+ "accepted"
3367
+ ].includes(failure.submissionState ?? "");
3368
+ }
3369
+ function uncertainImage(operationId, cause, status, failure) {
3370
+ return new MediaError(hostMessage("imageUncertain"), "SUBMISSION_UNCERTAIN", {
3371
+ category: "submission_uncertain",
3372
+ stage: "submit",
3373
+ submissionState: failure?.submissionState === "accepted" ? "accepted" : "unknown",
3374
+ billingState: failure?.billingState ?? "unknown",
3375
+ retryable: false,
3376
+ retryAction: "none",
3377
+ ...operationId === void 0 ? {} : { operationId },
3378
+ ...status === void 0 ? {} : { status }
3379
+ }, { cause });
3380
+ }
3381
+ /**
3382
+ * A legacy busy/backoff hint. This never proves a submission or billing outcome;
3383
+ * media creation callers disable automatic busy retries.
1751
3384
  */
1752
3385
  function isBusy(status, failure, wait) {
1753
3386
  if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return false;
@@ -1768,21 +3401,22 @@ function failureError$1(status, failure, wait) {
1768
3401
  ...facts,
1769
3402
  ...wait === void 0 ? {} : { retryAfterMs: wait }
1770
3403
  };
1771
- if (failure.code !== void 0 && TASK_LIMIT_CODES.has(failure.code)) return new MediaError(`The VibeDev account already runs as many ${failure.code.startsWith("VIDEO") ? "video" : "audio"} tasks at once as it may${failure.active === void 0 || failure.limit === void 0 ? "" : ` (${failure.active} of ${failure.limit})`}. Wait for one of them to finish (media_tasks lists them), then submit again; nothing was charged.`, failure.code, {
3404
+ if (failure.category !== void 0 || failure.gatewayCode !== void 0) return new MediaError(safeGatewayMessage(failure), failure.code ?? `HTTP_${status}`, details);
3405
+ 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). Billing is confirmed only by the gateway receipt.`, failure.code, {
1772
3406
  ...details,
1773
3407
  retryable: true
1774
3408
  });
1775
- if (status === 402) return new MediaError(`The VibeDev account balance is not enough for this request${(failure.estimatedCny === void 0 ? "" : `: this task is estimated at ¥${failure.estimatedCny}${failure.availableCny === void 0 ? "" : `, and ¥${failure.availableCny} is available`}${failure.pendingCny === void 0 || Number(failure.pendingCny) === 0 ? "" : ` (tasks in progress hold ¥${failure.pendingCny})`}`) || words}. Nothing was charged. Ask the user to top up their VibeDev balance${failure.rechargeUrl === void 0 ? "" : ` at ${failure.rechargeUrl}`}.`, "INSUFFICIENT_BALANCE", {
3409
+ 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}. Billing is confirmed only by the gateway receipt. Ask the user to top up their VibeDev balance.`, "INSUFFICIENT_BALANCE", {
1776
3410
  ...details,
1777
3411
  retryable: false
1778
3412
  });
1779
- if (status === 401) return new MediaError(`The VibeDev gateway rejected the sign-in${words}. Ask the user to sign in to VibeDev again.`, "SIGN_IN_REJECTED", {
3413
+ if (status === 401 && isUserAuthenticationFailure(failure)) return new MediaError(`The VibeDev gateway rejected the sign-in${words}. Ask the user to sign in to VibeDev again.`, "SIGN_IN_REJECTED", {
1780
3414
  ...details,
1781
3415
  retryable: false
1782
3416
  });
1783
3417
  if (isBusy(status, failure, wait)) {
1784
3418
  const seconds = wait === void 0 ? void 0 : Math.ceil(wait / 1e3);
1785
- return new MediaError(`The VibeDev gateway is busy${words}. ${seconds === void 0 ? "Try again shortly" : `Try again in about ${seconds} s`}; nothing was charged.`, failure.code ?? (status === 429 ? "RATE_LIMITED" : "GATEWAY_BUSY"), {
3419
+ return new MediaError(`The VibeDev gateway is busy${words}. ${seconds === void 0 ? "Try again shortly" : `Try again in about ${seconds} s`}; billing is confirmed only by the gateway receipt.`, failure.code ?? (status === 429 ? "RATE_LIMITED" : "GATEWAY_BUSY"), {
1786
3420
  ...details,
1787
3421
  retryable: true,
1788
3422
  busy: true
@@ -3973,7 +5607,7 @@ function isContextOverflow(message, contextWindow) {
3973
5607
  }
3974
5608
  //#endregion
3975
5609
  //#region node_modules/@earendil-works/pi-ai/dist/api/anthropic-messages.lazy.js
3976
- const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-BgIfgjNt.js").then((n) => n.t));
5610
+ const anthropicMessagesApi = () => lazyApi(() => import("./anthropic-messages-QcnVMGaA.js").then((n) => n.t));
3977
5611
  //#endregion
3978
5612
  //#region node_modules/@earendil-works/pi-ai/dist/api/openai-completions.lazy.js
3979
5613
  const openAICompletionsApi = () => lazyApi(() => import("./openai-completions-DqTCiqpS.js"));
@@ -4404,11 +6038,11 @@ const CLAUDE_CACHE_TTLS = [
4404
6038
  "5m",
4405
6039
  "1h"
4406
6040
  ];
4407
- const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
6041
+ const object$1 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
4408
6042
  function cacheBlock(value, ttl, nested) {
4409
- const block = object(value);
6043
+ const block = object$1(value);
4410
6044
  if (block === void 0) return value;
4411
- const marker = object(block.cache_control);
6045
+ const marker = object$1(block.cache_control);
4412
6046
  const next = marker?.type === "ephemeral" ? {
4413
6047
  ...block,
4414
6048
  cache_control: {
@@ -4417,7 +6051,7 @@ function cacheBlock(value, ttl, nested) {
4417
6051
  }
4418
6052
  } : { ...block };
4419
6053
  if (nested && Array.isArray(block.content)) next.content = block.content.map((child) => cacheBlock(child, ttl, true));
4420
- const source = object(block.source);
6054
+ const source = object$1(block.source);
4421
6055
  if (nested && block.type === "document" && source?.type === "content" && Array.isArray(source.content)) next.source = {
4422
6056
  ...source,
4423
6057
  content: source.content.map((child) => cacheBlock(child, ttl, true))
@@ -4436,7 +6070,7 @@ function withClaudeCacheTtl(payload, ttl) {
4436
6070
  if (Array.isArray(payload.system)) next.system = payload.system.map((block) => cacheBlock(block, ttl, true));
4437
6071
  if (Array.isArray(payload.tools)) next.tools = payload.tools.map((tool) => cacheBlock(tool, ttl, false));
4438
6072
  if (Array.isArray(payload.messages)) next.messages = payload.messages.map((value) => {
4439
- const message = object(value);
6073
+ const message = object$1(value);
4440
6074
  return message !== void 0 && Array.isArray(message.content) ? {
4441
6075
  ...message,
4442
6076
  content: message.content.map((block) => cacheBlock(block, ttl, true))
@@ -4736,6 +6370,7 @@ var GatewayAdapter = class extends LlmAdapter {
4736
6370
  }) } } : {},
4737
6371
  signal: AbortSignal.any([watchdog.signal, attemptStop.signal]),
4738
6372
  headers: {
6373
+ "x-vibedev-capabilities": CLIENT_CAPABILITIES.join(","),
4739
6374
  ...model.api === "anthropic-messages" ? { "x-api-key": null } : {},
4740
6375
  ...model.api !== "anthropic-messages" && sessionId !== void 0 ? { session_id: sessionId } : {},
4741
6376
  authorization: `Bearer ${token}`,
@@ -4768,6 +6403,7 @@ var GatewayAdapter = class extends LlmAdapter {
4768
6403
  return;
4769
6404
  }
4770
6405
  const chunk = result.value;
6406
+ const hadOutput = yielded;
4771
6407
  if (!yielded) {
4772
6408
  if (chunk.type === "usage") {
4773
6409
  held.push(chunk);
@@ -4782,7 +6418,18 @@ var GatewayAdapter = class extends LlmAdapter {
4782
6418
  for (const early of held.splice(0)) yield early;
4783
6419
  yielded = true;
4784
6420
  }
4785
- yield this.accountFailure(chunk, response, snapshot.origin);
6421
+ const mapped = this.accountFailure(chunk, response, snapshot.origin);
6422
+ yield hadOutput && mapped.type === "finish" && mapped.reason.kind === "error" && /^(?:TRANSPORT|TIMEOUT|SERVER|RATE_LIMIT|STREAM_CLOSED)$/.test(mapped.reason.failure.code) ? {
6423
+ ...mapped,
6424
+ reason: {
6425
+ ...mapped.reason,
6426
+ failure: {
6427
+ ...mapped.reason.failure,
6428
+ code: "VIBEDEV_STREAM_INTERRUPTED",
6429
+ message: "回复暂时中断,已收到的内容已保留。请确认后继续。"
6430
+ }
6431
+ }
6432
+ } : mapped;
4786
6433
  }
4787
6434
  } finally {
4788
6435
  if (!exhausted) {
@@ -4865,11 +6512,23 @@ var GatewayAdapter = class extends LlmAdapter {
4865
6512
  const status = response?.status;
4866
6513
  const requestId = response?.headers["x-request-id"] ?? response?.headers["request-id"];
4867
6514
  const failure = chunk.reason.failure;
6515
+ const gateway = sdkGatewayFailure(failure.message, response?.headers);
4868
6516
  const located = {
4869
6517
  ...failure,
4870
6518
  ...status === void 0 || status < 400 ? {} : { status },
4871
6519
  ...requestId === void 0 ? {} : { requestId }
4872
6520
  };
6521
+ if (gateway !== void 0) return {
6522
+ ...chunk,
6523
+ reason: {
6524
+ kind: "error",
6525
+ failure: {
6526
+ ...located,
6527
+ code: gateway.category === "authentication" ? SIGN_IN_REQUIRED_CODE : gateway.code ?? "VIBEDEV_GATEWAY_ERROR",
6528
+ message: gateway.category === "authentication" ? SESSION_ENDED_MESSAGE : safeGatewayMessage(gateway)
6529
+ }
6530
+ }
6531
+ };
4873
6532
  if (status === 402 || failure.code === QUOTA_EXCEEDED_CODE) return {
4874
6533
  ...chunk,
4875
6534
  reason: {
@@ -4881,7 +6540,7 @@ var GatewayAdapter = class extends LlmAdapter {
4881
6540
  }
4882
6541
  }
4883
6542
  };
4884
- if (status === 401) return {
6543
+ if (status === 401 && isUserAuthenticationFailure({ code: failure.code })) return {
4885
6544
  ...chunk,
4886
6545
  reason: {
4887
6546
  kind: "error",
@@ -4903,7 +6562,7 @@ var GatewayAdapter = class extends LlmAdapter {
4903
6562
  };
4904
6563
  /** Whether a chunk is the gateway refusing the credential (an error finish on an HTTP 401). */
4905
6564
  function isUnauthorized(chunk, response) {
4906
- return chunk.type === "finish" && chunk.reason.kind === "error" && response?.status === 401;
6565
+ return chunk.type === "finish" && chunk.reason.kind === "error" && response?.status === 401 && isUserAuthenticationFailure(sdkGatewayFailure(chunk.reason.failure.message, response.headers) ?? { code: chunk.reason.failure.code });
4907
6566
  }
4908
6567
  //#endregion
4909
6568
  //#region src/llm/index.ts
@@ -6366,14 +8025,14 @@ var MediaRuntime = class {
6366
8025
  const wanted = requested?.trim();
6367
8026
  if (wanted !== void 0 && wanted !== "") {
6368
8027
  const found = modelNamed(models, wanted);
6369
- if (found === void 0) throw new MediaError(`There is no model "${wanted}" on this VibeDev account. ${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`, "MODEL_NOT_FOUND", { field: "model" });
8028
+ if (found === void 0) throw localInputError(`There is no model "${wanted}" on this VibeDev account. ${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`, "MODEL_NOT_FOUND", { field: "model" });
6370
8029
  if (!ofKind.includes(found)) {
6371
- if (found.kind === "audio" && found.audioKind === void 0) throw new MediaError(`${found.id} does not declare what kind of audio it makes, so it cannot be used for ${slotLabel(slot).toLowerCase()}.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
6372
- throw new MediaError(`${found.id} is not a ${slotLabel(slot).toLowerCase()} model. ${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`, "MODEL_KIND_MISMATCH", { field: "model" });
8030
+ if (found.kind === "audio" && found.audioKind === void 0) throw localInputError(`${found.id} does not declare what kind of audio it makes, so it cannot be used for ${slotLabel(slot).toLowerCase()}.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
8031
+ throw localInputError(`${found.id} is not a ${slotLabel(slot).toLowerCase()} model. ${slotLabel(slot)} models: ${ofKind.map((model) => model.id).join(", ") || "none"}.`, "MODEL_KIND_MISMATCH", { field: "model" });
6373
8032
  }
6374
8033
  return found;
6375
8034
  }
6376
- if (ofKind.length === 0) throw new MediaError(`This VibeDev account has no ${slotLabel(slot).toLowerCase()} model available right now.`, "NO_MODEL_AVAILABLE");
8035
+ if (ofKind.length === 0) throw localInputError(`This VibeDev account has no ${slotLabel(slot).toLowerCase()} model available right now.`, "NO_MODEL_AVAILABLE");
6377
8036
  const pinnedName = this.settings.defaultModel(slot).trim();
6378
8037
  const pinned = pinnedName === "" ? void 0 : modelNamed(ofKind, pinnedName);
6379
8038
  const ordered = pinned === void 0 ? ofKind : [pinned, ...ofKind.filter((model) => model !== pinned)];
@@ -6388,7 +8047,7 @@ var MediaRuntime = class {
6388
8047
  */
6389
8048
  async findModel(requested, signal) {
6390
8049
  const found = modelNamed(await this.models(signal), requested.trim());
6391
- if (found === void 0) throw new MediaError(`There is no model "${requested}" on this VibeDev account.`, "MODEL_NOT_FOUND", { field: "model" });
8050
+ if (found === void 0) throw localInputError(`There is no model "${requested}" on this VibeDev account.`, "MODEL_NOT_FOUND", { field: "model" });
6392
8051
  return found;
6393
8052
  }
6394
8053
  /**
@@ -6445,12 +8104,12 @@ var MediaRuntime = class {
6445
8104
  ...signal === void 0 ? {} : { signal }
6446
8105
  });
6447
8106
  const info = await fs.stat(target, signal);
6448
- if (info === void 0) throw new MediaError(`"${path}" does not exist.`, "MEDIA_NOT_FOUND");
6449
- if (info.type !== "file") throw new MediaError(`"${path}" is not a file.`, "MEDIA_NOT_FOUND");
6450
- if (info.size !== void 0 && info.size > maxBytes) throw new MediaError(`"${path}" is ${(info.size / 1048576).toFixed(1)} MiB; the limit is ${(maxBytes / 1048576).toFixed(1)} MiB.`, "MEDIA_TOO_LARGE");
8107
+ if (info === void 0) throw localInputError(`"${path}" does not exist.`, "MEDIA_NOT_FOUND");
8108
+ if (info.type !== "file") throw localInputError(`"${path}" is not a file.`, "MEDIA_NOT_FOUND");
8109
+ if (info.size !== void 0 && info.size > maxBytes) throw localInputError(`"${path}" is ${(info.size / 1048576).toFixed(1)} MiB; the limit is ${(maxBytes / 1048576).toFixed(1)} MiB.`, "MEDIA_TOO_LARGE");
6451
8110
  return {
6452
8111
  data: await fs.readBytes(target, signal, maxBytes).catch((error) => {
6453
- if (error instanceof Error && "code" in error && error.code === "FS_TOO_LARGE") throw new MediaError(`"${path}" is larger than ${(maxBytes / 1048576).toFixed(1)} MiB.`, "MEDIA_TOO_LARGE");
8112
+ if (error instanceof Error && "code" in error && error.code === "FS_TOO_LARGE") throw localInputError(`"${path}" is larger than ${(maxBytes / 1048576).toFixed(1)} MiB.`, "MEDIA_TOO_LARGE");
6454
8113
  throw error;
6455
8114
  }),
6456
8115
  name: basename(fs.processPath(target))
@@ -6458,8 +8117,8 @@ var MediaRuntime = class {
6458
8117
  }
6459
8118
  const absolute = resolve(cwd ?? process.cwd(), path);
6460
8119
  const info = await stat(absolute).catch(() => void 0);
6461
- if (info === void 0 || !info.isFile()) throw new MediaError(`"${path}" does not exist or is not a file.`, "MEDIA_NOT_FOUND");
6462
- if (info.size > maxBytes) throw new MediaError(`"${path}" is ${(info.size / 1048576).toFixed(1)} MiB; the limit is ${(maxBytes / 1048576).toFixed(1)} MiB.`, "MEDIA_TOO_LARGE");
8120
+ if (info === void 0 || !info.isFile()) throw localInputError(`"${path}" does not exist or is not a file.`, "MEDIA_NOT_FOUND");
8121
+ if (info.size > maxBytes) throw localInputError(`"${path}" is ${(info.size / 1048576).toFixed(1)} MiB; the limit is ${(maxBytes / 1048576).toFixed(1)} MiB.`, "MEDIA_TOO_LARGE");
6463
8122
  return {
6464
8123
  data: new Uint8Array(await readFile(absolute)),
6465
8124
  name: basename(absolute)
@@ -6479,7 +8138,7 @@ var MediaRuntime = class {
6479
8138
  if (chat !== void 0) {
6480
8139
  const store = this.options.attachments?.();
6481
8140
  const agent = call.agent;
6482
- if (store === void 0 || agent === void 0) throw new MediaError(`"${source}" refers to a chat attachment, but this host does not expose them; pass a file path instead.`, "CHAT_REFERENCE_UNAVAILABLE");
8141
+ if (store === void 0 || agent === void 0) throw localInputError(`"${source}" refers to a chat attachment, but this host does not expose them; pass a file path instead.`, "CHAT_REFERENCE_UNAVAILABLE");
6483
8142
  return loadChatReference(chat, want, agent.session.deriveMessages(), store, maxBytes, call.signal);
6484
8143
  }
6485
8144
  return loadMedia(source, this.reader(call), maxBytes, call.signal);
@@ -6567,8 +8226,7 @@ function text$3(value) {
6567
8226
  }
6568
8227
  /** The gateway's own words for a failure, for error messages: ` (CODE: message)`. */
6569
8228
  function detail(failure) {
6570
- const parts = [failure.code, failure.message].filter((part) => part !== void 0);
6571
- return parts.length === 0 ? "" : ` (${parts.join(": ")})`;
8229
+ return gatewayWords(failure);
6572
8230
  }
6573
8231
  function aborted(signal, cause) {
6574
8232
  return new WebError("VibeDev web search aborted", "WEB_ABORTED", { cause: signal?.aborted === true ? signal.reason : cause });
@@ -6661,6 +8319,8 @@ async function readFailure(response) {
6661
8319
  return {};
6662
8320
  }
6663
8321
  const error = isRecord(payload) && isRecord(payload.error) ? payload.error : void 0;
8322
+ const normalized = gatewayFailureWithHeaders(payload, response.headers);
8323
+ if (normalized.category !== void 0 || normalized.gatewayCode !== void 0) return normalized;
6664
8324
  if (error === void 0) return {};
6665
8325
  const code = text$3(error.code);
6666
8326
  const message = text$3(error.message);
@@ -6673,10 +8333,12 @@ async function readFailure(response) {
6673
8333
  }
6674
8334
  /** The error for an answer the provider does not retry, worded for the model to act on. */
6675
8335
  function failureError(status, failure, wait) {
8336
+ const structured = failure;
8337
+ if (structured.category !== void 0 || structured.gatewayCode !== void 0) return new WebError(safeGatewayMessage(structured), structured.code ?? "WEB_PROVIDER_ERROR");
6676
8338
  switch (status) {
6677
8339
  case 400: return new WebError(failure.field === "query" ? `VibeDev web search rejected the query${detail(failure)}: it may be at most 400 characters. Search again with a shorter query.` : `VibeDev web search rejected the request${detail(failure)}.`, "WEB_PROVIDER_ERROR");
6678
8340
  case 401: return new WebError(`The VibeDev gateway rejected the sign-in used for web search${detail(failure)}. ${SIGN_IN_HINT}`, "WEB_PROVIDER_CREDENTIAL_REJECTED");
6679
- case 402: return new WebError(`The VibeDev account has no balance left, so the gateway refused this web search${detail(failure)}. Searching is free, but an empty balance blocks every gateway call: ask the user to top up their VibeDev balance.`, "WEB_SEARCH_BALANCE");
8341
+ case 402: return new WebError(`The gateway could not bill this web search${detail(failure)}. Check subscriptions and available billing methods in the VibeDev account center; top up if balance funding is needed.`, "WEB_SEARCH_BALANCE");
6680
8342
  case 429: return new WebError(`VibeDev web search is rate-limited${detail(failure)}. Wait about ${Math.ceil(wait / 1e3)} s before searching again, or answer from what you already have.`, "WEB_SEARCH_RATE_LIMITED");
6681
8343
  case 502:
6682
8344
  case 503: return new WebError(`VibeDev web search is temporarily unavailable${detail(failure)}. Tell the user search is unavailable right now and answer without it, or try again later.`, "WEB_SEARCH_UNAVAILABLE");
@@ -6719,14 +8381,14 @@ var GatewaySearchProvider = class {
6719
8381
  const response = await this.post(body, credential.token, signal);
6720
8382
  if (response.ok) return mapSearchResponse(await this.json(response, signal));
6721
8383
  const failure = await readFailure(response);
6722
- if (response.status === 401 && credential.kind !== "key" && !renewed) {
8384
+ if (response.status === 401 && isUserAuthenticationFailure(failure) && credential.kind !== "key" && !renewed) {
6723
8385
  renewed = true;
6724
8386
  await abortable(this.options.rejectCredential?.(credential) ?? Promise.resolve(), signal);
6725
8387
  credential = await this.credential(signal);
6726
8388
  continue;
6727
8389
  }
6728
8390
  const wait = searchRetryAfterMs(response.headers.get("retry-after")) ?? DEFAULT_RETRY_MS;
6729
- if ((response.status === 429 || response.status === 503) && retries < this.options.maxRetries && wait <= this.options.maxRetryWaitMs) {
8391
+ if ((failure.category === void 0 || failure.category === "rate_limited" || failure.category === "service_unavailable") && (response.status === 429 || response.status === 503) && retries < this.options.maxRetries && wait <= this.options.maxRetryWaitMs) {
6730
8392
  retries++;
6731
8393
  await (this.options.sleep ?? delay)(wait, signal);
6732
8394
  continue;
@@ -7063,8 +8725,8 @@ function quoteAudio(model, inputSeconds) {
7063
8725
  ...base,
7064
8726
  amountCny: price.amount,
7065
8727
  basis: {
7066
- en: `${label.en}, charged only if it succeeds`,
7067
- zh: `${label.zh},成功才扣费`
8728
+ en: `${label.en}, final billing follows the gateway receipt`,
8729
+ zh: `${label.zh},实际计费以网关回执为准`
7068
8730
  }
7069
8731
  };
7070
8732
  if (unit === "original_second") return {
@@ -7462,7 +9124,7 @@ const SPEECH_ONLY = [
7462
9124
  ];
7463
9125
  /** Default limit on one reference file when the catalog states none. */
7464
9126
  const DEFAULT_REFERENCE_BYTES = 20971520;
7465
- const OPERATION_ID = /^[\w-]{1,80}$/;
9127
+ const OPERATION_ID = /^[\w-]{8,80}$/;
7466
9128
  const has = (value) => value !== void 0 && value.trim() !== "";
7467
9129
  /**
7468
9130
  * What an audio model makes, from its declaration only.
@@ -7492,7 +9154,7 @@ function promptFieldOf(model) {
7492
9154
  ].find((name) => fields.includes(name));
7493
9155
  }
7494
9156
  function refuse(message, field) {
7495
- throw new MediaError(message, "AUDIO_OPTION_INVALID", field === void 0 ? {} : { field });
9157
+ throw localInputError(message, "AUDIO_OPTION_INVALID", field === void 0 ? {} : { field });
7496
9158
  }
7497
9159
  /** Check one value against the model's declared choices for a field. */
7498
9160
  function checkChoice(audio, wire, value) {
@@ -7532,10 +9194,10 @@ function audioConfigOf(model, format, sampleRate) {
7532
9194
  */
7533
9195
  function audioRequestBody(model, request) {
7534
9196
  const kind = audioKindOf(model);
7535
- if (kind === void 0) throw new MediaError(`${model.id} does not declare what kind of audio it makes, so it cannot be used for generation.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
9197
+ if (kind === void 0) throw localInputError(`${model.id} does not declare what kind of audio it makes, so it cannot be used for generation.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
7536
9198
  const audio = model.audio;
7537
9199
  const fields = requestFieldsOf(model);
7538
- if (fields.length === 0) throw new MediaError(`${model.id} declares no request fields, so no request can be built for it.`, "AUDIO_FIELDS_UNDECLARED", { field: "model" });
9200
+ if (fields.length === 0) throw localInputError(`${model.id} declares no request fields, so no request can be built for it.`, "AUDIO_FIELDS_UNDECLARED", { field: "model" });
7539
9201
  if (kind !== "speech") for (const name of SPEECH_ONLY) {
7540
9202
  const value = request[name];
7541
9203
  if (value !== void 0 && !(Array.isArray(value) && value.length === 0)) refuse(`${name === "sampleRate" ? "sample_rate" : name} is for speech; ${kind === "music" ? "music" : "a podcast"} does not take it.`, name);
@@ -7580,9 +9242,9 @@ function audioRequestBody(model, request) {
7580
9242
  if (config !== void 0) body.audio_config = config;
7581
9243
  }
7582
9244
  if ((request.references?.length ?? 0) > 0 && !takes("references")) refuse(`${model.id} does not take reference audio.`, "references");
7583
- if (kind === "music" && !has(prompt)) throw new MediaError("Music needs a prompt describing the song.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
7584
- if (kind === "podcast" && !has(prompt) && body.source_url === void 0) throw new MediaError("A podcast needs a prompt (the topic), a source_url, or both.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
7585
- if (kind === "speech" && !has(prompt)) throw new MediaError("Speech needs the text to speak.", "AUDIO_PROMPT_REQUIRED", { field: promptField ?? "prompt" });
9245
+ if (kind === "music" && !has(prompt)) throw localInputError("Music needs a prompt describing the song.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
9246
+ if (kind === "podcast" && !has(prompt) && body.source_url === void 0) throw localInputError("A podcast needs a prompt (the topic), a source_url, or both.", "AUDIO_PROMPT_REQUIRED", { field: "prompt" });
9247
+ if (kind === "speech" && !has(prompt)) throw localInputError("Speech needs the text to speak.", "AUDIO_PROMPT_REQUIRED", { field: promptField ?? "prompt" });
7586
9248
  return body;
7587
9249
  }
7588
9250
  /** Load, check and upload the reference audio of a speech request; their measured lengths are checked too. */
@@ -7596,7 +9258,7 @@ async function uploadReferences(runtime, call, model, sources, body) {
7596
9258
  const loaded = [];
7597
9259
  for (const source of sources) {
7598
9260
  const media = await runtime.load(call, source, "audio", maxBytes);
7599
- if (limits.mimes !== void 0 && !limits.mimes.includes(media.mime)) throw new MediaError(`"${media.source}" is ${media.mime}; ${model.id} takes reference audio as ${limits.mimes.join(", ")}.`, "REFERENCE_MEDIA_TYPE_UNSUPPORTED", { field: "references" });
9261
+ if (limits.mimes !== void 0 && !limits.mimes.includes(media.mime)) throw localInputError(`"${media.source}" is ${media.mime}; ${model.id} takes reference audio as ${limits.mimes.join(", ")}.`, "REFERENCE_MEDIA_TYPE_UNSUPPORTED", { field: "references" });
7600
9262
  loaded.push(media);
7601
9263
  }
7602
9264
  const checked = [];
@@ -7604,10 +9266,10 @@ async function uploadReferences(runtime, call, model, sources, body) {
7604
9266
  for (const media of loaded) {
7605
9267
  const asset = await runtime.library.upload(media, limits.purpose ?? "audio_reference", call.signal);
7606
9268
  const seconds = asset.durationMs === void 0 ? void 0 : asset.durationMs / 1e3;
7607
- if (seconds === void 0 && (limits.minSeconds !== void 0 || limits.maxSeconds !== void 0 || limits.maxTotalSeconds !== void 0)) throw new MediaError(`The gateway could not measure the length of "${media.source}". Export it as a standard WAV or MP3 and try again.`, "REFERENCE_DURATION_UNKNOWN", { field: "references" });
9269
+ if (seconds === void 0 && (limits.minSeconds !== void 0 || limits.maxSeconds !== void 0 || limits.maxTotalSeconds !== void 0)) throw localInputError(`The gateway could not measure the length of "${media.source}". Export it as a standard WAV or MP3 and try again.`, "REFERENCE_DURATION_UNKNOWN", { field: "references" });
7608
9270
  if (seconds !== void 0) {
7609
- if (limits.minSeconds !== void 0 && seconds < limits.minSeconds) throw new MediaError(`"${media.source}" is ${seconds.toFixed(1)} s; ${model.id} needs reference audio of at least ${limits.minSeconds} s.`, "REFERENCE_AUDIO_TOO_SHORT", { field: "references" });
7610
- if (limits.maxSeconds !== void 0 && seconds > limits.maxSeconds) throw new MediaError(`"${media.source}" is ${seconds.toFixed(1)} s; ${model.id} takes reference audio of at most ${limits.maxSeconds} s.`, "REFERENCE_AUDIO_TOO_LONG", { field: "references" });
9271
+ if (limits.minSeconds !== void 0 && seconds < limits.minSeconds) throw localInputError(`"${media.source}" is ${seconds.toFixed(1)} s; ${model.id} needs reference audio of at least ${limits.minSeconds} s.`, "REFERENCE_AUDIO_TOO_SHORT", { field: "references" });
9272
+ if (limits.maxSeconds !== void 0 && seconds > limits.maxSeconds) throw localInputError(`"${media.source}" is ${seconds.toFixed(1)} s; ${model.id} takes reference audio of at most ${limits.maxSeconds} s.`, "REFERENCE_AUDIO_TOO_LONG", { field: "references" });
7611
9273
  totalSeconds += seconds;
7612
9274
  }
7613
9275
  checked.push({
@@ -7615,7 +9277,7 @@ async function uploadReferences(runtime, call, model, sources, body) {
7615
9277
  asset
7616
9278
  });
7617
9279
  }
7618
- if (limits.maxTotalSeconds !== void 0 && totalSeconds > limits.maxTotalSeconds) throw new MediaError(`The reference audio adds up to ${totalSeconds.toFixed(1)} s; ${model.id} takes at most ${limits.maxTotalSeconds} s in total.`, "REFERENCE_TOTAL_TOO_LONG", { field: "references" });
9280
+ if (limits.maxTotalSeconds !== void 0 && totalSeconds > limits.maxTotalSeconds) throw localInputError(`The reference audio adds up to ${totalSeconds.toFixed(1)} s; ${model.id} takes at most ${limits.maxTotalSeconds} s in total.`, "REFERENCE_TOTAL_TOO_LONG", { field: "references" });
7619
9281
  return checked;
7620
9282
  }
7621
9283
  /**
@@ -7623,11 +9285,11 @@ async function uploadReferences(runtime, call, model, sources, body) {
7623
9285
  * pinned or first model of the kind. A named model must make the kind asked for.
7624
9286
  */
7625
9287
  async function chooseAudioModel(runtime, request, signal) {
7626
- if (request.kind === void 0 && !has(request.model)) throw new MediaError("Say what to make (music, podcast or speech), or name a model.", "AUDIO_KIND_REQUIRED", { field: "type" });
9288
+ if (request.kind === void 0 && !has(request.model)) throw localInputError("Say what to make (music, podcast or speech), or name a model.", "AUDIO_KIND_REQUIRED", { field: "type" });
7627
9289
  if (request.kind !== void 0) return runtime.pickModel("audio", request.kind, request.model, void 0, signal);
7628
9290
  const model = await runtime.findModel(request.model, signal);
7629
- if (model.kind !== "audio") throw new MediaError(`${model.id} is not an audio generation model.`, "MODEL_KIND_MISMATCH", { field: "model" });
7630
- if (audioKindOf(model) === void 0) throw new MediaError(`${model.id} does not declare what kind of audio it makes, so it cannot be used for generation.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
9291
+ if (model.kind !== "audio") throw localInputError(`${model.id} is not an audio generation model.`, "MODEL_KIND_MISMATCH", { field: "model" });
9292
+ if (audioKindOf(model) === void 0) throw localInputError(`${model.id} does not declare what kind of audio it makes, so it cannot be used for generation.`, "AUDIO_KIND_UNDECLARED", { field: "model" });
7631
9293
  return model;
7632
9294
  }
7633
9295
  /**
@@ -7641,7 +9303,8 @@ async function chooseAudioModel(runtime, request, signal) {
7641
9303
  * @returns the prepared task.
7642
9304
  */
7643
9305
  async function prepareAudioTask(runtime, call, request, save) {
7644
- if (request.operationId !== void 0 && !OPERATION_ID.test(request.operationId)) throw new MediaError("operationId may hold only letters, digits, \"-\" and \"_\" (at most 80).", "AUDIO_OPTION_INVALID", { field: "operationId" });
9306
+ const accountScope = await runtime.store.currentScope();
9307
+ if (request.operationId !== void 0 && !OPERATION_ID.test(request.operationId)) throw localInputError("operationId may hold only letters, digits, \"-\" and \"_\" (8-80).", "AUDIO_OPTION_INVALID", { field: "operationId" });
7645
9308
  const model = await chooseAudioModel(runtime, request, call.signal);
7646
9309
  const kind = audioKindOf(model);
7647
9310
  const body = audioRequestBody(model, request);
@@ -7677,6 +9340,7 @@ async function prepareAudioTask(runtime, call, request, save) {
7677
9340
  id: request.operationId ?? randomUUID(),
7678
9341
  kind: "audio",
7679
9342
  model: model.id,
9343
+ ...accountScope === void 0 ? {} : { accountScope },
7680
9344
  label: excerptOf(prompt ?? request.sourceUrl ?? kind),
7681
9345
  createdAt: now,
7682
9346
  updatedAt: now,
@@ -7973,10 +9637,9 @@ function progressWords(task, now) {
7973
9637
  * The durable list of video and audio tasks, one file per task under
7974
9638
  * `<state dir>/tasks/`, so harness processes sharing a home never overwrite
7975
9639
  * each other's tasks. A task is recorded before it is submitted, under the id
7976
- * that doubles as its `Idempotency-Key`: a submission cut short is resent under
7977
- * the same key (the gateway returns the original task instead of creating a
7978
- * second one), and a task still running when the host restarts is followed to
7979
- * the end. A claim file names the process following a task, so two processes
9640
+ * that doubles as its `Idempotency-Key`. A submission cut short stays unknown
9641
+ * with bounded checks using only its original key and saved body. A known gateway task is queried after
9642
+ * restart to recover its result. A claim file names the process following a task, so two processes
7980
9643
  * never poll and download the same one.
7981
9644
  * @module dsh-vibedev/tasks/store
7982
9645
  */
@@ -8004,18 +9667,146 @@ function parse(text) {
8004
9667
  return;
8005
9668
  }
8006
9669
  }
9670
+ async function readRecord(path) {
9671
+ try {
9672
+ const record = parse(await readFile(path, "utf8"));
9673
+ if (record === void 0) throw new Error("invalid task record");
9674
+ return record;
9675
+ } catch (error) {
9676
+ if (error.code === "ENOENT") return void 0;
9677
+ throw new MediaError(hostMessage("lookupUnavailable"), "TASK_LOOKUP_UNAVAILABLE", { retryable: true }, { cause: error });
9678
+ }
9679
+ }
8007
9680
  /** Task records under `<state dir>/tasks/`. */
8008
- var TaskStore = class {
9681
+ var TaskStore = class TaskStore {
8009
9682
  directory;
8010
9683
  now;
9684
+ resolveScope;
8011
9685
  chains = /* @__PURE__ */ new Map();
9686
+ scopes = /* @__PURE__ */ new Map();
9687
+ legacyRecords = /* @__PURE__ */ new Map();
9688
+ migrations = /* @__PURE__ */ new Map();
9689
+ verifiedScope;
9690
+ scopeEpoch = 0;
9691
+ activeScope = new AsyncLocalStorage();
8012
9692
  /**
8013
9693
  * @param directory - the plugin state directory.
8014
9694
  * @param now - clock.
8015
9695
  */
8016
- constructor(directory, now = Date.now) {
9696
+ constructor(directory, now = Date.now, resolveScope) {
8017
9697
  this.directory = directory;
8018
9698
  this.now = now;
9699
+ this.resolveScope = resolveScope;
9700
+ }
9701
+ /** Resolve once per operation, so a switch while writing cannot move an old record into the new account. */
9702
+ async scoped() {
9703
+ const bound = this.activeScope.getStore();
9704
+ if (bound !== void 0) return bound;
9705
+ return this.resolveCurrentScope();
9706
+ }
9707
+ async resolveCurrentScope() {
9708
+ const epoch = this.scopeEpoch;
9709
+ this.verifiedScope = void 0;
9710
+ const scope = await this.resolveScope?.();
9711
+ if (scope === void 0) return void 0;
9712
+ const key = createHash("sha256").update(scope).digest("hex");
9713
+ let store = this.scopes.get(key);
9714
+ if (store === void 0) {
9715
+ store = new TaskStore(join(this.directory, "accounts", key), this.now);
9716
+ this.scopes.set(key, store);
9717
+ }
9718
+ const target = store;
9719
+ const migration = (this.migrations.get(key) ?? Promise.resolve()).then(() => this.prepareLegacy(target, key, scope));
9720
+ this.migrations.set(key, migration.catch(() => void 0));
9721
+ await migration;
9722
+ if (epoch === this.scopeEpoch) this.verifiedScope = key;
9723
+ return {
9724
+ store,
9725
+ key
9726
+ };
9727
+ }
9728
+ /** Synchronous capability, valid only after an awaited account-scoped lookup initialized this scope. */
9729
+ supportsDurableTaskLookup(kind) {
9730
+ return (kind === "video" || kind === "audio") && this.verifiedScope !== void 0;
9731
+ }
9732
+ invalidateScope() {
9733
+ this.scopeEpoch++;
9734
+ this.verifiedScope = void 0;
9735
+ }
9736
+ /** Bind legacy files once, without rewriting or removing the released plugin's records. */
9737
+ async prepareLegacy(store, key, identity) {
9738
+ const legacy = await new TaskStore(this.directory, this.now).list();
9739
+ if (legacy.length === 0) return;
9740
+ const markerDir = join(this.directory, "legacy-task-owners");
9741
+ await mkdir(markerDir, { recursive: true });
9742
+ const visible = [];
9743
+ for (const record of legacy) {
9744
+ if (!SAFE_ID.test(record.id)) continue;
9745
+ const metadata = record;
9746
+ const userId = metadata.userId ?? metadata.user_id ?? metadata.accountUserId;
9747
+ if (record.accountScope !== void 0 && record.accountScope !== key) continue;
9748
+ if (userId !== void 0 && identity.split("\nuser:")[1] !== String(userId)) continue;
9749
+ const marker = join(markerDir, `${record.id}.json`);
9750
+ try {
9751
+ const handle = await open(marker, "wx");
9752
+ try {
9753
+ await handle.writeFile(JSON.stringify({
9754
+ version: 1,
9755
+ accountScope: key,
9756
+ at: this.now()
9757
+ }));
9758
+ } finally {
9759
+ await handle.close();
9760
+ }
9761
+ } catch (error) {
9762
+ if (error.code !== "EEXIST") throw error;
9763
+ }
9764
+ if ((await readFile(marker, "utf8").then((text) => JSON.parse(text), () => void 0))?.accountScope !== key) continue;
9765
+ const scoped = {
9766
+ ...record,
9767
+ accountScope: key,
9768
+ migratedFrom: "gateway-tasks-v1"
9769
+ };
9770
+ if (isFinished(record)) visible.push(scoped);
9771
+ if (isFinished(record) || await store.get(record.id) !== void 0) continue;
9772
+ await mkdir(store.dir, { recursive: true });
9773
+ try {
9774
+ const handle = await open(store.file(record.id), "wx");
9775
+ try {
9776
+ await handle.writeFile(JSON.stringify(scoped, null, 2));
9777
+ } finally {
9778
+ await handle.close();
9779
+ }
9780
+ } catch (error) {
9781
+ if (error.code !== "EEXIST") throw error;
9782
+ }
9783
+ }
9784
+ this.legacyRecords.set(key, visible);
9785
+ }
9786
+ async currentScope() {
9787
+ return this.resolveScope === void 0 ? void 0 : (await this.resolveCurrentScope())?.key;
9788
+ }
9789
+ /** Bind a whole asynchronous operation to its initial account's files. */
9790
+ async withScope(run) {
9791
+ if (this.resolveScope === void 0 || this.activeScope.getStore() !== void 0) return run();
9792
+ const scope = await this.resolveCurrentScope();
9793
+ if (scope === void 0) throw new MediaError(hostMessage("accountUnavailable"), "ACCOUNT_UNAVAILABLE", {
9794
+ category: "service_unavailable",
9795
+ stage: "auth",
9796
+ retryable: true,
9797
+ submissionState: "not_submitted"
9798
+ });
9799
+ return this.activeScope.run(scope, run);
9800
+ }
9801
+ /** Namespaces in-memory polling/claim keys just like the durable records. */
9802
+ scopeKey(id) {
9803
+ return `${this.activeScope.getStore()?.key ?? ""}:${id}`;
9804
+ }
9805
+ boundStore() {
9806
+ return this.activeScope.getStore()?.store ?? this;
9807
+ }
9808
+ async isCurrent(record) {
9809
+ return this.resolveScope === void 0 || record.accountScope !== void 0 && record.accountScope === await this.currentScope();
8019
9810
  }
8020
9811
  get dir() {
8021
9812
  return join(this.directory, "tasks");
@@ -8036,8 +9827,18 @@ var TaskStore = class {
8036
9827
  }
8037
9828
  /** All tasks, newest first, as they are on disk now (other processes' tasks included). */
8038
9829
  async list() {
8039
- const names = await readdir(this.dir).catch(() => []);
8040
- return (await Promise.all(names.filter((name) => name.endsWith(".json")).map((name) => readFile(join(this.dir, name), "utf8").then(parse, () => void 0)))).filter((record) => record !== void 0).sort((a, b) => b.createdAt - a.createdAt);
9830
+ if (this.resolveScope !== void 0) {
9831
+ const scope = await this.scoped();
9832
+ if (scope === void 0) return [];
9833
+ const records = new Map((this.legacyRecords.get(scope.key) ?? []).map((record) => [record.id, record]));
9834
+ for (const record of await scope.store.list()) records.set(record.id, record);
9835
+ return [...records.values()].sort((a, b) => b.createdAt - a.createdAt);
9836
+ }
9837
+ const names = await readdir(this.dir).catch((error) => {
9838
+ if (error.code === "ENOENT") return [];
9839
+ throw error;
9840
+ });
9841
+ return (await Promise.all(names.filter((name) => name.endsWith(".json")).map((name) => readRecord(join(this.dir, name))))).filter((record) => record !== void 0).sort((a, b) => b.createdAt - a.createdAt);
8041
9842
  }
8042
9843
  /**
8043
9844
  * One task.
@@ -8045,14 +9846,31 @@ var TaskStore = class {
8045
9846
  * @returns the task, or undefined.
8046
9847
  */
8047
9848
  async get(id) {
8048
- return readFile(this.file(id), "utf8").then(parse, () => void 0);
9849
+ if (this.resolveScope !== void 0) {
9850
+ const scope = await this.scoped();
9851
+ try {
9852
+ return scope === void 0 ? void 0 : await scope.store.get(id) ?? this.legacyRecords.get(scope.key)?.find((record) => record.id === id);
9853
+ } catch (error) {
9854
+ this.invalidateScope();
9855
+ throw error;
9856
+ }
9857
+ }
9858
+ return await readRecord(this.file(id)) ?? readRecord(join(this.directory, "task-receipts", `${id}.json`));
8049
9859
  }
8050
9860
  /**
8051
9861
  * Record a new task.
8052
9862
  * @param record - the task.
8053
9863
  * @returns the stored task.
8054
9864
  */
8055
- add(record) {
9865
+ async add(record) {
9866
+ if (this.resolveScope !== void 0) {
9867
+ const scoped = await this.scoped();
9868
+ if (scoped === void 0 || record.accountScope !== void 0 && record.accountScope !== scoped.key) throw new Error("The task account changed; the original task was preserved.");
9869
+ return scoped.store.add({
9870
+ ...record,
9871
+ accountScope: scoped.key
9872
+ });
9873
+ }
8056
9874
  return this.serial(record.id, async () => {
8057
9875
  await writeFileAtomic(this.file(record.id), new TextEncoder().encode(JSON.stringify(record, null, 2)));
8058
9876
  await this.prune().catch(() => void 0);
@@ -8065,7 +9883,16 @@ var TaskStore = class {
8065
9883
  * @param patch - the fields to replace.
8066
9884
  * @returns the updated task, or undefined when it is unknown.
8067
9885
  */
8068
- update(id, patch) {
9886
+ async update(id, patch) {
9887
+ if (this.resolveScope !== void 0) {
9888
+ const scope = await this.scoped();
9889
+ if (scope === void 0) return void 0;
9890
+ if (await scope.store.get(id) === void 0) {
9891
+ const legacy = this.legacyRecords.get(scope.key)?.find((record) => record.id === id);
9892
+ if (legacy !== void 0) await scope.store.add(legacy);
9893
+ }
9894
+ return scope.store.update(id, patch);
9895
+ }
8069
9896
  return this.serial(id, async () => {
8070
9897
  const current = await this.get(id);
8071
9898
  if (current === void 0) return void 0;
@@ -8082,8 +9909,14 @@ var TaskStore = class {
8082
9909
  * Forget a task, such as a submission the gateway refused outright.
8083
9910
  * @param id - its local id.
8084
9911
  */
8085
- remove(id) {
9912
+ async remove(id) {
9913
+ if (this.resolveScope !== void 0) {
9914
+ await (await this.scoped())?.store.remove(id);
9915
+ return;
9916
+ }
8086
9917
  return this.serial(id, async () => {
9918
+ const record = await this.get(id);
9919
+ if (record !== void 0) await this.retainReceipt(record);
8087
9920
  await rm(this.file(id), { force: true });
8088
9921
  await rm(this.file(id, "claim"), { force: true });
8089
9922
  });
@@ -8097,6 +9930,8 @@ var TaskStore = class {
8097
9930
  * @returns whether this process now holds the claim.
8098
9931
  */
8099
9932
  async claim(id, holder, staleMs) {
9933
+ if (this.resolveScope !== void 0) return (await this.scoped())?.store.claim(id, holder, staleMs) ?? false;
9934
+ await mkdir(this.dir, { recursive: true });
8100
9935
  const path = this.file(id, "claim");
8101
9936
  for (let attempt = 0; attempt < 2; attempt++) {
8102
9937
  try {
@@ -8127,6 +9962,10 @@ var TaskStore = class {
8127
9962
  * @param holder - this process's claim id.
8128
9963
  */
8129
9964
  async renewClaim(id, holder) {
9965
+ if (this.resolveScope !== void 0) {
9966
+ await (await this.scoped())?.store.renewClaim(id, holder);
9967
+ return;
9968
+ }
8130
9969
  await writeFileAtomic(this.file(id, "claim"), new TextEncoder().encode(JSON.stringify({
8131
9970
  holder,
8132
9971
  at: this.now()
@@ -8138,16 +9977,24 @@ var TaskStore = class {
8138
9977
  * @param holder - this process's claim id.
8139
9978
  */
8140
9979
  async release(id, holder) {
9980
+ if (this.resolveScope !== void 0) {
9981
+ await (await this.scoped())?.store.release(id, holder);
9982
+ return;
9983
+ }
8141
9984
  const path = this.file(id, "claim");
8142
9985
  if ((await readFile(path, "utf8").then((text) => JSON.parse(text), () => void 0))?.holder === holder) await rm(path, { force: true });
8143
9986
  }
8144
9987
  async prune() {
8145
9988
  const finished = (await this.list()).filter(isFinished);
8146
9989
  for (const record of finished.slice(KEEP_FINISHED)) {
9990
+ await this.retainReceipt(record);
8147
9991
  await rm(this.file(record.id), { force: true });
8148
9992
  await rm(this.file(record.id, "claim"), { force: true });
8149
9993
  }
8150
9994
  }
9995
+ async retainReceipt(record) {
9996
+ await writeFileAtomic(join(this.directory, "task-receipts", `${record.id}.json`), new TextEncoder().encode(JSON.stringify(record, null, 2)));
9997
+ }
8151
9998
  };
8152
9999
  //#endregion
8153
10000
  //#region src/tools/common.ts
@@ -8403,6 +10250,11 @@ function form(fields, references) {
8403
10250
  * @returns the model, the saved images, the estimate and a revised prompt.
8404
10251
  */
8405
10252
  async function generateImages(runtime, call, request, save) {
10253
+ if (request.operationId !== void 0 && !/^[\w-]{8,80}$/.test(request.operationId)) throw new MediaError(hostMessage("operationIdentifier"), "IMAGE_OPTION_INVALID", {
10254
+ field: "operationId",
10255
+ submissionState: "not_submitted"
10256
+ });
10257
+ const accountScope = await runtime.store.currentScope();
8406
10258
  const count = Math.min(4, Math.max(1, Math.trunc(request.n ?? 1)));
8407
10259
  const size = request.size?.trim().toLowerCase();
8408
10260
  if (size !== void 0 && size !== "" && size !== "auto" && !SIZE.test(size)) throw new MediaError(`size "${request.size ?? ""}" is not WIDTHxHEIGHT (such as 1024x1024) or auto.`, "IMAGE_OPTION_INVALID", { field: "size" });
@@ -8430,6 +10282,9 @@ async function generateImages(runtime, call, request, save) {
8430
10282
  };
8431
10283
  const { images, revisedPrompt } = await decodeImages(runtime, await runtime.http.json(references.length === 0 ? "/v1/images/generations" : "/v1/images/edits", {
8432
10284
  method: "POST",
10285
+ idempotencyKey: request.operationId ?? randomUUID(),
10286
+ busyRetries: 0,
10287
+ isCurrentAccount: async () => accountScope === await runtime.store.currentScope(),
8433
10288
  ...references.length === 0 ? { json: Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0)) } : { body: form(fields, references) },
8434
10289
  timeoutMs: 12e4 + count * 9e4,
8435
10290
  signal: call.signal
@@ -8758,7 +10613,7 @@ function pick(allowed, value, label, model, normalize = (v) => v.trim()) {
8758
10613
  const wanted = normalize(value);
8759
10614
  if (allowed === void 0) return wanted;
8760
10615
  const match = allowed.find((item) => item.toLowerCase() === wanted.toLowerCase());
8761
- if (match === void 0) throw new MediaError(`${model.id} does not support ${label} "${value}"; choose one of ${allowed.join(", ")}.`, "VIDEO_OPTION_UNSUPPORTED", { field: label });
10616
+ if (match === void 0) throw localInputError(`${model.id} does not support ${label} "${value}"; choose one of ${allowed.join(", ")}.`, "VIDEO_OPTION_UNSUPPORTED", { field: label });
8762
10617
  return match;
8763
10618
  }
8764
10619
  /**
@@ -8770,7 +10625,7 @@ function pick(allowed, value, label, model, normalize = (v) => v.trim()) {
8770
10625
  */
8771
10626
  function planVideo(model, options) {
8772
10627
  const fail = (message, code = "VIDEO_REQUEST_UNSUPPORTED", fieldName) => {
8773
- throw new MediaError([message, describeVideoModel(model)].filter((part) => part !== "").join(" "), code, fieldName === void 0 ? {} : { field: fieldName });
10628
+ throw localInputError([message, describeVideoModel(model)].filter((part) => part !== "").join(" "), code, fieldName === void 0 ? {} : { field: fieldName });
8774
10629
  };
8775
10630
  if (model.kind !== "video" || model.video === void 0) fail(`${model.id} is not a video model.`, "NOT_A_VIDEO_MODEL");
8776
10631
  const video = model.video;
@@ -8841,9 +10696,9 @@ function checkReferenceFile(model, input, media) {
8841
10696
  const kind = INPUT_KIND[input];
8842
10697
  const param = INPUT_PARAM[input];
8843
10698
  const allowed = (kind === "image" ? video.allowedImageMimes : kind === "video" ? video.allowedVideoMimes : video.allowedAudioMimes) ?? DEFAULT_REFERENCE_MIMES[kind];
8844
- if (!allowed.includes(media.mime)) throw new MediaError(`${param} "${media.source}" is ${media.mime}; ${model.id} accepts ${allowed.join(", ")} for ${kind} references. Convert the file first (for example with ffmpeg) and try again.`, "REFERENCE_MEDIA_TYPE_UNSUPPORTED", { field: param });
10699
+ if (!allowed.includes(media.mime)) throw localInputError(`${param} "${media.source}" is ${media.mime}; ${model.id} accepts ${allowed.join(", ")} for ${kind} references. Convert the file first (for example with ffmpeg) and try again.`, "REFERENCE_MEDIA_TYPE_UNSUPPORTED", { field: param });
8845
10700
  const limit = referenceByteLimit(model, input);
8846
- if (media.bytes > limit) throw new MediaError(`${param} "${media.source}" is ${(media.bytes / 1048576).toFixed(1)} MiB; the limit is ${(limit / 1048576).toFixed(1)} MiB.`, "REFERENCE_TOO_LARGE", { field: param });
10701
+ if (media.bytes > limit) throw localInputError(`${param} "${media.source}" is ${(media.bytes / 1048576).toFixed(1)} MiB; the limit is ${(limit / 1048576).toFixed(1)} MiB.`, "REFERENCE_TOO_LARGE", { field: param });
8847
10702
  }
8848
10703
  /**
8849
10704
  * The largest file one input may be: the model's per-kind limit, its asset
@@ -8901,27 +10756,27 @@ function checkReferenceDurations(model, videos, audios = [], plan) {
8901
10756
  let totalMs = 0;
8902
10757
  for (const [index, clip] of videos.entries()) {
8903
10758
  if (clip.durationMs === void 0) {
8904
- if (video.minReferenceVideoSeconds !== void 0 || video.maxReferenceVideoSeconds !== void 0 || video.maxTotalReferenceVideoSeconds !== void 0) throw new MediaError(`The gateway could not measure the length of reference video ${index + 1} ("${clip.source}"), so ${model.id}'s length limits cannot be checked. Re-encode it as a standard MP4 and try again.`, "REFERENCE_DURATION_UNKNOWN", { field: "reference_videos" });
10759
+ if (video.minReferenceVideoSeconds !== void 0 || video.maxReferenceVideoSeconds !== void 0 || video.maxTotalReferenceVideoSeconds !== void 0) throw localInputError(`The gateway could not measure the length of reference video ${index + 1} ("${clip.source}"), so ${model.id}'s length limits cannot be checked. Re-encode it as a standard MP4 and try again.`, "REFERENCE_DURATION_UNKNOWN", { field: "reference_videos" });
8905
10760
  continue;
8906
10761
  }
8907
10762
  const seconds = clip.durationMs / 1e3;
8908
- 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" });
10763
+ if (video.minReferenceVideoSeconds !== void 0 && seconds < video.minReferenceVideoSeconds) throw localInputError(`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" });
8909
10764
  if (limit !== void 0 && seconds > limit.seconds) {
8910
10765
  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)`;
8911
- 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" });
10766
+ throw localInputError(`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" });
8912
10767
  }
8913
10768
  totalMs += clip.durationMs;
8914
10769
  }
8915
- 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" });
10770
+ if (video.maxTotalReferenceVideoSeconds !== void 0 && totalMs / 1e3 > video.maxTotalReferenceVideoSeconds) throw localInputError(`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" });
8916
10771
  const audioLimits = video.minReferenceAudioSeconds !== void 0 || video.maxReferenceAudioSeconds !== void 0;
8917
10772
  for (const [index, clip] of audios.entries()) {
8918
10773
  if (clip.durationMs === void 0) {
8919
- if (audioLimits) throw new MediaError(`The gateway could not measure the length of reference audio ${index + 1} ("${clip.source}"), so ${model.id}'s length limits cannot be checked. Export it as a standard MP3 or WAV and try again.`, "REFERENCE_DURATION_UNKNOWN", { field: "reference_audios" });
10774
+ if (audioLimits) throw localInputError(`The gateway could not measure the length of reference audio ${index + 1} ("${clip.source}"), so ${model.id}'s length limits cannot be checked. Export it as a standard MP3 or WAV and try again.`, "REFERENCE_DURATION_UNKNOWN", { field: "reference_audios" });
8920
10775
  continue;
8921
10776
  }
8922
10777
  const seconds = clip.durationMs / 1e3;
8923
- if (video.minReferenceAudioSeconds !== void 0 && seconds < video.minReferenceAudioSeconds) throw new MediaError(`Reference audio ${index + 1} ("${clip.source}") is ${seconds.toFixed(2)} s; ${model.id} needs at least ${video.minReferenceAudioSeconds} s of reference audio.`, "REFERENCE_AUDIO_TOO_SHORT", { field: "reference_audios" });
8924
- if (video.maxReferenceAudioSeconds !== void 0 && seconds > video.maxReferenceAudioSeconds) throw new MediaError(`Reference audio ${index + 1} ("${clip.source}") is ${seconds.toFixed(2)} s; ${model.id} takes at most ${video.maxReferenceAudioSeconds} s of reference audio per clip. Trim it first, or use a shorter excerpt.`, "REFERENCE_AUDIO_TOO_LONG", { field: "reference_audios" });
10778
+ if (video.minReferenceAudioSeconds !== void 0 && seconds < video.minReferenceAudioSeconds) throw localInputError(`Reference audio ${index + 1} ("${clip.source}") is ${seconds.toFixed(2)} s; ${model.id} needs at least ${video.minReferenceAudioSeconds} s of reference audio.`, "REFERENCE_AUDIO_TOO_SHORT", { field: "reference_audios" });
10779
+ if (video.maxReferenceAudioSeconds !== void 0 && seconds > video.maxReferenceAudioSeconds) throw localInputError(`Reference audio ${index + 1} ("${clip.source}") is ${seconds.toFixed(2)} s; ${model.id} takes at most ${video.maxReferenceAudioSeconds} s of reference audio per clip. Trim it first, or use a shorter excerpt.`, "REFERENCE_AUDIO_TOO_LONG", { field: "reference_audios" });
8925
10780
  }
8926
10781
  }
8927
10782
  /**
@@ -8996,7 +10851,7 @@ async function chooseModel(runtime, requested, options, signal) {
8996
10851
  if (ordered.length === 1) throw error;
8997
10852
  refusals.push(`${model.id}: ${firstSentence(error.message)}`);
8998
10853
  }
8999
- throw new MediaError(`No video model on this VibeDev account can serve this request. ${refusals.join(" ")} Use media_models to see what each model accepts, then adjust the inputs or options.`, "VIDEO_REQUEST_UNSUPPORTED");
10854
+ throw localInputError(`No video model on this VibeDev account can serve this request. ${refusals.join(" ")} Use media_models to see what each model accepts, then adjust the inputs or options.`, "VIDEO_REQUEST_UNSUPPORTED");
9000
10855
  }
9001
10856
  /** Run `run` over `items`, `limit` at a time; after the first failure no new item starts. */
9002
10857
  async function mapLimited(items, limit, run) {
@@ -9029,7 +10884,9 @@ async function mapLimited(items, limit, run) {
9029
10884
  * @returns the prepared task.
9030
10885
  */
9031
10886
  async function prepareVideoTask(runtime, call, request, save) {
9032
- const { model: requested, ...options } = request;
10887
+ const accountScope = await runtime.store.currentScope();
10888
+ const { model: requested, operationId, quoteId, ...options } = request;
10889
+ if (operationId !== void 0 && !/^[\w-]{8,80}$/.test(operationId)) throw localInputError("operationId must contain 8-80 letters, numbers, underscores or hyphens.", "VIDEO_OPTION_INVALID", { field: "operationId" });
9033
10890
  const { model, plan } = await chooseModel(runtime, requested, options, call.signal);
9034
10891
  const sources = [];
9035
10892
  for (const input of VIDEO_INPUTS) for (const source of plan.inputs[input] ?? []) sources.push({
@@ -9109,25 +10966,29 @@ async function prepareVideoTask(runtime, call, request, save) {
9109
10966
  zh: `,${quote.label.zh}(${quote.basis.zh})`
9110
10967
  };
9111
10968
  await runtime.confirmSpending(call, "video_generate", {
9112
- en: `Generate a video with ${model.id} (${plan.mode}${shape === "" ? "" : `, ${shape}`})${price.en}. Charged only if it succeeds.`,
9113
- zh: `用 ${model.id} 生成视频(${plan.mode}${shape === "" ? "" : `,${shape}`})${price.zh},成功才扣费。`
10969
+ en: `Generate a video with ${model.id} (${plan.mode}${shape === "" ? "" : `, ${shape}`})${price.en}. Final billing follows the gateway receipt.`,
10970
+ zh: `用 ${model.id} 生成视频(${plan.mode}${shape === "" ? "" : `,${shape}`})${price.zh},实际计费以网关回执为准。`
9114
10971
  });
9115
10972
  const now = runtime.now();
9116
10973
  return {
9117
10974
  model,
9118
10975
  plan,
9119
10976
  draft: {
9120
- id: randomUUID(),
10977
+ id: operationId ?? randomUUID(),
9121
10978
  kind: "video",
9122
10979
  model: model.id,
9123
10980
  label: excerpt(request.prompt),
9124
10981
  createdAt: now,
9125
10982
  updatedAt: now,
10983
+ ...accountScope === void 0 ? {} : { accountScope },
9126
10984
  ...call.agent === void 0 ? {} : { owner: call.agent.id },
9127
10985
  outputDir: save.folder,
9128
10986
  stem: save.stem,
9129
10987
  endpoint: "/v1/videos",
9130
- body: videoRequestBody(model.id, request.prompt, plan, urls),
10988
+ body: {
10989
+ ...videoRequestBody(model.id, request.prompt, plan, urls),
10990
+ ...quoteId === void 0 ? {} : { quote_id: quoteId }
10991
+ },
9131
10992
  status: "submitting",
9132
10993
  ...estimatedCny === void 0 ? {} : { estimatedCny }
9133
10994
  },
@@ -9334,6 +11195,20 @@ function progressView(record) {
9334
11195
  }
9335
11196
  const view = (record) => ({
9336
11197
  id: record.id,
11198
+ operationId: record.id,
11199
+ ...Object.fromEntries(Object.entries({
11200
+ taskId: record.gatewayId,
11201
+ submissionState: record.submissionState,
11202
+ billingState: record.billingState,
11203
+ billingSource: record.billingSource,
11204
+ subscriptionId: record.subscriptionId,
11205
+ nextPollAfterSeconds: record.nextPollAfterSeconds,
11206
+ quoteId: record.quoteId,
11207
+ pricingVersion: record.pricingVersion,
11208
+ reservedAmount: record.reservedAmount,
11209
+ settledAmount: record.settledAmount,
11210
+ releasedAmount: record.releasedAmount
11211
+ }).filter(([, value]) => value !== void 0)),
9337
11212
  kind: record.kind,
9338
11213
  ...record.audioKind === void 0 ? {} : { audioKind: record.audioKind },
9339
11214
  model: record.model,
@@ -9356,12 +11231,134 @@ function sameRequest(record, draft) {
9356
11231
  const { references: _b, ...right } = draft.body;
9357
11232
  return record.kind === draft.kind && record.model === draft.model && JSON.stringify(left) === JSON.stringify(right);
9358
11233
  }
11234
+ const object = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
11235
+ function canonical(value) {
11236
+ if (Array.isArray(value)) return value.map(canonical);
11237
+ const record = object(value);
11238
+ return record === void 0 ? value : Object.fromEntries(Object.keys(record).sort().filter((key) => record[key] !== void 0).map((key) => [key, canonical(record[key])]));
11239
+ }
11240
+ function validateOperation(id) {
11241
+ if (id !== void 0 && !/^[\w-]{8,80}$/.test(id)) throw localInputError(hostMessage("operationIdentifier"), "INVALID_INPUT", { field: "operationId" });
11242
+ }
9359
11243
  var MediaHostService = class {
9360
11244
  runtime;
9361
11245
  version;
9362
- constructor(runtime, version) {
11246
+ accountHooks;
11247
+ boundQuotes = /* @__PURE__ */ new Map();
11248
+ /** Current initialized account only; images have no durable local lookup contract. */
11249
+ supportsDurableTaskLookup(kind) {
11250
+ return this.runtime.store.supportsDurableTaskLookup(kind);
11251
+ }
11252
+ capabilities = CLIENT_CAPABILITIES;
11253
+ constructor(runtime, version, accountHooks) {
9363
11254
  this.runtime = runtime;
9364
11255
  this.version = version;
11256
+ this.accountHooks = accountHooks;
11257
+ }
11258
+ async account() {
11259
+ const account = await (this.accountHooks?.account() ?? Promise.resolve({
11260
+ gatewayOrigin: this.runtime.http.origin,
11261
+ signedIn: false
11262
+ }));
11263
+ await this.runtime.store.currentScope().catch(() => void 0);
11264
+ return account;
11265
+ }
11266
+ openAccountCenter(options = {}) {
11267
+ const page = options.page ?? "dashboard";
11268
+ if (!ACCOUNT_PAGES.includes(page)) throw new MediaError("Unknown account page.", "INVALID_INPUT", { field: "page" });
11269
+ this.accountHooks?.open(page);
11270
+ }
11271
+ refreshAccount() {
11272
+ this.runtime.http.invalidateAccountSnapshots();
11273
+ this.accountHooks?.refresh();
11274
+ }
11275
+ async quoteVideo(request, signal) {
11276
+ const local = await this.videoQuote(request, signal);
11277
+ if (request.operationId === void 0) return local;
11278
+ validateOperation(request.operationId);
11279
+ const context = await this.account();
11280
+ if (!context.signedIn || context.userId === void 0) return local;
11281
+ const scope = `${this.runtime.http.origin}\nuser:${context.userId}`;
11282
+ const entitlements = await this.runtime.http.entitlements(scope, {
11283
+ signal,
11284
+ timeoutMs: 3e4
11285
+ }).catch((error) => {
11286
+ if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405)) return void 0;
11287
+ throw error;
11288
+ });
11289
+ const envelope = object(entitlements);
11290
+ const data = object(envelope?.data) ?? envelope;
11291
+ if (!Array.isArray(data?.capabilities) || !data.capabilities.includes("media-quotes-v1")) return local;
11292
+ const videos = request.references?.videos ?? [];
11293
+ if (videos.some((video) => video.durationSeconds === void 0) || (request.references?.audios ?? 0) > 0) return local;
11294
+ const response = await this.runtime.http.json("/v1/media/quotes", {
11295
+ method: "POST",
11296
+ signal,
11297
+ timeoutMs: 3e4,
11298
+ busyRetries: 0,
11299
+ json: {
11300
+ kind: "video",
11301
+ model: local.model,
11302
+ operation_id: request.operationId,
11303
+ parameters: {
11304
+ ...request.mode === void 0 ? {} : { mode: request.mode },
11305
+ ...request.durationSeconds === void 0 ? {} : { duration_seconds: request.durationSeconds },
11306
+ ...request.resolution === void 0 ? {} : { resolution: request.resolution },
11307
+ ...request.aspectRatio === void 0 ? {} : { ratio: request.aspectRatio },
11308
+ ...request.generateAudio === void 0 ? {} : { generate_audio: request.generateAudio },
11309
+ reference_image_count: request.references?.images ?? 0,
11310
+ ...videos.length === 0 ? {} : { reference_video_seconds: videos.reduce((sum, video) => sum + (video.durationSeconds ?? 0), 0) }
11311
+ },
11312
+ preferred_billing_source: null
11313
+ }
11314
+ }).catch((error) => {
11315
+ if (error instanceof MediaError && (error.details.status === 404 || error.details.status === 405)) return void 0;
11316
+ throw error;
11317
+ });
11318
+ if (response === void 0) return local;
11319
+ const root = object(response);
11320
+ const quote = object(root?.data) ?? root;
11321
+ if (quote?.object !== "media.quote" || quote.operation_id !== request.operationId || quote.model !== local.model || quote.currency !== "CNY" || typeof quote.quote_id !== "string" || !/^\d+(?:\.\d+)?$/.test(quote.estimated_amount) || !["balance", "subscription"].includes(quote.billing_source?.kind) || typeof quote.pricing_version !== "string" || quote.pricing_version === "" || !Number.isFinite(Date.parse(quote.expires_at)) || ![
11322
+ "token_million",
11323
+ "video_token_million",
11324
+ "output_second",
11325
+ "original_audio_second",
11326
+ "image",
11327
+ "request"
11328
+ ].includes(quote.unit) || typeof quote.unit_price !== "string" || !/^\d+(?:\.\d+)?$/.test(quote.unit_price) || typeof quote.is_estimate !== "boolean") throw new MediaError(hostMessage("quoteUnavailable"), "GATEWAY_BAD_RESPONSE", { stage: "quote" });
11329
+ this.boundQuotes.set(quote.quote_id, {
11330
+ operationId: quote.operation_id,
11331
+ scope,
11332
+ expiresAt: Date.parse(quote.expires_at)
11333
+ });
11334
+ for (const [id, binding] of this.boundQuotes) if (binding.expiresAt <= Date.now() || this.boundQuotes.size > 256) this.boundQuotes.delete(id);
11335
+ return {
11336
+ status: "estimate",
11337
+ mode: quote.unit === "token_million" || quote.unit === "video_token_million" ? "video_token" : "legacy",
11338
+ model: quote.model,
11339
+ currency: quote.currency,
11340
+ amountCny: quote.estimated_amount,
11341
+ label: {
11342
+ zh: `预估 ${yuan(Number(quote.estimated_amount))}`,
11343
+ en: `Estimated ${yuan(Number(quote.estimated_amount))}`
11344
+ },
11345
+ basis: {
11346
+ zh: "最终费用以网关账务回执为准",
11347
+ en: "Final billing follows the gateway receipt"
11348
+ },
11349
+ operationId: quote.operation_id,
11350
+ quoteId: quote.quote_id,
11351
+ pricingVersion: quote.pricing_version,
11352
+ expiresAt: quote.expires_at,
11353
+ unit: quote.unit,
11354
+ unitPrice: quote.unit_price,
11355
+ isEstimate: quote.is_estimate,
11356
+ reservationAmount: quote.reservation_amount,
11357
+ billingSource: {
11358
+ kind: quote.billing_source.kind,
11359
+ subscriptionId: quote.billing_source.subscription_id
11360
+ }
11361
+ };
9365
11362
  }
9366
11363
  call(target, signal) {
9367
11364
  return {
@@ -9457,20 +11454,52 @@ var MediaHostService = class {
9457
11454
  /**
9458
11455
  * Submit a video. The plugin follows the task in the background and saves
9459
11456
  * the video when it finishes; watch it with {@link task} and {@link onTask}.
9460
- * A submission the gateway did not confirm is resent in the background
9461
- * under the same key, so it is reported as a task still being submitted
9462
- * rather than as a failure.
11457
+ * An unconfirmed submission is preserved under its original operation key.
11458
+ * Recovery may check only the original key and persisted body within its budget.
9463
11459
  * @param request - what to generate.
9464
11460
  * @param target - the workspace and where the video goes.
9465
11461
  * @param signal - cancels the preparation and the submission.
9466
11462
  * @returns the task.
9467
11463
  */
9468
11464
  async startVideo(request, target, signal) {
11465
+ validateOperation(request.operationId);
11466
+ return this.runtime.store.withScope(() => this.startVideoScoped(request, target, signal));
11467
+ }
11468
+ async startVideoScoped(request, target, signal) {
11469
+ const { operationId: _operationId, quoteId: _quoteId, ...semantic } = request;
11470
+ const fingerprint = createHash("sha256").update(JSON.stringify(canonical(semantic))).digest("hex");
11471
+ if (request.operationId !== void 0) {
11472
+ const earlier = await this.runtime.store.get(request.operationId);
11473
+ if (earlier !== void 0) {
11474
+ if (earlier.kind !== "video" || earlier.requestFingerprint !== void 0 && earlier.requestFingerprint !== fingerprint) throw new MediaError("This operation already belongs to another request.", "IDEMPOTENCY_CONFLICT", { field: "operationId" });
11475
+ return view(earlier.gatewayId === void 0 && earlier.status === "submitting" ? await this.runtime.tracker.refresh(earlier.id, signal) : earlier);
11476
+ }
11477
+ }
11478
+ if (request.quoteId !== void 0) {
11479
+ const context = await this.account();
11480
+ const binding = this.boundQuotes.get(request.quoteId);
11481
+ if (binding === void 0 || binding.operationId !== request.operationId || binding.scope !== `${this.runtime.http.origin}\nuser:${context.userId ?? ""}` || binding.expiresAt <= Date.now()) throw new MediaError(hostMessage("quoteMismatch"), "QUOTE_MISMATCH", {
11482
+ category: "invalid_input",
11483
+ stage: "quote",
11484
+ submissionState: "not_submitted",
11485
+ retryAction: "modify_input",
11486
+ field: "quoteId",
11487
+ retryable: false
11488
+ });
11489
+ }
9469
11490
  const prepared = await prepareVideoTask(this.runtime, this.call(target, signal), request, {
9470
11491
  folder: target.folder,
9471
11492
  stem: target.stem
9472
11493
  });
9473
- return this.submit(prepared.draft, signal);
11494
+ const raced = await this.runtime.store.get(prepared.draft.id);
11495
+ if (raced !== void 0) {
11496
+ if (!sameRequest(raced, prepared.draft)) throw new MediaError("This operation already belongs to another request.", "OPERATION_CONFLICT", { field: "operationId" });
11497
+ return view(raced);
11498
+ }
11499
+ return this.submit({
11500
+ ...prepared.draft,
11501
+ requestFingerprint: fingerprint
11502
+ }, signal, request.operationId === void 0);
9474
11503
  }
9475
11504
  /**
9476
11505
  * Submit music, a podcast episode or speech. Fields are checked against
@@ -9486,29 +11515,35 @@ var MediaHostService = class {
9486
11515
  * @returns the task.
9487
11516
  */
9488
11517
  async startAudio(request, target, signal) {
11518
+ validateOperation(request.operationId);
11519
+ return this.runtime.store.withScope(() => this.startAudioScoped(request, target, signal));
11520
+ }
11521
+ async startAudioScoped(request, target, signal) {
9489
11522
  if (request.operationId !== void 0) {
9490
- const earlier = await this.runtime.store.get(request.operationId).catch(() => void 0);
11523
+ const earlier = await this.runtime.store.get(request.operationId);
9491
11524
  if (earlier !== void 0) {
9492
11525
  if (earlier.kind !== "audio") throw new MediaError(`Operation ${request.operationId} already belongs to a ${earlier.kind} task.`, "OPERATION_CONFLICT", { field: "operationId" });
9493
- return view(earlier);
11526
+ return view(earlier.gatewayId === void 0 && earlier.status === "submitting" ? await this.runtime.tracker.refresh(earlier.id, signal) : earlier);
9494
11527
  }
9495
11528
  }
9496
11529
  const prepared = await prepareAudioTask(this.runtime, this.call(target, signal), request, {
9497
11530
  folder: target.folder,
9498
11531
  stem: target.stem
9499
11532
  });
9500
- const raced = await this.runtime.store.get(prepared.draft.id).catch(() => void 0);
11533
+ const raced = await this.runtime.store.get(prepared.draft.id);
9501
11534
  if (raced !== void 0) {
9502
11535
  if (!sameRequest(raced, prepared.draft)) throw new MediaError(`Operation ${prepared.draft.id} already belongs to a different request.`, "OPERATION_CONFLICT", { field: "operationId" });
9503
11536
  return view(raced);
9504
11537
  }
9505
- return this.submit(prepared.draft, signal);
11538
+ return this.submit(prepared.draft, signal, request.operationId === void 0);
9506
11539
  }
9507
- async submit(draft, signal) {
11540
+ async submit(draft, signal, legacyCaller = false) {
9508
11541
  try {
9509
- return view(await this.runtime.tracker.submit(draft, signal));
11542
+ const record = await this.runtime.tracker.submit(draft, signal);
11543
+ if (!await this.runtime.store.isCurrent(record)) throw new MediaError(hostMessage("accountChanged"), "ACCOUNT_CHANGED");
11544
+ return view(record);
9510
11545
  } catch (error) {
9511
- if (error instanceof MediaError && error.code === "SUBMISSION_UNCONFIRMED") {
11546
+ if (error instanceof MediaError && (error.code === "SUBMISSION_UNCONFIRMED" || legacyCaller && error.details.category === "submission_uncertain")) {
9512
11547
  const recorded = await this.runtime.store.get(draft.id);
9513
11548
  if (recorded !== void 0) return view(recorded);
9514
11549
  }
@@ -9525,7 +11560,8 @@ var MediaHostService = class {
9525
11560
  return record === void 0 ? void 0 : view(record);
9526
11561
  }
9527
11562
  /**
9528
- * Ask the gateway about a task again — a query, never a submission: a
11563
+ * Ask the gateway about the same task again: a budgeted original-key check
11564
+ * while unconfirmed, and only a query once a task ID is known. A
9529
11565
  * finished task gets fresh links and its missing files are downloaded
9530
11566
  * again, and a pending settlement is read again. A running task is followed.
9531
11567
  * @param id - the task id.
@@ -9534,7 +11570,9 @@ var MediaHostService = class {
9534
11570
  */
9535
11571
  async refreshTask(id, signal) {
9536
11572
  if (await this.runtime.store.get(id) === void 0) return void 0;
9537
- return view(await this.runtime.tracker.refresh(id, signal));
11573
+ const record = await this.runtime.tracker.refresh(id, signal);
11574
+ if (!await this.runtime.store.isCurrent(record)) throw new MediaError(hostMessage("accountChanged"), "ACCOUNT_CHANGED");
11575
+ return view(record);
9538
11576
  }
9539
11577
  /**
9540
11578
  * The files of a finished task, ready to play or download: saved files by
@@ -9547,7 +11585,9 @@ var MediaHostService = class {
9547
11585
  async result(id, signal) {
9548
11586
  const record = await this.runtime.store.get(id);
9549
11587
  if (record === void 0 || record.status !== "completed") return void 0;
9550
- return (((record.outputs ?? []).length > 0 && (record.outputs ?? []).every((output) => output.path !== void 0) ? record : await this.runtime.tracker.refresh(id, signal).catch(() => record)).outputs ?? []).map(({ index: _index, bytes: _bytes, ...output }) => ({ ...output }));
11588
+ const current = (record.outputs ?? []).length > 0 && (await Promise.all((record.outputs ?? []).map((output) => savedFileExists(output.path)))).every(Boolean) ? record : await this.runtime.tracker.refresh(id, signal).catch(() => record);
11589
+ if (!await this.runtime.store.isCurrent(current)) throw new MediaError(hostMessage("accountChanged"), "ACCOUNT_CHANGED");
11590
+ return (current.outputs ?? []).map(({ index: _index, bytes: _bytes, ...output }) => ({ ...output }));
9551
11591
  }
9552
11592
  /**
9553
11593
  * Hear about every change to one task.
@@ -9683,9 +11723,35 @@ function errorOf(raw) {
9683
11723
  const message = text$1(nested?.message) ?? text$1(raw.error) ?? text$1(raw.failure_reason) ?? text$1(raw.error_message) ?? text$1(raw.fail_reason);
9684
11724
  const code = text$1(nested?.code) ?? text$1(nested?.type) ?? text$1(raw.error_code);
9685
11725
  if (message === void 0 && code === void 0) return void 0;
11726
+ const failure = parseGatewayFailure({
11727
+ ...raw,
11728
+ error: {
11729
+ ...nested,
11730
+ code: code ?? "GENERATION_FAILED",
11731
+ message
11732
+ }
11733
+ });
11734
+ return {
11735
+ ...failure,
11736
+ code: failure.code ?? "GENERATION_FAILED",
11737
+ message: safeGatewayMessage(failure)
11738
+ };
11739
+ }
11740
+ function receiptFacts(raw) {
11741
+ const effective = record$1(raw.effective) ?? {};
11742
+ const source = effective.billing_source;
9686
11743
  return {
9687
- code: code ?? "GENERATION_FAILED",
9688
- message: message ?? code ?? "generation failed"
11744
+ ...Object.fromEntries(Object.entries({
11745
+ submissionState: text$1(raw.submission_state),
11746
+ billingState: text$1(effective.billing_state) ?? text$1(raw.billing_state),
11747
+ subscriptionId: text$1(effective.subscription_id),
11748
+ quoteId: text$1(effective.quote_id),
11749
+ pricingVersion: text$1(effective.pricing_version),
11750
+ reservedAmount: amount(effective.reserved_amount),
11751
+ settledAmount: amount(effective.settled_amount),
11752
+ releasedAmount: amount(effective.released_amount)
11753
+ }).filter(([, value]) => value !== void 0)),
11754
+ ...source === "balance" || source === "subscription" ? { billingSource: source } : {}
9689
11755
  };
9690
11756
  }
9691
11757
  function progressOf(value) {
@@ -9697,6 +11763,7 @@ function receipt(raw) {
9697
11763
  const estimatedCny = amount(effective.estimated_cny);
9698
11764
  const chargedCny = amount(effective.charged_cny) ?? amount(raw.charged_cny);
9699
11765
  return {
11766
+ receipt: receiptFacts(raw),
9700
11767
  ...estimatedCny === void 0 ? {} : { estimatedCny },
9701
11768
  ...chargedCny === void 0 ? {} : { chargedCny }
9702
11769
  };
@@ -9803,21 +11870,13 @@ function parseAudioTask(body, receivedAt = Date.now()) {
9803
11870
  * background job, so a task keeps being followed after its job is stopped and
9804
11871
  * after the host restarts.
9805
11872
  *
9806
- * Money rules, and the rule that one operation creates at most one task:
9807
- *
9808
- * - A submission is settled by the gateway's structured verdict
9809
- * (`submission_state` and `retry_action`) first, and only by the HTTP status
9810
- * when it sends none. `rejected`/`retry_action: none` is final: the reason is
9811
- * saved and nothing is sent again — not by the tool, not by the background
9812
- * loop, not after a restart. `retryable` on its own never authorizes creating
9813
- * another task.
9814
- * - An unknown outcome keeps the record and settles it under the SAME key and
9815
- * the SAME body, which the gateway answers with the original task when there
9816
- * is one. A new key is minted only for a new request the user asks for.
9817
- * - Once a gateway task id is known the task is only polled; a failed poll
9818
- * never submits anything.
9819
- * - A refusal that left nothing under the key ends the record as failed with
9820
- * the gateway's own reason, so the person sees why.
11873
+ * Submission and billing facts are separate. Unknown/submitting states,
11874
+ * uncertainty categories and known unknown codes take precedence over weaker
11875
+ * refusal hints. Neither retryable nor retry_action authorizes a creation POST.
11876
+ * An unconfirmed operation remains recorded and is checked only under its
11877
+ * original key and saved body within a durable time/attempt budget;
11878
+ * once a gateway task id is known, recovery only queries that task. Billing is
11879
+ * shown only from explicit gateway receipts.
9821
11880
  * @module dsh-vibedev/tasks/tracker
9822
11881
  */
9823
11882
  const SPECS = {
@@ -9850,55 +11909,50 @@ const CONSECUTIVE_FAILURE_LIMIT = 30;
9850
11909
  * short client deadline would itself make outcomes unknown.
9851
11910
  */
9852
11911
  const SUBMIT_TIMEOUT_MS = 3e5;
9853
- /**
9854
- * The gateway could not tell whether the provider received an earlier
9855
- * submission under this key, so it created no task and charges nothing; the
9856
- * key answers this forever. Resubmitting needs a new key.
9857
- */
9858
- const SUBMISSION_AMBIGUOUS = "VIDEO_SUBMISSION_AMBIGUOUS";
11912
+ /** These codes never prove whether the provider accepted or billed the request. */
11913
+ const UNKNOWN_SUBMISSION_CODES = /* @__PURE__ */ new Set([
11914
+ "VIDEO_SUBMISSION_AMBIGUOUS",
11915
+ "SEED_AUDIO_SUBMISSION_UNKNOWN",
11916
+ "MEDIA_SUBMISSION_UNKNOWN",
11917
+ "SUBMISSION_UNCERTAIN"
11918
+ ]);
9859
11919
  /** The same key was sent with a different body: a plugin bug, never retried. */
9860
- const KEY_CONFLICT = /_IDEMPOTENCY_CONFLICT$/;
11920
+ const KEY_CONFLICT = /(?:^|_)IDEMPOTENCY_CONFLICT$/;
9861
11921
  /** Structured verdicts the gateway sends; an unknown word falls back to the older protocol. */
9862
11922
  const REJECTED_STATES = /* @__PURE__ */ new Set([
11923
+ "not_submitted",
9863
11924
  "rejected",
9864
11925
  "refused",
9865
11926
  "denied"
9866
11927
  ]);
9867
- const RECONCILE_STATES = /* @__PURE__ */ new Set(["unknown", "accepted"]);
9868
- /** `retry_action` values that keep the same key: a lookup of this submission, never a new one. */
11928
+ const RECONCILE_STATES = /* @__PURE__ */ new Set([
11929
+ "unknown",
11930
+ "submitting",
11931
+ "accepted"
11932
+ ]);
11933
+ /** Recovery hints preserve the operation; they do not grant permission to repeat creation. */
9869
11934
  const SAME_KEY_ACTIONS = /* @__PURE__ */ new Set([
9870
11935
  "reconcile",
9871
11936
  "retry_same_key",
9872
11937
  "retry_same"
9873
11938
  ]);
9874
11939
  /**
9875
- * What a failed submission means.
9876
- *
9877
- * The two STOP rules are read before anything that would keep the operation
9878
- * alive, so no verdict can talk the plugin into sending a refused request
9879
- * again: `retry_action: none` (the provider refused it) and
9880
- * `VIDEO_SUBMISSION_AMBIGUOUS` (the gateway's key answers this forever) end the
9881
- * operation even when the same answer also says the outcome is unknown.
9882
- *
9883
- * After those, the gateway's structured verdict decides, and only when it
9884
- * sends none do the HTTP status and the older codes. `retryable` says recovery
9885
- * is still needed; it never authorizes creating another task.
9886
- * @param error - the failure.
9887
- * @returns how it may be taken further.
11940
+ * Unknown submission facts take precedence over refusal/retry hints. A retry
11941
+ * limit, retryable=false or an unqualified 5xx cannot prove a rejection.
11942
+ * Reconciliation always retains the original operation key.
9888
11943
  */
9889
11944
  function submissionRecovery(error) {
9890
11945
  if (!(error instanceof MediaError)) return "rejected";
9891
- const { submissionState, retryAction, status, busy, retryable } = error.details;
9892
- if (retryAction === "none") return "rejected";
9893
- if (error.code === SUBMISSION_AMBIGUOUS || KEY_CONFLICT.test(error.code)) return "rejected";
11946
+ const { submissionState, retryAction, status, busy, category } = error.details;
11947
+ if (category === "submission_uncertain" || UNKNOWN_SUBMISSION_CODES.has(error.code) || submissionState !== void 0 && RECONCILE_STATES.has(submissionState)) return "reconcile";
9894
11948
  if (submissionState !== void 0 && REJECTED_STATES.has(submissionState)) return "rejected";
11949
+ if (status === 429 || busy === true) return "reconcile";
11950
+ if (status !== void 0 && status >= 500) return "reconcile";
11951
+ if (retryAction === "none" || retryAction === "modify_input" || KEY_CONFLICT.test(error.code)) return "rejected";
9895
11952
  if (retryAction !== void 0 && SAME_KEY_ACTIONS.has(retryAction)) return "reconcile";
9896
11953
  if (retryAction === "retry") return "wait";
9897
- if (submissionState !== void 0 && RECONCILE_STATES.has(submissionState)) return "reconcile";
9898
11954
  if (NO_ANSWER_CODES.has(error.code)) return "reconcile";
9899
- if (busy === true) return "wait";
9900
11955
  if (status !== void 0 && status >= 400 && status < 500) return status === 409 ? "reconcile" : "rejected";
9901
- if (status !== void 0 && status >= 500) return retryable === false ? "rejected" : "reconcile";
9902
11956
  return "rejected";
9903
11957
  }
9904
11958
  /**
@@ -9915,13 +11969,9 @@ function terminalFailure(error) {
9915
11969
  code: "SUBMISSION_REJECTED",
9916
11970
  message: messageOf(error)
9917
11971
  };
9918
- if (error.code === SUBMISSION_AMBIGUOUS) return {
9919
- code: error.code,
9920
- message: "The gateway could not confirm this submission with the provider, so it created no task and charged nothing, and this request key will answer the same way. If the provider did receive it, that task is not visible here. Check the task list and the account usage before generating the same thing again."
9921
- };
9922
11972
  if (KEY_CONFLICT.test(error.code)) return {
9923
11973
  code: error.code,
9924
- message: "The gateway refused the request: its key was already used for a different request. Nothing was charged. Check the task list for the earlier request before generating again."
11974
+ message: "The gateway refused the request: its key was already used for a different request. Check the task list and billing receipt for the earlier request before generating again."
9925
11975
  };
9926
11976
  return {
9927
11977
  code: error.code,
@@ -9969,10 +12019,16 @@ function progressLine(task) {
9969
12019
  /** Follows tasks; one poll loop per task. */
9970
12020
  var TaskTracker = class {
9971
12021
  options;
12022
+ reconciliations = /* @__PURE__ */ new Map();
12023
+ pendingListeners = /* @__PURE__ */ new Set();
9972
12024
  following = /* @__PURE__ */ new Map();
9973
12025
  submissions = /* @__PURE__ */ new Map();
12026
+ submissionFingerprints = /* @__PURE__ */ new Map();
9974
12027
  listeners = /* @__PURE__ */ new Map();
9975
12028
  claims = /* @__PURE__ */ new Map();
12029
+ claimAcquisitions = /* @__PURE__ */ new Map();
12030
+ claimReleases = /* @__PURE__ */ new Map();
12031
+ disposing;
9976
12032
  downloadFailures = /* @__PURE__ */ new Map();
9977
12033
  controller = new AbortController();
9978
12034
  holder = randomUUID();
@@ -9995,78 +12051,127 @@ var TaskTracker = class {
9995
12051
  /**
9996
12052
  * Record and submit a new task. An outright refusal of the first attempt
9997
12053
  * throws and leaves no record. When the outcome stays open, the task stays
9998
- * recorded and is resent in the background, and this throws `SUBMISSION_UNCONFIRMED`.
12054
+ * recorded as unknown and checked only under the original key and saved body.
9999
12055
  * @param draft - the task, with status `submitting`.
10000
12056
  * @param signal - cancels waiting for the submission.
10001
12057
  * @returns the accepted task.
10002
12058
  */
10003
12059
  async submit(draft, signal) {
12060
+ return this.options.store.withScope(() => this.submitScoped(draft, signal));
12061
+ }
12062
+ async submitScoped(draft, signal) {
12063
+ const key = this.options.store.scopeKey(draft.id);
12064
+ const pending = this.submissions.get(key);
12065
+ if (pending !== void 0) {
12066
+ const fingerprint = this.submissionFingerprints.get(key);
12067
+ if (fingerprint !== void 0 && draft.requestFingerprint !== fingerprint) throw new MediaError("This operation already belongs to another request.", "IDEMPOTENCY_CONFLICT", {
12068
+ status: 409,
12069
+ field: "operationId"
12070
+ });
12071
+ return pending;
12072
+ }
12073
+ const recorded = await this.options.store.get(draft.id);
12074
+ if (recorded !== void 0) return recorded.gatewayId === void 0 && !isFinished(recorded) ? this.reconcileOnce(recorded, signal) : recorded;
12075
+ const raced = this.submissions.get(key);
12076
+ if (raced !== void 0) {
12077
+ const fingerprint = this.submissionFingerprints.get(key);
12078
+ if (fingerprint !== void 0 && draft.requestFingerprint !== fingerprint) throw new MediaError("This operation already belongs to another request.", "IDEMPOTENCY_CONFLICT", {
12079
+ status: 409,
12080
+ field: "operationId"
12081
+ });
12082
+ return raced;
12083
+ }
10004
12084
  const submission = this.runSubmission(draft, signal);
10005
- this.submissions.set(draft.id, submission);
12085
+ this.submissions.set(key, submission);
12086
+ this.submissionFingerprints.set(key, draft.requestFingerprint);
10006
12087
  try {
10007
12088
  return await submission;
10008
12089
  } finally {
10009
- this.submissions.delete(draft.id);
12090
+ this.submissions.delete(key);
12091
+ this.submissionFingerprints.delete(key);
10010
12092
  }
10011
12093
  }
10012
- async runSubmission(draft, signal) {
10013
- const spec = SPECS[draft.kind];
10014
- await this.options.store.add(draft);
10015
- await this.holdClaim(draft.id);
10016
- let unknown = false;
10017
- let lastError;
10018
- for (let attempt = 0; attempt < 3; attempt++) {
12094
+ async runSubmission(input, signal) {
12095
+ if (!await this.holdClaim(input.id)) {
12096
+ for (let n = 0; n < 100; n++) {
12097
+ const existing = await this.options.store.get(input.id);
12098
+ if (existing !== void 0) return existing;
12099
+ await this.sleep(25, this.signal);
12100
+ }
12101
+ throw new MediaError(hostMessage("submissionUncertain").replace("{operationId}", input.id), "SUBMISSION_UNCONFIRMED", {
12102
+ operationId: input.id,
12103
+ category: "submission_uncertain",
12104
+ submissionState: "unknown"
12105
+ });
12106
+ }
12107
+ try {
12108
+ const existing = await this.options.store.get(input.id);
12109
+ if (existing !== void 0) return existing.gatewayId === void 0 && !isFinished(existing) ? await this.reconcileOnce(existing, signal) : existing;
12110
+ let draft = await this.options.store.add(input);
12111
+ const spec = SPECS[draft.kind];
10019
12112
  let task;
10020
- try {
10021
- task = spec.parse(await this.options.http.json(spec.endpoint, {
10022
- method: "POST",
10023
- json: draft.body,
10024
- idempotencyKey: draft.id,
10025
- timeoutMs: SUBMIT_TIMEOUT_MS,
10026
- ...signal === void 0 ? {} : { signal }
10027
- }), this.now());
10028
- if (task === void 0) throw new MediaError("The VibeDev gateway accepted the request but returned no task id.", "GATEWAY_BAD_RESPONSE");
10029
- } catch (error) {
10030
- if (signal?.aborted === true) {
10031
- await this.finish(draft.id, {
10032
- status: "lost",
10033
- error: {
10034
- code: "SUBMISSION_CANCELLED",
10035
- message: "The request was cancelled while it was being submitted. If the gateway had already created the task, it runs and is charged, but dsh-vibedev cannot follow it."
10036
- }
10037
- }).catch(() => void 0);
10038
- await this.releaseClaim(draft.id);
10039
- throw error;
12113
+ for (let attempt = 0; attempt < this.budget(draft).initialLimit; attempt++) {
12114
+ const budget = this.budget(draft);
12115
+ if (this.now() - draft.createdAt >= (this.options.maxAgeMs ?? 108e5)) {
12116
+ draft = await this.expireUnknown(draft);
12117
+ break;
10040
12118
  }
10041
- const recovery = submissionRecovery(error);
10042
- if (recovery === "rejected") {
10043
- const settled = terminalFailure(error);
10044
- if (!unknown) {
10045
- this.dropClaim(draft.id);
12119
+ if (attempt > 0 && (this.now() >= budget.deadlineAt || this.signal.aborted || signal?.aborted === true)) break;
12120
+ draft = await this.update(draft.id, { recovery: {
12121
+ ...budget,
12122
+ initialAttempts: budget.initialAttempts + 1
12123
+ } });
12124
+ try {
12125
+ task = spec.parse(await this.options.http.json(spec.endpoint, {
12126
+ method: "POST",
12127
+ json: draft.body,
12128
+ idempotencyKey: draft.id,
12129
+ timeoutMs: SUBMIT_TIMEOUT_MS,
12130
+ busyRetries: 0,
12131
+ isCurrentAccount: () => this.options.store.isCurrent(draft),
12132
+ signal: signal === void 0 ? this.signal : AbortSignal.any([this.signal, signal])
12133
+ }), this.now());
12134
+ if (task === void 0) throw new MediaError("The VibeDev gateway accepted the request but returned no task id.", "GATEWAY_BAD_RESPONSE");
12135
+ break;
12136
+ } catch (error) {
12137
+ if (!await this.options.store.isCurrent(draft)) throw new MediaError("The active VibeDev account changed. The original operation is preserved.", "ACCOUNT_CHANGED");
12138
+ if ((signal?.aborted === true ? "reconcile" : submissionRecovery(error)) === "rejected" && draft.submissionState !== "unknown" && draft.error?.category !== "submission_uncertain") {
12139
+ const submissionState = "rejected";
12140
+ await this.options.store.update(draft.id, {
12141
+ status: "failed",
12142
+ submissionState,
12143
+ error: {
12144
+ ...terminalFailure(error),
12145
+ submissionState
12146
+ }
12147
+ });
10046
12148
  await this.options.store.remove(draft.id);
12149
+ if (error instanceof MediaError) throw new MediaError(error.message, error.code, {
12150
+ ...error.details,
12151
+ submissionState
12152
+ }, { cause: error });
10047
12153
  throw error;
10048
12154
  }
10049
- await this.finish(draft.id, {
10050
- status: "failed",
10051
- error: settled
10052
- }).catch(() => void 0);
10053
- await this.releaseClaim(draft.id);
10054
- throw new MediaError(settled.message, settled.code, { retryable: false }, { cause: error });
12155
+ draft = await this.keepUnknown(draft, error, 2e3 * (attempt + 1));
12156
+ if (draft.recovery?.stopped !== void 0 || attempt + 1 >= this.budget(draft).initialLimit || signal?.aborted === true) break;
12157
+ draft = await this.waitInitialRecovery(draft, signal);
10055
12158
  }
10056
- if (!unknown && recovery === "wait") {
10057
- this.dropClaim(draft.id);
10058
- await this.options.store.remove(draft.id);
10059
- throw error;
10060
- }
10061
- unknown = true;
10062
- lastError = error;
10063
- await this.sleep(2e3 * (attempt + 1), this.signal);
10064
- continue;
12159
+ }
12160
+ if (task === void 0) {
12161
+ if (!isFinished(draft) && this.budget(draft).backgroundLimit > 0) this.followQuietly(draft.id);
12162
+ throw new MediaError(draft.error?.message ?? hostMessage("submissionUncertain").replace("{operationId}", draft.id), draft.error?.code ?? "SUBMISSION_UNCONFIRMED", {
12163
+ operationId: draft.id,
12164
+ category: "submission_uncertain",
12165
+ stage: "submit",
12166
+ submissionState: "unknown",
12167
+ billingState: draft.billingState ?? "unknown",
12168
+ retryAction: "reconcile",
12169
+ retryable: false
12170
+ });
10065
12171
  }
10066
12172
  try {
10067
12173
  const accepted = await this.apply(draft, task);
10068
- if (isFinished(accepted)) await this.releaseClaim(accepted.id);
10069
- else this.followQuietly(accepted.id);
12174
+ if (!isFinished(accepted)) this.followQuietly(accepted.id);
10070
12175
  return accepted;
10071
12176
  } catch (error) {
10072
12177
  this.log(`recording task ${draft.id} (${task.id}) failed, following it anyway: ${messageOf(error)}`);
@@ -10082,9 +12187,123 @@ var TaskTracker = class {
10082
12187
  updatedAt: this.now()
10083
12188
  };
10084
12189
  }
12190
+ } finally {
12191
+ await this.releaseClaim(input.id);
12192
+ }
12193
+ }
12194
+ budget(record) {
12195
+ return record.recovery ?? {
12196
+ deadlineAt: record.createdAt + (this.options.resendWindowMs ?? 3e5),
12197
+ initialLimit: Math.max(1, Math.floor(this.options.submitAttempts ?? 3)),
12198
+ backgroundLimit: Math.max(0, Math.floor(this.options.reconcileAttempts ?? CONSECUTIVE_FAILURE_LIMIT)),
12199
+ initialAttempts: 0,
12200
+ backgroundAttempts: 0,
12201
+ nextAttemptAt: this.now()
12202
+ };
12203
+ }
12204
+ async waitInitialRecovery(input, signal) {
12205
+ const waiting = signal === void 0 ? this.signal : AbortSignal.any([this.signal, signal]);
12206
+ let record = input;
12207
+ while (!waiting.aborted) {
12208
+ record = await this.options.store.get(input.id) ?? record;
12209
+ const budget = this.budget(record);
12210
+ const until = Math.min(budget.nextAttemptAt, budget.deadlineAt, record.createdAt + (this.options.maxAgeMs ?? 108e5));
12211
+ if (isFinished(record) || this.now() >= until) break;
12212
+ try {
12213
+ await this.sleep(until - this.now(), waiting);
12214
+ } catch (error) {
12215
+ if (!waiting.aborted) throw error;
12216
+ }
12217
+ }
12218
+ return await this.options.store.get(input.id) ?? record;
12219
+ }
12220
+ async keepUnknown(record, error, fallbackWait) {
12221
+ const details = error instanceof MediaError ? error.details : {};
12222
+ const code = error instanceof MediaError ? error.code : "SUBMISSION_UNCONFIRMED";
12223
+ const budget = this.budget(record);
12224
+ const retryAt = details.retryAt === void 0 ? 0 : Date.parse(details.retryAt);
12225
+ const nextAttemptAt = Math.max(this.now() + fallbackWait, this.now() + (details.retryAfterMs ?? (details.retryAfterSeconds ?? 0) * 1e3), Number.isFinite(retryAt) ? retryAt : 0);
12226
+ const stopped = /(?:^|_)SUBMISSION_AMBIGUOUS$/.test(code) ? "ambiguous" : submissionRecovery(error) === "rejected" ? "rejected_after_unknown" : budget.stopped;
12227
+ return this.update(record.id, {
12228
+ submissionState: "unknown",
12229
+ recovery: {
12230
+ ...budget,
12231
+ nextAttemptAt,
12232
+ ...stopped === void 0 ? {} : { stopped }
12233
+ },
12234
+ error: {
12235
+ code,
12236
+ message: hostMessage("submissionUncertain").replace("{operationId}", record.id),
12237
+ category: "submission_uncertain",
12238
+ stage: "submit",
12239
+ submissionState: "unknown",
12240
+ retryAction: "reconcile"
12241
+ }
12242
+ });
12243
+ }
12244
+ reconcileOnce(record, signal) {
12245
+ const key = this.options.store.scopeKey(record.id);
12246
+ const pending = this.reconciliations.get(key);
12247
+ if (pending !== void 0) return pending;
12248
+ const run = this.reconcileClaimed(record, signal).finally(() => {
12249
+ this.reconciliations.delete(key);
12250
+ });
12251
+ this.reconciliations.set(key, run);
12252
+ return run;
12253
+ }
12254
+ async reconcileClaimed(input, signal) {
12255
+ const key = this.options.store.scopeKey(input.id);
12256
+ const held = this.claims.has(key);
12257
+ if (!await this.holdClaim(input.id)) return await this.options.store.get(input.id) ?? input;
12258
+ try {
12259
+ let record = await this.options.store.get(input.id) ?? input;
12260
+ if (!await this.options.store.isCurrent(record) || isFinished(record) || record.gatewayId !== void 0 || this.signal.aborted || signal?.aborted === true) return record;
12261
+ if (this.now() - record.createdAt >= (this.options.maxAgeMs ?? 108e5)) return this.expireUnknown(record);
12262
+ const budget = this.budget(record);
12263
+ const limit = budget.backgroundLimit;
12264
+ if (budget.stopped !== void 0 || limit <= 0) return record;
12265
+ if (this.now() >= budget.deadlineAt) return record;
12266
+ if (budget.backgroundAttempts >= limit) return this.expireUnknown(record);
12267
+ if (this.now() < budget.nextAttemptAt) return record;
12268
+ record = await this.update(record.id, { recovery: {
12269
+ ...budget,
12270
+ backgroundAttempts: budget.backgroundAttempts + 1
12271
+ } });
12272
+ const spec = SPECS[record.kind];
12273
+ try {
12274
+ const task = spec.parse(await this.options.http.json(spec.endpoint, {
12275
+ method: "POST",
12276
+ json: record.body,
12277
+ idempotencyKey: record.id,
12278
+ timeoutMs: SUBMIT_TIMEOUT_MS,
12279
+ busyRetries: 0,
12280
+ isCurrentAccount: () => this.options.store.isCurrent(record),
12281
+ signal: signal === void 0 ? this.signal : AbortSignal.any([this.signal, signal])
12282
+ }), this.now());
12283
+ if (!await this.options.store.isCurrent(record)) return record;
12284
+ if (task === void 0) throw new MediaError("The gateway returned no task id.", "GATEWAY_BAD_RESPONSE");
12285
+ return await this.apply(record, task);
12286
+ } catch (error) {
12287
+ if (!await this.options.store.isCurrent(record)) return record;
12288
+ return this.keepUnknown(record, error, Math.min(6e4, 5e3 * 2 ** Math.min(budget.backgroundAttempts, 4)));
12289
+ }
12290
+ } finally {
12291
+ if (!held) await this.releaseClaim(input.id);
10085
12292
  }
10086
- this.followQuietly(draft.id);
10087
- throw new MediaError(`The VibeDev gateway did not confirm the request (${messageOf(lastError)}). dsh-vibedev keeps settling it under the same request key for a few minutes — that key can only ever answer with the one task it may have created — and saves the result if it runs. Check media_tasks for task ${draft.id}; do not submit the same request again.`, "SUBMISSION_UNCONFIRMED", { retryable: false });
12293
+ }
12294
+ expireUnknown(record) {
12295
+ return this.finish(record.id, {
12296
+ status: "lost",
12297
+ submissionState: "unknown",
12298
+ error: {
12299
+ code: record.error?.code ?? "SUBMISSION_UNCONFIRMED",
12300
+ message: hostMessage("submissionUncertain").replace("{operationId}", record.id),
12301
+ category: "submission_uncertain",
12302
+ stage: "submit",
12303
+ submissionState: "unknown",
12304
+ retryAction: "none"
12305
+ }
12306
+ });
10088
12307
  }
10089
12308
  /**
10090
12309
  * Follow a recorded task until it ends or the tracker is disposed. A task
@@ -10093,13 +12312,17 @@ var TaskTracker = class {
10093
12312
  * @returns the task at the end (or at disposal, still running).
10094
12313
  */
10095
12314
  follow(id) {
10096
- const running = this.following.get(id);
12315
+ return this.options.store.withScope(() => this.followScoped(id));
12316
+ }
12317
+ followScoped(id) {
12318
+ const key = this.options.store.scopeKey(id);
12319
+ const running = this.following.get(key);
10097
12320
  if (running !== void 0) return running;
10098
- const submission = this.submissions.get(id);
12321
+ const submission = this.submissions.get(key);
10099
12322
  const loop = (submission === void 0 ? Promise.resolve() : submission.then(() => void 0, () => void 0)).then(() => this.loop(id)).finally(() => {
10100
- this.following.delete(id);
12323
+ this.following.delete(key);
10101
12324
  });
10102
- this.following.set(id, loop);
12325
+ this.following.set(key, loop);
10103
12326
  return loop;
10104
12327
  }
10105
12328
  followQuietly(id) {
@@ -10114,30 +12337,67 @@ var TaskTracker = class {
10114
12337
  * @returns unsubscribe.
10115
12338
  */
10116
12339
  onUpdate(id, listener) {
10117
- const set = this.listeners.get(id) ?? /* @__PURE__ */ new Set();
10118
- set.add(listener);
10119
- this.listeners.set(id, set);
12340
+ const subscription = {
12341
+ id,
12342
+ listener,
12343
+ stopped: false
12344
+ };
12345
+ this.pendingListeners.add(subscription);
12346
+ this.options.store.withScope(async () => {
12347
+ this.bindListener(subscription);
12348
+ }).catch(() => void 0);
10120
12349
  return () => {
10121
- set.delete(listener);
10122
- if (set.size === 0) this.listeners.delete(id);
12350
+ subscription.stopped = true;
12351
+ this.pendingListeners.delete(subscription);
12352
+ if (subscription.key !== void 0) {
12353
+ const listeners = this.listeners.get(subscription.key);
12354
+ listeners?.delete(listener);
12355
+ if (listeners?.size === 0) this.listeners.delete(subscription.key);
12356
+ }
10123
12357
  };
10124
12358
  }
12359
+ bindListener(subscription) {
12360
+ if (subscription.stopped || subscription.key !== void 0) return;
12361
+ subscription.key = this.options.store.scopeKey(subscription.id);
12362
+ const listeners = this.listeners.get(subscription.key) ?? /* @__PURE__ */ new Set();
12363
+ listeners.add(subscription.listener);
12364
+ this.listeners.set(subscription.key, listeners);
12365
+ this.pendingListeners.delete(subscription);
12366
+ }
10125
12367
  /** Follow every task that has not ended, as after a restart. */
10126
12368
  async resume() {
10127
- for (const record of await this.options.store.list()) if (!isFinished(record)) this.followQuietly(record.id);
12369
+ await this.options.store.withScope(async () => {
12370
+ for (const subscription of this.pendingListeners) this.bindListener(subscription);
12371
+ for (const record of await this.options.store.list()) if (!isFinished(record)) this.followQuietly(record.id);
12372
+ }).catch((error) => {
12373
+ if (!(error instanceof MediaError) || error.code !== "ACCOUNT_UNAVAILABLE") throw error;
12374
+ });
10128
12375
  }
10129
12376
  /** Stop all polling and give up this process's claims; tasks stay recorded and are resumed next time. */
10130
12377
  dispose() {
12378
+ return this.disposing ??= this.disposeAll();
12379
+ }
12380
+ async disposeAll() {
10131
12381
  this.controller.abort();
10132
- for (const id of [...this.claims.keys()]) {
10133
- this.dropClaim(id);
10134
- this.options.store.release(id, this.holder).catch(() => void 0);
10135
- }
12382
+ await Promise.allSettled([...this.claimAcquisitions.values()]);
12383
+ const claims = [...this.claims.values()];
12384
+ this.claims.clear();
12385
+ for (const claim of claims) clearInterval(claim.timer);
12386
+ await Promise.allSettled([
12387
+ ...this.following.values(),
12388
+ ...this.submissions.values(),
12389
+ ...this.reconciliations.values(),
12390
+ ...this.claimReleases.values(),
12391
+ ...claims.map((claim) => this.releaseHeldClaim(claim))
12392
+ ]);
10136
12393
  }
10137
12394
  notify(record) {
10138
- for (const listener of this.listeners.get(record.id) ?? []) try {
10139
- listener(record);
10140
- } catch {}
12395
+ const listeners = [...this.listeners.get(this.options.store.scopeKey(record.id)) ?? []];
12396
+ this.options.store.isCurrent(record).then((current) => {
12397
+ if (current) for (const listener of listeners) try {
12398
+ listener(record);
12399
+ } catch {}
12400
+ }).catch(() => void 0);
10141
12401
  }
10142
12402
  async update(id, patch) {
10143
12403
  const next = await this.options.store.update(id, patch);
@@ -10165,25 +12425,63 @@ var TaskTracker = class {
10165
12425
  }
10166
12426
  /** Hold (or keep) this process's claim on a task, renewing it while held. */
10167
12427
  async holdClaim(id) {
10168
- if (this.claims.has(id)) return true;
12428
+ const key = this.options.store.scopeKey(id);
12429
+ if (this.signal.aborted) return false;
12430
+ const releasing = this.claimReleases.get(key);
12431
+ if (releasing !== void 0) {
12432
+ await releasing;
12433
+ return this.holdClaim(id);
12434
+ }
12435
+ if (this.claims.has(key)) return true;
12436
+ const pending = this.claimAcquisitions.get(key);
12437
+ if (pending !== void 0) return pending;
12438
+ const store = this.options.store.boundStore();
10169
12439
  const stale = this.options.claimStaleMs ?? 6e4;
10170
- if (!await this.options.store.claim(id, this.holder, stale).catch(() => false)) return false;
12440
+ const acquiring = this.acquireClaim(key, id, store, stale).finally(() => {
12441
+ this.claimAcquisitions.delete(key);
12442
+ });
12443
+ this.claimAcquisitions.set(key, acquiring);
12444
+ return acquiring;
12445
+ }
12446
+ async acquireClaim(key, id, store, stale) {
12447
+ if (!await store.claim(id, this.holder, stale).catch(() => false)) return false;
12448
+ if (this.signal.aborted) {
12449
+ await store.release(id, this.holder).catch(() => void 0);
12450
+ return false;
12451
+ }
12452
+ let claim;
10171
12453
  const timer = setInterval(() => {
10172
- this.options.store.renewClaim(id, this.holder).catch(() => void 0);
12454
+ if (this.signal.aborted || this.claims.get(key) !== claim) return;
12455
+ claim.renewing = (claim.renewing ?? Promise.resolve()).then(async () => {
12456
+ if (!this.signal.aborted && this.claims.get(key) === claim) await store.renewClaim(id, this.holder);
12457
+ }).catch(() => void 0);
10173
12458
  }, Math.max(1e3, Math.floor(stale / 3)));
10174
12459
  timer.unref?.();
10175
- this.claims.set(id, timer);
12460
+ claim = {
12461
+ id,
12462
+ timer,
12463
+ store
12464
+ };
12465
+ this.claims.set(key, claim);
10176
12466
  return true;
10177
12467
  }
10178
- dropClaim(id) {
10179
- const timer = this.claims.get(id);
10180
- if (timer !== void 0) clearInterval(timer);
10181
- this.claims.delete(id);
12468
+ async releaseHeldClaim(claim) {
12469
+ await claim.renewing;
12470
+ await claim.store.release(claim.id, this.holder).catch(() => void 0);
10182
12471
  }
10183
12472
  async releaseClaim(id) {
10184
- if (!this.claims.has(id)) return;
10185
- this.dropClaim(id);
10186
- await this.options.store.release(id, this.holder).catch(() => void 0);
12473
+ const key = this.options.store.scopeKey(id);
12474
+ const pending = this.claimReleases.get(key);
12475
+ if (pending !== void 0) return pending;
12476
+ const claim = this.claims.get(key);
12477
+ if (claim === void 0) return;
12478
+ clearInterval(claim.timer);
12479
+ this.claims.delete(key);
12480
+ const releasing = this.releaseHeldClaim(claim).finally(() => {
12481
+ this.claimReleases.delete(key);
12482
+ });
12483
+ this.claimReleases.set(key, releasing);
12484
+ return releasing;
10187
12485
  }
10188
12486
  async loop(id) {
10189
12487
  let record = await this.options.store.get(id);
@@ -10194,45 +12492,49 @@ var TaskTracker = class {
10194
12492
  try {
10195
12493
  while (!this.signal.aborted) try {
10196
12494
  record = await this.options.store.get(id) ?? record;
12495
+ if (!await this.options.store.isCurrent(record)) return record;
10197
12496
  if (isFinished(record)) return record;
10198
12497
  if (!await this.holdClaim(id)) {
10199
12498
  await this.sleep(3e4, this.signal);
10200
12499
  continue;
10201
12500
  }
10202
12501
  const age = this.now() - record.createdAt;
10203
- if (age > maxAge) return await this.finish(id, {
10204
- status: "lost",
10205
- error: {
10206
- code: "TASK_TIMED_OUT",
10207
- message: `No result after ${Math.round(maxAge / 36e5)} hours; dsh-vibedev stopped following it.`
10208
- }
10209
- });
10210
- let task;
10211
- if (record.status === "submitting" || record.gatewayId === void 0) {
10212
- if (age > (this.options.resendWindowMs ?? 3e5)) return await this.finish(id, {
12502
+ if (age >= maxAge) {
12503
+ if (record.gatewayId === void 0) return await this.expireUnknown(record);
12504
+ return await this.finish(id, {
10213
12505
  status: "lost",
10214
12506
  error: {
10215
- code: "SUBMISSION_UNCONFIRMED",
10216
- message: "The gateway never confirmed this request. If it did run, it is not visible to dsh-vibedev."
12507
+ code: "TASK_TIMED_OUT",
12508
+ message: `No result after ${Math.round(maxAge / 36e5)} hours; dsh-vibedev stopped following it.`
10217
12509
  }
10218
12510
  });
10219
- task = spec.parse(await this.options.http.json(spec.endpoint, {
10220
- method: "POST",
10221
- json: record.body,
10222
- idempotencyKey: record.id,
10223
- timeoutMs: SUBMIT_TIMEOUT_MS,
10224
- signal: this.signal
10225
- }), this.now());
10226
- } else task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
12511
+ }
12512
+ let task;
12513
+ if (record.gatewayId === void 0) {
12514
+ if (this.budget(record).backgroundLimit <= 0) return record.submissionState === void 0 ? this.keepUnknown(record, new MediaError("", "SUBMISSION_UNCONFIRMED"), 0) : record;
12515
+ record = await this.reconcileOnce(record);
12516
+ if (isFinished(record)) return record;
12517
+ if (record.gatewayId === void 0) {
12518
+ const budget = this.budget(record);
12519
+ const expiresAt = record.createdAt + maxAge;
12520
+ const until = budget.stopped === void 0 && this.now() < budget.deadlineAt ? Math.min(budget.nextAttemptAt, budget.deadlineAt, expiresAt) : expiresAt;
12521
+ await this.sleep(Math.min(6e4, Math.max(1, until - this.now())), this.signal);
12522
+ continue;
12523
+ }
12524
+ }
12525
+ task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
10227
12526
  timeoutMs: 3e4,
10228
- signal: this.signal
12527
+ signal: this.signal,
12528
+ isCurrentAccount: () => this.options.store.isCurrent(record)
10229
12529
  }), this.now());
10230
12530
  if (task === void 0) throw new MediaError("The VibeDev gateway returned an unreadable task.", "GATEWAY_BAD_RESPONSE");
12531
+ if (!await this.options.store.isCurrent(record)) return record;
10231
12532
  record = await this.apply(record, task);
10232
12533
  failures = 0;
10233
12534
  if (isFinished(record)) return record;
10234
12535
  await this.sleep(task.nextPollAfterSeconds === void 0 ? spec.interval(age) : task.nextPollAfterSeconds * 1e3, this.signal);
10235
12536
  } catch (error) {
12537
+ if (!await this.options.store.isCurrent(record)) return record;
10236
12538
  if (this.signal.aborted) break;
10237
12539
  failures++;
10238
12540
  const wait = await this.afterFailure(record, error, failures).catch((failure) => {
@@ -10261,7 +12563,7 @@ var TaskTracker = class {
10261
12563
  return 6e4;
10262
12564
  }
10263
12565
  if (submitting) {
10264
- if (submissionRecovery(error) === "rejected") {
12566
+ if (submissionRecovery(error) === "rejected" && record.submissionState !== "unknown" && record.error?.category !== "submission_uncertain") {
10265
12567
  await this.finish(record.id, {
10266
12568
  status: "failed",
10267
12569
  error: terminalFailure(error)
@@ -10269,41 +12571,55 @@ var TaskTracker = class {
10269
12571
  return;
10270
12572
  }
10271
12573
  if (failures >= CONSECUTIVE_FAILURE_LIMIT) {
10272
- await this.finish(record.id, {
10273
- status: "failed",
12574
+ await this.update(record.id, {
12575
+ submissionState: "unknown",
10274
12576
  error: {
10275
- code: code ?? "SUBMISSION_FAILED",
10276
- message: `The submission could not be settled ${failures} times in a row: ${messageOf(error)}`
12577
+ code: code ?? "SUBMISSION_UNCONFIRMED",
12578
+ category: "submission_uncertain",
12579
+ stage: "submit",
12580
+ submissionState: "unknown",
12581
+ retryAction: "reconcile",
12582
+ message: `The submission remains unconfirmed after ${failures} checks: ${messageOf(error)}`
10277
12583
  }
10278
12584
  });
10279
12585
  return;
10280
12586
  }
10281
- return Math.min(6e4, 5e3 * 2 ** Math.min(failures - 1, 4));
10282
- }
10283
- if (status === 402) {
10284
- await this.update(record.id, { progress: "paused: the VibeDev balance is used up; top up to receive the result" });
10285
- return 6e4;
10286
- }
10287
- if (status === 404) {
10288
- await this.finish(record.id, {
10289
- status: "lost",
12587
+ await this.update(record.id, {
12588
+ submissionState: "unknown",
10290
12589
  error: {
10291
- code: "TASK_NOT_FOUND",
10292
- message: "The VibeDev gateway no longer knows this task."
12590
+ code: code ?? "SUBMISSION_UNCONFIRMED",
12591
+ category: "submission_uncertain",
12592
+ stage: "submit",
12593
+ submissionState: "unknown",
12594
+ retryAction: "reconcile",
12595
+ message: messageOf(error)
10293
12596
  }
10294
12597
  });
10295
- return;
12598
+ return Math.min(6e4, 5e3 * 2 ** Math.min(failures - 1, 4));
10296
12599
  }
10297
- if (failures >= CONSECUTIVE_FAILURE_LIMIT) {
10298
- await this.finish(record.id, {
10299
- status: "lost",
12600
+ if (status === 402) {
12601
+ await this.update(record.id, {
12602
+ progress: hostMessage("pollBilling"),
10300
12603
  error: {
10301
- code: code ?? "POLL_FAILED",
10302
- message: `Checking the task failed ${failures} times in a row: ${messageOf(error)}`
12604
+ code: code ?? "BILLING_SOURCE_UNAVAILABLE",
12605
+ category: "billing",
12606
+ stage: "poll",
12607
+ retryAction: "poll",
12608
+ message: hostMessage("pollBilling")
10303
12609
  }
10304
12610
  });
10305
- return;
12611
+ return 6e4;
10306
12612
  }
12613
+ await this.update(record.id, {
12614
+ progress: hostMessage("pollUnavailable"),
12615
+ error: {
12616
+ code: code ?? "TASK_QUERY_UNAVAILABLE",
12617
+ category: "service_unavailable",
12618
+ stage: "poll",
12619
+ message: hostMessage("pollUnavailable"),
12620
+ retryAction: "poll"
12621
+ }
12622
+ });
10307
12623
  return Math.min(6e4, 5e3 * 2 ** Math.min(failures - 1, 4));
10308
12624
  }
10309
12625
  /**
@@ -10325,6 +12641,7 @@ var TaskTracker = class {
10325
12641
  ...task.billedTokens === void 0 ? {} : { tokens: task.billedTokens }
10326
12642
  } } : {};
10327
12643
  return {
12644
+ ...task.receipt,
10328
12645
  ...task.estimatedCny === void 0 ? {} : { estimatedCny: task.estimatedCny },
10329
12646
  ...settlement === "pending" ? {
10330
12647
  settlement,
@@ -10346,6 +12663,7 @@ var TaskTracker = class {
10346
12663
  */
10347
12664
  progressFactsOf(record, task) {
10348
12665
  return {
12666
+ ...task.nextPollAfterSeconds === void 0 && record.nextPollAfterSeconds === void 0 ? {} : { nextPollAfterSeconds: task.nextPollAfterSeconds },
10349
12667
  ...task.timing === void 0 && record.timing === void 0 ? {} : { timing: task.timing },
10350
12668
  ...task.queue === void 0 && record.queue === void 0 ? {} : { queue: task.queue }
10351
12669
  };
@@ -10353,9 +12671,24 @@ var TaskTracker = class {
10353
12671
  /** Record what the gateway says about a task; save the outputs of a finished one. */
10354
12672
  async apply(record, task) {
10355
12673
  const money = this.moneyOf(record, task);
12674
+ if (task.state === "failed" && (task.error?.category === "submission_uncertain" || task.error !== void 0 && UNKNOWN_SUBMISSION_CODES.has(task.error.code) || task.receipt?.submissionState !== void 0 && RECONCILE_STATES.has(task.receipt.submissionState))) return this.update(record.id, {
12675
+ gatewayId: task.id,
12676
+ status: "pending",
12677
+ ...money,
12678
+ submissionState: "unknown",
12679
+ error: {
12680
+ code: task.error?.code ?? "SUBMISSION_UNCONFIRMED",
12681
+ message: hostMessage("submissionUncertain").replace("{operationId}", record.id),
12682
+ category: "submission_uncertain",
12683
+ stage: "generation",
12684
+ submissionState: "unknown",
12685
+ retryAction: "poll"
12686
+ }
12687
+ });
10356
12688
  if (task.state === "pending") return this.update(record.id, {
10357
12689
  gatewayId: task.id,
10358
12690
  status: "pending",
12691
+ error: void 0,
10359
12692
  progress: progressLine(task),
10360
12693
  ...money,
10361
12694
  ...this.progressFactsOf(record, task)
@@ -10369,6 +12702,7 @@ var TaskTracker = class {
10369
12702
  const current = await this.update(record.id, {
10370
12703
  gatewayId: task.id,
10371
12704
  status: "pending",
12705
+ error: void 0,
10372
12706
  progress: SAVING_PROGRESS,
10373
12707
  ...money,
10374
12708
  ...this.progressFactsOf(record, task)
@@ -10383,7 +12717,8 @@ var TaskTracker = class {
10383
12717
  if (money.chargedCny === void 0 && task.settlement !== "pending") {
10384
12718
  const settled = await this.options.http.json(SPECS[record.kind].poll(task.id), {
10385
12719
  timeoutMs: 15e3,
10386
- signal: this.signal
12720
+ signal: this.signal,
12721
+ isCurrentAccount: () => this.options.store.isCurrent(record)
10387
12722
  }).then((body) => SPECS[record.kind].parse(body, this.now()), () => void 0);
10388
12723
  if (settled !== void 0) charged = {
10389
12724
  ...money,
@@ -10395,26 +12730,40 @@ var TaskTracker = class {
10395
12730
  status: "completed",
10396
12731
  outputs,
10397
12732
  ...charged,
10398
- ...missing === 0 ? {} : { error: {
12733
+ error: missing === 0 ? void 0 : {
10399
12734
  code: "DOWNLOAD_FAILED",
10400
- message: `${missing} of ${outputs.length} result file(s) could not be downloaded; the gateway links are listed instead.`
10401
- } }
12735
+ category: "service_unavailable",
12736
+ stage: "download",
12737
+ retryAction: "download",
12738
+ message: hostMessage("downloadFailed")
12739
+ }
10402
12740
  });
10403
12741
  }
10404
12742
  /**
10405
- * Ask the gateway about a task again, by query only: a finished task gets
12743
+ * Ask about the same task again: an unconfirmed operation may consume one
12744
+ * budgeted original-key/body check; a finished task gets
10406
12745
  * fresh links (signed links expire), files that are missing locally are
10407
12746
  * downloaded again, and a pending settlement is read again. Nothing is ever
10408
- * submitted from here, so a failed query or download cannot create a task.
12747
+ * submitted under a new key, so a failed query/download never starts a new operation.
10409
12748
  * A task still running is followed as usual.
10410
12749
  * @param id - the local task id.
10411
12750
  * @param signal - cancels the query.
10412
12751
  * @returns the task after the query.
10413
12752
  */
10414
12753
  async refresh(id, signal) {
12754
+ return this.options.store.withScope(() => this.refreshScoped(id, signal));
12755
+ }
12756
+ async refreshScoped(id, signal) {
12757
+ const submitting = this.submissions.get(this.options.store.scopeKey(id));
12758
+ if (submitting !== void 0) await submitting.catch(() => void 0);
10415
12759
  const record = await this.options.store.get(id);
10416
12760
  if (record === void 0) throw new MediaError(`dsh-vibedev has no task ${id}.`, "UNKNOWN_TASK");
10417
12761
  if (!isFinished(record)) {
12762
+ if (record.gatewayId === void 0) {
12763
+ const current = await this.reconcileOnce(record, signal);
12764
+ if (!isFinished(current) && this.budget(current).backgroundLimit > 0) this.followQuietly(id);
12765
+ return current;
12766
+ }
10418
12767
  this.followQuietly(id);
10419
12768
  return record;
10420
12769
  }
@@ -10422,13 +12771,15 @@ var TaskTracker = class {
10422
12771
  const spec = SPECS[record.kind];
10423
12772
  const task = spec.parse(await this.options.http.json(spec.poll(record.gatewayId), {
10424
12773
  timeoutMs: 3e4,
12774
+ isCurrentAccount: () => this.options.store.isCurrent(record),
10425
12775
  ...signal === void 0 ? {} : { signal }
10426
12776
  }), this.now());
12777
+ if (!await this.options.store.isCurrent(record)) return record;
10427
12778
  if (task === void 0) throw new MediaError("The VibeDev gateway returned an unreadable task.", "GATEWAY_BAD_RESPONSE");
10428
12779
  const money = this.moneyOf(record, task);
10429
12780
  if (task.state !== "completed") return this.update(id, money);
10430
12781
  const fresh = new Map(task.outputs.map((output) => [output.index, output]));
10431
- const known = (record.outputs ?? []).filter((output) => output.path !== void 0 && output.index !== void 0).map((output) => ({
12782
+ const known = (await this.existingOutputs(record.outputs ?? [])).filter((output) => output.index !== void 0).map((output) => ({
10432
12783
  ...output,
10433
12784
  ...fresh.get(output.index)?.url === void 0 ? {} : { url: fresh.get(output.index)?.url }
10434
12785
  }));
@@ -10451,7 +12802,7 @@ var TaskTracker = class {
10451
12802
  */
10452
12803
  async saveOutputs(record, task) {
10453
12804
  const spec = SPECS[record.kind];
10454
- const saved = new Map((record.outputs ?? []).filter((output) => output.path !== void 0 && output.index !== void 0).map((output) => [output.index, output]));
12805
+ const saved = new Map((await this.existingOutputs(record.outputs ?? [])).filter((output) => output.index !== void 0).map((output) => [output.index, output]));
10455
12806
  const outputs = [];
10456
12807
  let missing = 0;
10457
12808
  for (const [position, output] of task.outputs.entries()) {
@@ -10494,6 +12845,10 @@ var TaskTracker = class {
10494
12845
  missing
10495
12846
  };
10496
12847
  }
12848
+ async existingOutputs(outputs) {
12849
+ const existing = await Promise.all(outputs.map((output) => savedFileExists(output.path)));
12850
+ return outputs.filter((_, index) => existing[index]);
12851
+ }
10497
12852
  /** Use a returned signed URL verbatim and without the app token; old gateways without a URL use `/content`. */
10498
12853
  async fetchOutput(record, task, output, temporary) {
10499
12854
  const spec = SPECS[record.kind];
@@ -10513,7 +12868,8 @@ var TaskTracker = class {
10513
12868
  headers: { accept: "*/*" },
10514
12869
  anonymous: source.anonymous,
10515
12870
  timeoutMs: 9e5,
10516
- signal: this.signal
12871
+ signal: this.signal,
12872
+ isCurrentAccount: () => this.options.store.isCurrent(record)
10517
12873
  }), temporary, this.options.maxDownloadBytes ?? 2 * 1024 ** 3, this.signal);
10518
12874
  } catch (error) {
10519
12875
  lastError = error;
@@ -10636,7 +12992,7 @@ function mediaAccountTool(runtime, chain, login) {
10636
12992
  function audioGenerateTool(runtime) {
10637
12993
  return defineTool({
10638
12994
  name: "audio_generate",
10639
- description: "Generate music (a song with vocals or an instrumental), a podcast episode (a spoken conversation about a topic or a web page) or speech (text read aloud, optionally in the voice of reference audio) with a VibeDev audio model. It runs as a background job: this call returns once the gateway accepts the task, you are notified when it finishes, and the files are saved in the workspace (media/audio/). Each model takes only the fields it declares; media_models lists them with prices (music and podcasts per request, speech per second of original audio). Charged only when it succeeds.",
12995
+ description: "Generate music (a song with vocals or an instrumental), a podcast episode (a spoken conversation about a topic or a web page) or speech (text read aloud, optionally in the voice of reference audio) with a VibeDev audio model. It runs as a background job: this call returns once the gateway accepts the task, you are notified when it finishes, and the files are saved in the workspace (media/audio/). Each model takes only the fields it declares; media_models lists them with prices (music and podcasts per request, speech per second of original audio). Final billing follows the gateway receipt.",
10640
12996
  parameters: {
10641
12997
  type: {
10642
12998
  type: "string",
@@ -11262,6 +13618,9 @@ const Config = Schema.object({
11262
13618
  preferredModels: Schema.array(Schema.string()).default([]),
11263
13619
  openBrowserOnSignIn: Schema.boolean().default(true),
11264
13620
  catalogRefreshMinutes: Schema.number().min(1).max(1440).default(30),
13621
+ resendWindowMs: Schema.natural().min(1e3).max(108e5).default(3e5),
13622
+ submitAttempts: Schema.natural().min(1).max(30).default(3),
13623
+ reconcileAttempts: Schema.natural().max(30).default(30),
11265
13624
  confirmSpending: Schema.boolean().default(false).volatile(),
11266
13625
  outputDir: Schema.string().default("media").volatile(),
11267
13626
  imageModel: Schema.string().default("").volatile(),
@@ -11283,6 +13642,9 @@ const Config = Schema.object({
11283
13642
  preferredModels: "排在最前的 VibeDev 模型(按顺序,留空按网关顺序)",
11284
13643
  openBrowserOnSignIn: "登录时自动打开系统浏览器",
11285
13644
  catalogRefreshMinutes: "模型目录定时刷新间隔(分钟;没人打开余额卡片、账号菜单或设置时的兜底)",
13645
+ resendWindowMs: "原键提交核对窗口(毫秒;仅适用于新操作,默认5分钟)",
13646
+ submitAttempts: "原键首次提交总尝试数(含首次,默认3)",
13647
+ reconcileAttempts: "原键后台核对次数(0关闭,默认30)",
11286
13648
  confirmSpending: "每次付费生成前先询问(默认关闭)",
11287
13649
  outputDir: "保存目录(相对于工作区)",
11288
13650
  imageModel: "默认生图模型(留空由 Agent 按目录选择)",
@@ -11304,6 +13666,9 @@ const Config = Schema.object({
11304
13666
  preferredModels: "VibeDev models listed first, in this order (empty: the gateway's order)",
11305
13667
  openBrowserOnSignIn: "Open the system browser when signing in",
11306
13668
  catalogRefreshMinutes: "Model catalog refresh interval in minutes (the fallback when nobody opens the balance card, the account menu or Settings)",
13669
+ resendWindowMs: "Same-key recovery window in milliseconds (new operations only; default 5 minutes)",
13670
+ submitAttempts: "Initial same-key attempts including first dispatch (default 3)",
13671
+ reconcileAttempts: "Additional same-key checks (0 disables; default 30)",
11307
13672
  confirmSpending: "Ask before each paid generation (off by default)",
11308
13673
  outputDir: "Output folder (relative to the workspace)",
11309
13674
  imageModel: "Default image model (empty: the agent chooses from the catalog)",
@@ -11364,12 +13729,18 @@ function apply(ctx, config) {
11364
13729
  if (method === "POST" && PAID_PATH.test(path)) spent();
11365
13730
  }
11366
13731
  });
11367
- const store = new TaskStore(gatewayStateDirectory(stateDir, origin));
13732
+ const store = new TaskStore(gatewayStateDirectory(stateDir, origin), Date.now, async () => {
13733
+ const identity = await account?.identity();
13734
+ if (identity?.signedIn === true && identity.userId !== void 0) return `${origin}\nuser:${identity.userId}`;
13735
+ });
11368
13736
  const tracker = new TaskTracker({
11369
13737
  http,
11370
13738
  store,
11371
13739
  log: warn,
11372
- onFinished: spent
13740
+ onFinished: spent,
13741
+ resendWindowMs: config.resendWindowMs,
13742
+ submitAttempts: config.submitAttempts,
13743
+ reconcileAttempts: config.reconcileAttempts
11373
13744
  });
11374
13745
  const slots = {
11375
13746
  image: config.imageModel,
@@ -11405,7 +13776,20 @@ function apply(ctx, config) {
11405
13776
  mediaTasksTool(runtime),
11406
13777
  mediaAccountTool(runtime, chain, login)
11407
13778
  ]) ctx.tools.register(tool);
11408
- ctx.effect(() => ctx.provide("vibedevMedia", new MediaHostService(runtime, version)), "dsh-vibedev: media host service");
13779
+ ctx.effect(() => ctx.provide("vibedevMedia", new MediaHostService(runtime, version, {
13780
+ account: async () => {
13781
+ const identity = await account?.identity();
13782
+ const snapshot = await account?.view();
13783
+ return {
13784
+ gatewayOrigin: origin,
13785
+ signedIn: identity?.signedIn === true,
13786
+ ...identity?.signedIn !== true || identity.userId === void 0 ? {} : { userId: identity.userId },
13787
+ ...snapshot === void 0 ? {} : { revision: String(snapshot.revision) }
13788
+ };
13789
+ },
13790
+ open: (page) => account?.openAccountCenter(page),
13791
+ refresh: spent
13792
+ })), "dsh-vibedev: media host service");
11409
13793
  const prompt = ctx.get("systemPrompt");
11410
13794
  if (prompt !== void 0) prompt.section({
11411
13795
  name: "tool:dsh-vibedev",
@@ -11449,6 +13833,13 @@ function apply(ctx, config) {
11449
13833
  chain,
11450
13834
  login,
11451
13835
  primary: config.primary,
13836
+ identityAvailable: () => {
13837
+ tracker.resume().catch(() => void 0);
13838
+ },
13839
+ identityInvalidated: () => {
13840
+ store.invalidateScope();
13841
+ http.invalidateAccountSnapshots();
13842
+ },
11452
13843
  models: () => ({
11453
13844
  count: route?.models().length ?? 0,
11454
13845
  ...route?.hidden() === void 0 ? {} : { hidden: route.hidden() }
@@ -11461,7 +13852,11 @@ function apply(ctx, config) {
11461
13852
  userAgent
11462
13853
  });
11463
13854
  ctx.inject(["connection"], (scoped) => {
11464
- for (const accountRoute of [...accountRoutes(accountService), ...latencyRoutes(latency)]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
13855
+ for (const accountRoute of [
13856
+ ...accountRoutes(accountService),
13857
+ ...accountCenterRoutes(http, accountService),
13858
+ ...latencyRoutes(latency)
13859
+ ]) scoped.effect(() => scoped.connection.fetch.register(accountRoute), `dsh-vibedev: ${accountRoute.path}`);
11465
13860
  });
11466
13861
  const feedback = installFeedback(ctx, {
11467
13862
  gateway: {
@@ -11482,12 +13877,13 @@ function apply(ctx, config) {
11482
13877
  const unsubscribe = login.onChange(() => {
11483
13878
  runtime.invalidateCatalog();
11484
13879
  accountService.credentialChanged();
13880
+ tracker.resume().catch(() => void 0);
11485
13881
  });
11486
- return () => {
13882
+ return async () => {
11487
13883
  unsubscribe();
11488
13884
  accountService.dispose();
11489
- tracker.dispose();
11490
13885
  login.dispose();
13886
+ await tracker.dispose();
11491
13887
  };
11492
13888
  }, "dsh-vibedev: tasks and sign-in");
11493
13889
  ctx.inject(["deepseekAccount"], (accountCtx) => {