@lingda-ai/dsh-plugin-quota 0.0.0-stage → 0.1.2
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/LICENSE +202 -0
- package/README.md +123 -2
- package/cordis.patch.yml +8 -0
- package/icon.svg +5 -0
- package/index.js +212 -0
- package/lib/book.js +290 -0
- package/lib/breaker.js +80 -0
- package/lib/client.js +438 -0
- package/lib/policy.js +125 -0
- package/lib/rates.js +172 -0
- package/lib/redact.js +58 -0
- package/lib/route.js +68 -0
- package/lib/tool.js +70 -0
- package/lib/usage.js +72 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +77 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,124 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 航油 · dsh-plugin-quota
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
> 灵搭「空港」套件的续航岗位。给 Agent 一个**按日/周/月的预算**:
|
|
4
|
+
> 实时看见花了多少、按当前速度会不会超、到线时自动降级模型而不是把会话掐死。
|
|
5
|
+
|
|
6
|
+
装上之后右侧栏多一个「航油」页签,同时 Agent 可以用 `quota_query` 自己问额度。
|
|
7
|
+
|
|
8
|
+
## 为什么需要它
|
|
9
|
+
|
|
10
|
+
黑匣子能告诉你"这一次会话花了多少",但它不拦人。真正会烧钱的是**没有上限的日常使用**:
|
|
11
|
+
一天里开了十个会话,每个都不贵,加起来一月几百。
|
|
12
|
+
|
|
13
|
+
航油只做三件事:
|
|
14
|
+
|
|
15
|
+
1. **记**:跨会话累计本周期的花费(含缓存命中折扣后的真实金额);
|
|
16
|
+
2. **判**:按阈值分三档——正常 / 提醒 / 到线;
|
|
17
|
+
3. **做**:到线按你的策略行事:只提醒,或把模型降级到便宜的继续干。
|
|
18
|
+
|
|
19
|
+
它**不**做的事:不记对话内容、不改你的 prompt、不在会话中途硬杀请求。
|
|
20
|
+
|
|
21
|
+
## 安装
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
dsh plugin --profile <你的 profile> add @lingda-ai/dsh-plugin-quota
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
或写进 profile 的 `dsh.profile.bundles`。
|
|
28
|
+
|
|
29
|
+
## 配置:一个文件,改完即生效
|
|
30
|
+
|
|
31
|
+
`~/.dsh/ops/quota/policy.json`
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"budget": { "period": "month", "amount": 20 },
|
|
36
|
+
"thresholds": { "warn": 0.8, "limit": 1 },
|
|
37
|
+
"action": { "atWarn": "notify", "atLimit": "downgrade", "downgradeModel": "deepseek-v4-flash" }
|
|
38
|
+
}
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| 字段 | 含义 | 默认 |
|
|
42
|
+
|---|---|---|
|
|
43
|
+
| `budget.period` | `day` / `week` / `month`(本地时区为界) | `month` |
|
|
44
|
+
| `budget.amount` | 周期预算,单位与费率表一致(元) | **不设**(等于不限制) |
|
|
45
|
+
| `thresholds.warn` | 提醒线,`(0,1]` | `0.8` |
|
|
46
|
+
| `thresholds.limit` | 到线,`>=1` | `1` |
|
|
47
|
+
| `action.atWarn` | 提醒时做什么:`notify` | `notify` |
|
|
48
|
+
| `action.atLimit` | 到线时做什么:`notify` 或 `downgrade` | `downgrade` |
|
|
49
|
+
| `action.downgradeModel` | 降级到哪个模型 | `deepseek-v4-flash` |
|
|
50
|
+
| `sessionCap` | 单会话上限(预留) | 不设 |
|
|
51
|
+
|
|
52
|
+
**不设 `amount` 就等于没开预算**——默认什么都不拦。这是刻意的:一个默认拦人的插件没人敢装。
|
|
53
|
+
|
|
54
|
+
字段写错不会让整个预算失效:非法值退回默认并在面板里列出原因(`policyWarnings`)。
|
|
55
|
+
把 `amount` 写成字符串、把 `period` 写成 `quarter`、把阈值写成倒置,都会看到具体哪一条不对。
|
|
56
|
+
|
|
57
|
+
## 到线时到底发生什么
|
|
58
|
+
|
|
59
|
+
**降级**走宿主的 `agent/request` waterfall:把这次调用的 `LlmCallConfig.model` 换成便宜模型,
|
|
60
|
+
**会话继续,上下文不丢**。这是宿主提供的原生能力(账本已在线上验证过),不是我们伪造的拦截。
|
|
61
|
+
|
|
62
|
+
两条必须知道的边界:
|
|
63
|
+
|
|
64
|
+
- 降级发生在**请求真正发出之前**,但累计金额是**上一次调用之后**的值——
|
|
65
|
+
所以可能出现"这一轮略超线、下一轮才降级",最多差一次调用的钱。
|
|
66
|
+
- **没有硬停**。真正"不许再调模型"需要宿主提供阻断能力,当前版本没有;
|
|
67
|
+
与其假装能拦,不如说清楚:到线后仍会继续,只是用便宜的模型。
|
|
68
|
+
|
|
69
|
+
## 面板读什么
|
|
70
|
+
|
|
71
|
+
- **已用 / 预算** 与进度条(80% 处有提醒刻度)
|
|
72
|
+
- **按当前速度,周期结束约多少**(周期开始 3% 时间内不给外推,避免"第一个小时×720 小时"的鬼话)
|
|
73
|
+
- **缓存已省**:命中缓存相对全价的差额
|
|
74
|
+
- **本周期日消耗**:最近 7 天柱状
|
|
75
|
+
- **最贵的会话** 前 5
|
|
76
|
+
- 费率未知的调用单独计数,**不摊进合计**,并在面板上标出来
|
|
77
|
+
|
|
78
|
+
## 落盘
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
~/.dsh/ops/quota/state.json # 单文件快照,原子写(tmp + rename)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
只存:金额、次数、会话 id、目录名、标题、按天桶。**不存**对话文本、工具参数、绝对路径、错误消息。
|
|
85
|
+
|
|
86
|
+
- 换周期自动滚动:总量清零,旧日桶按保留期(默认 120 天)裁剪
|
|
87
|
+
- 会话超过 500 个时淘汰最久未用的
|
|
88
|
+
- 写失败不会影响采集,下次重试
|
|
89
|
+
|
|
90
|
+
## 权限与兼容
|
|
91
|
+
|
|
92
|
+
| 项 | 事实 |
|
|
93
|
+
|---|---|
|
|
94
|
+
| 落盘路径 | `~/.dsh/ops/quota/`,只写这一个目录 |
|
|
95
|
+
| 网络 | **无任何外网请求**;只提供本机 `GET /dsh-quota/api` 只读接口 |
|
|
96
|
+
| 读取范围 | 可选读 `~/.dsh/ledger/pricing.json`(与账本同源的费率覆盖文件) |
|
|
97
|
+
| 宿主接口 | `session/event`、`agent/request`、`webServer`、`tools`;缺任何一个都降级而不是失效 |
|
|
98
|
+
| Node | ≥ 22.6 |
|
|
99
|
+
| 运行时依赖 | 无 |
|
|
100
|
+
|
|
101
|
+
没有 `agent/request` 能力时:只记钱与提醒,不降级。
|
|
102
|
+
没有 `webServer` 时:只记钱与降级,没有面板。
|
|
103
|
+
没有 `tools` 时:面板与记账照常,只是 Agent 不能自己查。
|
|
104
|
+
|
|
105
|
+
## 开发
|
|
106
|
+
|
|
107
|
+
```bash
|
|
108
|
+
node --test test/*.test.mjs # 42 项断言
|
|
109
|
+
node scripts/check-listing.mjs # 收录前自检
|
|
110
|
+
node scripts/verify-real-host.mjs --profile quota-check # 真机:记钱 + 到线降级
|
|
111
|
+
node scripts/dev-stub-llm.mjs 8791 # 没 key 时联调界面用的假端点
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
`verify-real-host.mjs` 是最能说明问题的一条:它把预算设成 0.0001 元,
|
|
115
|
+
让第一轮就超线,然后断言**第二次请求真的换了模型**——不是看日志,是看请求本身。
|
|
116
|
+
|
|
117
|
+
## 与另外两件的关系
|
|
118
|
+
|
|
119
|
+
- **黑匣子**:每一步花了多少(明细)。航油:这个周期还能花多少(总额)。
|
|
120
|
+
- **机库**:把配置改坏了怎么退回去。航油:钱花超了怎么继续。
|
|
121
|
+
|
|
122
|
+
## 许可
|
|
123
|
+
|
|
124
|
+
Apache-2.0 © LingDaAi
|
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
|
|
2
|
+
<path d="M12 3.5c3.2 3.6 5.5 6.3 5.5 9.2a5.5 5.5 0 0 1-11 0c0-2.9 2.3-5.6 5.5-9.2Z"/>
|
|
3
|
+
<path d="M9.6 13.4a2.4 2.4 0 0 0 4.8 0"/>
|
|
4
|
+
<path d="M5 20.5h14"/>
|
|
5
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lingda-ai/dsh-plugin-quota —— 航油:预算与熔断。
|
|
3
|
+
*
|
|
4
|
+
* 三件事,边界很清楚:
|
|
5
|
+
* 1. **记**:订阅 session/event,把每一次计费调用累进"本周期已花"(跨会话);
|
|
6
|
+
* 2. **判**:按 policy.json 的阈值判定当前处于哪一档(正常 / 提醒 / 到线);
|
|
7
|
+
* 3. **做**:到线时按策略降级模型——通过 `agent/request` waterfall 替换 LlmCallConfig,
|
|
8
|
+
* 这是宿主提供的原生能力(账本 0.1.x 已在线验证),不是我们伪造的拦截。
|
|
9
|
+
*
|
|
10
|
+
* 三条硬约束(与套件其它两件一致):
|
|
11
|
+
* - 采集只订阅,不改事件;热路径不抛错;
|
|
12
|
+
* - 缺服务就降级(没有 webServer 就不提供查询,记账照常);
|
|
13
|
+
* - 算不出的金额单独计数,绝不摊进合计。
|
|
14
|
+
*/
|
|
15
|
+
import { createBook, defaultStatePath } from './lib/book.js'
|
|
16
|
+
import { loadPolicy, defaultPolicyPath, budgetArmed } from './lib/policy.js'
|
|
17
|
+
import { createBreaker, actionOf, LEVEL_LIMIT, LEVEL_WARN } from './lib/breaker.js'
|
|
18
|
+
import { loadRates, defaultPricingPath, normalizeUsage } from './lib/rates.js'
|
|
19
|
+
import { spendOf } from './lib/usage.js'
|
|
20
|
+
import { createApi, handleRequest, API_PREFIX } from './lib/route.js'
|
|
21
|
+
import { createQuotaTool } from './lib/tool.js'
|
|
22
|
+
import { baseName } from './lib/redact.js'
|
|
23
|
+
|
|
24
|
+
export const name = '@lingda-ai/dsh-plugin-quota'
|
|
25
|
+
|
|
26
|
+
/** 不强制依赖任何服务:没有 webServer 也照常记账与降级。 */
|
|
27
|
+
export const inject = []
|
|
28
|
+
|
|
29
|
+
const SERVICE_KEY = 'quota'
|
|
30
|
+
|
|
31
|
+
export function apply(ctx, config = {}) {
|
|
32
|
+
const policyPath = config.policyPath ?? defaultPolicyPath()
|
|
33
|
+
const rates = loadRates({ pricingPath: config.pricingPath ?? defaultPricingPath() })
|
|
34
|
+
|
|
35
|
+
let cachedPolicy = loadPolicy({ path: policyPath })
|
|
36
|
+
let cachedAt = 0
|
|
37
|
+
/** 策略热读:改文件即生效。1 秒缓存,避免每条事件都读盘。 */
|
|
38
|
+
function policyNow() {
|
|
39
|
+
const at = Date.now()
|
|
40
|
+
if (at - cachedAt > 1000) {
|
|
41
|
+
cachedPolicy = loadPolicy({ path: policyPath })
|
|
42
|
+
// 一个只有真机遇得到的问题:降级目标不在价表里,
|
|
43
|
+
// 降级后的花费会整段变成"未知"——面板上看起来像记账坏了。
|
|
44
|
+
// 与其等用户困惑,不如一开始就说清楚。
|
|
45
|
+
const probe = normalizeUsage({ inputTokens: 1, outputTokens: 1, cacheReadTokens: 0, cacheWriteTokens: 0 })
|
|
46
|
+
const target = cachedPolicy.policy?.action?.downgradeModel
|
|
47
|
+
if (target && budgetArmed(cachedPolicy.policy) && rates.costOf(probe, { model: target }).kind === 'unknown') {
|
|
48
|
+
cachedPolicy = {
|
|
49
|
+
...cachedPolicy,
|
|
50
|
+
warnings: [...cachedPolicy.warnings, `降级目标 ${target} 不在价表里,降级后的花费会记为未知`],
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
cachedAt = at
|
|
54
|
+
} else if (cachedAt === 0) {
|
|
55
|
+
cachedAt = at
|
|
56
|
+
}
|
|
57
|
+
return cachedPolicy
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const book = createBook({
|
|
61
|
+
statePath: config.statePath ?? defaultStatePath(),
|
|
62
|
+
period: cachedPolicy.policy.budget.period,
|
|
63
|
+
currency: cachedPolicy.policy.currency,
|
|
64
|
+
retentionDays: config.retentionDays,
|
|
65
|
+
flushMs: config.flushMs,
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
const breakers = new Map()
|
|
69
|
+
let downgrades = 0
|
|
70
|
+
let storageError = null
|
|
71
|
+
|
|
72
|
+
function breakerOf(sid) {
|
|
73
|
+
let breaker = breakers.get(sid)
|
|
74
|
+
if (breaker === undefined) {
|
|
75
|
+
const { policy } = policyNow()
|
|
76
|
+
breaker = createBreaker({ warn: policy.thresholds.warn, limit: policy.thresholds.limit })
|
|
77
|
+
breakers.set(sid, breaker)
|
|
78
|
+
}
|
|
79
|
+
return breaker
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---- 采集 ---------------------------------------------------------------
|
|
83
|
+
const onEvent = (session, event) => {
|
|
84
|
+
try {
|
|
85
|
+
const sid = session?.id
|
|
86
|
+
if (typeof sid !== 'string' || sid.length === 0) return
|
|
87
|
+
const spend = spendOf(event, rates)
|
|
88
|
+
if (spend === null) return
|
|
89
|
+
const result = book.add(sid, spend)
|
|
90
|
+
if (result.added) {
|
|
91
|
+
const cwd = session?.header?.cwd
|
|
92
|
+
const title = session?.title
|
|
93
|
+
if (typeof cwd === 'string' || typeof title === 'string') {
|
|
94
|
+
book.annotate(sid, {
|
|
95
|
+
cwdName: typeof cwd === 'string' ? baseName(cwd) : undefined,
|
|
96
|
+
title: typeof title === 'string' ? title.slice(0, 60) : undefined,
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const { policy } = policyNow()
|
|
101
|
+
if (budgetArmed(policy)) {
|
|
102
|
+
const ratio = policy.budget.amount > 0 ? result.total.amount / policy.budget.amount : null
|
|
103
|
+
breakerOf(sid).update(ratio)
|
|
104
|
+
}
|
|
105
|
+
} catch (error) {
|
|
106
|
+
storageError = error instanceof Error ? error.message : String(error)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (typeof ctx.on === 'function') ctx.on('session/event', onEvent)
|
|
111
|
+
|
|
112
|
+
// ---- 决策:到线降级 -----------------------------------------------------
|
|
113
|
+
const onRequest = async (payload, next) => {
|
|
114
|
+
let current
|
|
115
|
+
try {
|
|
116
|
+
current = await next()
|
|
117
|
+
} catch (error) {
|
|
118
|
+
throw error // 上游失败照常冒泡,这里不替它报错
|
|
119
|
+
}
|
|
120
|
+
try {
|
|
121
|
+
const { policy } = policyNow()
|
|
122
|
+
if (!budgetArmed(policy)) return current
|
|
123
|
+
const sid = payload?.agent?.session?.id
|
|
124
|
+
if (typeof sid !== 'string' || sid.length === 0) return current
|
|
125
|
+
|
|
126
|
+
const state = book.snapshot(policy)
|
|
127
|
+
const ratio = state.ratio
|
|
128
|
+
const level = breakerOf(sid).update(ratio)
|
|
129
|
+
const action = actionOf(level, policy)
|
|
130
|
+
if (!action || action.kind !== 'downgrade' || !action.model) return current
|
|
131
|
+
// 已经是降级模型就别再动:避免把用户的显式选择覆盖成默认值
|
|
132
|
+
if (current?.model === action.model) return current
|
|
133
|
+
downgrades += 1
|
|
134
|
+
return { ...current, model: action.model }
|
|
135
|
+
} catch {
|
|
136
|
+
// 任何判断失败都退回原配置:宁可超预算,也不能让请求崩掉
|
|
137
|
+
return current
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
if (typeof ctx.on === 'function') ctx.on('agent/request', (payload, next) => onRequest(payload, next))
|
|
142
|
+
|
|
143
|
+
// ---- 读面:HTTP(面板用) ------------------------------------------------
|
|
144
|
+
const api = createApi({ book, policyLoader: () => ({ ...policyNow(), warnings: policyNow().warnings }) })
|
|
145
|
+
const route = {
|
|
146
|
+
kind: 'prefix',
|
|
147
|
+
path: API_PREFIX,
|
|
148
|
+
handler: (req, res) => handleRequest(api, req, res),
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
try {
|
|
152
|
+
if (typeof ctx.inject === 'function') {
|
|
153
|
+
ctx.inject(['webServer'], (inner) => {
|
|
154
|
+
const webServer = inner.webServer ?? (typeof inner.get === 'function' ? inner.get('webServer') : null)
|
|
155
|
+
if (!webServer || typeof webServer.register !== 'function') return
|
|
156
|
+
if (typeof inner.effect === 'function') inner.effect(() => webServer.register(route))
|
|
157
|
+
else webServer.register(route)
|
|
158
|
+
})
|
|
159
|
+
}
|
|
160
|
+
} catch {
|
|
161
|
+
/* 没有 web 前端:只记账,不提供查询 */
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// ---- 读面:工具(Agent 用) ----------------------------------------------
|
|
165
|
+
try {
|
|
166
|
+
if (ctx.tools && typeof ctx.tools.register === 'function') {
|
|
167
|
+
ctx.tools.register(createQuotaTool({
|
|
168
|
+
snapshot: () => book.snapshot(policyNow().policy),
|
|
169
|
+
policyOf: () => policyNow().policy,
|
|
170
|
+
}))
|
|
171
|
+
}
|
|
172
|
+
} catch {
|
|
173
|
+
/* 没有 tools 服务:面板与记账不受影响 */
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ---- 服务暴露:给同进程其它插件只读用 ------------------------------------
|
|
177
|
+
try {
|
|
178
|
+
if (typeof ctx.provide === 'function' && !ctx.get?.(SERVICE_KEY)) {
|
|
179
|
+
ctx.provide(SERVICE_KEY, {
|
|
180
|
+
snapshot: () => book.snapshot(policyNow().policy),
|
|
181
|
+
policy: () => policyNow().policy,
|
|
182
|
+
diagnostics: () => ({
|
|
183
|
+
statePath: book.statePath,
|
|
184
|
+
policyPath,
|
|
185
|
+
policyExists: cachedPolicy.exists,
|
|
186
|
+
warnings: cachedPolicy.warnings,
|
|
187
|
+
downgrades,
|
|
188
|
+
storageError,
|
|
189
|
+
ratesAsOf: rates.asOf ?? null,
|
|
190
|
+
}),
|
|
191
|
+
})
|
|
192
|
+
}
|
|
193
|
+
} catch {
|
|
194
|
+
/* 重复装配(HMR)时 provide 会抛,忽略 */
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---- 卸载 ---------------------------------------------------------------
|
|
198
|
+
const cleanup = () => {
|
|
199
|
+
try {
|
|
200
|
+
book.close()
|
|
201
|
+
} catch {}
|
|
202
|
+
breakers.clear()
|
|
203
|
+
}
|
|
204
|
+
if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
|
|
205
|
+
else if (typeof ctx.on === 'function') ctx.on('dispose', cleanup)
|
|
206
|
+
|
|
207
|
+
return {
|
|
208
|
+
snapshot: () => book.snapshot(policyNow().policy),
|
|
209
|
+
diagnostics: () => ({ statePath: book.statePath, policyPath, downgrades, storageError }),
|
|
210
|
+
__test: { LEVEL_WARN, LEVEL_LIMIT },
|
|
211
|
+
}
|
|
212
|
+
}
|