dsh-cost-meter 1.9.63 → 1.9.65
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 +122 -122
- package/README.zh-CN.md +122 -122
- package/docs/custom-balance-sources.en.md +182 -150
- package/docs/custom-balance-sources.md +238 -206
- package/docs/display-settings.md +69 -67
- package/docs/features.en.md +95 -95
- package/docs/features.md +95 -95
- package/docs/install.en.md +4 -4
- package/docs/install.md +4 -4
- package/docs/pricing-history-storage.md +36 -30
- package/docs/update-notes-1.9.60.md +33 -33
- package/docs/update-notes-1.9.62.md +21 -21
- package/docs/update-notes-1.9.64.md +21 -0
- package/docs/update-notes-1.9.65.md +31 -0
- package/lib/balance-expression.js +4 -0
- package/lib/billing-history.js +20 -10
- package/lib/client.display.js +3 -3
- package/lib/client.js +9 -9
- package/lib/index.js +4 -3
- package/lib/ledger-writer-worker.js +1 -1
- package/lib/pricing-history-codec.js +4 -1
- package/lib/pricing.js +35 -1
- package/lib/store.js +3 -2
- package/lib/typert.host.js +1 -0
- package/package.json +288 -286
|
@@ -1,150 +1,182 @@
|
|
|
1
|
-
# Custom balance configuration
|
|
2
|
-
|
|
3
|
-
[简体中文](custom-balance-sources.md) · [Features](features.en.md)
|
|
4
|
-
|
|
5
|
-
## Request and response configuration
|
|
6
|
-
|
|
7
|
-
**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}}`:
|
|
8
|
-
|
|
9
|
-
```json
|
|
10
|
-
{"account_id":"example-account","include_credit":true}
|
|
11
|
-
```
|
|
12
|
-
|
|
13
|
-
Set **Extract rules (JSON)** to `{"remaining":"data.balance"}`. Valid JSON is saved per entry and sent exactly as entered, including nested values and large integer IDs. Invalid JSON shows an error and keeps the last valid configuration; clearing the editor removes the body. GET/HEAD send no body while retaining it for a later switch back to POST. `Content-Type: application/json` is added automatically unless you supply a Content-Type header (any capitalization).
|
|
14
|
-
|
|
15
|
-
Existing `request.body` objects and raw strings remain supported. The body is ordinary saved configuration; `{{VAR}}` credential substitution applies only to request headers. For header authentication, use a reference such as `{"Authorization":"Bearer {{MY_API_KEY}}"}` and the credential input below it.
|
|
16
|
-
|
|
17
|
-
**Display currency conversion:** open **Settings → Cost → Quota**, expand a custom balance entry, and enable **Convert USD balance to display currency**. It defaults to off for each entry. Keep **Source currency** set to the endpoint's actual currency. With a USD balance of 54.3792, a CNY display rate of 7.2 and two decimal places, the balance displays as **¥391.53**. Spend and API/manual limits convert together in the sidebar, settings and tooltips; progress percentages and stored balances do not change. Enter a manual limit in the source currency. The setting persists as `convertToDisplayCurrency: true` inside that `customBalances[]` entry (legacy `customBalance` is also supported).
|
|
18
|
-
|
|
19
|
-
The global exchange rate converts **USD to the display currency**. CNY/EUR source balances and Credits keep their original units; the switch is disabled for them. Alibaba Cloud balances use the currency returned by its API. No exchange-rate lookup or extra balance request is made when toggling this setting. Turning it off restores the original currency immediately.
|
|
20
|
-
|
|
21
|
-
**DeepSeek CNY billing:** USD prices × the display exchange rate and the official CNY table can give different amounts. Settings → Cost → Prices now explains this and provides a CNY selection button. See [currency selection, sync and settlement timing](billing-currency.md#english).
|
|
22
|
-
|
|
23
|
-
For Qianwen / Alibaba Cloud fund accounts, use **Add Qianwen / Alibaba Cloud balance** to query available funds with a RAM AccessKey signature. The card uses the currency returned by the API. See the [setup, permissions and balance definition](qianwen-balance.md#english).
|
|
24
|
-
|
|
25
|
-
Qwen Token Plan can use the [official CLI subscription quota](qwen-cli-quota.md#english). Install the CLI on the DSH host and run `qianwen auth login` as the same OS user. Local estimates remain the default; CLI mode shows current account credits without changing the local ledger.
|
|
26
|
-
|
|
27
|
-
Local Qwen Token Plan credits include Plan calls assigned to Qwen. Existing subscription aliases such as `qwen` and `qwen-tokenplan` remain supported; custom providers can select Qwen under Model statistics → Billing class, or use an explicit vendor name and plan marker for auto detection. Explicit API calls are excluded. The pay-as-you-go `qianwen` provider is not assigned merely because its model ID is identical. Models outside the credits table need all three rates configured.
|
|
28
|
-
|
|
29
|
-
Baidu Qianfan Token Plan Personal now supports [quota queries via console Cookie](baidu-token-plan.md), including credits and Token modes. Store the Cookie in the Baidu quota card or set `BAIDU_QIANFAN_COOKIE` on the DSH host.
|
|
30
|
-
|
|
31
|
-
Xiaomi MiMo Token Plan quotas are queried with the **MiMo console cookie**, not an API key: log in at `platform.xiaomimimo.com`, press F12 → Network → find the `balanceAlertConfig` request and paste the full `cookie` request header into the MiMo card in Settings → Cost → Quotas (it must include `serviceToken` and `userId`; the DSH credential store keeps it as `MIMO_COOKIE`). The card shows the plan/compensation credit windows with the period-end reset (Beijing time) plus a balance row. Copy a fresh console cookie when the card reports an expired login. Token Plan inference keys (`tp-*` / `ttp-*`) are not accepted by this console adapter. Local plan statistics use the calendar month; compensation and balance are displayed without estimates because local calls cannot be attributed to those pools.
|
|
32
|
-
|
|
33
|
-
Each CLIProxyAPI source has a **Gemini quota only** option for its Antigravity groups. It defaults to off. Intentional filtering to no visible quota shows an empty list; malformed quota data still reports an error.
|
|
34
|
-
|
|
35
|
-
The `extract` rules support constants, dot paths, arithmetic, nested operations, `expression` formulas and `sum` over arrays. See the formula examples below. **`divide` fits NewApi and other endpoints that meter balance in integer quota** (1 USD = 500000 quota — the same conversion cc-switch uses).
|
|
36
|
-
|
|
37
|
-
- **`unit: "CREDITS"`**: displays non-monetary credits using the configured decimal precision and a Credits suffix. Dollar spend is not converted to credits or shown as today's credit usage. Credit bars use the endpoint's credit cap; the global monetary budget does not apply.
|
|
38
|
-
- **Plain HTTP is allowed for loopback endpoints**: `http://` is accepted when the host is `127.0.0.1` / `localhost` / `[::1]` (the traffic never leaves the machine), which covers local read-only routes that listen on loopback only and serve no TLS (e.g. `dsh-workbuddy-connect`'s `/plugins/dsh-workbuddy-connect/status`). **LAN HTTP** requires `allowInsecureHttp` and an exact `host:port` allowlist entry.
|
|
39
|
-
|
|
40
|
-
### WorkBuddy credits example (local plugin route)
|
|
41
|
-
|
|
42
|
-
The dedicated **WorkBuddy credits** quota card now supports dsh-xdpool. Select **Credit source → dsh-xdpool** when using multiple connectors; current, all and selected accounts work across CN/global pools. See the [integration notes](update-notes-1.9.38.md#english).
|
|
43
|
-
|
|
44
|
-
With `dsh-workbuddy-connect` installed, its web status route already returns the aggregated credit total — no credential needs to be copied:
|
|
45
|
-
|
|
46
|
-
```json
|
|
47
|
-
{
|
|
48
|
-
"enabled": true,
|
|
49
|
-
"display": "sidebar",
|
|
50
|
-
"refreshMinutes": 15,
|
|
51
|
-
"label": "WorkBuddy 积分",
|
|
52
|
-
"labelEn": "WorkBuddy Credits",
|
|
53
|
-
"unit": "CREDITS",
|
|
54
|
-
"request": { "url": "http://127.0.0.1:3080/plugins/dsh-workbuddy-connect/status", "method": "GET", "headers": {} },
|
|
55
|
-
"extract": { "remaining": "credits.total" }
|
|
56
|
-
}
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
Adjust the port and response fields to the local service. This example requires the other plugin to expose that route. Cost-meter refuses redirects and continues to enforce configured credential host allowlists.
|
|
60
|
-
|
|
61
|
-
For NewApi `GET /api/usage/token` (response `{ "code": 200, "data": { "total_granted": ..., "total_used": ..., "total_available": ..., "unlimited_quota": false } }`):
|
|
62
|
-
|
|
63
|
-
```json
|
|
64
|
-
{
|
|
65
|
-
"enabled": true,
|
|
66
|
-
"display": "both",
|
|
67
|
-
"refreshMinutes": 15,
|
|
68
|
-
"label": "NewApi",
|
|
69
|
-
"labelEn": "NewApi",
|
|
70
|
-
"unit": "USD",
|
|
71
|
-
"request": {
|
|
72
|
-
"url": "https://your-newapi-host/api/usage/token",
|
|
73
|
-
"method": "GET",
|
|
74
|
-
"headers": { "Authorization": "Bearer {{NEWAPI_API_KEY}}" }
|
|
75
|
-
},
|
|
76
|
-
"extract": {
|
|
77
|
-
"remaining": { "op": "divide", "path": "data.total_available", "by": 500000 },
|
|
78
|
-
"maxBudget": { "op": "divide", "path": "data.total_granted", "by": 500000 },
|
|
79
|
-
"spend": { "op": "divide", "path": "data.total_used", "by": 500000 },
|
|
80
|
-
"unit": "USD"
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
```
|
|
84
|
-
|
|
85
|
-
- `{{NEWAPI_API_KEY}}` resolves from the DSH credential vault or an environment variable (**placeholders work in headers only** — URLs accept full addresses or host-relative paths beginning with one slash, without placeholders);
|
|
86
|
-
- Unlimited-quota tokens (`unlimited_quota: true`) have no `total_available`, so `remaining` cannot be extracted and the query reports “remaining is missing or not numeric” — use a limited-quota token or a middle-layer endpoint that converts the units;
|
|
87
|
-
- Entry point: Settings → Cost (Quota tab) → “Custom provider balance” → expand config; or write `config.customBalance` in `storages/cost-meter/ledger.json`.
|
|
88
|
-
|
|
89
|
-
### Credentials & security
|
|
90
|
-
|
|
91
|
-
- **Variable naming**: `{{VAR_NAME}}` follows the `<ROUTE>_API_KEY` convention — `<ROUTE>` is the Provider ID from the DSH Models page (Settings → Models), uppercased with non-alphanumeric characters replaced by underscores, e.g. `openai`→`{{OPENAI_API_KEY}}`, `anthropic`→`{{ANTHROPIC_API_KEY}}`, `abc23-d`→`{{ABC23_D_API_KEY}}`. Sharing a name with the Models page means the balance query and model calls **share the same key** (both resolve from the DSH credential store). This note is also shown above the “Headers (JSON)” input in Settings.
|
|
92
|
-
- **Credential input fields**: after expanding an entry, the “Credential input” section renders one write-only field per `{{VAR}}` placeholder found in the headers — the key goes straight into the DSH credential store (excluded from plugin configuration and ledger files, and never echoed back); no need to hand-edit environment variables or credential files.
|
|
93
|
-
- **Automatic plaintext migration**: older versions let a literal `Bearer sk-…` in the headers leak into `ledger.json` in plaintext. The plugin imports such keys into the DSH credential store at startup and replaces the header value with a `{{CUSTOM_BALANCE_KEY_…}}` placeholder (derived from the entry's host + header name, stable across restarts) — nothing breaks. From now on `ledger.json` and the config shipped to the browser **never contain plaintext keys**: suspected secret headers (Authorization / X-Api-Key / Bearer / sk- prefixes / long opaque strings) are blanked, while placeholders and ordinary headers pass through.
|
|
94
|
-
- **Credential allowlist `allowedHosts`**: when headers carry credentials (placeholders or plaintext), the outbound host must be on this list or the request is refused — protection against leaked keys when importing someone else's config. Without a list, requests proceed with a one-time logged warning. The entry panel provides an “Allowed hosts” input (comma-separated).
|
|
95
|
-
- **Mixed credential templates**: a header containing both a static secret and dynamic placeholders cannot be migrated as one nested credential. It is reported as pending and excluded from persisted/client config. Store the static part separately and use credential references throughout. Pure forms such as `Bearer {{VAR}}` and `{{USER}}:{{PASS}}` remain supported.
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
## Formulas and subscription balances
|
|
99
|
-
|
|
100
|
-
Since 1.9.47, **Cost → Quotas → Custom balance → Extract rules (JSON)** supports `expression` formulas and nested operations. Use `remaining` for available balance, `spend` for usage and `maxBudget` for the total allowance; do not map a usage field directly to `remaining`.
|
|
101
|
-
|
|
102
|
-
For example, if the endpoint returns `{"data":{"amount_total":15000000,"amount_used":2500000}}` and uses 500000 quota units per USD, enter:
|
|
103
|
-
|
|
104
|
-
```json
|
|
105
|
-
{
|
|
106
|
-
"remaining": {"expression": "(data.amount_total - data.amount_used) / 500000"},
|
|
107
|
-
"spend": {"expression": "data.amount_used / 500000"},
|
|
108
|
-
"maxBudget": {"expression": "data.amount_total / 500000"}
|
|
109
|
-
}
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
This example shows $25 remaining, $5 used and $30 total. Adjust field paths and the conversion factor to the endpoint's actual response. NewAPI subscription objects use `amount_total` and `amount_used`, but their response wrapper differs from the account-balance endpoint; adapt the paths accordingly. See the [upstream field definitions](https://github.com/QuantumNous/new-api/blob/main/web/src/features/subscriptions/types.ts).
|
|
113
|
-
|
|
114
|
-
If `data.subscriptions` is an array and each item contains `subscription.amount_total` and `subscription.amount_used`, calculate each item's value and sum the results:
|
|
115
|
-
|
|
116
|
-
```json
|
|
117
|
-
{
|
|
118
|
-
"remaining": {
|
|
119
|
-
"op": "sum",
|
|
120
|
-
"path": "data.subscriptions",
|
|
121
|
-
"value": {"expression": "(subscription.amount_total - subscription.amount_used) / 500000"}
|
|
122
|
-
},
|
|
123
|
-
"spend": {
|
|
124
|
-
"op": "sum",
|
|
125
|
-
"path": "data.subscriptions",
|
|
126
|
-
"value": {"expression": "subscription.amount_used / 500000"}
|
|
127
|
-
},
|
|
128
|
-
"maxBudget": {
|
|
129
|
-
"op": "sum",
|
|
130
|
-
"path": "data.subscriptions",
|
|
131
|
-
"value": {"expression": "subscription.amount_total / 500000"}
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
The array must contain the active subscriptions you intend to display. Existing paths, constants, `add`/`subtract` rules with `paths`, and `divide` rules with `path`/`by` remain supported. Use `args` for nested operations:
|
|
137
|
-
|
|
138
|
-
```json
|
|
139
|
-
{"remaining":{"op":"divide","args":[{"op":"subtract","args":["data.amount_total","data.amount_used"]},500000]}}
|
|
140
|
-
```
|
|
141
|
-
|
|
142
|
-
Expressions support `+ - * / % **`, parentheses, array indices, and `min`, `max`, `abs`, `round`, `floor` and `ceil`. They do not run JavaScript. Missing fields, non-numeric values, division by zero and non-finite results report a parsing failure instead of showing a zero balance.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
1
|
+
# Custom balance configuration
|
|
2
|
+
|
|
3
|
+
[简体中文](custom-balance-sources.md) · [Features](features.en.md)
|
|
4
|
+
|
|
5
|
+
## Request and response configuration
|
|
6
|
+
|
|
7
|
+
**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}}`:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{"account_id":"example-account","include_credit":true}
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Set **Extract rules (JSON)** to `{"remaining":"data.balance"}`. Valid JSON is saved per entry and sent exactly as entered, including nested values and large integer IDs. Invalid JSON shows an error and keeps the last valid configuration; clearing the editor removes the body. GET/HEAD send no body while retaining it for a later switch back to POST. `Content-Type: application/json` is added automatically unless you supply a Content-Type header (any capitalization).
|
|
14
|
+
|
|
15
|
+
Existing `request.body` objects and raw strings remain supported. The body is ordinary saved configuration; `{{VAR}}` credential substitution applies only to request headers. For header authentication, use a reference such as `{"Authorization":"Bearer {{MY_API_KEY}}"}` and the credential input below it.
|
|
16
|
+
|
|
17
|
+
**Display currency conversion:** open **Settings → Cost → Quota**, expand a custom balance entry, and enable **Convert USD balance to display currency**. It defaults to off for each entry. Keep **Source currency** set to the endpoint's actual currency. With a USD balance of 54.3792, a CNY display rate of 7.2 and two decimal places, the balance displays as **¥391.53**. Spend and API/manual limits convert together in the sidebar, settings and tooltips; progress percentages and stored balances do not change. Enter a manual limit in the source currency. The setting persists as `convertToDisplayCurrency: true` inside that `customBalances[]` entry (legacy `customBalance` is also supported).
|
|
18
|
+
|
|
19
|
+
The global exchange rate converts **USD to the display currency**. CNY/EUR source balances and Credits keep their original units; the switch is disabled for them. Alibaba Cloud balances use the currency returned by its API. No exchange-rate lookup or extra balance request is made when toggling this setting. Turning it off restores the original currency immediately.
|
|
20
|
+
|
|
21
|
+
**DeepSeek CNY billing:** USD prices × the display exchange rate and the official CNY table can give different amounts. Settings → Cost → Prices now explains this and provides a CNY selection button. See [currency selection, sync and settlement timing](billing-currency.md#english).
|
|
22
|
+
|
|
23
|
+
For Qianwen / Alibaba Cloud fund accounts, use **Add Qianwen / Alibaba Cloud balance** to query available funds with a RAM AccessKey signature. The card uses the currency returned by the API. See the [setup, permissions and balance definition](qianwen-balance.md#english).
|
|
24
|
+
|
|
25
|
+
Qwen Token Plan can use the [official CLI subscription quota](qwen-cli-quota.md#english). Install the CLI on the DSH host and run `qianwen auth login` as the same OS user. Local estimates remain the default; CLI mode shows current account credits without changing the local ledger.
|
|
26
|
+
|
|
27
|
+
Local Qwen Token Plan credits include Plan calls assigned to Qwen. Existing subscription aliases such as `qwen` and `qwen-tokenplan` remain supported; custom providers can select Qwen under Model statistics → Billing class, or use an explicit vendor name and plan marker for auto detection. Explicit API calls are excluded. The pay-as-you-go `qianwen` provider is not assigned merely because its model ID is identical. Models outside the credits table need all three rates configured.
|
|
28
|
+
|
|
29
|
+
Baidu Qianfan Token Plan Personal now supports [quota queries via console Cookie](baidu-token-plan.md), including credits and Token modes. Store the Cookie in the Baidu quota card or set `BAIDU_QIANFAN_COOKIE` on the DSH host.
|
|
30
|
+
|
|
31
|
+
Xiaomi MiMo Token Plan quotas are queried with the **MiMo console cookie**, not an API key: log in at `platform.xiaomimimo.com`, press F12 → Network → find the `balanceAlertConfig` request and paste the full `cookie` request header into the MiMo card in Settings → Cost → Quotas (it must include `serviceToken` and `userId`; the DSH credential store keeps it as `MIMO_COOKIE`). The card shows the plan/compensation credit windows with the period-end reset (Beijing time) plus a balance row. Copy a fresh console cookie when the card reports an expired login. Token Plan inference keys (`tp-*` / `ttp-*`) are not accepted by this console adapter. Local plan statistics use the calendar month; compensation and balance are displayed without estimates because local calls cannot be attributed to those pools.
|
|
32
|
+
|
|
33
|
+
Each CLIProxyAPI source has a **Gemini quota only** option for its Antigravity groups. It defaults to off. Intentional filtering to no visible quota shows an empty list; malformed quota data still reports an error.
|
|
34
|
+
|
|
35
|
+
The `extract` rules support constants, dot paths, arithmetic, nested operations, `expression` formulas and `sum` over arrays. See the formula examples below. **`divide` fits NewApi and other endpoints that meter balance in integer quota** (1 USD = 500000 quota — the same conversion cc-switch uses).
|
|
36
|
+
|
|
37
|
+
- **`unit: "CREDITS"`**: displays non-monetary credits using the configured decimal precision and a Credits suffix. Dollar spend is not converted to credits or shown as today's credit usage. Credit bars use the endpoint's credit cap; the global monetary budget does not apply.
|
|
38
|
+
- **Plain HTTP is allowed for loopback endpoints**: `http://` is accepted when the host is `127.0.0.1` / `localhost` / `[::1]` (the traffic never leaves the machine), which covers local read-only routes that listen on loopback only and serve no TLS (e.g. `dsh-workbuddy-connect`'s `/plugins/dsh-workbuddy-connect/status`). **LAN HTTP** requires `allowInsecureHttp` and an exact `host:port` allowlist entry.
|
|
39
|
+
|
|
40
|
+
### WorkBuddy credits example (local plugin route)
|
|
41
|
+
|
|
42
|
+
The dedicated **WorkBuddy credits** quota card now supports dsh-xdpool. Select **Credit source → dsh-xdpool** when using multiple connectors; current, all and selected accounts work across CN/global pools. See the [integration notes](update-notes-1.9.38.md#english).
|
|
43
|
+
|
|
44
|
+
With `dsh-workbuddy-connect` installed, its web status route already returns the aggregated credit total — no credential needs to be copied:
|
|
45
|
+
|
|
46
|
+
```json
|
|
47
|
+
{
|
|
48
|
+
"enabled": true,
|
|
49
|
+
"display": "sidebar",
|
|
50
|
+
"refreshMinutes": 15,
|
|
51
|
+
"label": "WorkBuddy 积分",
|
|
52
|
+
"labelEn": "WorkBuddy Credits",
|
|
53
|
+
"unit": "CREDITS",
|
|
54
|
+
"request": { "url": "http://127.0.0.1:3080/plugins/dsh-workbuddy-connect/status", "method": "GET", "headers": {} },
|
|
55
|
+
"extract": { "remaining": "credits.total" }
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Adjust the port and response fields to the local service. This example requires the other plugin to expose that route. Cost-meter refuses redirects and continues to enforce configured credential host allowlists.
|
|
60
|
+
|
|
61
|
+
For NewApi `GET /api/usage/token` (response `{ "code": 200, "data": { "total_granted": ..., "total_used": ..., "total_available": ..., "unlimited_quota": false } }`):
|
|
62
|
+
|
|
63
|
+
```json
|
|
64
|
+
{
|
|
65
|
+
"enabled": true,
|
|
66
|
+
"display": "both",
|
|
67
|
+
"refreshMinutes": 15,
|
|
68
|
+
"label": "NewApi",
|
|
69
|
+
"labelEn": "NewApi",
|
|
70
|
+
"unit": "USD",
|
|
71
|
+
"request": {
|
|
72
|
+
"url": "https://your-newapi-host/api/usage/token",
|
|
73
|
+
"method": "GET",
|
|
74
|
+
"headers": { "Authorization": "Bearer {{NEWAPI_API_KEY}}" }
|
|
75
|
+
},
|
|
76
|
+
"extract": {
|
|
77
|
+
"remaining": { "op": "divide", "path": "data.total_available", "by": 500000 },
|
|
78
|
+
"maxBudget": { "op": "divide", "path": "data.total_granted", "by": 500000 },
|
|
79
|
+
"spend": { "op": "divide", "path": "data.total_used", "by": 500000 },
|
|
80
|
+
"unit": "USD"
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- `{{NEWAPI_API_KEY}}` resolves from the DSH credential vault or an environment variable (**placeholders work in headers only** — URLs accept full addresses or host-relative paths beginning with one slash, without placeholders);
|
|
86
|
+
- Unlimited-quota tokens (`unlimited_quota: true`) have no `total_available`, so `remaining` cannot be extracted and the query reports “remaining is missing or not numeric” — use a limited-quota token or a middle-layer endpoint that converts the units;
|
|
87
|
+
- Entry point: Settings → Cost (Quota tab) → “Custom provider balance” → expand config; or write `config.customBalance` in `storages/cost-meter/ledger.json`.
|
|
88
|
+
|
|
89
|
+
### Credentials & security
|
|
90
|
+
|
|
91
|
+
- **Variable naming**: `{{VAR_NAME}}` follows the `<ROUTE>_API_KEY` convention — `<ROUTE>` is the Provider ID from the DSH Models page (Settings → Models), uppercased with non-alphanumeric characters replaced by underscores, e.g. `openai`→`{{OPENAI_API_KEY}}`, `anthropic`→`{{ANTHROPIC_API_KEY}}`, `abc23-d`→`{{ABC23_D_API_KEY}}`. Sharing a name with the Models page means the balance query and model calls **share the same key** (both resolve from the DSH credential store). This note is also shown above the “Headers (JSON)” input in Settings.
|
|
92
|
+
- **Credential input fields**: after expanding an entry, the “Credential input” section renders one write-only field per `{{VAR}}` placeholder found in the headers — the key goes straight into the DSH credential store (excluded from plugin configuration and ledger files, and never echoed back); no need to hand-edit environment variables or credential files.
|
|
93
|
+
- **Automatic plaintext migration**: older versions let a literal `Bearer sk-…` in the headers leak into `ledger.json` in plaintext. The plugin imports such keys into the DSH credential store at startup and replaces the header value with a `{{CUSTOM_BALANCE_KEY_…}}` placeholder (derived from the entry's host + header name, stable across restarts) — nothing breaks. From now on `ledger.json` and the config shipped to the browser **never contain plaintext keys**: suspected secret headers (Authorization / X-Api-Key / Bearer / sk- prefixes / long opaque strings) are blanked, while placeholders and ordinary headers pass through.
|
|
94
|
+
- **Credential allowlist `allowedHosts`**: when headers carry credentials (placeholders or plaintext), the outbound host must be on this list or the request is refused — protection against leaked keys when importing someone else's config. Without a list, requests proceed with a one-time logged warning. The entry panel provides an “Allowed hosts” input (comma-separated).
|
|
95
|
+
- **Mixed credential templates**: a header containing both a static secret and dynamic placeholders cannot be migrated as one nested credential. It is reported as pending and excluded from persisted/client config. Store the static part separately and use credential references throughout. Pure forms such as `Bearer {{VAR}}` and `{{USER}}:{{PASS}}` remain supported.
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
## Formulas and subscription balances
|
|
99
|
+
|
|
100
|
+
Since 1.9.47, **Cost → Quotas → Custom balance → Extract rules (JSON)** supports `expression` formulas and nested operations. Use `remaining` for available balance, `spend` for usage and `maxBudget` for the total allowance; do not map a usage field directly to `remaining`.
|
|
101
|
+
|
|
102
|
+
For example, if the endpoint returns `{"data":{"amount_total":15000000,"amount_used":2500000}}` and uses 500000 quota units per USD, enter:
|
|
103
|
+
|
|
104
|
+
```json
|
|
105
|
+
{
|
|
106
|
+
"remaining": {"expression": "(data.amount_total - data.amount_used) / 500000"},
|
|
107
|
+
"spend": {"expression": "data.amount_used / 500000"},
|
|
108
|
+
"maxBudget": {"expression": "data.amount_total / 500000"}
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
This example shows $25 remaining, $5 used and $30 total. Adjust field paths and the conversion factor to the endpoint's actual response. NewAPI subscription objects use `amount_total` and `amount_used`, but their response wrapper differs from the account-balance endpoint; adapt the paths accordingly. See the [upstream field definitions](https://github.com/QuantumNous/new-api/blob/main/web/src/features/subscriptions/types.ts).
|
|
113
|
+
|
|
114
|
+
If `data.subscriptions` is an array and each item contains `subscription.amount_total` and `subscription.amount_used`, calculate each item's value and sum the results:
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
{
|
|
118
|
+
"remaining": {
|
|
119
|
+
"op": "sum",
|
|
120
|
+
"path": "data.subscriptions",
|
|
121
|
+
"value": {"expression": "(subscription.amount_total - subscription.amount_used) / 500000"}
|
|
122
|
+
},
|
|
123
|
+
"spend": {
|
|
124
|
+
"op": "sum",
|
|
125
|
+
"path": "data.subscriptions",
|
|
126
|
+
"value": {"expression": "subscription.amount_used / 500000"}
|
|
127
|
+
},
|
|
128
|
+
"maxBudget": {
|
|
129
|
+
"op": "sum",
|
|
130
|
+
"path": "data.subscriptions",
|
|
131
|
+
"value": {"expression": "subscription.amount_total / 500000"}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
The array must contain the active subscriptions you intend to display. Existing paths, constants, `add`/`subtract` rules with `paths`, and `divide` rules with `path`/`by` remain supported. Use `args` for nested operations:
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{"remaining":{"op":"divide","args":[{"op":"subtract","args":["data.amount_total","data.amount_used"]},500000]}}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Expressions support `+ - * / % **`, parentheses, array indices, and `min`, `max`, `abs`, `round`, `floor` and `ceil`. They do not run JavaScript. Missing fields, non-numeric values, division by zero and non-finite results report a parsing failure instead of showing a zero balance.
|
|
143
|
+
|
|
144
|
+
A `sum` rule also accepts an optional `where` object: only array items whose listed fields strictly equal the given values are summed, for example `{"op":"sum","path":"data","where":{"provider":"workbuddy"},"value":{"expression":"windows[2].limit"}}`. `where` allows at most 16 fields and rejects `__proto__` / `prototype` / `constructor` keys.
|
|
145
|
+
|
|
146
|
+
## Dashboard links and local services
|
|
147
|
+
|
|
148
|
+
Each custom balance entry has an optional **Dashboard link** (`dashboardUrl`) under **Cost → Quotas**. Use a complete HTTP(S) account or billing URL without embedded credentials. The sidebar row and progress card show an arrow next to that entry's name; it opens a new tab without refreshing the balance. Leave it blank to omit the link. Query URLs, headers and credentials are never used to construct navigation links.
|
|
149
|
+
|
|
150
|
+
Root-relative URLs such as `/plugins/dsh-workbuddy-connect/status` follow the running DSH web server's actual port. Independent WorkBuddy2API deployments use an absolute URL. Non-loopback HTTP requires both `allowInsecureHttp: true` and an exact `host:port` in `allowedHosts`; this explicitly permits plaintext transport. Redirects remain blocked.
|
|
151
|
+
|
|
152
|
+
The **+ WorkBuddy2API credits** preset reads `GET /api/credits/expiry?package_limit=1` with an admin `X-Admin-Token` stored as `WORKBUDDY2API_ADMIN_TOKEN` in DSH credentials. Set the real server address and matching allowlist, update expired admin tokens, then enable the card. The displayed `summary.available_remaining` is the active account pool's available credits, not currency, a single model API key's allowance, or the incomplete expiry snapshot total. No model request or upstream credit-refresh task is triggered. Authentication was tested with synthetic responses, not a live account.
|
|
153
|
+
|
|
154
|
+
## Magpie WorkBuddy credits example
|
|
155
|
+
|
|
156
|
+
Under **Cost → Quotas → Custom provider balance**, choose **Add entry** and fill in:
|
|
157
|
+
|
|
158
|
+
```json
|
|
159
|
+
{
|
|
160
|
+
"label": "Magpie WorkBuddy credits",
|
|
161
|
+
"unit": "CREDITS",
|
|
162
|
+
"refreshMinutes": 5,
|
|
163
|
+
"request": {
|
|
164
|
+
"url": "http://127.0.0.1:3425/v1/magpie/quotas",
|
|
165
|
+
"method": "GET",
|
|
166
|
+
"headers": {}
|
|
167
|
+
},
|
|
168
|
+
"extract": {
|
|
169
|
+
"remaining": { "op": "sum", "path": "data", "where": { "provider": "workbuddy" }, "value": { "expression": "windows[2].limit * windows[2].remaining / 100" } },
|
|
170
|
+
"maxBudget": { "op": "sum", "path": "data", "where": { "provider": "workbuddy" }, "value": { "expression": "windows[2].limit" } },
|
|
171
|
+
"spend": { "op": "sum", "path": "data", "where": { "provider": "workbuddy" }, "value": { "expression": "windows[2].limit * windows[2].used / 100" } }
|
|
172
|
+
},
|
|
173
|
+
"allowedHosts": ["127.0.0.1:3425"],
|
|
174
|
+
"allowInsecureHttp": false
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Magpie's `/v1/magpie/quotas` returns multiple providers and accounts. The `where` clause on a `sum` rule matches fields exactly, so only `provider=workbuddy` accounts are summed; Trae, MiniMax and other providers are excluded. WorkBuddy's `used` / `remaining` values are percentages (0–100) and `limit` is the credit capacity, so the example converts them to absolute credits with `limit * percentage / 100`. It uses `windows[2]` (`Total credits`, base plus extra credits) as the total. Change all three `windows[2]` references to `windows[0]` to show only the base monthly credits, or `windows[1]` for extra credits only.
|
|
179
|
+
|
|
180
|
+
No API key is needed when Magpie runs locally on the default `127.0.0.1:3425`. If Magpie runs on another host or enables authentication, edit the URL, add `Authorization: Bearer {{MAGPIE_API_KEY}}` to the request headers, add the exact `host:port` to the allowlist and save the key in the credential field. Prefer HTTPS; enable **Allow non-loopback HTTP** only for a non-loopback HTTP URL. The query only reads Magpie's existing statistics and makes no model requests.
|
|
181
|
+
|
|
182
|
+
This preset does not depend on the official WorkBuddy desktop login or a WorkBuddy connector. Users who already run `dsh-magpie-quota` can keep using it; the two displays are independent.
|