dsh-cost-meter 1.9.76 → 1.9.78

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <p align="center">Cost tracking and subscription quotas for DeepSeek Harness</p>
4
4
 
5
5
  <p align="center">
6
- <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.76-4176E6?style=flat-square" alt="version"></a>
6
+ <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.78-4176E6?style=flat-square" alt="version"></a>
7
7
  <a href="https://www.npmjs.com/package/dsh-cost-meter"><img src="https://img.shields.io/npm/dm/dsh-cost-meter?label=downloads&style=flat-square&color=4176E6" alt="npm monthly downloads"></a>
8
8
  <a href="https://github.com/Han-1413141/dsh-cost-meter/stargazers"><img src="https://img.shields.io/github/stars/Han-1413141/dsh-cost-meter?label=stars&style=flat-square&color=D9A400" alt="GitHub stars"></a>
9
9
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="MIT license"></a>
@@ -42,20 +42,20 @@ Restart `dsh web` after installation or updates. **Desktop** uses its bundled CL
42
42
  The PowerShell installer checks pnpm and Git and uses the `web` profile by default:
43
43
 
44
44
  ```powershell
45
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.76/install.ps1 | iex
45
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.78/install.ps1 | iex
46
46
  ```
47
47
 
48
48
  Install a pinned Git tag:
49
49
 
50
50
  ```sh
51
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.76
51
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.78
52
52
  ```
53
53
 
54
54
  See [installation and updates](docs/install.en.md) for uninstalling or installing without Git.
55
55
 
56
56
  </details>
57
57
 
58
- Current release **v1.9.76**: [release notes](docs/release-notes/v1.9.76.md) · [troubleshooting](docs/install-troubleshooting.md)
58
+ Current release **v1.9.78**: [release notes](docs/release-notes/v1.9.78.md) · [troubleshooting](docs/install-troubleshooting.md)
59
59
 
60
60
  ## Feature overview
61
61
 
package/README.zh-CN.md CHANGED
@@ -3,7 +3,7 @@
3
3
  <p align="center">DeepSeek Harness 费用统计与订阅额度插件</p>
4
4
 
5
5
  <p align="center">
6
- <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.76-4176E6?style=flat-square" alt="version"></a>
6
+ <a href="https://github.com/Han-1413141/dsh-cost-meter/releases/latest"><img src="https://img.shields.io/badge/version-1.9.78-4176E6?style=flat-square" alt="version"></a>
7
7
  <a href="https://www.npmjs.com/package/dsh-cost-meter"><img src="https://img.shields.io/npm/dm/dsh-cost-meter?label=downloads&style=flat-square&color=4176E6" alt="npm monthly downloads"></a>
8
8
  <a href="https://github.com/Han-1413141/dsh-cost-meter/stargazers"><img src="https://img.shields.io/github/stars/Han-1413141/dsh-cost-meter?label=stars&style=flat-square&color=D9A400" alt="GitHub stars"></a>
9
9
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green?style=flat-square" alt="MIT license"></a>
@@ -42,20 +42,20 @@ dsh plugin --profile web add dsh-cost-meter
42
42
  PowerShell 脚本自动检查 pnpm 和 Git,默认安装到 `web` Profile:
43
43
 
44
44
  ```powershell
45
- irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.76/install.ps1 | iex
45
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.78/install.ps1 | iex
46
46
  ```
47
47
 
48
48
  固定 Git tag 安装:
49
49
 
50
50
  ```sh
51
- dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.76
51
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.78
52
52
  ```
53
53
 
54
54
  更新、卸载及无 Git 的安装方法见[安装说明](docs/install.md)。
55
55
 
56
56
  </details>
57
57
 
58
- 当前版本 **v1.9.76**:[更新说明](docs/release-notes/v1.9.76.md) · [安装排障](docs/install-troubleshooting.md)
58
+ 当前版本 **v1.9.78**:[更新说明](docs/release-notes/v1.9.78.md) · [安装排障](docs/install-troubleshooting.md)
59
59
 
60
60
  ## 功能总览
61
61
 
@@ -246,3 +246,11 @@ Magpie 的 `/v1/magpie/quotas` 会返回多个 provider 和多个账号;`sum`
246
246
  Magpie 在本机运行(默认 `127.0.0.1:3425`)时无需 API Key;若 Magpie 在其它主机或开启了鉴权,请把 URL 改成实际地址,在请求头加入 `Authorization: Bearer {{MAGPIE_API_KEY}}`,在白名单填写准确的 `主机:端口`,然后在凭据输入框保存该密钥。优先使用 HTTPS;只有访问非回环 HTTP 地址时才勾选「允许非回环 HTTP」。查询只读取 Magpie 已有统计,不发模型请求。
247
247
 
248
248
  该预设不依赖官方 WorkBuddy 桌面登录或 WorkBuddy 连接插件;已经安装 `dsh-magpie-quota` 的用户也可以继续使用那个插件,二者展示互不影响。
249
+
250
+ ## Fireworks.ai
251
+
252
+ 在「费用 → 额度」点击「+ Fireworks.ai」,展开卡片,填写返回剩余余额的完整 HTTPS 地址、对应的允许主机及 JSON 字段。预设使用 USD 和 `FIREWORKS_API_KEY` 凭据,默认允许 `api.fireworks.ai`。自有网关请改用该网关对应的主机和凭据。若接口返回 `{"wallet":{"available":12.5}}`,将解析规则设为 `{"remaining":"wallet.available"}`。启用后可手动刷新,查询成功后在侧栏显示;卡片上的开关控制侧栏可见性。
253
+
254
+ Fireworks 的公开账单摘要提供按时间段统计的费用。插件将余额接口留给用户填写;可直接在 Fireworks 控制台查看预付费余额。[官方账单接口](https://docs.fireworks.ai/api-reference/get-billing-summary) · [预付费说明](https://docs.fireworks.ai/faq-new/billing-pricing/how-does-billing-and-credit-usage-work)
255
+
256
+ In **Cost → Quotas**, add **Fireworks.ai** and configure a trusted HTTPS endpoint returning your remaining balance. Enter its exact allowed hostname and the JSON path for the remaining amount. Save the endpoint credential in DSH, then enable the source. The result shows the balance, its unit and the last successful lookup time. Fireworks' documented billing summary reports spending over a date range. The billing console is available from the card.
@@ -0,0 +1,33 @@
1
+ # Host 动态报价接口
2
+
3
+ 从 v1.9.78 起,Host 插件可在 `costMeter` 服务可用时调用 `registerPriceCalculator`。每个注册项负责一个精确的 `provider` 和 `model` 组合。重复注册会抛出异常。注册方法返回注销函数,可交给 Cordis 管理插件卸载。
4
+
5
+ ```js
6
+ export function apply(ctx) {
7
+ ctx.inject(['costMeter'], scope => scope.effect(() =>
8
+ scope.get('costMeter').registerPriceCalculator({
9
+ provider: 'my-gateway',
10
+ model: 'my-model',
11
+ calculate({ usage, atMs }) {
12
+ const multiplier = new Date(atMs).getUTCHours() < 6 ? 0.5 : 1
13
+ const input = usage.input * 2e-6 * multiplier
14
+ const output = usage.output * 6e-6 * multiplier
15
+ return {
16
+ currency: 'USD',
17
+ total: input + output,
18
+ breakdown: { input, output },
19
+ context: { version: 1, multiplier },
20
+ }
21
+ },
22
+ })
23
+ ))
24
+ }
25
+ ```
26
+
27
+ 回调同步接收 `provider`、`model`、毫秒时间戳 `atMs`,以及 `usage` 的 `input`、`output`、`cacheRead`、`cacheWrite` 和 `reasoning` 五个非负整数。示例对输入和输出收费,另外三项免费。Host 在记录调用时取价,插件可提前把自己的费率加载到内存。
28
+
29
+ 返回值的 `currency` 支持 USD、CNY、EUR。`total` 是该币种下本次调用的金额,允许零。`breakdown` 可省略,也可按上述用量字段提供金额,合计须与总额相符,零用量分项应为零。`context` 可记录 `version`、`tier`、`multiplier` 和五种用量字段的数值,例如当次使用的价格版本及倍率。以上金额和上下文数值须有限且在 0 到 10¹² 之间。
30
+
31
+ 返回 `null`、没有注册项、回调报错、返回 Promise 或报价未通过校验时,本次调用采用已有的价格匹配规则。无效报价在该注册项生命周期内最多输出一次提示。官方按次收取的请求费沿用专门的计价规则。套餐的等值费用与实际 API 支出沿用现有分类。
32
+
33
+ 账本与本次用量一并保存原币总额、分项、上下文、计费时间和记录时的汇率。显式重算会跳过含冻结报价的会话、日期和渠道桶;明细按路由、时间和用量匹配到唯一报价时使用原始记录。扩展方法只接受同一 Host 进程中的回调。
@@ -0,0 +1,19 @@
1
+ ## v1.9.78 更新
2
+
3
+ - 在额度页启用套餐后,首次成功查询会自动在侧栏显示结果。套餐、网关、积分和自定义余额卡片旁的「侧栏」开关与显示设置同步,关闭后仍可刷新额度。
4
+ - 自定义余额可以填写归属渠道,进度条按这些渠道的当日支出计算。感谢 @PersueFree 在 [#543](https://github.com/Han-1413141/dsh-cost-meter/issues/543) 提供渠道账单和金额对照。
5
+ - 历史重算识别失败尝试的用量、标题请求及 fork 的继承范围。标题调用缺少逐次用量时,仅在账本差额能确定价格时重算。感谢 @wexther 在 [#544](https://github.com/Han-1413141/dsh-cost-meter/issues/544) 提供日志结构和复现条件。
6
+ - DS Bot 模式下,费用卡片显示在左栏底部,返回标准界面后恢复原位置。感谢 @Tommy8081 在 [#545](https://github.com/Han-1413141/dsh-cost-meter/issues/545) 提供布局信息。
7
+ - DSH Desktop 关闭浏览器访问后,Antigravity 额度可通过桌面窗口已有的同源会话读取与刷新。感谢 @liluosama55 在 [#546](https://github.com/Han-1413141/dsh-cost-meter/issues/546) 报告 HTTP 403 的触发条件。
8
+ - Host 插件可以为指定渠道和模型注册动态报价。账本保存每次调用的报价、分项和汇率。感谢 @SnowNight777 在 [#547](https://github.com/Han-1413141/dsh-cost-meter/issues/547) 提出扩展接口和历史报价需求。[接口文档](https://github.com/Han-1413141/dsh-cost-meter/blob/v1.9.78/docs/host-price-calculators.md)
9
+ - 额度页增加 Fireworks.ai 余额来源,可配置可信的 HTTPS 余额接口,通过 DSH 凭据库鉴权,并显示余额和查询时间。感谢 @Huaweidev 在 [#549](https://github.com/Han-1413141/dsh-cost-meter/issues/549) 提出需求和自定义接口方案。
10
+
11
+ ## 升级
12
+
13
+ 已安装用户在任意终端重跑一行即可(重跑即为更新):
14
+
15
+ ```powershell
16
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.78/install.ps1 | iex
17
+ ```
18
+
19
+ 升级后**重启 dsh web** 使插件服务端代码生效,浏览器端刷新页面即可。
@@ -0,0 +1,86 @@
1
+ const POOL_PATH = '/plugins/agy-link/pool'
2
+ const FAMILIES = { google: 'Gemini', argon: 'Gemini Argon', anthropic: 'Claude', openai: 'GPT', unknown: 'Other' }
3
+
4
+ async function accountRows(payload, zh, hashId) {
5
+ const byId = new Map()
6
+ for (const raw of payload.accounts.slice(0, 16)) {
7
+ if (typeof raw?.id !== 'string' || !raw.id || raw.enabled === false) continue
8
+ const id = await hashId(raw.id)
9
+ const windows = []
10
+ const timestamps = []
11
+ for (const [family, label] of Object.entries(FAMILIES)) {
12
+ const quota = raw.quotas?.[family]
13
+ if (!quota || raw.authRequired === true) continue
14
+ if (Number.isFinite(quota.updatedAt) && quota.updatedAt > 0) timestamps.push(quota.updatedAt)
15
+ for (const [key, hours, value, reset] of [
16
+ ['rolling', 5, quota.remainingFraction, quota.resetTime],
17
+ ['weekly', 168, quota.weeklyFraction, quota.weeklyResetTime],
18
+ ]) {
19
+ if (!Number.isFinite(value) || value < 0 || value > 1) continue
20
+ const resetMs = typeof reset === 'string' ? Date.parse(reset) : NaN
21
+ windows.push({ id: `${family}-${key}`, label: label + (hours === 5 ? (zh ? ' · 5 小时' : ' · 5 h') : (zh ? ' · 7 天' : ' · 7 d')),
22
+ percent: (1 - value) * 100, resetsAt: Number.isFinite(resetMs) ? new Date(resetMs).toISOString() : null, periodHours: hours, scope: family })
23
+ }
24
+ }
25
+ const alias = typeof raw.alias === 'string' ? raw.alias.trim() : ''
26
+ const label = alias && !/[@\u0000-\u001f\u007f]/.test(alias) ? alias.slice(0, 80) : (zh ? '账号 ' : 'Account ') + (byId.size + 1)
27
+ const status = raw.authRequired === true ? 'error' : windows.length ? 'ok' : 'unknown'
28
+ const message = status === 'error' ? (zh ? '请在 dsh-agy-link 重新登录' : 'Sign in again in dsh-agy-link')
29
+ : status === 'unknown' ? (zh ? '上游暂未返回额度' : 'No quota reported yet') : ''
30
+ byId.set(id, { account: { id, provider: 'antigravity', label, status, message, windows }, updatedAt: Math.max(0, ...timestamps) })
31
+ }
32
+ return byId
33
+ }
34
+
35
+ export async function readAgyPool(base, { read, hashId, force, locale, signal, now = Date.now, wait }) {
36
+ const zh = locale !== 'en'
37
+ const fail = message => ({ ...base, status: 'error', message })
38
+ const readAccounts = async () => {
39
+ const payload = await read(POOL_PATH)
40
+ if (!Array.isArray(payload?.accounts)) throw new Error('Invalid account pool')
41
+ return accountRows(payload, zh, hashId)
42
+ }
43
+ let rows
44
+ let refreshing = false
45
+ let denied = false
46
+ try {
47
+ rows = await readAccounts()
48
+ const expected = [...rows].filter(([, row]) => row.account.status !== 'error')
49
+ if (force && expected.length > 0) {
50
+ const result = await read(POOL_PATH + '/refresh-quota', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
51
+ if (result?.ok !== true) throw new Error('Refresh failed')
52
+ if (result.pending === true) {
53
+ refreshing = true
54
+ for (let i = 0; i < 12; i++) {
55
+ await wait(2000, undefined, { signal })
56
+ rows = await readAccounts()
57
+ refreshing = expected.some(([id, before]) => {
58
+ const latest = rows.get(id)
59
+ return latest && latest.account.status !== 'error' && latest.updatedAt <= before.updatedAt
60
+ && JSON.stringify(latest.account.windows) === JSON.stringify(before.account.windows)
61
+ })
62
+ if (!refreshing) break
63
+ }
64
+ } else rows = await readAccounts()
65
+ }
66
+ } catch (error) {
67
+ signal?.throwIfAborted()
68
+ denied = error?.status === 403
69
+ if (denied && !rows?.size) return { ...fail(zh
70
+ ? 'DSH 拒绝访问额度接口(HTTP 403)。关闭浏览器访问时,请在 dsh-agy-link 的账号池查看或刷新额度。'
71
+ : 'DSH denied quota access (HTTP 403). With browser access disabled, view or refresh quotas in the dsh-agy-link account pool.'), browserAccessDenied: true }
72
+ if (!rows || rows.size === 0) return fail(error?.status === 404
73
+ ? (zh ? '请安装并启用 dsh-agy-link' : 'Install and enable dsh-agy-link')
74
+ : (zh ? '读取 dsh-agy-link 额度失败,请重试' : 'Could not read dsh-agy-link quota. Retry later.'))
75
+ refreshing = true
76
+ }
77
+ const accounts = [...rows.values()].map(row => row.account)
78
+ const updatedAt = Math.max(0, ...[...rows.values()].map(row => row.updatedAt))
79
+ const hasQuota = accounts.some(row => row.windows.length > 0)
80
+ return { ...base, accounts, ...(denied ? { browserAccessDenied: true } : {}),
81
+ status: !refreshing && hasQuota && accounts.every(row => row.status === 'ok') ? 'ok' : 'partial',
82
+ message: denied ? (zh ? 'DSH 拒绝刷新(HTTP 403),显示最近读取的额度。请在 dsh-agy-link 账号池刷新。' : 'DSH denied the refresh (HTTP 403). Showing cached quotas. Refresh in the dsh-agy-link account pool.')
83
+ : refreshing ? (zh ? '上游尚未确认刷新完成,显示最近一次读取的额度' : 'Refresh is unconfirmed; showing the last quota read')
84
+ : !accounts.length ? (zh ? '请在 dsh-agy-link 登录 Google 账号' : 'Sign in to Google in dsh-agy-link') : '',
85
+ fetchedAt: updatedAt || (hasQuota ? now() : 0) }
86
+ }
@@ -1,95 +1,20 @@
1
- import { createHash } from 'node:crypto'
2
- import { setTimeout as sleep } from 'node:timers/promises'
3
- import { fetchWithRetry, readJsonBounded } from './net.js'
4
-
5
- const POOL_PATH = '/plugins/agy-link/pool'
6
- const FAMILIES = { google: 'Gemini', argon: 'Gemini Argon', anthropic: 'Claude', openai: 'GPT', unknown: 'Other' }
7
-
8
- function accountRows(payload, zh) {
9
- const byId = new Map()
10
- for (const raw of payload.accounts.slice(0, 16)) {
11
- if (typeof raw?.id !== 'string' || !raw.id || raw.enabled === false) continue
12
- const id = createHash('sha256').update(raw.id).digest('hex').slice(0, 16)
13
- const windows = []
14
- const timestamps = []
15
- for (const [family, label] of Object.entries(FAMILIES)) {
16
- const quota = raw.quotas?.[family]
17
- if (!quota || raw.authRequired === true) continue
18
- if (Number.isFinite(quota.updatedAt) && quota.updatedAt > 0) timestamps.push(quota.updatedAt)
19
- for (const [key, hours, value, reset] of [
20
- ['rolling', 5, quota.remainingFraction, quota.resetTime],
21
- ['weekly', 168, quota.weeklyFraction, quota.weeklyResetTime],
22
- ]) {
23
- if (!Number.isFinite(value) || value < 0 || value > 1) continue
24
- const resetMs = typeof reset === 'string' ? Date.parse(reset) : NaN
25
- windows.push({ id: `${family}-${key}`, label: label + (hours === 5 ? (zh ? ' · 5 小时' : ' · 5 h') : (zh ? ' · 7 天' : ' · 7 d')),
26
- percent: (1 - value) * 100, resetsAt: Number.isFinite(resetMs) ? new Date(resetMs).toISOString() : null, periodHours: hours, scope: family })
27
- }
28
- }
29
- const alias = typeof raw.alias === 'string' ? raw.alias.trim() : ''
30
- const label = alias && !/[@\u0000-\u001f\u007f]/.test(alias) ? alias.slice(0, 80) : (zh ? '账号 ' : 'Account ') + (byId.size + 1)
31
- const status = raw.authRequired === true ? 'error' : windows.length ? 'ok' : 'unknown'
32
- const message = status === 'error' ? (zh ? '请在 dsh-agy-link 重新登录' : 'Sign in again in dsh-agy-link')
33
- : status === 'unknown' ? (zh ? '上游暂未返回额度' : 'No quota reported yet') : ''
34
- byId.set(id, { account: { id, provider: 'antigravity', label, status, message, windows }, updatedAt: Math.max(0, ...timestamps) })
35
- }
36
- return byId
37
- }
38
-
39
- export async function queryAgyLinkQuota(base, { hostOrigin, force, locale, signal, fetchImpl,
40
- now = Date.now, wait = sleep } = {}) {
41
- const zh = locale !== 'en'
42
- const fail = message => ({ ...base, status: 'error', message })
43
- if (base.status === 'off') return base
44
- if (!hostOrigin) return fail(zh ? 'DSH Web 服务尚未就绪' : 'The DSH web server is not ready')
45
- const read = async (path, init) => {
46
- const response = await fetchWithRetry(hostOrigin + path, { ...init, signal, redirect: 'error' }, { attempts: 1, timeoutMs: 3500, fetchImpl })
47
- if (!response.ok) {
48
- await response.body?.cancel().catch(() => {})
49
- throw Object.assign(new Error('dsh-agy-link query failed'), { status: response.status })
50
- }
51
- return readJsonBounded(response, 524288, { signal })
52
- }
53
- const readAccounts = async () => {
54
- const payload = await read(POOL_PATH)
55
- if (!Array.isArray(payload?.accounts)) throw new Error('Invalid account pool')
56
- return accountRows(payload, zh)
57
- }
58
- let rows
59
- let refreshing = false
60
- try {
61
- rows = await readAccounts()
62
- const expected = [...rows].filter(([, row]) => row.account.status !== 'error')
63
- if (force && expected.length > 0) {
64
- const result = await read(POOL_PATH + '/refresh-quota', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
65
- if (result?.ok !== true) throw new Error('Refresh failed')
66
- if (result.pending === true) {
67
- refreshing = true
68
- for (let i = 0; i < 12; i++) {
69
- await wait(2000, undefined, { signal })
70
- rows = await readAccounts()
71
- refreshing = expected.some(([id, before]) => {
72
- const latest = rows.get(id)
73
- return latest && latest.account.status !== 'error' && latest.updatedAt <= before.updatedAt
74
- && JSON.stringify(latest.account.windows) === JSON.stringify(before.account.windows)
75
- })
76
- if (!refreshing) break
77
- }
78
- } else rows = await readAccounts()
79
- }
80
- } catch (error) {
81
- signal?.throwIfAborted()
82
- if (!rows || rows.size === 0) return fail(error?.status === 404
83
- ? (zh ? '请安装并启用 dsh-agy-link' : 'Install and enable dsh-agy-link')
84
- : (zh ? '读取 dsh-agy-link 额度失败,请重试' : 'Could not read dsh-agy-link quota. Retry later.'))
85
- refreshing = true
86
- }
87
- const accounts = [...rows.values()].map(row => row.account)
88
- const updatedAt = Math.max(0, ...[...rows.values()].map(row => row.updatedAt))
89
- const hasQuota = accounts.some(row => row.windows.length > 0)
90
- return { ...base, accounts,
91
- status: !refreshing && hasQuota && accounts.every(row => row.status === 'ok') ? 'ok' : 'partial',
92
- message: refreshing ? (zh ? '上游尚未确认刷新完成,显示最近一次读取的额度' : 'Refresh is unconfirmed; showing the last quota read')
93
- : !accounts.length ? (zh ? '请在 dsh-agy-link 登录 Google 账号' : 'Sign in to Google in dsh-agy-link') : '',
94
- fetchedAt: updatedAt || (hasQuota ? now() : 0) }
95
- }
1
+ import { createHash } from 'node:crypto'
2
+ import { setTimeout as sleep } from 'node:timers/promises'
3
+ import { fetchWithRetry, readJsonBounded } from './net.js'
4
+
5
+ import { readAgyPool } from './agy-link-pool.js'
6
+
7
+ export async function queryAgyLinkQuota(base, { hostOrigin, force, locale, signal, fetchImpl, now, wait = sleep } = {}) {
8
+ if (base.status === 'off') return base
9
+ if (!hostOrigin) return { ...base, status: 'error', message: locale === 'en' ? 'The DSH web server is not ready' : 'DSH Web 服务尚未就绪' }
10
+ const read = async (path, init) => {
11
+ const response = await fetchWithRetry(hostOrigin + path, { ...init, signal, redirect: 'error' }, { attempts: 1, timeoutMs: 3500, fetchImpl })
12
+ if (!response.ok) {
13
+ await response.body?.cancel().catch(() => {})
14
+ throw Object.assign(new Error('dsh-agy-link query failed'), { status: response.status })
15
+ }
16
+ return readJsonBounded(response, 524288, { signal })
17
+ }
18
+ return readAgyPool(base, { read, force, locale, signal, now, wait,
19
+ hashId: id => createHash('sha256').update(id).digest('hex').slice(0, 16) })
20
+ }
package/lib/backfill.js CHANGED
@@ -15,7 +15,9 @@ import { open } from 'node:fs/promises'
15
15
  import { StringDecoder } from 'node:string_decoder'
16
16
  import { totalUsageTokens } from './usage-totals.js'
17
17
  import * as zlib from 'node:zlib'
18
- import { costOf, providerPriceEntryFor, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
18
+ import { hasRecordedQuotes, findRecordedQuote } from './dynamic-pricing.js'
19
+ import { attemptUsage, forkSeedLength } from './session-billing-events.js'
20
+ import { tierFor, costOf, providerPriceEntryFor, usdFromCost, isWrapperProviderId, wrapperUpstreamProvider } from './pricing.js'
19
21
  import { localDayKey, zeroDay, splitLedgerApiCost } from './store.js'
20
22
  import { billingClassOf, enabledPlanSetOf, planProviderIdOf, isRoutedThirdPartyCall, appendHourBucket, planUsageFingerprint, HOUR_BUCKET_RETENTION_MS, localMidnightMs } from './plan-billing.js'
21
23
  import { USAGE_DEDUP_WINDOW_MS, usageFingerprint } from './usage-dedup.js'
@@ -458,7 +460,7 @@ export async function repairPlanHourBuckets(ledger, sessionsRoot, { nowMs = Date
458
460
  * @param wantDates - 只统计这些日期键(YYYY-MM-DD)内的调用;null = 全部。
459
461
  * @returns { sessionId, title, createdAt, days, seedDays }。
460
462
  */
461
- export function replaySessionRecords(records, config, wantDates = null, collectSamples = false) {
463
+ export function replaySessionRecords(records, config, wantDates = null, collectSamples = false, missingCalls = null) {
462
464
  records = excludeBillionReportedUsage(records)
463
465
  const samples = collectSamples ? new Map() : null
464
466
  // One replay has fixed classification settings. Price versions can differ per
@@ -486,7 +488,7 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
486
488
  }
487
489
  let sessionId = ''
488
490
  let title = ''
489
- let createdAt = 0
491
+ let createdAt = 0, seedLength = 0
490
492
  let provider = 'deepseek'
491
493
  let model = 'default'
492
494
  let last = null
@@ -552,6 +554,7 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
552
554
  if (event === null || typeof event !== 'object') continue
553
555
  if (event.type === 'session' && typeof event.id === 'string') {
554
556
  sessionId = event.id
557
+ seedLength = forkSeedLength(event)
555
558
  const created = Number(event.createdAt)
556
559
  if (Number.isFinite(created) && created > 0) createdAt = created
557
560
  continue
@@ -567,6 +570,21 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
567
570
  if (event.type === 'step/start' && Number.isFinite(eventMs)) stepStarts.set(`${event.data?.turn ?? 0}:${event.data?.step ?? 0}`, eventMs)
568
571
  // fork 种子事件判定:时间戳早于会话创建时刻 = 从父会话拷来的历史。
569
572
  const isSeed = createdAt > 0 && Number.isFinite(eventMs) && eventMs > 0 && eventMs < createdAt
573
+ || Number.isSafeInteger(event.seq) && event.seq >= 0 && event.seq < seedLength
574
+ const attempt = event.type === 'assistant/attempt'
575
+ const failedUsage = attempt ? attemptUsage(event.data) : null
576
+ if (event.type === 'session/title-llm-request' || attempt && !failedUsage) {
577
+ if (missingCalls && !isSeed && Number.isFinite(eventMs) && eventMs > 0) {
578
+ const route = attempt ? { provider, model } : event.data?.route
579
+ if (typeof route?.provider === 'string' && typeof route.model === 'string') {
580
+ const key = JSON.stringify([sessionId, localDayKey(eventMs), route.provider + ':' + route.model])
581
+ if (!missingCalls.has(key)) missingCalls.set(key, [])
582
+ missingCalls.get(key).push(eventMs)
583
+ }
584
+ }
585
+ if (attempt) last = null
586
+ continue
587
+ }
570
588
  if (event.type === 'request/header') {
571
589
  // header 一律更新计费口径(与旧版状态机一致):种子段用量必须按
572
590
  // 父会话当时的模型计价,seedDays 才能与旧版写入账本的污染量对齐,
@@ -594,8 +612,8 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
594
612
  usage = event.data.chunk.usage
595
613
  turn = event.data.turn ?? 0
596
614
  step = event.data.step ?? 0
597
- } else if (event.type === 'assistant/message' && event.data?.usage != null) {
598
- usage = event.data.usage
615
+ } else if (failedUsage || event.type === 'assistant/message' && event.data?.usage != null) {
616
+ usage = failedUsage || event.data.usage
599
617
  turn = event.data.turn ?? 0
600
618
  step = event.data.step ?? 0
601
619
  } else if (metered && event.data?.usage != null && typeof event.data.requestId === 'string') {
@@ -660,10 +678,11 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
660
678
  // 去重与旧版完全一致:单一 (turn,step) 状态机跨种子/own 段连续生效;
661
679
  // 摘要键独立,永不与循环步的样本替换相互干扰。
662
680
  const prev = last !== null && last.key === key ? last : null
663
- if (prev !== null && prev.providerKey === `${effectiveProvider}:${sampleModel}`
681
+ if (prev !== null && prev.seed === isSeed && prev.providerKey === `${effectiveProvider}:${sampleModel}`
664
682
  && prev.buckets.input === buckets.input && prev.buckets.output === buckets.output
665
683
  && prev.buckets.cacheRead === buckets.cacheRead && prev.buckets.cacheWrite === buckets.cacheWrite
666
684
  && prev.buckets.reasoning === buckets.reasoning) {
685
+ if (attempt) last = null
667
686
  continue
668
687
  }
669
688
  // 按事件时刻计费(历史正确):峰谷时代前用 legacyBase,之后按峰谷两档。
@@ -682,8 +701,10 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
682
701
  // 按展示汇率折算为美元入账——与 store.account() 完全同口径。
683
702
  const priced = requestFee ? requestFeeCostCny(requestFee, atMs) : resolved.priced ? costOf(buckets, resolved.entry, pricedAtMs, peak) : 0
684
703
  // 每个回放样本只带冻结金额用得到的汇率,不复制整张展示币种目录。
685
- const fxRates = fxHistoryRatesOf(pricing)
686
- const canonical = usdFromCost(priced, resolved.currency, fxRates.CNY)
704
+ const quote = !metered && !isSeed && findRecordedQuote(config, localDayKey(pricedAtMs), sessionId,
705
+ effectiveProvider + ':' + sampleModel, buckets, pricedAtMs, atMs)
706
+ const fxRates = quote?.fx ?? fxHistoryRatesOf(pricing)
707
+ const canonical = quote ? quote.total / quote.fx[quote.currency] : usdFromCost(priced, resolved.currency, fxRates.CNY)
687
708
  // 冻结币种(CNY/EUR)用记录时的汇率折算;其余展示币种没有历史汇率,按 1 处理,
688
709
  // 由展示层乘回当前汇率——与 currencyLedger 的「美元等值」契约一致。
689
710
  const displayFactor = config._displayCurrency ? (fxRates[config._displayCurrency] ?? config.exchangeRate) / config.exchangeRate : 1
@@ -696,16 +717,16 @@ export function replaySessionRecords(records, config, wantDates = null, collectS
696
717
  // 聚合目标按事件分段路由;被替换的旧样本从它当时所在的段扣回(与旧版
697
718
  // 单流先减后加的净效果一致,仅种子段的量落到 seedDays 而非 days)。
698
719
  if (prev !== null) shift(prev, -1, prev.seed ? seedDays : days)
699
- const sample = { key, date, providerKey, buckets, cost, apiCost, ...frozenAmounts(cost, apiCost, pricing), seed: isSeed }
720
+ const sample = { key, date, providerKey, buckets, cost, apiCost, ...frozenAmounts(cost, apiCost, quote ? { fxRates } : pricing), seed: isSeed }
700
721
  if (samples) {
701
722
  if (prev) samples.delete(prev)
702
- samples.set(sample, { ...sample, ...(requestFee ? { requestFee } : {}), ...(isNativeSearch && event.data.webSource ? { webSource: event.data.webSource } : {}), ...(isNativeSearch && event.data.webSelection ? { webSelection: event.data.webSelection } : {}), displayFactor, exchangeRate: fxRates.CNY, fxRates, pricedAtMs, atMs, logSeq: !metered && Number.isSafeInteger(event.seq) && event.seq >= 0 ? event.seq : null, provider: effectiveProvider, model: sampleModel, resolved, peak, plan, kind: isCompaction ? 'compaction' : requestFee ? requestFee.kind : isNativeSearch ? 'search' : 'model',
723
+ samples.set(sample, { ...sample, ...(quote ? { quote } : {}), ...(requestFee ? { requestFee } : {}), ...(isNativeSearch && event.data.webSource ? { webSource: event.data.webSource } : {}), ...(isNativeSearch && event.data.webSelection ? { webSelection: event.data.webSelection } : {}), displayFactor, exchangeRate: fxRates.CNY, fxRates, pricedAtMs, atMs, logSeq: !metered && Number.isSafeInteger(event.seq) && event.seq >= 0 ? event.seq : null, provider: effectiveProvider, model: sampleModel, resolved: quote ? { ...resolved, priced: true } : resolved, peak, plan, kind: isCompaction ? 'compaction' : requestFee ? requestFee.kind : isNativeSearch ? 'search' : 'model',
703
724
  ...(isBillion ? { metering: event.data.metering } : {}),
704
725
  turn: Number.isSafeInteger(event.data?.turn) && event.data.turn >= 0 ? event.data.turn : null,
705
726
  step: Number.isSafeInteger(event.data?.step) && event.data.step >= 0 ? event.data.step : null })
706
727
  }
707
728
  shift(sample, 1, isSeed ? seedDays : days)
708
- if (!metered) last = sample
729
+ if (!metered) last = attempt ? null : sample
709
730
  }
710
731
  return { sessionId, title, createdAt, days, seedDays, ...(samples ? { samples: [...samples.values()] } : {}) }
711
732
  }
@@ -1120,6 +1141,7 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1120
1141
  if (explicit) result.skippedDetails = []
1121
1142
  const pricingConfig = explicit ? currentPricingConfig(ledger.config) : ledger.config
1122
1143
  if (explicit && model) pricingConfig._repriceFxConfig = ledger.config
1144
+ const missingCalls = explicit ? new Map() : null
1123
1145
  const originalPricing = explicit ? JSON.stringify(pricingSnapshot(ledger.config)) : null
1124
1146
  const originalHistory = explicit ? pricingHistoryFingerprint(ledger.config) : null
1125
1147
  const reset = JSON.stringify(ledger.historyReset ?? null)
@@ -1130,7 +1152,7 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1130
1152
  let replayed
1131
1153
  try {
1132
1154
  if (records === null) continue
1133
- replayed = replaySessionRecords(records, pricingConfig, null)
1155
+ replayed = replaySessionRecords(records, pricingConfig, null, false, missingCalls)
1134
1156
  } catch {
1135
1157
  continue // 单文件损坏(含解压预算超限)不阻断整体重算。
1136
1158
  }
@@ -1169,6 +1191,11 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1169
1191
  let replaceable = serverSearchOnly || (newKeys.length > 0 && newKeys.length === Object.keys(oldPm).length)
1170
1192
  const residualModels = []
1171
1193
  for (const key of serverSearchOnly ? newKeys : new Set([...Object.keys(oldPm), ...newKeys])) {
1194
+ if ((!model || key === model) && hasRecordedQuotes(day, sessionId, key)) {
1195
+ replaceable = false
1196
+ detail(sessionId, date, key, 'dynamicQuote')
1197
+ continue
1198
+ }
1172
1199
  const oldBucket = oldPm[key]
1173
1200
  const dayBucket = dayPm[key]
1174
1201
  const newBucket = pm[key]
@@ -1189,6 +1216,14 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1189
1216
  || hasUnloggedResidualRevision(ledger.pricingHistory, sessionId, date, key)
1190
1217
  const logIsSubset = !webRequest && (Number(newBucket.calls) || 0) > 0
1191
1218
  && tokenFields.every(field => (Number(oldBucket[field]) || 0) >= (Number(newBucket[field]) || 0))
1219
+ const times = missingCalls?.get(JSON.stringify([sessionId, date, key]))
1220
+ if (logIsSubset && times && oldBucket.calls - newBucket.calls === times.length
1221
+ && priceMissingUsage(pricingConfig, sessionId, key, oldBucket, newBucket, times)) continue
1222
+ if (times?.length) {
1223
+ replaceable = false
1224
+ detail(sessionId, date, key, 'auxiliaryUsage', fields)
1225
+ continue
1226
+ }
1192
1227
  if (explicit && wasUnpriced && logIsSubset) {
1193
1228
  residualModels.push(key)
1194
1229
  continue
@@ -1244,6 +1279,36 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1244
1279
  return result
1245
1280
  }
1246
1281
 
1282
+ // Ledger totals give the exact missing tokens. Use them only if every possible
1283
+ // allocation across the logged requests has the same price and frozen FX rates.
1284
+ function priceMissingUsage(config, sessionId, key, oldBucket, replay, times) {
1285
+ const colon = key.indexOf(':'), provider = key.slice(0, colon), model = key.slice(colon + 1)
1286
+ const tokens = Object.fromEntries(['input', 'cacheRead', 'cacheWrite', 'output', 'reasoning']
1287
+ .map(field => [field, (oldBucket[field] ?? 0) - (replay[field] ?? 0)]))
1288
+ let first, signature
1289
+ for (const at of times) {
1290
+ const pricing = pricingConfigAt(config, at, sessionId, key)
1291
+ const resolved = providerPriceEntryFor(provider, model, pricing.prices, { mode: pricing.priceMatch, overrides: pricing.priceOverrides })
1292
+ if (!resolved.priced) return false
1293
+ const peak = { enabled: ['deepseek-peak', 'utc-peak'].includes(resolved.billingMode) && pricing.peakEnabled === true,
1294
+ effectiveAtMs: Date.parse(pricing.peakEffectiveAt), windows: pricing.peakWindows, holidays: pricing.peakHolidays }
1295
+ const tier = tierFor(resolved.entry, at, peak)
1296
+ if (times.length > 1 && tier.longContext && tokens.input + tokens.cacheRead + tokens.cacheWrite > tier.longContext.aboveInputTokens) return false
1297
+ const rates = fxHistoryRatesOf(pricing)
1298
+ const next = JSON.stringify([tier, resolved.currency, rates])
1299
+ if (first && next !== signature) return false
1300
+ if (!first) {
1301
+ const cost = usdFromCost(costOf(tokens, resolved.entry, at, peak), resolved.currency, rates.CNY)
1302
+ const apiCost = billingClassOf(provider, model, config.planBilling, enabledPlanSetOf(config), config.prices) === 'plan' ? 0 : cost
1303
+ first = { cost, apiCost, ...frozenAmounts(cost, apiCost, pricing) }
1304
+ signature = next
1305
+ }
1306
+ }
1307
+ if (!first) return false
1308
+ for (const [field, amount] of Object.entries(first)) replay[field] = (replay[field] ?? 0) + amount
1309
+ return true
1310
+ }
1311
+
1247
1312
  /** 从目标桶(可变)中减去源桶,逐字段 clamp ≥ 0(清洗不产生负数)。 */
1248
1313
  function subtractBucketInto(target, source) {
1249
1314
  target.input = Math.max(0, (target.input ?? 0) - (source.input ?? 0))
@@ -27,7 +27,7 @@ const modelsOnly = (models, memo) => memoized(models, memo?.models, () => Object
27
27
  const runFields = ['at', 'before', 'after', 'days', 'sessions', 'skipped']
28
28
  export function validRepricingDetail(row) {
29
29
  return typeof row?.sessionId === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(row.date) && typeof row.model === 'string'
30
- && ['usage', 'ledgerModelMissing', 'logModelMissing', 'dayModelMissing', 'logMissing'].includes(row.reason)
30
+ && ['usage', 'auxiliaryUsage', 'dynamicQuote', 'ledgerModelMissing', 'logModelMissing', 'dayModelMissing', 'logMissing'].includes(row.reason)
31
31
  && Array.isArray(row.fields) && row.fields.every(item => ['input', 'output', 'cacheRead', 'cacheWrite', 'reasoning', 'calls'].includes(item?.field)
32
32
  && Number.isFinite(item.ledger) && item.ledger >= 0 && Number.isFinite(item.log) && item.log >= 0)
33
33
  }
@@ -0,0 +1 @@
1
+ ;(function(S){const m=window.__ModuleLoader__,b=m[Symbol.for("@dsh-plugin/dsh-loader:load-wrap")];return(S.id==="dsh-cost-meter"&&m.load===b?.ours&&typeof b.original=="function"?b.original:m.load).call(m,S)})({id:"dsh-cost-meter",chunk:"client.agy-quota.js",factory:()=>{const T="/plugins/agy-link/pool",S={google:"Gemini",argon:"Gemini Argon",anthropic:"Claude",openai:"GPT",unknown:"Other"};async function m(w,a,g){const l=new Map;for(const e of w.accounts.slice(0,16)){if(typeof e?.id!="string"||!e.id||e.enabled===!1)continue;const d=await g(e.id),u=[],f=[];for(const[o,y]of Object.entries(S)){const c=e.quotas?.[o];if(!(!c||e.authRequired===!0)){Number.isFinite(c.updatedAt)&&c.updatedAt>0&&f.push(c.updatedAt);for(const[h,k,n,p]of[["rolling",5,c.remainingFraction,c.resetTime],["weekly",168,c.weeklyFraction,c.weeklyResetTime]]){if(!Number.isFinite(n)||n<0||n>1)continue;const A=typeof p=="string"?Date.parse(p):NaN;u.push({id:`${o}-${h}`,label:y+(k===5?a?" · 5 小时":" · 5 h":a?" · 7 天":" · 7 d"),percent:(1-n)*100,resetsAt:Number.isFinite(A)?new Date(A).toISOString():null,periodHours:k,scope:o})}}}const t=typeof e.alias=="string"?e.alias.trim():"",i=t&&!/[@\u0000-\u001f\u007f]/.test(t)?t.slice(0,80):(a?"账号 ":"Account ")+(l.size+1),s=e.authRequired===!0?"error":u.length?"ok":"unknown",r=s==="error"?a?"请在 dsh-agy-link 重新登录":"Sign in again in dsh-agy-link":s==="unknown"?a?"上游暂未返回额度":"No quota reported yet":"";l.set(d,{account:{id:d,provider:"antigravity",label:i,status:s,message:r,windows:u},updatedAt:Math.max(0,...f)})}return l}async function b(w,{read:a,hashId:g,force:l,locale:e,signal:d,now:u=Date.now,wait:f}){const t=e!=="en",i=n=>({...w,status:"error",message:n}),s=async()=>{const n=await a(T);if(!Array.isArray(n?.accounts))throw new Error("Invalid account pool");return m(n,t,g)};let r,o=!1,y=!1;try{r=await s();const n=[...r].filter(([,p])=>p.account.status!=="error");if(l&&n.length>0){const p=await a(T+"/refresh-quota",{method:"POST",headers:{"content-type":"application/json"},body:"{}"});if(p?.ok!==!0)throw new Error("Refresh failed");if(p.pending===!0){o=!0;for(let A=0;A<12&&(await f(2e3,void 0,{signal:d}),r=await s(),o=n.some(([H,q])=>{const D=r.get(H);return D&&D.account.status!=="error"&&D.updatedAt<=q.updatedAt&&JSON.stringify(D.account.windows)===JSON.stringify(q.account.windows)}),!!o);A++);}else r=await s()}}catch(n){if(d?.throwIfAborted(),y=n?.status===403,y&&!r?.size)return{...i(t?"DSH 拒绝访问额度接口(HTTP 403)。关闭浏览器访问时,请在 dsh-agy-link 的账号池查看或刷新额度。":"DSH denied quota access (HTTP 403). With browser access disabled, view or refresh quotas in the dsh-agy-link account pool."),browserAccessDenied:!0};if(!r||r.size===0)return i(n?.status===404?t?"请安装并启用 dsh-agy-link":"Install and enable dsh-agy-link":t?"读取 dsh-agy-link 额度失败,请重试":"Could not read dsh-agy-link quota. Retry later.");o=!0}const c=[...r.values()].map(n=>n.account),h=Math.max(0,...[...r.values()].map(n=>n.updatedAt)),k=c.some(n=>n.windows.length>0);return{...w,accounts:c,...y?{browserAccessDenied:!0}:{},status:!o&&k&&c.every(n=>n.status==="ok")?"ok":"partial",message:y?t?"DSH 拒绝刷新(HTTP 403),显示最近读取的额度。请在 dsh-agy-link 账号池刷新。":"DSH denied the refresh (HTTP 403). Showing cached quotas. Refresh in the dsh-agy-link account pool.":o?t?"上游尚未确认刷新完成,显示最近一次读取的额度":"Refresh is unconfirmed; showing the last quota read":c.length?"":t?"请在 dsh-agy-link 登录 Google 账号":"Sign in to Google in dsh-agy-link",fetchedAt:h||(k?u():0)}}async function v(w){const a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(w));return Array.from(new Uint8Array(a,0,8),g=>g.toString(16).padStart(2,"0")).join("")}async function R(w,a,g){const l=await window.fetch(w,{...a,mode:"same-origin",credentials:"same-origin",redirect:"error",signal:AbortSignal.any([g,AbortSignal.timeout(4e3)])});if(!l.ok)throw await l.body?.cancel(),Object.assign(new Error("Quota request failed"),{status:l.status});const e=l.body.getReader(),d=new TextDecoder;let u=0,f="";try{for(;;){const{value:t,done:i}=await e.read();if(i)break;if(u+=t.byteLength,u>524288)throw await e.cancel(),new Error("Quota response exceeds limit");f+=d.decode(t,{stream:!0})}return JSON.parse(f+d.decode())}finally{e.releaseLock()}}function x(w){const a=new Map;function g(e,d){if(e.pending)return d&&!e.forced?e.pending.then(()=>g(e,!0)):e.pending;if(e.controller.signal.aborted)return Promise.resolve({ok:!1,message:""});e.forced=d;const u=e.controller.signal,f=b(e.base,{force:d,locale:e.locale,signal:u,hashId:v,wait:t=>new Promise(i=>setTimeout(i,t)),read:(t,i)=>R(t,i,u)}).then(t=>{if(u.aborted)return{ok:!1,message:""};e.nextRead=Date.now()+e.interval;const i=["ok","partial"].includes(t.status)&&t.browserAccessDenied!==!0;return e.value=i?t:{...e.value??e.base,status:(e.value??e.base).accounts?.length?"stale":"error",message:t.message},w(),{ok:i,message:t.message||(e.locale==="en"?"Quota updated":"额度已更新")}}).catch(()=>({ok:!1,message:e.base.message})).finally(()=>{e.pending=null});return e.pending=f,f}function l(e,d){const u=e?.config?.gatewayQuotas?.sources??[],f=e?.gatewayQuotas??[],t=new Set,i=f.map(s=>{const r=u.find(h=>h.id===s.id&&h.type==="agy-link"&&h.enabled&&h.display!=="off");if(!r||!s.browserAccessDenied)return s;t.add(r.id);let o=a.get(r.id);o||(o={controller:new AbortController,nextRead:0},a.set(r.id,o));const{browserAccessDenied:y,...c}=s;return Object.assign(o,{base:c,locale:d,interval:Math.max(1,r.refreshMinutes||15)*6e4}),Date.now()>=o.nextRead&&!o.pending&&g(o,!1),o.value?{...o.value,browserAccessDenied:!0}:s});for(const[s,r]of a)t.has(s)||(r.controller.abort(),a.delete(s));return t.size?{...e,gatewayQuotas:i}:e}return{decorate:l,refresh:e=>a.has(e)?g(a.get(e),!0):null,dispose(){for(const e of a.values())e.controller.abort();a.clear()}}}return{mount:x}}});