opencode-visual-cache 1.7.0-beta.2 → 1.7.0-beta.4

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.
@@ -1 +1 @@
1
- export declare const PLUGIN_VERSION = "1.7.0-beta.2";
1
+ export declare const PLUGIN_VERSION = "1.7.0-beta.4";
package/dist/_version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  // auto-generated
2
- export const PLUGIN_VERSION = "1.7.0-beta.2";
2
+ export const PLUGIN_VERSION = "1.7.0-beta.4";
@@ -103,8 +103,34 @@ const moonshotProvider = {
103
103
  return [{ currency: "CNY", total: String(balance) }];
104
104
  },
105
105
  };
106
+ const hyperProvider = {
107
+ id: "hyper",
108
+ name: "Charm Hyper",
109
+ keyPlaceholder: "sk-hyper-...",
110
+ async fetchBalance(apiKey, signal) {
111
+ // 官方接口:GET /v1/credits → {"balance": 98}(积分余额)
112
+ const res = await fetch("https://hyper.charm.land/v1/credits", {
113
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
114
+ signal,
115
+ });
116
+ if (!res.ok) {
117
+ if (res.status === 401)
118
+ throw new BalanceError("401");
119
+ if (res.status === 403)
120
+ throw new BalanceError("403");
121
+ throw new BalanceError(String(res.status));
122
+ }
123
+ const json = await res.json();
124
+ const balance = json.balance;
125
+ if (typeof balance === "undefined" || balance === null)
126
+ throw new BalanceError("EMPTY");
127
+ // hyper 积分换算:100 积分 = $5,即 1 积分 = $0.05
128
+ const usd = (Number(balance) * 0.05).toFixed(2);
129
+ return [{ currency: "USD", total: usd }];
130
+ },
131
+ };
106
132
  /** 已注册的 provider 列表(按需追加新适配器)。 */
107
- export const balanceProviders = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider];
133
+ export const balanceProviders = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider, hyperProvider];
108
134
  /** 按 id 取 provider;未知 id 回退到第一个。 */
109
135
  export function getBalanceProvider(id) {
110
136
  return balanceProviders.find((p) => p.id === id) ?? balanceProviders[0] ?? deepseekProvider;
package/dist/index.js CHANGED
@@ -425,7 +425,10 @@ const tui = async (api) => {
425
425
  order: 55,
426
426
  slots: {
427
427
  session_prompt(_ctx, input) {
428
- return (_jsx(api.ui.Prompt, { sessionID: input.session_id, visible: input.visible, disabled: input.disabled, onSubmit: input.on_submit, ref: input.ref, hint: _jsx(BottomStatusBar, { api: api, signals: signals, sessionId: input.session_id }) }));
428
+ return (_jsx(api.ui.Prompt, { sessionID: input.session_id, visible: input.visible, disabled: input.disabled, onSubmit: input.on_submit, ref: input.ref, hint: _jsx(BottomStatusBar, { api: api, signals: signals, sessionId: input.session_id }),
429
+ // 接管 session_prompt 后需透传宿主的 session_prompt_right 插槽,
430
+ // 否则 oc-tps 等依赖该插槽的插件无法显示;无注册时 Slot 为 null。
431
+ right: _jsx(api.ui.Slot, { name: "session_prompt_right", session_id: input.session_id }) }));
429
432
  },
430
433
  },
431
434
  });
package/dist/server.d.ts CHANGED
@@ -1,6 +1,3 @@
1
1
  import type { PluginModule } from "@opencode-ai/plugin";
2
- import v2Mod from "./v2/index";
3
- declare const mod: PluginModule & {
4
- setup: typeof v2Mod.setup;
5
- };
2
+ declare const mod: PluginModule;
6
3
  export default mod;
package/dist/server.js CHANGED
@@ -1,10 +1,6 @@
1
- import v2Mod from "./v2/index";
2
- // V1 server 插件(空实现,保持原行为);V2 经 exports["./server"] 加载此入口,
3
- // 需要 default.setup——此处复用 v2 的 setup,一个入口同时满足 V1(server)与 V2(setup)。
4
1
  const server = async () => ({});
5
2
  const mod = {
6
3
  id: "opencode-visual-cache",
7
4
  server,
8
- setup: v2Mod.setup,
9
5
  };
10
6
  export default mod;
package/dist/tui.js CHANGED
@@ -95,7 +95,28 @@ var moonshotProvider = {
95
95
  return [{ currency: "CNY", total: String(balance) }];
96
96
  }
97
97
  };
98
- var balanceProviders = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider];
98
+ var hyperProvider = {
99
+ id: "hyper",
100
+ name: "Charm Hyper",
101
+ keyPlaceholder: "sk-hyper-...",
102
+ async fetchBalance(apiKey, signal) {
103
+ const res = await fetch("https://hyper.charm.land/v1/credits", {
104
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
105
+ signal
106
+ });
107
+ if (!res.ok) {
108
+ if (res.status === 401) throw new BalanceError("401");
109
+ if (res.status === 403) throw new BalanceError("403");
110
+ throw new BalanceError(String(res.status));
111
+ }
112
+ const json = await res.json();
113
+ const balance = json.balance;
114
+ if (typeof balance === "undefined" || balance === null) throw new BalanceError("EMPTY");
115
+ const usd = (Number(balance) * 0.05).toFixed(2);
116
+ return [{ currency: "USD", total: usd }];
117
+ }
118
+ };
119
+ var balanceProviders = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider, hyperProvider];
99
120
  function getBalanceProvider(id) {
100
121
  return balanceProviders.find((p) => p.id === id) ?? balanceProviders[0] ?? deepseekProvider;
101
122
  }
@@ -684,7 +705,7 @@ import { createElement as _$createElement } from "@opentui/solid";
684
705
  import { createMemo, createSignal, createEffect, onMount, onCleanup, Show, untrack } from "solid-js";
685
706
 
686
707
  // src/_version.ts
687
- var PLUGIN_VERSION = "1.7.0-beta.2";
708
+ var PLUGIN_VERSION = "1.7.0-beta.4";
688
709
 
689
710
  // src/panel/TokenCachePanel.tsx
690
711
  var MIN_PANEL_WIDTH = 20;
@@ -2415,6 +2436,14 @@ var tui = async (api) => {
2415
2436
  return input.session_id;
2416
2437
  }
2417
2438
  });
2439
+ },
2440
+ get right() {
2441
+ return _$createComponent2(api.ui.Slot, {
2442
+ name: "session_prompt_right",
2443
+ get session_id() {
2444
+ return input.session_id;
2445
+ }
2446
+ });
2418
2447
  }
2419
2448
  });
2420
2449
  }
@@ -1,4 +1,6 @@
1
1
  /** @jsxImportSource @opentui/solid */
2
2
  import type { PluginModule } from "./types";
3
- declare const mod: PluginModule;
3
+ declare const mod: PluginModule & {
4
+ server: () => Promise<Record<string, never>>;
5
+ };
4
6
  export default mod;
package/dist/v2/index.js CHANGED
@@ -159,5 +159,8 @@ const mod = {
159
159
  // 偏好持久化(实验:storage.store 用法验证)
160
160
  context.storage.store("opencode-visual-cache.panel", { initial: { collapsed: false } });
161
161
  },
162
+ // V1 server 空实现(兼容标记):参考 oh-my-opencode-slim 的 { id, server, setup }——
163
+ // v2 加载 setup,但 V1 检测需要 server 字段识别为插件
164
+ server: async () => ({}),
162
165
  };
163
166
  export default mod;
package/dist/v2.js CHANGED
@@ -252,7 +252,28 @@ var moonshotProvider = {
252
252
  return [{ currency: "CNY", total: String(balance) }];
253
253
  }
254
254
  };
255
- var balanceProviders = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider];
255
+ var hyperProvider = {
256
+ id: "hyper",
257
+ name: "Charm Hyper",
258
+ keyPlaceholder: "sk-hyper-...",
259
+ async fetchBalance(apiKey, signal) {
260
+ const res = await fetch("https://hyper.charm.land/v1/credits", {
261
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
262
+ signal
263
+ });
264
+ if (!res.ok) {
265
+ if (res.status === 401) throw new BalanceError("401");
266
+ if (res.status === 403) throw new BalanceError("403");
267
+ throw new BalanceError(String(res.status));
268
+ }
269
+ const json = await res.json();
270
+ const balance = json.balance;
271
+ if (typeof balance === "undefined" || balance === null) throw new BalanceError("EMPTY");
272
+ const usd = (Number(balance) * 0.05).toFixed(2);
273
+ return [{ currency: "USD", total: usd }];
274
+ }
275
+ };
276
+ var balanceProviders = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider, hyperProvider];
256
277
  function getBalanceProvider(id) {
257
278
  return balanceProviders.find((p) => p.id === id) ?? balanceProviders[0] ?? deepseekProvider;
258
279
  }
@@ -822,7 +843,7 @@ function estimateTokens(text) {
822
843
  }
823
844
 
824
845
  // src/_version.ts
825
- var PLUGIN_VERSION = "1.7.0-beta.2";
846
+ var PLUGIN_VERSION = "1.7.0-beta.4";
826
847
 
827
848
  // src/panel/TokenCachePanel.tsx
828
849
  var MIN_PANEL_WIDTH = 20;
@@ -2933,7 +2954,10 @@ var mod = {
2933
2954
  collapsed: false
2934
2955
  }
2935
2956
  });
2936
- }
2957
+ },
2958
+ // V1 server 空实现(兼容标记):参考 oh-my-opencode-slim 的 { id, server, setup }——
2959
+ // v2 加载 setup,但 V1 检测需要 server 字段识别为插件
2960
+ server: async () => ({})
2937
2961
  };
2938
2962
  var index_default = mod;
2939
2963
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-visual-cache",
3
- "version": "1.7.0-beta.2",
3
+ "version": "1.7.0-beta.4",
4
4
  "description": "OpenCode TUI plugin displaying real-time token cache hit rate in the sidebar",
5
5
  "type": "module",
6
6
  "types": "dist/index.d.ts",
@@ -10,7 +10,7 @@
10
10
  "types": "./dist/server.d.ts"
11
11
  },
12
12
  "./tui": {
13
- "import": "./dist/tui.js",
13
+ "import": "./tui/index.js",
14
14
  "config": {
15
15
  "enabled": true
16
16
  }
@@ -22,6 +22,7 @@
22
22
  "files": [
23
23
  "dist",
24
24
  "src",
25
+ "tui",
25
26
  "install.mjs",
26
27
  "README.md",
27
28
  "README_EN.md"
package/src/_version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // auto-generated
2
- export const PLUGIN_VERSION="1.7.0-beta.2";
2
+ export const PLUGIN_VERSION="1.7.0-beta.4";
@@ -125,8 +125,32 @@ const moonshotProvider: BalanceProvider = {
125
125
  },
126
126
  }
127
127
 
128
+ const hyperProvider: BalanceProvider = {
129
+ id: "hyper",
130
+ name: "Charm Hyper",
131
+ keyPlaceholder: "sk-hyper-...",
132
+ async fetchBalance(apiKey, signal) {
133
+ // 官方接口:GET /v1/credits → {"balance": 98}(积分余额)
134
+ const res = await fetch("https://hyper.charm.land/v1/credits", {
135
+ headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
136
+ signal,
137
+ })
138
+ if (!res.ok) {
139
+ if (res.status === 401) throw new BalanceError("401")
140
+ if (res.status === 403) throw new BalanceError("403")
141
+ throw new BalanceError(String(res.status))
142
+ }
143
+ const json = await res.json() as { balance?: string | number }
144
+ const balance = json.balance
145
+ if (typeof balance === "undefined" || balance === null) throw new BalanceError("EMPTY")
146
+ // hyper 积分换算:100 积分 = $5,即 1 积分 = $0.05
147
+ const usd = (Number(balance) * 0.05).toFixed(2)
148
+ return [{ currency: "USD", total: usd }]
149
+ },
150
+ }
151
+
128
152
  /** 已注册的 provider 列表(按需追加新适配器)。 */
129
- export const balanceProviders: BalanceProvider[] = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider]
153
+ export const balanceProviders: BalanceProvider[] = [deepseekProvider, siliconflowProvider, openrouterProvider, moonshotProvider, hyperProvider]
130
154
 
131
155
  /** 按 id 取 provider;未知 id 回退到第一个。 */
132
156
  export function getBalanceProvider(id: string): BalanceProvider {
package/src/core/color.ts CHANGED
@@ -1,108 +1,108 @@
1
- /** Extract { r, g, b } (0–255) from a hex string or RGBA-like object. */
2
- export function rgb(raw: unknown): { r: number; g: number; b: number } | null {
3
- if (typeof raw === "string" && raw.startsWith("#")) {
4
- const h = raw.slice(1)
5
- return {
6
- r: parseInt(h.slice(0, 2), 16),
7
- g: parseInt(h.slice(2, 4), 16),
8
- b: parseInt(h.slice(4, 6), 16),
9
- }
10
- }
11
- if (raw && typeof raw === "object") {
12
- const o = raw as Record<string, unknown>
13
- if (typeof o.r === "number" && typeof o.g === "number" && typeof o.b === "number") {
14
- // RGBA channels may be 0-1 floats; detect and upscale.
15
- const scale = o.r > 1 || o.g > 1 || o.b > 1 ? 1 : 255
16
- return {
17
- r: Math.round(o.r * scale),
18
- g: Math.round(o.g * scale),
19
- b: Math.round(o.b * scale),
20
- }
21
- }
22
- }
23
- return null
24
- }
25
-
26
- /** HSL saturation of an RGB color (0–1). */
27
- export function saturation(r: number, g: number, b: number): number {
28
- const max = Math.max(r, g, b) / 255
29
- const min = Math.min(r, g, b) / 255
30
- const delta = max - min
31
- if (delta === 0) return 0
32
- const L = (max + min) / 2
33
- return L <= 0.5 ? delta / (max + min) : delta / (2 - max - min)
34
- }
35
-
36
- /**
37
- * If the colour's saturation exceeds `maxSat`, pull it toward grey
38
- * until saturation drops to maxSat. Returns a hex string.
39
- */
40
- export function desaturateTo(raw: unknown, maxSat: number, fallback: string): string {
41
- const c = rgb(raw)
42
- if (!c) return fallback
43
- const sat = saturation(c.r, c.g, c.b)
44
- if (sat <= maxSat) {
45
- // already muted — return as hex
46
- return "#" + [c.r, c.g, c.b].map((v) => v.toString(16).padStart(2, "0")).join("")
47
- }
48
- /**
49
- * Binary search for the optimal grey-mix ratio α (0…1).
50
- *
51
- * 12 iterations → 1/2^12 ≈ 1/4096 resolution. The downstream RGB
52
- * channels are only 0–255 (8 bit), so 8 iterations (1/256) would
53
- * technically suffice; 12 is intentionally over-budget — the extra
54
- * precision costs almost nothing and guarantees the saturation probe
55
- * converges to within a fraction of an 8‑bit step, eliminating
56
- * colour banding in edge cases.
57
- */
58
- // Bt.601 luma (perceptual brightness used as the grey anchor)
59
- const luma = c.r * 0.299 + c.g * 0.587 + c.b * 0.114
60
- let lo = 0, hi = 1
61
- for (let i = 0; i < 12; i++) {
62
- const mid = (lo + hi) / 2
63
- const nr = Math.round(c.r + (luma - c.r) * mid)
64
- const ng = Math.round(c.g + (luma - c.g) * mid)
65
- const nb = Math.round(c.b + (luma - c.b) * mid)
66
- if (saturation(nr, ng, nb) > maxSat) lo = mid
67
- else hi = mid
68
- }
69
- const nr = Math.round(c.r + (luma - c.r) * hi)
70
- const ng = Math.round(c.g + (luma - c.g) * hi)
71
- const nb = Math.round(c.b + (luma - c.b) * hi)
72
- return "#" + [nr, ng, nb].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("")
73
- }
74
-
75
- /** Darken a hex colour by multiplying each channel by `factor` (0–1). */
76
- export function dimColor(hex: string, factor = 0.5): string {
77
- const c = rgb(hex)
78
- if (!c) return hex
79
- const r = Math.round(c.r * factor)
80
- const g = Math.round(c.g * factor)
81
- const b = Math.round(c.b * factor)
82
- return "#" + [r, g, b].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("")
83
- }
84
-
85
- // Morandi fallbacks — used when a theme colour cannot be resolved
86
- export const FALLBACK = {
87
- primary: "#8B9DAF",
88
- text: "#C5C5BB",
89
- muted: "#7A7A72",
90
- success: "#9CAF8B",
91
- warning: "#C5B88D",
92
- error: "#B08A8A",
93
- border: "#6B6B63",
94
- } as const
95
-
96
- /**
97
- * Desaturation ceiling for the Morandi-style palette.
98
- *
99
- * Morandi colours float around 0.15–0.30 saturation in HSL space.
100
- * 0.28 sits near the upper end of that range: it strips the aggressive
101
- * punch from high-saturation themes (Dracula, Solarized …) while
102
- * preserving enough colour identity that green / orange / red hit-rate
103
- * coding stays distinguishable.
104
- *
105
- * Lower → more grey, harder to tell colours apart.
106
- * Higher → bright themes bleed through and defeat the muted look.
107
- */
108
- export const MAX_SAT = 0.28
1
+ /** Extract { r, g, b } (0–255) from a hex string or RGBA-like object. */
2
+ export function rgb(raw: unknown): { r: number; g: number; b: number } | null {
3
+ if (typeof raw === "string" && raw.startsWith("#")) {
4
+ const h = raw.slice(1)
5
+ return {
6
+ r: parseInt(h.slice(0, 2), 16),
7
+ g: parseInt(h.slice(2, 4), 16),
8
+ b: parseInt(h.slice(4, 6), 16),
9
+ }
10
+ }
11
+ if (raw && typeof raw === "object") {
12
+ const o = raw as Record<string, unknown>
13
+ if (typeof o.r === "number" && typeof o.g === "number" && typeof o.b === "number") {
14
+ // RGBA channels may be 0-1 floats; detect and upscale.
15
+ const scale = o.r > 1 || o.g > 1 || o.b > 1 ? 1 : 255
16
+ return {
17
+ r: Math.round(o.r * scale),
18
+ g: Math.round(o.g * scale),
19
+ b: Math.round(o.b * scale),
20
+ }
21
+ }
22
+ }
23
+ return null
24
+ }
25
+
26
+ /** HSL saturation of an RGB color (0–1). */
27
+ export function saturation(r: number, g: number, b: number): number {
28
+ const max = Math.max(r, g, b) / 255
29
+ const min = Math.min(r, g, b) / 255
30
+ const delta = max - min
31
+ if (delta === 0) return 0
32
+ const L = (max + min) / 2
33
+ return L <= 0.5 ? delta / (max + min) : delta / (2 - max - min)
34
+ }
35
+
36
+ /**
37
+ * If the colour's saturation exceeds `maxSat`, pull it toward grey
38
+ * until saturation drops to maxSat. Returns a hex string.
39
+ */
40
+ export function desaturateTo(raw: unknown, maxSat: number, fallback: string): string {
41
+ const c = rgb(raw)
42
+ if (!c) return fallback
43
+ const sat = saturation(c.r, c.g, c.b)
44
+ if (sat <= maxSat) {
45
+ // already muted — return as hex
46
+ return "#" + [c.r, c.g, c.b].map((v) => v.toString(16).padStart(2, "0")).join("")
47
+ }
48
+ /**
49
+ * Binary search for the optimal grey-mix ratio α (0…1).
50
+ *
51
+ * 12 iterations → 1/2^12 ≈ 1/4096 resolution. The downstream RGB
52
+ * channels are only 0–255 (8 bit), so 8 iterations (1/256) would
53
+ * technically suffice; 12 is intentionally over-budget — the extra
54
+ * precision costs almost nothing and guarantees the saturation probe
55
+ * converges to within a fraction of an 8‑bit step, eliminating
56
+ * colour banding in edge cases.
57
+ */
58
+ // Bt.601 luma (perceptual brightness used as the grey anchor)
59
+ const luma = c.r * 0.299 + c.g * 0.587 + c.b * 0.114
60
+ let lo = 0, hi = 1
61
+ for (let i = 0; i < 12; i++) {
62
+ const mid = (lo + hi) / 2
63
+ const nr = Math.round(c.r + (luma - c.r) * mid)
64
+ const ng = Math.round(c.g + (luma - c.g) * mid)
65
+ const nb = Math.round(c.b + (luma - c.b) * mid)
66
+ if (saturation(nr, ng, nb) > maxSat) lo = mid
67
+ else hi = mid
68
+ }
69
+ const nr = Math.round(c.r + (luma - c.r) * hi)
70
+ const ng = Math.round(c.g + (luma - c.g) * hi)
71
+ const nb = Math.round(c.b + (luma - c.b) * hi)
72
+ return "#" + [nr, ng, nb].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("")
73
+ }
74
+
75
+ /** Darken a hex colour by multiplying each channel by `factor` (0–1). */
76
+ export function dimColor(hex: string, factor = 0.5): string {
77
+ const c = rgb(hex)
78
+ if (!c) return hex
79
+ const r = Math.round(c.r * factor)
80
+ const g = Math.round(c.g * factor)
81
+ const b = Math.round(c.b * factor)
82
+ return "#" + [r, g, b].map((v) => Math.max(0, Math.min(255, v)).toString(16).padStart(2, "0")).join("")
83
+ }
84
+
85
+ // Morandi fallbacks — used when a theme colour cannot be resolved
86
+ export const FALLBACK = {
87
+ primary: "#8B9DAF",
88
+ text: "#C5C5BB",
89
+ muted: "#7A7A72",
90
+ success: "#9CAF8B",
91
+ warning: "#C5B88D",
92
+ error: "#B08A8A",
93
+ border: "#6B6B63",
94
+ } as const
95
+
96
+ /**
97
+ * Desaturation ceiling for the Morandi-style palette.
98
+ *
99
+ * Morandi colours float around 0.15–0.30 saturation in HSL space.
100
+ * 0.28 sits near the upper end of that range: it strips the aggressive
101
+ * punch from high-saturation themes (Dracula, Solarized …) while
102
+ * preserving enough colour identity that green / orange / red hit-rate
103
+ * coding stays distinguishable.
104
+ *
105
+ * Lower → more grey, harder to tell colours apart.
106
+ * Higher → bright themes bleed through and defeat the muted look.
107
+ */
108
+ export const MAX_SAT = 0.28
@@ -1,46 +1,46 @@
1
- import type { BalanceEntry } from "../balance-providers"
2
- import { formatBalanceAmount } from "./format"
3
-
4
- export const CURRENCIES: Record<string, string> = {
5
- USD: "$", CNY: "¥", EUR: "€", JPY: "JP¥", GBP: "£", KRW: "₩",
6
- }
7
- /** Approximate USD exchange rates — used as defaults when switching currency.
8
- * Users can override via /cache-rate. Last updated 2026-05. */
9
- export const DEFAULT_RATES: Record<string, number> = {
10
- USD: 1, CNY: 7.2, EUR: 0.92, JPY: 150, GBP: 0.79, KRW: 1350,
11
- }
12
-
13
- /**
14
- * 将余额从来源币种换算为目标币种。
15
- * DEFAULT_RATES 以 USD=1 为基准:先折算为 USD,再换算到目标币种。
16
- */
17
- export function convertBalance(target: string, targetRate: number, amount: number, from: string): number {
18
- if (from === target) return amount
19
- const fromRate = DEFAULT_RATES[from] ?? 1
20
- const usd = from === "USD" ? amount : amount / fromRate
21
- return target === "USD" ? usd : usd * targetRate
22
- }
23
-
24
- /** 货币符号:优先取 /cache-currency 内置映射,未知币种回退为代码。 */
25
- export function balanceSymbol(currency: string): string {
26
- const sym = CURRENCIES[currency]
27
- return sym ?? currency + " "
28
- }
29
-
30
- /**
31
- * 将余额列表格式化为单行文本。
32
- * 优先直接显示偏好币种(CNY/USD…);偏好币种为换算币种时按汇率折算第一条余额。
33
- */
34
- export function formatBalanceText(list: BalanceEntry[], pref: string, rate: number): string {
35
- const native = pref ? list.find((x) => x.currency === pref) : undefined
36
- if (native) return balanceSymbol(native.currency) + formatBalanceAmount(native.total)
37
- const base = list[0]
38
- const baseAmt = parseFloat(base.total)
39
- const converted = Number.isFinite(baseAmt)
40
- ? convertBalance(pref || base.currency, rate, baseAmt, base.currency)
41
- : baseAmt
42
- const shown = pref && base.currency !== pref
43
- ? converted.toLocaleString("en-US", { maximumFractionDigits: 2 })
44
- : formatBalanceAmount(base.total)
45
- return balanceSymbol(pref || base.currency) + shown
46
- }
1
+ import type { BalanceEntry } from "../balance-providers"
2
+ import { formatBalanceAmount } from "./format"
3
+
4
+ export const CURRENCIES: Record<string, string> = {
5
+ USD: "$", CNY: "¥", EUR: "€", JPY: "JP¥", GBP: "£", KRW: "₩",
6
+ }
7
+ /** Approximate USD exchange rates — used as defaults when switching currency.
8
+ * Users can override via /cache-rate. Last updated 2026-05. */
9
+ export const DEFAULT_RATES: Record<string, number> = {
10
+ USD: 1, CNY: 7.2, EUR: 0.92, JPY: 150, GBP: 0.79, KRW: 1350,
11
+ }
12
+
13
+ /**
14
+ * 将余额从来源币种换算为目标币种。
15
+ * DEFAULT_RATES 以 USD=1 为基准:先折算为 USD,再换算到目标币种。
16
+ */
17
+ export function convertBalance(target: string, targetRate: number, amount: number, from: string): number {
18
+ if (from === target) return amount
19
+ const fromRate = DEFAULT_RATES[from] ?? 1
20
+ const usd = from === "USD" ? amount : amount / fromRate
21
+ return target === "USD" ? usd : usd * targetRate
22
+ }
23
+
24
+ /** 货币符号:优先取 /cache-currency 内置映射,未知币种回退为代码。 */
25
+ export function balanceSymbol(currency: string): string {
26
+ const sym = CURRENCIES[currency]
27
+ return sym ?? currency + " "
28
+ }
29
+
30
+ /**
31
+ * 将余额列表格式化为单行文本。
32
+ * 优先直接显示偏好币种(CNY/USD…);偏好币种为换算币种时按汇率折算第一条余额。
33
+ */
34
+ export function formatBalanceText(list: BalanceEntry[], pref: string, rate: number): string {
35
+ const native = pref ? list.find((x) => x.currency === pref) : undefined
36
+ if (native) return balanceSymbol(native.currency) + formatBalanceAmount(native.total)
37
+ const base = list[0]
38
+ const baseAmt = parseFloat(base.total)
39
+ const converted = Number.isFinite(baseAmt)
40
+ ? convertBalance(pref || base.currency, rate, baseAmt, base.currency)
41
+ : baseAmt
42
+ const shown = pref && base.currency !== pref
43
+ ? converted.toLocaleString("en-US", { maximumFractionDigits: 2 })
44
+ : formatBalanceAmount(base.total)
45
+ return balanceSymbol(pref || base.currency) + shown
46
+ }
@@ -1,36 +1,36 @@
1
- // ── token estimation ──
2
- // Character-based BPE approximation. Default ratios (~4 ASCII or ~1.5 CJK
3
- // chars per token) work well for natural language but systematically
4
- // under-count tokens in JSON and source code where every punctuation mark
5
- // tends to be its own token. Detect these cases and tighten the ratio.
6
- // See: GPT-4 / Claude tokenizer behaviour with structured text.
7
-
8
- export function estimateTokens(text: string): number {
9
- if (!text || text.length === 0) return 0
10
- let ascii = 0
11
- let cjk = 0
12
- for (const c of text) {
13
- const code = c.codePointAt(0) ?? 0
14
- if (code >= 0x4E00 && code <= 0x9FFF) cjk++ // CJK Unified
15
- else if (code >= 0x3040 && code <= 0x30FF) cjk++ // Hiragana/Katakana
16
- else if (code >= 0xAC00 && code <= 0xD7A3) cjk++ // Hangul
17
- else if (code >= 0x1100 && code <= 0x11FF) cjk++ // Hangul Jamo
18
- else if (code >= 0x2E80 && code <= 0x2EFF) cjk++ // CJK Radicals
19
- else ascii++
20
- }
21
-
22
- // Real BPE tokenizers (cl100k_base, o200k_base) average ~3.5-4.0
23
- // ASCII chars/token for both JSON and source code — close to prose.
24
- // The old 2.0 / 2.5 ratios matched minified-JS extremes, not typical
25
- // payloads, and systematically over-estimated token counts.
26
- const trimmed = text.trimStart()
27
- // Strip markdown code-fence prefix so that ```json … is detected as JSON
28
- const strippedFence = trimmed.replace(/^\x60{3}\w*\s*\n?/, "")
29
- const jsonLike = (strippedFence.startsWith("{") || strippedFence.startsWith("["))
30
- && /"[^"]+"\s*:/.test(text)
31
- const codeLike = !jsonLike
32
- && /```|^import |^export |^function |^const |^let |^var |^class |^interface |^type |^def |^fn |^pub |^use |^mod |^package /m.test(text)
33
-
34
- const asciiPerToken = jsonLike ? 3.5 : codeLike ? 3.5 : 4
35
- return Math.max(1, Math.ceil(ascii / asciiPerToken + cjk / 1.0))
36
- }
1
+ // ── token estimation ──
2
+ // Character-based BPE approximation. Default ratios (~4 ASCII or ~1.5 CJK
3
+ // chars per token) work well for natural language but systematically
4
+ // under-count tokens in JSON and source code where every punctuation mark
5
+ // tends to be its own token. Detect these cases and tighten the ratio.
6
+ // See: GPT-4 / Claude tokenizer behaviour with structured text.
7
+
8
+ export function estimateTokens(text: string): number {
9
+ if (!text || text.length === 0) return 0
10
+ let ascii = 0
11
+ let cjk = 0
12
+ for (const c of text) {
13
+ const code = c.codePointAt(0) ?? 0
14
+ if (code >= 0x4E00 && code <= 0x9FFF) cjk++ // CJK Unified
15
+ else if (code >= 0x3040 && code <= 0x30FF) cjk++ // Hiragana/Katakana
16
+ else if (code >= 0xAC00 && code <= 0xD7A3) cjk++ // Hangul
17
+ else if (code >= 0x1100 && code <= 0x11FF) cjk++ // Hangul Jamo
18
+ else if (code >= 0x2E80 && code <= 0x2EFF) cjk++ // CJK Radicals
19
+ else ascii++
20
+ }
21
+
22
+ // Real BPE tokenizers (cl100k_base, o200k_base) average ~3.5-4.0
23
+ // ASCII chars/token for both JSON and source code — close to prose.
24
+ // The old 2.0 / 2.5 ratios matched minified-JS extremes, not typical
25
+ // payloads, and systematically over-estimated token counts.
26
+ const trimmed = text.trimStart()
27
+ // Strip markdown code-fence prefix so that ```json … is detected as JSON
28
+ const strippedFence = trimmed.replace(/^\x60{3}\w*\s*\n?/, "")
29
+ const jsonLike = (strippedFence.startsWith("{") || strippedFence.startsWith("["))
30
+ && /"[^"]+"\s*:/.test(text)
31
+ const codeLike = !jsonLike
32
+ && /```|^import |^export |^function |^const |^let |^var |^class |^interface |^type |^def |^fn |^pub |^use |^mod |^package /m.test(text)
33
+
34
+ const asciiPerToken = jsonLike ? 3.5 : codeLike ? 3.5 : 4
35
+ return Math.max(1, Math.ceil(ascii / asciiPerToken + cjk / 1.0))
36
+ }