@jerry_chzy/dsh-token-usage 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,311 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "@jerry_chzy/dsh-token-usage",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ let react_jsx_runtime = require("react/jsx-runtime");
8
+ //#region src/format.ts
9
+ /**
10
+ * Compact token count: 517 / 12.3K / 1.2M.
11
+ * @param value - non-negative token count.
12
+ * @param units - suffix renderers, owned by the caller's locale or fixed text.
13
+ * @returns compact display string.
14
+ */
15
+ function formatTokens(value, units) {
16
+ const scaled = (candidate) => candidate >= 100 ? String(Math.round(candidate)) : String(Math.round(candidate * 10) / 10);
17
+ if (value < 1e3) return String(value);
18
+ if (value < 1e6) return units.thousand(scaled(value / 1e3));
19
+ return units.million(scaled(value / 1e6));
20
+ }
21
+ /**
22
+ * Cost with enough precision to stay non-zero on cheap sessions: two decimals
23
+ * once the figure is a yuan, three below it, and trailing-zero-trimmed
24
+ * micro-precision for sub-fen amounts.
25
+ * @param value - non-negative cost amount.
26
+ * @returns display amount that never rounds a real cost to bare zero.
27
+ */
28
+ function formatAmount(value) {
29
+ if (value === 0) return "0";
30
+ if (value < .01) return value.toFixed(6).replace(/0+$/u, "").replace(/\.$/u, "");
31
+ if (value < 1) return value.toFixed(3);
32
+ return value.toFixed(2);
33
+ }
34
+ Object.freeze({
35
+ "deepseek-flash": Object.freeze({
36
+ inputMiss: 2,
37
+ inputHit: .04,
38
+ output: 8
39
+ }),
40
+ "deepseek-v4-flash": Object.freeze({
41
+ inputMiss: 3,
42
+ inputHit: .1,
43
+ output: 9
44
+ }),
45
+ "deepseek-v4-flash-vision-exp": Object.freeze({
46
+ inputMiss: 3,
47
+ inputHit: .1,
48
+ output: 9
49
+ }),
50
+ "deepseek-v4-pro": Object.freeze({
51
+ inputMiss: 9,
52
+ inputHit: .3,
53
+ output: 27
54
+ })
55
+ });
56
+ /**
57
+ * Resolve a model id against a price table by longest matching prefix.
58
+ *
59
+ * Prefixes, not exact ids, because adapters append route suffixes (vision,
60
+ * dated snapshots) that share the base model's price. The value type is open
61
+ * because the readout's per-token price and the backfill's peak/off-peak pairs
62
+ * both key off the same prefix rule.
63
+ * @param model - the session's last-used model id.
64
+ * @param table - prices keyed by model-id prefix.
65
+ * @returns the matched entry, or undefined when no prefix matches.
66
+ */
67
+ function priceForModel(model, table) {
68
+ let best;
69
+ let bestLength = 0;
70
+ for (const [prefix, price] of Object.entries(table)) if (prefix.length > bestLength && model.startsWith(prefix)) {
71
+ best = price;
72
+ bestLength = prefix.length;
73
+ }
74
+ return best;
75
+ }
76
+ /**
77
+ * Estimate one conversation's cost in CNY.
78
+ *
79
+ * Prompt tokens that missed the cache (uncached input plus cache writes) bill
80
+ * at the miss rate; cache-hit prompt tokens bill at the hit rate; completion
81
+ * tokens bill at the output rate. The result is exact arithmetic over the
82
+ * projected buckets — the estimate error is entirely the price table's.
83
+ * @param usage - the session's four disjoint billing buckets.
84
+ * @param price - the matched model price.
85
+ * @returns estimated cost in CNY.
86
+ */
87
+ function estimateCostCny(usage, price) {
88
+ return ((usage.uncachedInputTokens + usage.cacheWriteTokens) * price.inputMiss + usage.cacheReadTokens * price.inputHit + usage.outputTokens * price.output) / 1e6;
89
+ }
90
+ /**
91
+ * Total billed tokens across the projection's four disjoint buckets.
92
+ * @param usage - the session's four disjoint billing buckets.
93
+ * @returns prompt-side billed input plus output.
94
+ */
95
+ function billedTokens(usage) {
96
+ return usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens + usage.outputTokens;
97
+ }
98
+ //#endregion
99
+ //#region \0dsh-css:C:\Users\Administrator\deepseek-harness\packages\client\ui-token-usage\src\client\TokenUsageDock.module.css.mjs
100
+ const css = ".ogYLWa_root{max-width:var(--dsh-chat-content-width);box-sizing:border-box;width:100%;padding:4px calc(var(--dsh-composer-side-clearance) + 16px) 0px;font-size:var(--dsh-content-font-size-secondary,13px);line-height:calc(20px + var(--dsh-content-font-delta-secondary,0px));flex-wrap:wrap;justify-content:center;margin:0 auto;display:flex}.ogYLWa_readout{min-width:0;color:var(--dsw-alias-label-tertiary);font-variant-numeric:tabular-nums;white-space:nowrap;align-items:baseline;gap:6px;display:flex}.ogYLWa_cell{align-items:baseline;gap:4px;min-width:0;display:inline-flex}.ogYLWa_sep{opacity:.5}.ogYLWa_name{opacity:.72}.ogYLWa_value,.ogYLWa_cost{color:var(--dsw-alias-label-secondary)}.ogYLWa_notice{text-align:center;color:var(--dsw-alias-label-tertiary);flex-basis:100%}";
101
+ const tagId = "@jerry_chzy/dsh-token-usage/TokenUsageDock.module.css";
102
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
103
+ const tag = document.createElement("style");
104
+ tag.dataset.plugin = "@jerry_chzy/dsh-token-usage";
105
+ tag.dataset.pluginCss = tagId;
106
+ tag.textContent = css;
107
+ document.head.appendChild(tag);
108
+ }
109
+ var TokenUsageDock_module_css_default = {
110
+ "cell": "ogYLWa_cell",
111
+ "cost": "ogYLWa_cost",
112
+ "name": "ogYLWa_name",
113
+ "notice": "ogYLWa_notice",
114
+ "readout": "ogYLWa_readout",
115
+ "root": "ogYLWa_root",
116
+ "sep": "ogYLWa_sep",
117
+ "value": "ogYLWa_value"
118
+ };
119
+ //#endregion
120
+ //#region src/client/TokenUsageDock.tsx
121
+ /**
122
+ * Bind the dictionary's compact-count suffixes to the shared formatter.
123
+ * @param t - tokenUsage locale seat.
124
+ * @returns suffix renderers for this namespace.
125
+ */
126
+ function localeUnits(t) {
127
+ return {
128
+ thousand: (value) => t("count.thousand", { value }),
129
+ million: (value) => t("count.million", { value })
130
+ };
131
+ }
132
+ /**
133
+ * One conversation's classified token readout; renders nothing before its
134
+ * first billed step or before the pricing projection arrives.
135
+ * @param props - the slot's standard session shares and this namespace's locale seat.
136
+ * @returns the readout row, or null when the session has no billed usage.
137
+ */
138
+ function TokenUsageDock({ useProjection, t }) {
139
+ const usage = useProjection("tokenUsage");
140
+ const selection = useProjection("modelSelection");
141
+ const pricing = useProjection("tokenPricing");
142
+ const backfill = useProjection("tokenCostBackfill");
143
+ const pressure = useProjection("contextPressure");
144
+ if (usage === void 0 || billedTokens(usage) === 0) return null;
145
+ const units = localeUnits(t);
146
+ const model = selection?.lastUsed?.model ?? selection?.next?.model;
147
+ const price = model === void 0 || pricing === void 0 ? void 0 : priceForModel(model, pricing.prices);
148
+ const cost = price === void 0 ? void 0 : estimateCostCny(usage, price);
149
+ const currencySymbol = pricing?.currencySymbol ?? "";
150
+ const total = billedTokens(usage);
151
+ const contextUsed = pressure?.projectedTokens ?? pressure?.pressureTokens;
152
+ const contextValue = contextUsed === void 0 ? void 0 : pressure?.contextWindow === void 0 ? formatTokens(contextUsed, units) : t("context.usage", {
153
+ used: formatTokens(contextUsed, units),
154
+ window: formatTokens(pressure.contextWindow, units)
155
+ });
156
+ const cells = [
157
+ {
158
+ key: "total",
159
+ label: t("label.total"),
160
+ value: formatTokens(total, units)
161
+ },
162
+ {
163
+ key: "label.input",
164
+ label: t("label.input"),
165
+ value: formatTokens(usage.uncachedInputTokens, units)
166
+ },
167
+ ...usage.cacheReadTokens === 0 ? [] : [{
168
+ key: "label.cacheRead",
169
+ label: t("label.cacheRead"),
170
+ value: formatTokens(usage.cacheReadTokens, units)
171
+ }],
172
+ ...usage.cacheWriteTokens === 0 ? [] : [{
173
+ key: "label.cacheWrite",
174
+ label: t("label.cacheWrite"),
175
+ value: formatTokens(usage.cacheWriteTokens, units)
176
+ }],
177
+ {
178
+ key: "label.output",
179
+ label: t("label.output"),
180
+ value: formatTokens(usage.outputTokens, units)
181
+ },
182
+ ...contextValue === void 0 ? [] : [{
183
+ key: "context",
184
+ label: t("label.context"),
185
+ value: contextValue
186
+ }]
187
+ ];
188
+ const aria = [
189
+ t("aria.readout", {
190
+ total: formatTokens(total, units),
191
+ input: formatTokens(usage.uncachedInputTokens, units),
192
+ cacheRead: formatTokens(usage.cacheReadTokens, units),
193
+ cacheWrite: formatTokens(usage.cacheWriteTokens, units),
194
+ output: formatTokens(usage.outputTokens, units)
195
+ }),
196
+ ...contextValue === void 0 ? [] : [t("aria.context", { value: contextValue })],
197
+ ...cost === void 0 ? [] : [t("aria.cost", {
198
+ symbol: currencySymbol,
199
+ amount: formatAmount(cost)
200
+ })]
201
+ ].join(" · ");
202
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
203
+ className: TokenUsageDock_module_css_default.root,
204
+ "data-token-usage": true,
205
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
206
+ className: TokenUsageDock_module_css_default.readout,
207
+ role: "group",
208
+ "aria-label": aria,
209
+ children: [cells.map((cell, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
210
+ className: TokenUsageDock_module_css_default.cell,
211
+ children: [
212
+ index > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
213
+ className: TokenUsageDock_module_css_default.sep,
214
+ "aria-hidden": true,
215
+ children: "·"
216
+ }),
217
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
218
+ className: TokenUsageDock_module_css_default.name,
219
+ children: cell.label
220
+ }),
221
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
222
+ className: TokenUsageDock_module_css_default.value,
223
+ children: cell.value
224
+ })
225
+ ]
226
+ }, cell.key)), cost !== void 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
227
+ className: TokenUsageDock_module_css_default.cost,
228
+ children: t("cost.estimate", {
229
+ symbol: currencySymbol,
230
+ amount: formatAmount(cost)
231
+ })
232
+ })]
233
+ }), backfill !== void 0 && backfill.unpricedRoutes.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
234
+ className: TokenUsageDock_module_css_default.notice,
235
+ role: "note",
236
+ children: backfill.filePath === null ? t("backfill.noticeNoPath", { count: backfill.unpricedRoutes.length }) : t("backfill.notice", {
237
+ count: backfill.unpricedRoutes.length,
238
+ path: backfill.filePath
239
+ })
240
+ })]
241
+ });
242
+ }
243
+ //#endregion
244
+ //#region src/client/locales.ts
245
+ /** `tokenUsage` namespace dictionaries: the composer-dock readout's copy. */
246
+ /** Dictionary namespace owned by this plugin. */
247
+ const NS = "tokenUsage";
248
+ /** Simplified Chinese dictionary (the key-set source of truth). */
249
+ const zh = {
250
+ "count.thousand": "{value}K",
251
+ "count.million": "{value}M",
252
+ "label.total": "合计",
253
+ "label.context": "上下文",
254
+ "label.input": "输入",
255
+ "label.output": "输出",
256
+ "label.cacheRead": "缓存读",
257
+ "label.cacheWrite": "缓存写",
258
+ "context.usage": "{used}/{window}",
259
+ "cost.estimate": "≈{symbol}{amount}",
260
+ "backfill.notice": "有 {count} 条模型路由没有配置价格,历史金额回填文件 {path} 内给出了补充价格的示范",
261
+ "backfill.noticeNoPath": "有 {count} 条模型路由没有配置价格;本会话未记录工作目录,没有生成回填文件",
262
+ "aria.readout": "本会话 token 用量:合计 {total},输入 {input},缓存读 {cacheRead},缓存写 {cacheWrite},输出 {output}",
263
+ "aria.context": "上下文已用 {value}",
264
+ "aria.cost": "估算花费 {symbol}{amount}"
265
+ };
266
+ /** English dictionary, checked complete against the zh key set. */
267
+ const en = {
268
+ "count.thousand": "{value}K",
269
+ "count.million": "{value}M",
270
+ "label.total": "total",
271
+ "label.context": "context",
272
+ "label.input": "in",
273
+ "label.output": "out",
274
+ "label.cacheRead": "cache read",
275
+ "label.cacheWrite": "cache write",
276
+ "context.usage": "{used}/{window}",
277
+ "cost.estimate": "≈{symbol}{amount}",
278
+ "backfill.notice": "{count} model route(s) have no configured price; the history cost file {path} shows how to add one",
279
+ "backfill.noticeNoPath": "{count} model route(s) have no configured price; this session records no working directory, so no cost file was written",
280
+ "aria.readout": "This conversation token usage: {total} total, {input} input, {cacheRead} cache read, {cacheWrite} cache write, {output} output",
281
+ "aria.context": "Context used {value}",
282
+ "aria.cost": "Estimated cost {symbol}{amount}"
283
+ };
284
+ //#endregion
285
+ //#region src/client/index.ts
286
+ /** Required services for the readout: slot contribution and its dictionaries. */
287
+ const inject = ["slots", "locale"];
288
+ /**
289
+ * Client plugin body: register the dictionaries and the composer-dock entry.
290
+ * @param ctx - client root context.
291
+ */
292
+ function apply(ctx) {
293
+ ctx.effect(() => ctx.locale.register(NS, {
294
+ zh,
295
+ en
296
+ }), "ui-token-usage: dictionaries");
297
+ ctx.slots.inject("conversation.composer.dock", () => ctx.slots.register({
298
+ name: "conversation.composer.dock",
299
+ id: "token-usage",
300
+ order: 10,
301
+ locale: NS
302
+ }, TokenUsageDock));
303
+ }
304
+ //#endregion
305
+ exports.apply = apply;
306
+ exports.inject = inject;
307
+ return module.exports;
308
+ }
309
+ });
310
+
311
+ //# sourceMappingURL=client.js.map