@kenz1117/dsh-ui-usage-billing 1.8.2 → 1.8.3-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -529,8 +529,16 @@ function extraModelByKey() {
529
529
  * - 剥离组织前缀(`deepseek/deepseek-v4-flash` → `deepseek-v4-flash`);
530
530
  * - 剥离尾部纯数字段(`deepseek-v4-flash-202605` / `-0731` → `deepseek-v4-flash`,
531
531
  * 覆盖 TokenHub / 官方按日期滚动的快照 id);
532
+ * - 剥离冒号分段:中转站路由前缀(`cn:deepseek-v4.1-flash` → `deepseek-v4.1-flash`)与
533
+ * 变体后缀(`deepseek-v4.1-flash:fast` → `deepseek-v4.1-flash`)——中转站
534
+ * 常按线路给模型加前缀(cn:/us:),网关常加变体后缀(:free / :1017),
535
+ * 这些形态此前一律落「未收录」记 0(issue #125);
532
536
  * - 两者组合派生。目录键本身(如 `mistral-large-2512`、`command-a-03-2025`)
533
537
  * 在直接查就已命中,永不进入派生分支,不受剥段影响。
538
+ *
539
+ * 口径纪律:候选必须**原样**命中目录键(精确别名或归一化索引)才算数——剥段
540
+ * 只是找同一模型的另一种写法,不做「相近即认」的模糊猜测;剥完仍未命中就
541
+ * 保持原 id(回退 other,不计费)。
534
542
  */
535
543
  function derivedKeyCandidates(id) {
536
544
  const out = [];
@@ -552,6 +560,19 @@ function derivedKeyCandidates(id) {
552
560
  push(bare);
553
561
  stripTrailingDigits(bare);
554
562
  }
563
+ const segments = id.split(/[::]/u);
564
+ if (segments.length > 1) {
565
+ for (let i = 1; i < segments.length; i += 1) {
566
+ const tail = segments.slice(i).join(":");
567
+ push(tail);
568
+ stripTrailingDigits(tail);
569
+ }
570
+ for (let i = 0; i < segments.length - 1; i += 1) {
571
+ const head = segments.slice(i, segments.length - 1).join(":");
572
+ push(head);
573
+ stripTrailingDigits(head);
574
+ }
575
+ }
555
576
  stripTrailingDigits(id);
556
577
  return out;
557
578
  }
@@ -604,13 +625,15 @@ function modelOf(key) {
604
625
  const live = livePriceOf(resolved);
605
626
  if (live === void 0) return base;
606
627
  if (base.price.offPeak !== void 0) return base;
628
+ const cacheWrite = base.price.cacheWrite !== void 0 && base.price.input > 0 ? live.input * (base.price.cacheWrite / base.price.input) : void 0;
607
629
  return {
608
630
  ...base,
609
631
  price: {
610
632
  currency: "USD",
611
633
  input: live.input,
612
634
  cacheHit: live.cacheHit,
613
- output: live.output
635
+ output: live.output,
636
+ ...cacheWrite !== void 0 ? { cacheWrite } : {}
614
637
  }
615
638
  };
616
639
  }
@@ -625,7 +648,8 @@ function extraEntryOf(extra) {
625
648
  currency: "USD",
626
649
  input: extra.price.input,
627
650
  cacheHit: extra.price.cacheHit,
628
- output: extra.price.output
651
+ output: extra.price.output,
652
+ ...extra.price.cacheWrite !== void 0 ? { cacheWrite: extra.price.cacheWrite } : {}
629
653
  }
630
654
  };
631
655
  }
@@ -641,14 +665,16 @@ function isPriced(key) {
641
665
  }
642
666
  /**
643
667
  * 促销在 nowMs 是否生效:factor 必须落在 [0,1) 区间(0 = 活动期免费,issue #86),
644
- * 截止时刻及之后视为过期;endsAtMs 缺省表示长期活动,在 factor 合法期间持续生效。
668
+ * 截止时刻及之后视为过期;endsAtMs 缺省表示长期活动,在 factor 合法期间持续生效;
669
+ * startsAtMs 给出时,该时刻之前尚未开始(按刊例价计,不套折扣)。
645
670
  * 导出供测试:纯函数。
646
671
  * @param promo - 待判定的促销窗口。
647
672
  * @param nowMs - 判定时刻(epoch ms)。
648
673
  */
649
674
  function isPromoActive(promo, nowMs) {
650
675
  const expired = promo.endsAtMs !== void 0 && nowMs >= promo.endsAtMs;
651
- return Number.isFinite(nowMs) && !expired && promo.factor >= 0 && promo.factor < 1;
676
+ const notStarted = promo.startsAtMs !== void 0 && nowMs < promo.startsAtMs;
677
+ return Number.isFinite(nowMs) && !expired && !notStarted && promo.factor >= 0 && promo.factor < 1;
652
678
  }
653
679
  /**
654
680
  * 把限时促销折入条目单价:生效期内返回 price 主档与 offPeak 逐档乘折扣系数的
@@ -669,6 +695,7 @@ function applyPromo(entry, nowMs) {
669
695
  input: band.input * factorOf("input"),
670
696
  cacheHit: band.cacheHit * factorOf("cacheHit"),
671
697
  ...band.cacheMiss !== void 0 ? { cacheMiss: band.cacheMiss * factorOf("cacheMiss") } : {},
698
+ ...band.cacheWrite !== void 0 ? { cacheWrite: band.cacheWrite * factorOf("cacheWrite") } : {},
672
699
  output: band.output * factorOf("output")
673
700
  });
674
701
  return {
@@ -687,11 +714,18 @@ function applyPromo(entry, nowMs) {
687
714
  * Providers that report only disjoint buckets carry `cacheMiss` explicitly;
688
715
  * otherwise the miss share is derived as `input - cacheHit`. Only USD-priced
689
716
  * bands go through the exchange rate.
717
+ *
718
+ * 缓存写入单列(issue #123):`cacheWrite` 是 `cacheMiss` 的子集,厂商对它
719
+ * 单独计价(`band.cacheWrite`,缺省按输入价)。拆分后普通未命中按
720
+ * `band.cacheMiss ?? band.input`、缓存写入按 `band.cacheWrite ?? band.input`
721
+ * ——`cacheWrite` 缺省时两者同价,与旧口径逐字一致。
690
722
  */
691
723
  function priceBandCost(band, buckets, currency) {
692
- const miss = buckets.cacheMiss > 0 ? buckets.cacheMiss : Math.max(0, buckets.input - buckets.cacheHit);
724
+ const missTotal = buckets.cacheMiss > 0 ? buckets.cacheMiss : Math.max(0, buckets.input - buckets.cacheHit);
725
+ const write = Math.min(buckets.cacheWrite ?? 0, missTotal);
726
+ const miss = missTotal - write;
693
727
  const hit = Math.min(buckets.cacheHit, buckets.input);
694
- const raw = (miss * (band.cacheMiss ?? band.input) + hit * band.cacheHit + buckets.output * band.output) / 1e6;
728
+ const raw = (miss * (band.cacheMiss ?? band.input) + write * (band.cacheWrite ?? band.input) + hit * band.cacheHit + buckets.output * band.output) / 1e6;
695
729
  return currency === "USD" ? raw * currentRate() : raw;
696
730
  }
697
731
  /**
@@ -802,6 +836,14 @@ function formatTokens(value) {
802
836
  * (models.dev 的 -cn 目录),该目录缺项时按 USD 价 × 汇率折算。既有条目一律
803
837
  * 不动——存量价格的更正走独立的调价节点,不与扩容混在一起。
804
838
  *
839
+ * 2026-11-04 扩容:补录腾讯混元 TokenHub 官方在售的 6 条新条目——Hy4 正式版
840
+ * (2026-11-03 上线,刊例价 ¥6/¥0.3/¥18,与 Preview 同价;官方同期公布「按
841
+ * 目录价格 5 折结算至 2026-12-31 23:59:59(北京时间)」的限时折扣,按 promo
842
+ * 建模:刊例价留在 price 表,折扣只在计价/显示出口折算)与混元 MT2-Pro/Plus/
843
+ * Lite、Role-Latest/Role 两个系列(翻译与角色扮演专用模型,无缓存命中档)。
844
+ * 价源 = 腾讯云 TokenHub「模型价格」页(2026-11-04 更新)的官方 CN 价。
845
+ * Hy4 preview 条目与其价格一律不动——同 id 不同模型的收录不构成调价。
846
+ *
805
847
  * Time-of-day billing (peak/off-peak) is now real: DeepSeek V4 officially
806
848
  * splits peak (09:00-12:00 / 14:00-18:00 Beijing) at 2x the off-peak rate
807
849
  * from 2026-08-17, and Gemini's Flex tier discounts spare-capacity traffic.
@@ -809,6 +851,56 @@ function formatTokens(value) {
809
851
  /** DeepSeek 官方高峰时段说明(峰谷分时计费目录条目共用)。 */
810
852
  const DEEPSEEK_PEAK_HOURS = "09:00-12:00 / 14:00-18:00";
811
853
  const GEMINI_PEAK_HOURS = "Standard / Flex";
854
+ /**
855
+ * 厂商「缓存写入」加价系数(issue #123):厂商对「把内容写入缓存」按输入价的
856
+ * 倍数单独计费,models.dev 原生字段 `cache_write` 即该倍率。
857
+ * 2026-11-14 核对 models.dev 实时目录:OpenAI 11/11 恒为 125%、Anthropic 18/18
858
+ * 恒为 125%、百炼(阿里通义)约 125%(`qwen3.8-flash` 例外 156%)。
859
+ * 未列的厂商不落数值 → 缓存写入按输入价计(DeepSeek、月之暗面等本就不单列
860
+ * 缓存写入费,与旧口径逐字一致;MiniMax 高速档倍率不恒定,故不给规则)。
861
+ */
862
+ const CACHE_WRITE_FACTORS = {
863
+ "OpenAI": 1.25,
864
+ "Anthropic": 1.25,
865
+ "阿里通义": 1.25
866
+ };
867
+ /** 条目内官方「显式缓存创建」价(extraRows 行标签)——厂商公布的缓存写入单价。 */
868
+ const CACHE_WRITE_ROW_LABEL = "显式缓存创建";
869
+ /** 单价取整到 6 位小数:消除浮点乘法的尾数噪声(0.3 × 1.25 = 0.375 而非 0.37499…)。 */
870
+ function roundUnitPrice(value) {
871
+ return Number(value.toFixed(6));
872
+ }
873
+ /**
874
+ * 给目录条目补出缓存写入单价(issue #123):条目自带官方「显式缓存创建」价时
875
+ * 以官方值为准(百炼各档比例不恒定),否则按厂商加价系数从输入价派生;
876
+ * 两者皆无 → 不落该字段,计价回退按输入价(与旧口径一致)。
877
+ * 只动主档:分时计价(offPeak)目前只有 DeepSeek,其缓存写入本就按输入价。
878
+ */
879
+ function withCacheWritePrice(entry) {
880
+ if (entry.price.cacheWrite !== void 0) return entry;
881
+ const official = entry.extraRows?.find((row) => row.label === CACHE_WRITE_ROW_LABEL)?.input;
882
+ if (official !== void 0 && official > 0) return {
883
+ ...entry,
884
+ price: {
885
+ ...entry.price,
886
+ cacheWrite: official
887
+ }
888
+ };
889
+ const factor = CACHE_WRITE_FACTORS[entry.provider];
890
+ if (factor === void 0 || !(entry.price.input > 0)) return entry;
891
+ return {
892
+ ...entry,
893
+ price: {
894
+ ...entry.price,
895
+ cacheWrite: roundUnitPrice(entry.price.input * factor)
896
+ }
897
+ };
898
+ }
899
+ /**
900
+ * 内置计费目录(导出态):在原始条目上派生缓存写入单价(issue #123),
901
+ * 使「缓存写入」成为独立计价维度——厂商对写入缓存单独计价时(OpenAI/
902
+ * Anthropic/百炼),缓存写入 token 不再按普通输入价估算。
903
+ */
812
904
  const BUILTIN_MODEL_CATALOG = [
813
905
  {
814
906
  key: "flash",
@@ -1548,6 +1640,84 @@ const BUILTIN_MODEL_CATALOG = [
1548
1640
  output: 18
1549
1641
  }
1550
1642
  },
1643
+ {
1644
+ key: "hunyuan-hy4",
1645
+ name: "混元 Hy4",
1646
+ provider: "腾讯混元",
1647
+ colorVar: "dsw-static-amber-400",
1648
+ price: {
1649
+ currency: "CNY",
1650
+ input: 6,
1651
+ cacheHit: .3,
1652
+ output: 18
1653
+ },
1654
+ promo: {
1655
+ factor: .5,
1656
+ startsAtMs: Date.UTC(2026, 10, 2, 16, 0, 0),
1657
+ endsAtMs: Date.UTC(2026, 11, 31, 15, 59, 59),
1658
+ note: "限时 5 折至 2026-12-31"
1659
+ }
1660
+ },
1661
+ {
1662
+ key: "hy-mt2-pro",
1663
+ name: "混元 MT2-Pro",
1664
+ provider: "腾讯混元",
1665
+ colorVar: "dsw-static-amber-300",
1666
+ price: {
1667
+ currency: "CNY",
1668
+ input: .5,
1669
+ cacheHit: 0,
1670
+ output: 2
1671
+ }
1672
+ },
1673
+ {
1674
+ key: "hy-mt2-plus",
1675
+ name: "混元 MT2-Plus",
1676
+ provider: "腾讯混元",
1677
+ colorVar: "dsw-static-amber-300",
1678
+ price: {
1679
+ currency: "CNY",
1680
+ input: .5,
1681
+ cacheHit: 0,
1682
+ output: 2
1683
+ }
1684
+ },
1685
+ {
1686
+ key: "hy-mt2-lite",
1687
+ name: "混元 MT2-Lite",
1688
+ provider: "腾讯混元",
1689
+ colorVar: "dsw-static-amber-300",
1690
+ price: {
1691
+ currency: "CNY",
1692
+ input: .3,
1693
+ cacheHit: 0,
1694
+ output: 1.2
1695
+ }
1696
+ },
1697
+ {
1698
+ key: "hunyuan-role-latest",
1699
+ name: "混元 Role-Latest",
1700
+ provider: "腾讯混元",
1701
+ colorVar: "dsw-static-amber-300",
1702
+ price: {
1703
+ currency: "CNY",
1704
+ input: 2.4,
1705
+ cacheHit: 0,
1706
+ output: 9.6
1707
+ }
1708
+ },
1709
+ {
1710
+ key: "hy-role",
1711
+ name: "混元 Role",
1712
+ provider: "腾讯混元",
1713
+ colorVar: "dsw-static-amber-300",
1714
+ price: {
1715
+ currency: "CNY",
1716
+ input: 2.4,
1717
+ cacheHit: 0,
1718
+ output: 9.6
1719
+ }
1720
+ },
1551
1721
  {
1552
1722
  key: "hunyuan-t1",
1553
1723
  name: "混元 T1",
@@ -3936,7 +4106,7 @@ const BUILTIN_MODEL_CATALOG = [
3936
4106
  output: 0
3937
4107
  }
3938
4108
  }
3939
- ];
4109
+ ].map(withCacheWritePrice);
3940
4110
  /**
3941
4111
  * 真实 provider model id → 计费目录键(`MODEL_CATALOG[].key`)的映射。未知 id
3942
4112
  * 原样保留并落回 `other`(未知模型不估算费用)。聚合层(aggregate.ts)在折叠时
@@ -3967,6 +4137,7 @@ const BUILTIN_MODEL_KEY_ALIASES = {
3967
4137
  "deepseek-v4-flash": "flash",
3968
4138
  "deepseek-v4-flash-vision-exp": "flash-vision-exp",
3969
4139
  "deepseek-v4.1-flash": "flash",
4140
+ "deepseek-v4.1": "flash",
3970
4141
  "deepseek-v4.1-flash-expires-on-0910": "flash",
3971
4142
  "deepseek-flash": "flash",
3972
4143
  "deepseek-v4.1-flash-1017": "flash",
@@ -4024,10 +4195,10 @@ const BUILTIN_MODEL_KEY_ALIASES = {
4024
4195
  "command-r-08-2024": "command-r-08-2024",
4025
4196
  "command-r": "command-r-08-2024",
4026
4197
  "hy3": "hunyuan",
4198
+ "hy4": "hunyuan-hy4",
4199
+ "hunyuan-hy4": "hunyuan-hy4",
4027
4200
  "hy4-preview": "hunyuan-hy4-preview",
4028
- "hy4": "hunyuan-hy4-preview",
4029
4201
  "hunyuan-hy4-preview": "hunyuan-hy4-preview",
4030
- "hunyuan-hy4": "hunyuan-hy4-preview",
4031
4202
  "longcat-2.0": "longcat-2.0",
4032
4203
  "longcat-2": "longcat-2.0",
4033
4204
  "minicpm-v-4.5": "minicpm-v-4.5",
@@ -4332,14 +4503,15 @@ function emptyUsage() {
4332
4503
  */
4333
4504
  function foldUsage(acc, usage, key, subscription, timeMs, official = false, pricedCost, unverifiedChannel = false) {
4334
4505
  const cacheHit = usage.cacheReadTokens ?? 0;
4335
- const cacheMiss = usage.inputTokens + (usage.cacheWriteTokens ?? 0);
4506
+ const cacheWrite = usage.cacheWriteTokens ?? 0;
4507
+ const cacheMiss = usage.inputTokens + cacheWrite;
4336
4508
  acc.calls += 1;
4337
- acc.input += usage.inputTokens + cacheHit + (usage.cacheWriteTokens ?? 0);
4509
+ acc.input += usage.inputTokens + cacheHit + cacheWrite;
4338
4510
  acc.output += usage.outputTokens;
4339
4511
  acc.reasoning += usage.reasoningTokens ?? 0;
4340
4512
  acc.cacheHit += cacheHit;
4341
4513
  acc.cacheMiss += cacheMiss;
4342
- if ((usage.cacheWriteTokens ?? 0) > 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + (usage.cacheWriteTokens ?? 0);
4514
+ if (cacheWrite > 0) acc.cacheWrite = (acc.cacheWrite ?? 0) + cacheWrite;
4343
4515
  if (official) acc.officialCalls += 1;
4344
4516
  if (pricedCost !== void 0) {
4345
4517
  acc.cost += pricedCost;
@@ -4351,6 +4523,7 @@ function foldUsage(acc, usage, key, subscription, timeMs, official = false, pric
4351
4523
  input: cacheHit + cacheMiss,
4352
4524
  cacheHit,
4353
4525
  cacheMiss,
4526
+ cacheWrite,
4354
4527
  output: usage.outputTokens
4355
4528
  }, timeMs);
4356
4529
  acc.cost += thisCost;
@@ -4358,6 +4531,54 @@ function foldUsage(acc, usage, key, subscription, timeMs, official = false, pric
4358
4531
  }
4359
4532
  }
4360
4533
  /**
4534
+ * 折叠一次模型调用:token 分桶 + 计价 + 订阅/官方标记 + 角色归因。
4535
+ *
4536
+ * `assistant/message`(对话主循环)与 `compaction/summary`(上下文压缩摘要,
4537
+ * issue #123)都是真实的模型调用——后者是宿主落盘的压缩摘要事件,自带
4538
+ * `provider`/`model`/`usage`,此前整段被跳过,压缩调用的次数与费用零计入。
4539
+ * 两者共用本函数,保证计费口径逐字一致。
4540
+ * @returns 本次调用的目录条目与费用(未计价时为 undefined)。
4541
+ */
4542
+ function foldModelCall(ctx) {
4543
+ const { fold, usage, modelKey, subscription, official, siteBucket, unverifiedChannel, timeMs, day } = ctx;
4544
+ const priced = !subscription && !unverifiedChannel && isPriced(modelKey);
4545
+ if (!subscription && !isPriced(modelKey)) fold.unpricedModels.add(modelKey);
4546
+ const entry = modelOf(modelKey);
4547
+ const thisCost = priced ? computeCostAt(entry, {
4548
+ input: (usage.cacheReadTokens ?? 0) + usage.inputTokens + (usage.cacheWriteTokens ?? 0),
4549
+ cacheHit: usage.cacheReadTokens ?? 0,
4550
+ cacheMiss: usage.inputTokens + (usage.cacheWriteTokens ?? 0),
4551
+ cacheWrite: usage.cacheWriteTokens ?? 0,
4552
+ output: usage.outputTokens
4553
+ }, timeMs) : void 0;
4554
+ foldUsage(fold.total, usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4555
+ foldUsage(usageCell(fold.byModel, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4556
+ foldUsage(usageCell(fold.byDay, day), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4557
+ foldUsage(modelDayCell(fold.byDayModels, day, modelKey), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4558
+ foldUsage(modelDaySiteCell(fold.byDayModelsSite, day, modelKey, siteBucket), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4559
+ foldUsage(usageCell(fold.bySite, siteBucket), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4560
+ if (entry.tierSemantics !== "latency") foldUsage(usageCell(fold.byTier, tierAt(timeMs)), usage, modelKey, subscription, timeMs, official, thisCost, unverifiedChannel);
4561
+ if (subscription) fold.planCalls.set(modelKey, (fold.planCalls.get(modelKey) ?? 0) + 1);
4562
+ if (subscription) {
4563
+ const sitePlanKey = planSiteKey(day, modelKey, siteBucket);
4564
+ fold.planSiteCalls.set(sitePlanKey, (fold.planSiteCalls.get(sitePlanKey) ?? 0) + 1);
4565
+ }
4566
+ if (thisCost !== void 0 && entry !== void 0) {
4567
+ const outputCost = computeCostAt(entry, {
4568
+ input: 0,
4569
+ cacheHit: 0,
4570
+ cacheMiss: 0,
4571
+ output: usage.outputTokens
4572
+ }, timeMs);
4573
+ fold.roles.outputCost += outputCost;
4574
+ fold.roles.inputCost += thisCost - outputCost;
4575
+ }
4576
+ return {
4577
+ entry,
4578
+ cost: thisCost
4579
+ };
4580
+ }
4581
+ /**
4361
4582
  * Fold one auxiliary web-search LLM request (issue #15) into an accumulator.
4362
4583
  * 这类调用绕过对话通道直连官方端点,日志只记请求(无响应/用量事件),token
4363
4584
  * 不可知:按「每次估值」计入费用并单独累计 `searchCalls`,不产生 token 维度。
@@ -4989,6 +5210,30 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
4989
5210
  }
4990
5211
  continue;
4991
5212
  }
5213
+ if (event.type === "compaction/summary") {
5214
+ const data = event.data;
5215
+ const compactionUsage = data.usage;
5216
+ if (compactionUsage === void 0) continue;
5217
+ if (typeof data.provider !== "string" || typeof data.model !== "string") continue;
5218
+ const provider = routeAliases[data.provider] ?? data.provider;
5219
+ const modelKey = resolveCatalogKey(data.model);
5220
+ const compactionSubscription = isSubscriptionCall(subscriptionProviders, provider);
5221
+ const siteRef = siteRefOf(provider, routes, { subscription: compactionSubscription });
5222
+ const compactionOfficial = officialChannelOf(provider, siteRef, officialProviderIds);
5223
+ const compactionSiteBucket = siteBucketKey(siteRef);
5224
+ foldModelCall({
5225
+ fold,
5226
+ usage: compactionUsage,
5227
+ modelKey,
5228
+ subscription: compactionSubscription,
5229
+ official: compactionOfficial,
5230
+ siteBucket: compactionSiteBucket,
5231
+ unverifiedChannel: compactionSiteBucket === "unknown",
5232
+ timeMs: event.time,
5233
+ day: dayStamp(event.time)
5234
+ });
5235
+ continue;
5236
+ }
4992
5237
  if (event.type !== "assistant/message") continue;
4993
5238
  const usage = event.data.usage;
4994
5239
  if (usage === void 0) continue;
@@ -5003,28 +5248,17 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
5003
5248
  }
5004
5249
  const modelKey = key;
5005
5250
  const day = dayStamp(event.time);
5006
- const unverifiedChannel = siteBucket === "unknown";
5007
- const priced = !subscription && !unverifiedChannel && isPriced(modelKey);
5008
- if (!subscription && !isPriced(modelKey)) fold.unpricedModels.add(modelKey);
5009
- const entry = modelOf(modelKey);
5010
- const thisCost = priced ? computeCostAt(entry, {
5011
- input: (usage.cacheReadTokens ?? 0) + usage.inputTokens + (usage.cacheWriteTokens ?? 0),
5012
- cacheHit: usage.cacheReadTokens ?? 0,
5013
- cacheMiss: usage.inputTokens + (usage.cacheWriteTokens ?? 0),
5014
- output: usage.outputTokens
5015
- }, event.time) : void 0;
5016
- foldUsage(fold.total, usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5017
- foldUsage(usageCell(fold.byModel, modelKey), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5018
- foldUsage(usageCell(fold.byDay, day), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5019
- foldUsage(modelDayCell(fold.byDayModels, day, modelKey), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5020
- foldUsage(modelDaySiteCell(fold.byDayModelsSite, day, modelKey, siteBucket), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5021
- foldUsage(usageCell(fold.bySite, siteBucket), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5022
- if (entry.tierSemantics !== "latency") foldUsage(usageCell(fold.byTier, tierAt(event.time)), usage, modelKey, subscription, event.time, official, thisCost, unverifiedChannel);
5023
- if (subscription) fold.planCalls.set(modelKey, (fold.planCalls.get(modelKey) ?? 0) + 1);
5024
- if (subscription) {
5025
- const sitePlanKey = planSiteKey(day, modelKey, siteBucket);
5026
- fold.planSiteCalls.set(sitePlanKey, (fold.planSiteCalls.get(sitePlanKey) ?? 0) + 1);
5027
- }
5251
+ const { entry, cost: thisCost } = foldModelCall({
5252
+ fold,
5253
+ usage,
5254
+ modelKey,
5255
+ subscription,
5256
+ official,
5257
+ siteBucket,
5258
+ unverifiedChannel: siteBucket === "unknown",
5259
+ timeMs: event.time,
5260
+ day
5261
+ });
5028
5262
  const turn = event.data.turn ?? -1;
5029
5263
  const state = turnState(turns, turn);
5030
5264
  state.model = modelKey;
@@ -5032,17 +5266,7 @@ function foldInto(fold, machine, events, subscriptionProviders, officialProvider
5032
5266
  state.output += usage.outputTokens;
5033
5267
  state.cacheHit += usage.cacheReadTokens ?? 0;
5034
5268
  state.cacheMiss += usage.inputTokens + (usage.cacheWriteTokens ?? 0);
5035
- if (thisCost !== void 0 && entry !== void 0) {
5036
- state.cost += thisCost;
5037
- const outputCost = computeCostAt(entry, {
5038
- input: 0,
5039
- cacheHit: 0,
5040
- cacheMiss: 0,
5041
- output: usage.outputTokens
5042
- }, event.time);
5043
- fold.roles.outputCost += outputCost;
5044
- fold.roles.inputCost += thisCost - outputCost;
5045
- }
5269
+ if (thisCost !== void 0 && entry !== void 0) state.cost += thisCost;
5046
5270
  if (state.startedAt === Number.MAX_SAFE_INTEGER) state.startedAt = event.time;
5047
5271
  const stepNum = event.data.step;
5048
5272
  if (typeof stepNum === "number") {
@@ -5197,6 +5421,28 @@ function configFingerprint(subscriptionMatcher, officialProviderIds, routeAliase
5197
5421
  origins
5198
5422
  ].join("|");
5199
5423
  }
5424
+ /** 失败原因摘要:给文档与日志用的短文本(截断,避免超长路径撑爆响应体)。
5425
+ * Error 取 message;非 Error 取字符串化值。截断上限与 task-queue 路由一致(300)。 */
5426
+ function reasonOf(error) {
5427
+ const trimmed = (error instanceof Error ? error.message : String(error)).trim();
5428
+ return trimmed.length > 300 ? `${trimmed.slice(0, 300)}…` : trimmed;
5429
+ }
5430
+ /**
5431
+ * 会话列表整体读不到(issue #119):宿主持久化后端整体故障,或会话目录里有
5432
+ * 读不了/对不上的日志。聚合无法枚举会话,只能降级到持久账本或磁盘快照——
5433
+ * 但「降级」必须让用户看得见,否则新装用户看到的是一片 ¥0(分不清没花钱
5434
+ * 还是没读到)。携带原因随文档下发,客户端据此显示「读取失败」。
5435
+ */
5436
+ var SessionListUnavailableError = class extends Error {
5437
+ /** 失败原因摘要(面向用户的中文/英文提示语,由调用方决定措辞)。 */
5438
+ reason;
5439
+ constructor(reason, cause) {
5440
+ super(`session list unavailable: ${reason}`);
5441
+ this.name = "SessionListUnavailableError";
5442
+ this.reason = reason;
5443
+ if (cause !== void 0) this.cause = cause;
5444
+ }
5445
+ };
5200
5446
  /** 会话格式拒读(宿主 SessionFormatUnsupportedError):日志完好,仅本构建读不了。
5201
5447
  * 宿主错误类显式落 error.name;经包装/重建的路径只在 message 里保留类名,两处都认。
5202
5448
  * 据此把「格式不受支持」与「损坏/其他读取失败」分开计数,供面板按原因归因(issue #84)。 */
@@ -5273,7 +5519,7 @@ function createUsageAggregator(persistence, options = {}) {
5273
5519
  ...cwd === void 0 ? {} : { cwd },
5274
5520
  ...subOf === void 0 ? {} : { subOf },
5275
5521
  ...stamp === null ? {} : { stamp },
5276
- foldVersion: 23,
5522
+ foldVersion: 24,
5277
5523
  fingerprint: foldFingerprint,
5278
5524
  foldedAt: Date.now(),
5279
5525
  fold: serializeFold(fold)
@@ -5366,13 +5612,16 @@ function createUsageAggregator(persistence, options = {}) {
5366
5612
  let formatUnreadable = 0;
5367
5613
  let noLedgerUnreadable = 0;
5368
5614
  let staleLedgerSessions = 0;
5615
+ let sessionListError;
5369
5616
  if (mode === "full") {
5370
5617
  let metas;
5371
5618
  try {
5372
5619
  metas = await persistence.list();
5373
5620
  } catch (error) {
5374
- if (options.ledger === void 0 || ledger.size === 0) throw error;
5621
+ const reason = reasonOf(error);
5622
+ sessionListError = reason;
5375
5623
  console.warn("[usage-billing] session list unavailable; serving durable usage ledger:", error);
5624
+ if (options.ledger === void 0 || ledger.size === 0) throw new SessionListUnavailableError(reason, error);
5376
5625
  metas = [];
5377
5626
  }
5378
5627
  let sliceAt = Date.now();
@@ -5397,7 +5646,7 @@ function createUsageAggregator(persistence, options = {}) {
5397
5646
  const cwd = meta.cwd;
5398
5647
  const subOf = subParentOf(meta);
5399
5648
  const ledgerRow = ledger.get(id);
5400
- if (ledgerRow !== void 0 && ledgerRow.stamp !== void 0 && stamp !== null && ledgerRow.stamp === stamp && (ledgerRow.foldVersion ?? 1) === 23 && ledgerRow.fingerprint === foldFingerprint && !foldNeedsReprice(ledgerRow.fold)) {
5649
+ if (ledgerRow !== void 0 && ledgerRow.stamp !== void 0 && stamp !== null && ledgerRow.stamp === stamp && (ledgerRow.foldVersion ?? 1) === 24 && ledgerRow.fingerprint === foldFingerprint && !foldNeedsReprice(ledgerRow.fold)) {
5401
5650
  const fold = deserializedFoldOf(ledgerRow.fold);
5402
5651
  folds.push({
5403
5652
  id,
@@ -5526,7 +5775,7 @@ function createUsageAggregator(persistence, options = {}) {
5526
5775
  }
5527
5776
  if (included.has(entry.id)) continue;
5528
5777
  try {
5529
- const stale = (entry.foldVersion ?? 1) < 23 || entry.fingerprint !== foldFingerprint;
5778
+ const stale = (entry.foldVersion ?? 1) < 24 || entry.fingerprint !== foldFingerprint;
5530
5779
  const fold = deserializedFoldOf(entry.fold);
5531
5780
  const hint = titleHints.get(entry.id);
5532
5781
  folds.push({
@@ -5736,7 +5985,8 @@ function createUsageAggregator(persistence, options = {}) {
5736
5985
  tool: roles.inputCost * (1 - userShare)
5737
5986
  };
5738
5987
  })(),
5739
- ...mode === "ledger-only" ? { staleSnapshot: true } : {}
5988
+ ...mode === "ledger-only" ? { staleSnapshot: true } : {},
5989
+ ...sessionListError === void 0 ? {} : { sessionListError }
5740
5990
  };
5741
5991
  if (mode === "full") {
5742
5992
  lastDoc = document;
@@ -7365,6 +7615,7 @@ function buildExtraModels(data) {
7365
7615
  if (input === void 0 || output === void 0) continue;
7366
7616
  const declaredCacheRead = asPrice(cost.cache_read);
7367
7617
  const cacheRead = declaredCacheRead ?? input * .1;
7618
+ const declaredCacheWrite = asPrice(cost.cache_write);
7368
7619
  const name = modelDoc.name;
7369
7620
  const familyValue = modelDoc.family;
7370
7621
  const family = typeof familyValue === "string" && familyValue !== "" ? familyValue : void 0;
@@ -7392,7 +7643,8 @@ function buildExtraModels(data) {
7392
7643
  price: {
7393
7644
  input,
7394
7645
  cacheHit: cacheRead,
7395
- output
7646
+ output,
7647
+ ...declaredCacheWrite !== void 0 ? { cacheWrite: declaredCacheWrite } : {}
7396
7648
  }
7397
7649
  },
7398
7650
  input,
@@ -9354,6 +9606,7 @@ function registerUsageStatsRoute(ctx, deps) {
9354
9606
  deps.persistSnapshot(decorate(stats));
9355
9607
  }, () => {});
9356
9608
  let fresh;
9609
+ let sessionListError;
9357
9610
  try {
9358
9611
  fresh = await Promise.race([aggregating.then((stats) => stats), new Promise((resolve) => {
9359
9612
  setTimeout(() => {
@@ -9362,16 +9615,19 @@ function registerUsageStatsRoute(ctx, deps) {
9362
9615
  })]);
9363
9616
  } catch (error) {
9364
9617
  console.error("[usage-billing] usage-stats aggregate failed, falling back to snapshot:", error);
9618
+ if (error instanceof SessionListUnavailableError) sessionListError = error.reason;
9365
9619
  }
9366
9620
  if (fresh !== void 0) {
9367
9621
  res.end(statsBodyOf(fresh));
9368
9622
  return;
9369
9623
  }
9624
+ const degraded = sessionListError === void 0 ? {} : { sessionListError };
9370
9625
  const recent = deps.lastDoc?.();
9371
9626
  if (recent !== void 0) {
9372
9627
  res.end(JSON.stringify({
9373
9628
  ...decorate(recent),
9374
- staleSnapshot: true
9629
+ staleSnapshot: true,
9630
+ ...degraded
9375
9631
  }));
9376
9632
  return;
9377
9633
  }
@@ -9380,11 +9636,15 @@ function registerUsageStatsRoute(ctx, deps) {
9380
9636
  if (doc === null) continue;
9381
9637
  res.end(JSON.stringify({
9382
9638
  ...decorate(doc),
9383
- staleSnapshot: true
9639
+ staleSnapshot: true,
9640
+ ...degraded
9384
9641
  }));
9385
9642
  return;
9386
9643
  }
9387
- res.end(JSON.stringify({ error: "usage stats unavailable" }));
9644
+ res.end(JSON.stringify({
9645
+ error: "usage stats unavailable",
9646
+ ...degraded
9647
+ }));
9388
9648
  }
9389
9649
  }), "usage-billing: usage-stats route");
9390
9650
  }
@@ -9402,6 +9662,15 @@ const QUEUE_VERSION = 1;
9402
9662
  const MAX_TASKS = 100;
9403
9663
  const MAX_QUEUED = 50;
9404
9664
  const MAX_PROMPT_LENGTH = 32e3;
9665
+ /** 会话 id 长度上限(宿主的 id 是 uuid;超长的入参一律当作没有来源会话)。 */
9666
+ const MAX_SESSION_ID_LENGTH = 200;
9667
+ /** 会话列表读面的超时(毫秒):拿不到就降级新建会话,不让队列卡住。 */
9668
+ const SESSION_LIST_TIMEOUT_MS = 1e4;
9669
+ /** 目录是否落在某个项目内(相等或为其子目录)。 */
9670
+ function isInsideDirectory(cwd, project) {
9671
+ if (project === "") return false;
9672
+ return cwd === project || cwd.startsWith(`${project}/`);
9673
+ }
9405
9674
  const LOCK_WAIT_MS = 5e3;
9406
9675
  const LEASE_MS = 45e3;
9407
9676
  const HEARTBEAT_MS = 15e3;
@@ -9429,7 +9698,7 @@ function validStoredTask(value) {
9429
9698
  "running",
9430
9699
  "completed",
9431
9700
  "failed"
9432
- ].includes(task.status ?? "") && (task.sessionId === void 0 || typeof task.sessionId === "string") && (task.owner === void 0 || typeof task.owner === "string") && (task.leaseUntil === void 0 || typeof task.leaseUntil === "number");
9701
+ ].includes(task.status ?? "") && (task.sessionId === void 0 || typeof task.sessionId === "string") && (task.sourceSessionId === void 0 || typeof task.sourceSessionId === "string") && (task.reuseSource === void 0 || typeof task.reuseSource === "boolean") && (task.fallbackReason === void 0 || typeof task.fallbackReason === "string") && (task.owner === void 0 || typeof task.owner === "string") && (task.leaseUntil === void 0 || typeof task.leaseUntil === "number");
9433
9702
  }
9434
9703
  function publicTask(task) {
9435
9704
  const { owner: _owner, leaseUntil: _leaseUntil, ...pub } = task;
@@ -9540,11 +9809,14 @@ var TaskQueueEngine = class {
9540
9809
  if (!workspaces.some((workspace) => workspace.path === cwd)) throw new TaskQueueError("workspace is no longer available", 409);
9541
9810
  if (typeof provider !== "string" || typeof model !== "string") throw new TaskQueueError("model is required");
9542
9811
  if (!models.some((candidate) => candidate.provider === provider && candidate.id === model)) throw new TaskQueueError("select an available DeepSeek time-of-day model", 409);
9812
+ const sourceSessionId = typeof input.sourceSessionId === "string" && input.sourceSessionId.trim() !== "" && input.sourceSessionId.length <= MAX_SESSION_ID_LENGTH ? input.sourceSessionId : void 0;
9543
9813
  return {
9544
9814
  prompt,
9545
9815
  cwd,
9546
9816
  provider,
9547
- model
9817
+ model,
9818
+ sourceSessionId,
9819
+ reuseSource: input.reuseSource === true && sourceSessionId !== void 0
9548
9820
  };
9549
9821
  } catch (error) {
9550
9822
  if (inputs.length > 1 && error instanceof TaskQueueError) throw new TaskQueueError(`task ${String(index + 1)}: ${error.message}`, error.status);
@@ -9679,11 +9951,21 @@ var TaskQueueEngine = class {
9679
9951
  await this.requeue(claimed.id);
9680
9952
  return;
9681
9953
  }
9682
- const { models: availableModels } = await this.modelOptions(controller, true);
9683
- if (!availableModels.some((model) => model.provider === claimed.provider && model.id === claimed.model)) throw new TaskQueueError("the selected official DeepSeek model is no longer available", 409);
9684
- const { sessionId } = await controller.create({ cwd: claimed.cwd });
9685
- if (!await this.patch(claimed.id, { sessionId })) return;
9686
- await controller.selectModel({
9954
+ const reuse = await this.resolveSourceSession(claimed, controller);
9955
+ let sessionId;
9956
+ if (reuse.ok) sessionId = reuse.sessionId;
9957
+ else {
9958
+ if (reuse.reason !== void 0) {
9959
+ if (!await this.patch(claimed.id, { fallbackReason: reuse.reason })) return;
9960
+ }
9961
+ const { models: availableModels } = await this.modelOptions(controller, true);
9962
+ if (!availableModels.some((model) => model.provider === claimed.provider && model.id === claimed.model)) throw new TaskQueueError("the selected official DeepSeek model is no longer available", 409);
9963
+ sessionId = (await this.createGroupedSession(controller, claimed.cwd)).sessionId;
9964
+ }
9965
+ const sessionPatch = { sessionId };
9966
+ if (reuse.ok) sessionPatch.fallbackReason = void 0;
9967
+ if (!await this.patch(claimed.id, sessionPatch)) return;
9968
+ if (!reuse.ok) await controller.selectModel({
9687
9969
  sessionId,
9688
9970
  provider: claimed.provider,
9689
9971
  model: claimed.model
@@ -9722,6 +10004,74 @@ var TaskQueueEngine = class {
9722
10004
  this.taskAbort = void 0;
9723
10005
  }
9724
10006
  }
10007
+ /**
10008
+ * issue #118:判断来源会话能否续跑。不能就给出降级原因(写进卡片)。
10009
+ *
10010
+ * 判据来自 issue 的安全边界:来源会话已删除 / 正在跑别的轮次 / 工作区变了时,
10011
+ * 回退为新建会话,不要往用户正在使用的会话里硬塞一轮。另外子智能体会话与
10012
+ * 归档会话也不能复用——前者归属子智能体路由,后者轮次会以 blocked 结束、
10013
+ * 看起来跑了其实没跑。
10014
+ */
10015
+ async resolveSourceSession(claimed, controller) {
10016
+ if (claimed.reuseSource !== true) return { ok: false };
10017
+ const sourceSessionId = claimed.sourceSessionId;
10018
+ if (sourceSessionId === void 0) return { ok: false };
10019
+ const list = controller.list;
10020
+ if (typeof list !== "function") return {
10021
+ ok: false,
10022
+ reason: "this host cannot inspect Sessions"
10023
+ };
10024
+ let items;
10025
+ try {
10026
+ items = (await list.call(controller, {}, AbortSignal.timeout(SESSION_LIST_TIMEOUT_MS)))?.items ?? [];
10027
+ } catch (error) {
10028
+ return {
10029
+ ok: false,
10030
+ reason: `source session lookup failed: ${messageOf(error)}`
10031
+ };
10032
+ }
10033
+ const summary = items.find((item) => item.sessionId === sourceSessionId);
10034
+ if (summary === void 0) return {
10035
+ ok: false,
10036
+ reason: "source session no longer exists"
10037
+ };
10038
+ if (summary.origin === "subagent") return {
10039
+ ok: false,
10040
+ reason: "source session belongs to a subagent"
10041
+ };
10042
+ const archived = this.options.getWorkspaceContext?.()?.archivedSessionIds;
10043
+ if (archived !== void 0 && archived.includes(sourceSessionId)) return {
10044
+ ok: false,
10045
+ reason: "source session is archived"
10046
+ };
10047
+ if (summary.running === true) return {
10048
+ ok: false,
10049
+ reason: "source session is busy"
10050
+ };
10051
+ const project = typeof summary.cwd === "string" ? summary.cwd : void 0;
10052
+ if (project !== void 0 && !isInsideDirectory(claimed.cwd, project)) return {
10053
+ ok: false,
10054
+ reason: "source session working directory changed"
10055
+ };
10056
+ return {
10057
+ ok: true,
10058
+ sessionId: sourceSessionId
10059
+ };
10060
+ }
10061
+ /**
10062
+ * 新建会话:cwd 恰好等于某个工作区时用 create({ workspaceId }),让宿主把会话挂进
10063
+ * 该工作区——create({ cwd }) 从不归组,这正是队列会话在侧栏里没有分组的原因。
10064
+ * 两者互斥:带 workspaceId 时不能再带 cwd。
10065
+ */
10066
+ async createGroupedSession(controller, cwd) {
10067
+ const workspaceId = this.options.getWorkspaceContext?.()?.workspaceIdOfPath(cwd);
10068
+ if (workspaceId !== void 0) try {
10069
+ return await controller.create({ workspaceId });
10070
+ } catch (error) {
10071
+ console.warn("[usage-billing] task queue workspace Session creation failed:", error);
10072
+ }
10073
+ return await controller.create({ cwd });
10074
+ }
9725
10075
  async watch(frames, requestId) {
9726
10076
  let admitted = false;
9727
10077
  for await (const raw of frames) {
@@ -9759,7 +10109,8 @@ var TaskQueueEngine = class {
9759
10109
  owner: void 0,
9760
10110
  leaseUntil: void 0,
9761
10111
  startedAt: void 0,
9762
- sessionId: void 0
10112
+ sessionId: void 0,
10113
+ fallbackReason: void 0
9763
10114
  });
9764
10115
  }
9765
10116
  async finish(id, status, error) {
@@ -10539,7 +10890,8 @@ function apply(ctx, config = {}) {
10539
10890
  const now = Date.now();
10540
10891
  if (now - lastSnapshotAt < SNAPSHOT_INTERVAL_MS) return;
10541
10892
  lastSnapshotAt = now;
10542
- const payload = JSON.stringify(doc);
10893
+ const { sessionListError: _liveError, ...data } = doc;
10894
+ const payload = JSON.stringify(data);
10543
10895
  (async () => {
10544
10896
  try {
10545
10897
  const existing = await readFile(snapshotPath, "utf8");
@@ -10591,6 +10943,20 @@ function apply(ctx, config = {}) {
10591
10943
  } catch {
10592
10944
  return [];
10593
10945
  }
10946
+ },
10947
+ getWorkspaceContext: () => {
10948
+ try {
10949
+ const registry = ctx.get("workspaceRegistry");
10950
+ if (registry === void 0) return void 0;
10951
+ const byPath = /* @__PURE__ */ new Map();
10952
+ for (const workspace of registry.list?.() ?? []) if (typeof workspace.path === "string" && workspace.path !== "" && typeof workspace.id === "string") byPath.set(workspace.path, workspace.id);
10953
+ return {
10954
+ archivedSessionIds: registry.archivedSessionIds ?? [],
10955
+ workspaceIdOfPath: (path) => byPath.get(path)
10956
+ };
10957
+ } catch {
10958
+ return;
10959
+ }
10594
10960
  }
10595
10961
  });
10596
10962
  registerTaskQueueRoute(ctx, {