dsh-cost-meter 1.9.72 → 1.9.74

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.72-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.74-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.72/install.ps1 | iex
45
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.74/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.72
51
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.74
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.72**: [release notes](docs/update-notes-1.9.72.md#english) · [troubleshooting](docs/install-troubleshooting.md)
58
+ Current release **v1.9.74**: [release notes](docs/update-notes-1.9.74.md#english) · [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.72-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.74-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.72/install.ps1 | iex
45
+ irm https://raw.githubusercontent.com/Han-1413141/dsh-cost-meter/v1.9.74/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.72
51
+ dsh plugin --profile web add github:Han-1413141/dsh-cost-meter#v1.9.74
52
52
  ```
53
53
 
54
54
  更新、卸载及无 Git 的安装方法见[安装说明](docs/install.md)。
55
55
 
56
56
  </details>
57
57
 
58
- 当前版本 **v1.9.72**:[更新说明](docs/update-notes-1.9.72.md#中文) · [安装排障](docs/install-troubleshooting.md)
58
+ 当前版本 **v1.9.74**:[更新说明](docs/update-notes-1.9.74.md#中文) · [安装排障](docs/install-troubleshooting.md)
59
59
 
60
60
  ## 功能总览
61
61
 
@@ -2,6 +2,12 @@
2
2
 
3
3
  [简体中文](custom-balance-sources.md) · [Features](features.en.md)
4
4
 
5
+ ## OpenAI API credits
6
+
7
+ In Settings → Cost → Quotas, choose Add OpenAI API credits. Enter the grant amount, start date and expiration date in UTC from [Credit grants](https://platform.openai.com/settings/organization/billing/credit-grants) for the linked API organization. Save its Admin API key and enable the card. DSH keeps the key in its credential store. You can also set `DSH_OPENAI_COST_ADMIN_KEY` on the server.
8
+
9
+ The card estimates the grant remaining from organization costs in the period using the [OpenAI Costs API](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/costs). Quota settings and the sidebar tooltip show the grant amount, organization costs, estimated remainder and expiration. Overlapping grants, different credit eligibility and reporting delays can affect the estimate. Use Credit grants for the official balance.
10
+
5
11
  ## Request and response configuration
6
12
 
7
13
  **POST with a JSON body:** in **Settings → Cost → Quota**, expand a custom balance entry, select **POST**, then fill in **Request body (JSON)**. For example, if the endpoint expects an account and returns `{"data":{"balance":12.5}}`:
@@ -2,6 +2,12 @@
2
2
 
3
3
  [English](custom-balance-sources.en.md) · [功能与截图](features.md)
4
4
 
5
+ ## OpenAI API 赠送额度
6
+
7
+ 在「设置 → 费用 → 额度」选择「添加 OpenAI API 赠送额度」。填写绑定的 API 组织在 [Credit grants](https://platform.openai.com/settings/organization/billing/credit-grants) 显示的赠送金额、生效日期及到期日期(UTC),然后保存该组织的 Admin API Key 并开启查询。密钥通过 DSH 凭据库保存,也可在服务端设置 `DSH_OPENAI_COST_ADMIN_KEY`。
8
+
9
+ 插件按 [OpenAI Costs API](https://developers.openai.com/api/reference/resources/admin/subresources/organization/subresources/usage/methods/costs) 返回的该组织期间费用计算预估余额。在额度页可看总额、组织费用、预估剩余和到期日,侧栏悬停可看明细。多个赠送额度叠加、不同费用的抵扣规则或统计延迟会影响预估,以官方 Credit grants 为准。
10
+
5
11
  ## 请求与响应配置
6
12
 
7
13
  **POST 携带 JSON 请求体:**进入**设置 → 费用 → 额度**,展开自定义余额,选择 **POST**,在**请求体 (JSON)** 中填写接口要求的内容。例如接口需要账号参数,并返回 `{"data":{"balance":12.5}}`:
@@ -108,3 +108,11 @@ SHA-512 校验、静态契约检查和实际发布包回归通过:原生及代
108
108
  ### 2026-11-17:billion-context 0.1.216
109
109
 
110
110
  处理 github-actions[bot] 在 [#524](https://github.com/Han-1413141/dsh-cost-meter/issues/524) 报告的版本变化。官方发布包 SHA-512 校验通过,接入函数指纹未变。实际发布包的原生与代理计费、四种协议、压缩、重试、缓存、父子会话、API/Plan 分类、回放、重启、取消及原版 CLI 自动接入检查通过。检查使用合成数据和本机服务,外部模型请求为 0。现有 v1.9.71 运行时代码已兼容;本次更新兼容基线并将 0.1.216 加入 CI。
111
+
112
+ ### 2026-11-18:Codex Subscription 3.2.21
113
+
114
+ 官方发布包 SHA-512 校验通过,四个额度接入函数语法指纹及静态契约未变。实际发布包的额度解析、单周和双窗口、默认缓存、强制刷新、账号切换、共享请求取消、登录失效及只读 HTTP/RPC 检查通过;测试仅使用合成数据与本机服务,外部账户及模型请求为 0。兼容基线更新至 `3.2.21`,两个既有宿主的 CI 矩阵均保留旧版本并加入 `3.2.21`。
115
+
116
+ ### 2026-11-18:Codex Subscription 3.2.24
117
+
118
+ [#531](https://github.com/Han-1413141/dsh-cost-meter/issues/531) 报告 `3.2.23`,核对时 npm 最新版为 `3.2.24`。两个发布包均通过额度解析、缓存、账号切换、授权失败恢复和宿主 RPC 回归。新版 `createSubscriptionRpcHandler` 的语法指纹有变化,静态契约检查通过。兼容基线和 CI 更新至 `3.2.24`。
@@ -0,0 +1,31 @@
1
+ # v1.9.74
2
+
3
+ ## 中文
4
+
5
+ - 更新 GitHub 首页的微信群二维码,欢迎加入插件交流 5 群。
6
+ - DeepSeek 余额直接读取官方数据。余额进度条缺少预算上限时仅显示金额;自定义余额可以用服务返回的上限绘制进度条。
7
+ - 自定义价格可以复制已有渠道和模型的币种、各项单价、倍率、峰谷规则及长上下文档位。可在保存前编辑复制结果。
8
+ - 显示设置将侧栏全局选项与组件选项分开。关闭示例数据时按实际配置渲染预览。会话费用明细支持点击弹窗外部关闭,并调整了按钮、提示和内容间距。
9
+ - 额度页可添加 OpenAI API 赠送额度。根据手填的赠送金额和有效期,以及 OpenAI 官方返回的组织 API 费用,显示预估剩余、总额、组织费用和到期日。
10
+ - 验证 `dsh-codex-subscription` 3.2.23 和 3.2.24,兼容基线更新到 3.2.24。
11
+
12
+ 感谢 [@cinast](https://github.com/cinast) 在 [#529](https://github.com/Han-1413141/dsh-cost-meter/issues/529) 提供显示设置和会话费用明细的截图与交互建议。[@PersueFree](https://github.com/PersueFree) 在 [#530](https://github.com/Han-1413141/dsh-cost-meter/issues/530) 提出自定义价格模板,在 [#532](https://github.com/Han-1413141/dsh-cost-meter/issues/532) 复现余额满格并定位上限缺失,并[提醒更新群二维码](https://github.com/Han-1413141/dsh-cost-meter/issues/530#issuecomment-6971033997)。感谢 [@Solismuchengxue](https://github.com/Solismuchengxue) 在 [#533](https://github.com/Han-1413141/dsh-cost-meter/issues/533) 提出 OpenAI API 赠送额度显示需求,以及 [GitHub Actions](https://github.com/apps/github-actions) 在 [#531](https://github.com/Han-1413141/dsh-cost-meter/issues/531) 报告上游版本变化。
13
+
14
+ ## English
15
+
16
+ - Update the repository README with the WeChat group 5 QR code.
17
+ - Use the official DeepSeek wallet balance. Show the balance amount without a progress bar when a budget cap is unavailable. Custom balance sources can use a cap supplied by their API.
18
+ - Copy currency, rates, multipliers, peak and off-peak settings, and long-context tiers from an existing custom model price into an editable draft.
19
+ - Group sidebar-wide settings apart from component options. With sample data disabled, the preview follows the active display settings. Click outside the session cost dialog to dismiss it.
20
+ - Add an OpenAI API credit estimate to Quotas and the sidebar. Enter the grant amount and dates, and use official organization API costs to estimate remaining credits.
21
+ - Verify `dsh-codex-subscription` 3.2.23 and 3.2.24, and update the compatibility baseline to 3.2.24.
22
+
23
+ Thanks to [@cinast](https://github.com/cinast) for the settings and dialog feedback ([#529](https://github.com/Han-1413141/dsh-cost-meter/issues/529)), [@PersueFree](https://github.com/PersueFree) for the price template proposal ([#530](https://github.com/Han-1413141/dsh-cost-meter/issues/530)), the balance progress reproduction and diagnosis ([#532](https://github.com/Han-1413141/dsh-cost-meter/issues/532)), and the [WeChat group report](https://github.com/Han-1413141/dsh-cost-meter/issues/530#issuecomment-6971033997), and [@Solismuchengxue](https://github.com/Solismuchengxue) for the OpenAI API credit request ([#533](https://github.com/Han-1413141/dsh-cost-meter/issues/533)). [GitHub Actions](https://github.com/apps/github-actions) reported the upstream version change in [#531](https://github.com/Han-1413141/dsh-cost-meter/issues/531).
24
+
25
+ ## 升级 / Upgrade
26
+
27
+ ```sh
28
+ dsh plugin --profile web add dsh-cost-meter@latest
29
+ ```
30
+
31
+ 更新后请完全退出并重启 DSH。Desktop 用户参见 [安装与更新](https://github.com/Han-1413141/dsh-cost-meter/blob/v1.9.74/docs/install-troubleshooting.md#desktop-安装与更新)。
package/lib/backfill.js CHANGED
@@ -24,7 +24,7 @@ import { isWebRequestModel } from './web-request-pricing.js'
24
24
  import { listSessionLogFiles } from './session-log-files.js'
25
25
  import { listNativeSearchHistory, readNativeSearchHistory, nativeSearchRecordsFor } from './native-search-history.js'
26
26
  import { BILLION_USAGE_EVENT, billionRecordsFor, excludeBillionReportedUsage, listBillionFiles, iterateBillionCalls } from './billion-context-history.js'
27
- import { pricingConfigAt, recordPricingRevision, currentPricingConfig, pricingSnapshot, pricingHistoryFingerprint } from './billing-history.js'
27
+ import { pricingConfigAt, recordPricingRevision, hasUnloggedResidualRevision, currentPricingConfig, pricingSnapshot, pricingHistoryFingerprint } from './billing-history.js'
28
28
 
29
29
  const ZSTD_MAGIC = 4247762216
30
30
  /** 打包行(文本/推理/工具调用增量游程)不含 header 与 usage,回放时跳过。 */
@@ -1166,6 +1166,7 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1166
1166
  const dayPm = day.byProviderModel !== null && typeof day.byProviderModel === 'object' ? day.byProviderModel : {}
1167
1167
  // Token 计价只要求五桶一致;按请求收费仍须核对 calls。重算只改金额,保留账本计量。
1168
1168
  let replaceable = newKeys.length > 0 && newKeys.length === Object.keys(oldPm).length
1169
+ const residualModels = []
1169
1170
  for (const key of new Set([...Object.keys(oldPm), ...newKeys])) {
1170
1171
  const oldBucket = oldPm[key]
1171
1172
  const dayBucket = dayPm[key]
@@ -1175,10 +1176,22 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1175
1176
  detail(sessionId, date, key, oldBucket === undefined ? 'ledgerModelMissing' : newBucket === undefined ? 'logModelMissing' : 'dayModelMissing')
1176
1177
  continue
1177
1178
  }
1179
+ if (model && key !== model) continue
1178
1180
  const fields = [...tokenFields, 'calls'].map(field => ({ field, ledger: Number(oldBucket[field]) || 0, log: Number(newBucket[field]) || 0 }))
1179
1181
  .filter(row => row.ledger !== row.log)
1180
1182
  const colon = key.indexOf(':')
1181
- if (fields.some(row => row.field !== 'calls' || isWebRequestModel(key.slice(0, colon), key.slice(colon + 1)))) {
1183
+ const webRequest = isWebRequestModel(key.slice(0, colon), key.slice(colon + 1))
1184
+ if (fields.some(row => row.field !== 'calls' || webRequest)) {
1185
+ // 此前未定价(cost=0)的会话若仅有宿主未写入日志的附属调用残差(如自动标题生成,账本五桶 ≥ 日志五桶且日志有实际调用),
1186
+ // 允许按已记录日志调用重算并在价格修订中登记该模型,避免整段历史与本会话明细永久卡在 0 + ?;已记过正数金额的桶仍严格保留原值。
1187
+ const wasUnpriced = ((Number(oldBucket.cost) || 0) === 0 && (Number(oldBucket.apiCost) || 0) === 0)
1188
+ || hasUnloggedResidualRevision(ledger.pricingHistory, sessionId, date, key)
1189
+ const logIsSubset = !webRequest && (Number(newBucket.calls) || 0) > 0
1190
+ && tokenFields.every(field => (Number(oldBucket[field]) || 0) >= (Number(newBucket[field]) || 0))
1191
+ if (explicit && wasUnpriced && logIsSubset) {
1192
+ residualModels.push(key)
1193
+ continue
1194
+ }
1182
1195
  replaceable = false
1183
1196
  detail(sessionId, date, key, 'usage', fields)
1184
1197
  }
@@ -1212,7 +1225,8 @@ export async function recomputeLedgerPricingBasis(ledger, sessionsRoot, includeB
1212
1225
  }
1213
1226
  result.recostedSessions += 1
1214
1227
  touchedDates.add(date)
1215
- if (explicit && ledger.pricingHistory) recordPricingRevision(ledger.pricingHistory, pricingConfig, sessionId, date, startedAt, previousAmount, { cost: row.cost, apiCost: row.apiCost }, model)
1228
+ const selectedResiduals = residualModels.filter(key => selected.includes(key))
1229
+ if (explicit && ledger.pricingHistory) recordPricingRevision(ledger.pricingHistory, pricingConfig, sessionId, date, startedAt, previousAmount, { cost: row.cost, apiCost: row.apiCost }, model, selectedResiduals)
1216
1230
  }
1217
1231
  }
1218
1232
  result.recostedDays = touchedDates.size
@@ -35,12 +35,15 @@ const compare = (a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0) |
35
35
  function indexOf(history) {
36
36
  let index = indexes.get(history)
37
37
  if (index) return index
38
- const revisions = new Map()
38
+ const revisions = new Map(), residualModels = new Set()
39
39
  for (const row of Object.values(history.revisions)) {
40
40
  const key = JSON.stringify([row.sessionId, row.date, row.model ?? '']), previous = revisions.get(key)
41
41
  if (!previous || compare(row, previous) >= 0) revisions.set(key, row)
42
+ if (Array.isArray(row.unloggedResidualModels)) {
43
+ for (const item of row.unloggedResidualModels) residualModels.add(JSON.stringify([row.sessionId, row.date, item]))
44
+ }
42
45
  }
43
- index = { changes: Object.values(history.changes).sort(compare), revisions, fingerprint: hash([history.changes, history.revisions, history.fxChanges]), fx: Object.values(history.fxChanges ?? {}).sort((a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0)) }
46
+ index = { changes: Object.values(history.changes).sort(compare), revisions, residualModels, fingerprint: hash([history.changes, history.revisions, history.fxChanges]), fx: Object.values(history.fxChanges ?? {}).sort((a, b) => a.at - b.at || (a.sequence ?? 0) - (b.sequence ?? 0)) }
44
47
  indexes.set(history, index)
45
48
  return index
46
49
  }
@@ -100,6 +103,7 @@ export function normalizePricingHistory(raw, config, previous, stored = false) {
100
103
  }
101
104
  const revisions = Object.fromEntries(Object.entries(raw.revisions ?? {}).filter(([id, row]) => safe(id) && typeof row?.sessionId === 'string'
102
105
  && (row.model === undefined || (typeof row.model === 'string' && row.model.includes(':') && row.model.length <= 2048))
106
+ && (row.unloggedResidualModels === undefined || (Array.isArray(row.unloggedResidualModels) && row.unloggedResidualModels.every(item => typeof item === 'string' && item.includes(':') && item.length <= 2048)))
103
107
  && /^\d{4}-\d{2}-\d{2}$/.test(row.date) && Number.isFinite(row.at) && versions[row.version]))
104
108
  const runs = Object.fromEntries(Object.entries(object(raw.runs) ? raw.runs : {}).filter(([id, row]) => safe(id) && runFields.every(key => Number.isFinite(row?.[key]) && row[key] >= 0))
105
109
  .map(([id, row]) => [id, { ...Object.fromEntries([...runFields, ...['beforeCny', 'afterCny', 'beforeEur', 'afterEur'].filter(key => Number.isFinite(row[key]) && row[key] >= 0)].map(key => [key, row[key]])), ...(typeof row.model === 'string' ? { model: row.model } : {}),
@@ -169,13 +173,18 @@ export function pricingConfigAt(config, at, sessionId = '', model = '') {
169
173
  }
170
174
 
171
175
  /** Repricing affects only fully replayable session/day records explicitly accepted by the user. */
172
- export function recordPricingRevision(history, config, sessionId, date, at, before, after, model = '') {
176
+ export function recordPricingRevision(history, config, sessionId, date, at, before, after, model = '', unloggedResidualModels = []) {
173
177
  const pricing = pricingSnapshot(config), version = hash(pricing)
174
178
  rememberPriceVersion(history.versions, version, pricing, indexOf(history).changes.at(-1)?.version)
175
- history.revisions[randomUUID()] = { sessionId, date, at, ...(model ? { model, preserveFx: true } : { fxRates: fxHistoryRatesOf(config) }), sequence: Object.keys(history.revisions).length + 1, version, before, after }
179
+ const residuals = Array.isArray(unloggedResidualModels) && unloggedResidualModels.length ? [...new Set(unloggedResidualModels)] : null
180
+ history.revisions[randomUUID()] = { sessionId, date, at, ...(model ? { model, preserveFx: true } : { fxRates: fxHistoryRatesOf(config) }), ...(residuals ? { unloggedResidualModels: residuals } : {}), sequence: Object.keys(history.revisions).length + 1, version, before, after }
176
181
  indexes.delete(history)
177
182
  }
178
183
 
184
+ export function hasUnloggedResidualRevision(history, sessionId, date, model) {
185
+ return Boolean(history && typeof model === 'string' && model.length > 0 && indexOf(history).residualModels.has(JSON.stringify([sessionId, date, model])))
186
+ }
187
+
179
188
  export function mergePricingHistory(local, disk) {
180
189
  if (!local) return disk
181
190
  if (!disk) return local
package/lib/bootstrap.js CHANGED
@@ -38,4 +38,4 @@ Issue: `+wi);return i.code=e==="version_too_old"?"BILLION_VERSION_TOO_OLD":"BILL
38
38
  `}else{N(t==="native","unknown_runtime_kind");let c=u("installNativeFetchIntercept"),x=Q(c.body,"send"),g=!1;$(c.body,b=>{b.type==="CallExpression"&&b.callee.type==="MemberExpression"&&b.callee.object.name==="Object"&&b.callee.property.name==="defineProperty"&&b.arguments[1]?.value==="fetch"&&(g=!0)});let v=Q(c.body,"installFetchChain").length;N(x.length>0&&(v===1||v===0&&g&&Q(c.body,"makeChain").length>0)&&Q(c.body,"fetch").length===0,"native_transport_changed");for(let{item:b}of x)N(b.arguments.length>=1&&!b.optional,"native_send_changed"),n.push({start:b.start,end:b.end,text:"__dshCmSend(send, "+b.arguments.map(k=>e.slice(k.start,k.end)).join(", ")+")"});o.nativeSends=x.length,o.nativeTransport=v?"chain":"global-fetch-accessor",d=`import { sendWithBillionMeter as __dshCmSend } from ${JSON.stringify(i.native??"./cost-meter-native.js")};
39
39
  `}n.sort((c,x)=>x.start-c.start||x.end-c.end);for(let c=1;c<n.length;c++)N(n[c].end<=n[c-1].start,"overlapping_runtime_hooks");for(let c of n)e=e.slice(0,c.start)+c.text+e.slice(c.end);let y=e.startsWith("#!")?e.indexOf(`
40
40
  `)+1:0;e=e.slice(0,y)+d+e.slice(y);try{Oe(e,{sourceType:"module",ecmaVersion:"latest"})}catch{throw ge("patched_syntax_changed")}return{source:e,capabilities:o}}var be=Symbol.for("dsh-cost-meter.billion-context.auto.v1"),Ti=Symbol.for("dsh-cost-meter.billion-context.peers.v1"),Vt=Symbol.for("dsh-cost-meter.billion-context.v1"),Fe="x-dsh-cost-meter-group",Li=new URL("./billion-context-preload.js",import.meta.url).href,Ri=e=>["127.0.0.1","localhost","[::1]","::1"].includes(e.hostname);function Tt(e){if(!Number.isSafeInteger(e)||e<1)return!1;try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Lt(e){try{let t=new URL(e.path,String(e.origin));return Ri(t)&&t.protocol==="http:"?t:null}catch{return null}}function ve(e,t){if(Array.isArray(e)){for(let i=0;i<e.length;i+=2)if(String(e[i]).toLowerCase()===t)return String(e[i+1])}else if(typeof e=="string"){for(let i of e.split(`\r
41
- `))if(i.slice(0,i.indexOf(":")).toLowerCase()===t)return i.slice(i.indexOf(":")+1).trim()}else if(e&&typeof e=="object")return e[t]==null?null:String(e[t]);return null}function Me(e){if(Ue(e).size>32*1024*1024)throw Error("runtime_size_changed");return Pi(e,"utf8")}function Oi(e,t={},i=new Map){if(!Array.isArray(e)||typeof e[0]!="string"||e[0].startsWith("-"))return null;let s;try{s=Ni(Vi(t.cwd??process.cwd(),e[0]))}catch{return null}if(je(s)!=="index.js"||je(De(s))!=="dist")return null;let a=De(De(s)),n;try{n=JSON.parse(Me(Nt(a,"package.json")))}catch{return null}if(n.name!=="billion-context"||n.dshCostMeterCompatibility)return null;if(Pt(n.version)!==!0)return{version:n.version,reason:"needs_update"};if(typeof Rt.register!="function")return{version:n.version,reason:"bridge_missing"};try{let o=Nt(a,"dist/agent/dsh-native.js"),u=[Ue(s),Ue(o)],h=s+":"+u.map(y=>[y.size,y.mtimeMs,y.ctimeMs].join(":")).join(":");if(i.has(h))return i.get(h);let f=Me(s);Be(f,"proxy"),Be(Me(o),"native");let d={script:s,version:n.version,fingerprint:Ii("sha256").update(f).digest("hex")};return i.set(h,d),i.size>8&&i.delete(i.keys().next().value),d}catch{return{version:n.version,reason:"changed"}}}function Ot(){let e=!1,t=c=>()=>{e||(e=!0,Bi(c))},i=globalThis[be];if(i)return i.references++,i.issue&&globalThis[Vt]?.adapterStatus?.(i.issue.version,i.issue.reason),t(i);let s=Ai.ChildProcess.prototype,a=s.spawn,n=new Map,o=new WeakMap,u=new Map,h=globalThis[Ti]??=new Map;i={references:1,original:a,subscriptions:[],children:u,prototype:s};let f=()=>globalThis[Vt],d=function(c){if(i.references<=0||!c||!Array.isArray(c.args)||!Array.isArray(c.envPairs))return a.apply(this,arguments);let x=c.file,g=c.args.slice(1);if(typeof x!="string"||!["node","node.exe","nodejs"].includes(je(x).toLowerCase())&&!c.envPairs.includes("ELECTRON_RUN_AS_NODE=1"))return a.apply(this,arguments);let v;try{v=Oi(g,c,n)}catch{}try{v?.reason&&(i.issue=v,f()?.adapterStatus?.(v.version,v.reason))}catch{}if(!v||v.reason)return a.apply(this,arguments);i.issue=void 0;let b=c.envPairs.filter(ye=>!ye.startsWith("DSH_COST_METER_BILLION_LOADER="));b.push("DSH_COST_METER_BILLION_LOADER="+JSON.stringify({script:v.script,fingerprint:v.fingerprint}));let k=a.call(this,{...c,args:[c.args[0],"--import",Li,...g],envPairs:b}),E=this;u.set(E.pid,E);let ee=()=>{u.delete(E.pid);for(let[ye,Ft]of h)Ft.pid===E.pid&&h.delete(ye)};return E.once("exit",ee),E.once("error",ee),k};i.wrapped=d,s.spawn=d;let y=(c,x)=>{let g=b=>{try{x(b)}catch{}},v=Ei(c);v.subscribe(g),i.subscriptions.push(()=>v.unsubscribe(g))};return y("undici:request:create",({request:c})=>{let x=Lt(c);if(c.method!=="POST")return;if(!x||!x.pathname.startsWith("/bili/")){f()?.begin?.(new URL(c.path,String(c.origin)).href);return}if(ve(c.headers,Fe))return;let g=h.get(x.origin);if(!g||!Tt(g.pid)){h.delete(x.origin),f()?.unsupported?.({changed:!1,missing:!g});return}let v=f(),b=v?.begin(x.href);b&&(c.addHeader(Fe,b),o.set(c,{bridge:v,id:b,origin:x.origin}))}),y("undici:request:headers",({request:c,response:x})=>{let g=Lt(c);if(g&&c.method==="GET"&&g.pathname==="/__bili/health"){let k=Number(ve(x.headers,"x-dsh-cost-meter-pid"));x.statusCode===200&&ve(x.headers,"x-dsh-cost-meter-protocol")==="1"&&Tt(k)?(h.set(g.origin,{pid:k}),h.size>128&&h.delete(h.keys().next().value)):h.delete(g.origin)}let v=o.get(c);if(!v)return;o.delete(c);let b=ve(x.headers,Fe)===v.id;v.bridge.ack(v.id,b),b||h.delete(v.origin)}),y("undici:request:error",({request:c})=>{let x=o.get(c);x&&(o.delete(c),x.bridge.ack(x.id,!1,{transient:!0}),h.delete(x.origin))}),globalThis[be]=i,t(i)}function Bi(e){if(!(--e.references>0||globalThis[be]!==e)){for(let t of e.subscriptions)t();e.prototype.spawn===e.wrapped&&(e.prototype.spawn=e.original),delete globalThis[be]}}var qe=Ot(),Bt;try{Bt=await import("./index.js")}catch(e){throw qe(),e}var Dt=setTimeout(qe,0);Dt.unref?.();var Zi="cost-meter";function Ji(e){clearTimeout(Dt);try{return Bt.apply(e)}finally{qe()}}export{Ji as apply,Zi as name};
41
+ `))if(i.slice(0,i.indexOf(":")).toLowerCase()===t)return i.slice(i.indexOf(":")+1).trim()}else if(e&&typeof e=="object")return e[t]==null?null:String(e[t]);return null}function Me(e){if(Ue(e).size>32*1024*1024)throw Error("runtime_size_changed");return Pi(e,"utf8")}function Oi(e,t={},i=new Map){if(!Array.isArray(e)||typeof e[0]!="string"||e[0].startsWith("-"))return null;let s;try{s=Ni(Vi(t.cwd??process.cwd(),e[0]))}catch{return null}if(je(s)!=="index.js"||je(De(s))!=="dist")return null;let a=De(De(s)),n;try{n=JSON.parse(Me(Nt(a,"package.json")))}catch{return null}if(n.name!=="billion-context"||n.dshCostMeterCompatibility)return null;if(Pt(n.version)!==!0)return{version:n.version,reason:"needs_update"};if(typeof Rt.register!="function")return{version:n.version,reason:"bridge_missing"};try{let o=Nt(a,"dist/agent/dsh-native.js"),u=[Ue(s),Ue(o)],h=s+":"+u.map(y=>[y.size,y.mtimeMs,y.ctimeMs].join(":")).join(":");if(i.has(h))return i.get(h);let f=Me(s);Be(f,"proxy"),Be(Me(o),"native");let d={script:s,version:n.version,fingerprint:Ii("sha256").update(f).digest("hex")};return i.set(h,d),i.size>8&&i.delete(i.keys().next().value),d}catch{return{version:n.version,reason:"changed"}}}function Ot(){let e=!1,t=c=>()=>{e||(e=!0,Bi(c))},i=globalThis[be];if(i)return i.references++,i.issue&&globalThis[Vt]?.adapterStatus?.(i.issue.version,i.issue.reason),t(i);let s=Ai.ChildProcess.prototype,a=s.spawn,n=new Map,o=new WeakMap,u=new Map,h=globalThis[Ti]??=new Map;i={references:1,original:a,subscriptions:[],children:u,prototype:s};let f=()=>globalThis[Vt],d=function(c){if(i.references<=0||!c||!Array.isArray(c.args)||!Array.isArray(c.envPairs))return a.apply(this,arguments);let x=c.file,g=c.args.slice(1);if(typeof x!="string"||!["node","node.exe","nodejs"].includes(je(x).toLowerCase())&&!c.envPairs.includes("ELECTRON_RUN_AS_NODE=1"))return a.apply(this,arguments);let v;try{v=Oi(g,c,n)}catch{}try{v?.reason&&(i.issue=v,f()?.adapterStatus?.(v.version,v.reason))}catch{}if(!v||v.reason)return a.apply(this,arguments);i.issue=void 0;let b=c.envPairs.filter(ye=>!ye.startsWith("DSH_COST_METER_BILLION_LOADER="));b.push("DSH_COST_METER_BILLION_LOADER="+JSON.stringify({script:v.script,fingerprint:v.fingerprint}));let k=a.call(this,{...c,args:[c.args[0],"--import",Li,...g],envPairs:b}),E=this;u.set(E.pid,E);let ee=()=>{u.delete(E.pid);for(let[ye,Ft]of h)Ft.pid===E.pid&&h.delete(ye)};return E.once("exit",ee),E.once("error",ee),k};i.wrapped=d,s.spawn=d;let y=(c,x)=>{let g=b=>{try{x(b)}catch{}},v=Ei(c);v.subscribe(g),i.subscriptions.push(()=>v.unsubscribe(g))};return y("undici:request:create",({request:c})=>{let x=Lt(c);if(c.method!=="POST")return;if(!x||!x.pathname.startsWith("/bili/")){f()?.begin?.(new URL(c.path,String(c.origin)).href);return}if(ve(c.headers,Fe))return;let g=h.get(x.origin);if(!g||!Tt(g.pid)){h.delete(x.origin),f()?.unsupported?.({changed:!1,missing:!g});return}let v=f(),b=v?.begin(x.href);b&&(c.addHeader(Fe,b),o.set(c,{bridge:v,id:b,origin:x.origin}))}),y("undici:request:headers",({request:c,response:x})=>{let g=Lt(c);if(g&&c.method==="GET"&&g.pathname==="/__bili/health"){let k=Number(ve(x.headers,"x-dsh-cost-meter-pid"));x.statusCode===200&&ve(x.headers,"x-dsh-cost-meter-protocol")==="1"&&Tt(k)?(h.set(g.origin,{pid:k}),h.size>128&&h.delete(h.keys().next().value)):h.delete(g.origin)}let v=o.get(c);if(!v)return;o.delete(c);let b=ve(x.headers,Fe)===v.id;v.bridge.ack(v.id,b),b||h.delete(v.origin)}),y("undici:request:error",({request:c})=>{let x=o.get(c);x&&(o.delete(c),x.bridge.ack(x.id,!1,{transient:!0}),h.delete(x.origin))}),globalThis[be]=i,t(i)}function Bi(e){if(!(--e.references>0||globalThis[be]!==e)){for(let t of e.subscriptions)t();e.prototype.spawn===e.wrapped&&(e.prototype.spawn=e.original),delete globalThis[be]}}var qe=Ot(),Bt;try{Bt=await import(new URL("./index.js"+new URL(import.meta.url).search,import.meta.url).href)}catch(e){throw qe(),e}var Dt=setTimeout(qe,0);Dt.unref?.();var Zi="cost-meter";function Ji(e){clearTimeout(Dt);try{return Bt.apply(e)}finally{qe()}}export{Ji as apply,Zi as name};