opencode-visual-cache 1.6.2 → 1.7.0-beta.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.
Files changed (62) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +247 -247
  3. package/README_EN.md +247 -247
  4. package/dist/_version.d.ts +1 -1
  5. package/dist/_version.js +1 -1
  6. package/dist/core/color.d.ts +37 -0
  7. package/dist/core/color.js +108 -0
  8. package/dist/core/currency.d.ts +17 -0
  9. package/dist/core/currency.js +43 -0
  10. package/dist/core/estimate.d.ts +1 -0
  11. package/dist/core/estimate.js +40 -0
  12. package/dist/core/format.d.ts +15 -0
  13. package/dist/core/format.js +90 -0
  14. package/dist/core/index.d.ts +5 -0
  15. package/dist/core/index.js +5 -0
  16. package/dist/core/types.d.ts +17 -0
  17. package/dist/core/types.js +1 -0
  18. package/dist/index.js +12 -818
  19. package/dist/panel/TokenCachePanel.d.ts +10 -0
  20. package/dist/panel/TokenCachePanel.js +549 -0
  21. package/dist/panel/panel-api.d.ts +119 -0
  22. package/dist/panel/panel-api.js +1 -0
  23. package/dist/tui.js +223 -209
  24. package/dist/v2/commands.d.ts +10 -0
  25. package/dist/v2/commands.js +490 -0
  26. package/dist/v2/data.d.ts +27 -0
  27. package/dist/v2/data.js +103 -0
  28. package/dist/v2/index.d.ts +4 -0
  29. package/dist/v2/index.js +163 -0
  30. package/dist/v2/sidebar.d.ts +6 -0
  31. package/dist/v2/sidebar.js +36 -0
  32. package/dist/v2/status.d.ts +14 -0
  33. package/dist/v2/status.js +83 -0
  34. package/dist/v2/theme.d.ts +8 -0
  35. package/dist/v2/theme.js +16 -0
  36. package/dist/v2/types.d.ts +219 -0
  37. package/dist/v2/types.js +6 -0
  38. package/dist/v2/v2-panel-api.d.ts +8 -0
  39. package/dist/v2/v2-panel-api.js +176 -0
  40. package/dist/v2.js +2941 -0
  41. package/package.json +72 -67
  42. package/src/_version.ts +1 -1
  43. package/src/balance-providers.ts +153 -153
  44. package/src/core/color.ts +108 -0
  45. package/src/core/currency.ts +46 -0
  46. package/src/core/estimate.ts +36 -0
  47. package/src/core/format.ts +81 -0
  48. package/src/core/index.ts +5 -0
  49. package/src/core/types.ts +17 -0
  50. package/src/i18n.ts +380 -380
  51. package/src/index.tsx +1035 -2120
  52. package/src/panel/TokenCachePanel.tsx +776 -0
  53. package/src/panel/panel-api.ts +104 -0
  54. package/src/server.ts +10 -10
  55. package/src/v2/commands.ts +471 -0
  56. package/src/v2/data.ts +112 -0
  57. package/src/v2/index.tsx +184 -0
  58. package/src/v2/sidebar.tsx +69 -0
  59. package/src/v2/status.tsx +96 -0
  60. package/src/v2/theme.ts +19 -0
  61. package/src/v2/types.ts +159 -0
  62. package/src/v2/v2-panel-api.ts +177 -0
package/src/v2/data.ts ADDED
@@ -0,0 +1,112 @@
1
+ import type { Context, MessageInfo } from "./types"
2
+ import { num } from "../core"
3
+
4
+ /** 汇总一个会话的 token 用量与费用(V2 adapter → 同构模型)。 */
5
+ export interface SessionStats {
6
+ input: number
7
+ output: number
8
+ cacheRead: number
9
+ cacheWrite: number
10
+ reasoning: number
11
+ cost: number
12
+ hasData: boolean
13
+ }
14
+
15
+ /** 从 messages 汇总 token:统计全部 assistant 消息的 API 精确值。 */
16
+ export function collectSessionStats(context: Context, sessionID: string): SessionStats {
17
+ const msgs = context.data.session.message.list(sessionID) ?? []
18
+ let input = 0
19
+ let output = 0
20
+ let cacheRead = 0
21
+ let cacheWrite = 0
22
+ let reasoning = 0
23
+ let cost = 0
24
+ let hasData = false
25
+
26
+ for (const m of msgs) {
27
+ if (m.type !== "assistant") continue
28
+ const t = m.tokens
29
+ if (!t) continue
30
+ input += num(t.input)
31
+ output += num(t.output)
32
+ reasoning += num(t.reasoning)
33
+ cacheRead += num(t.cache?.read)
34
+ cacheWrite += num(t.cache?.write)
35
+ hasData = true
36
+ }
37
+ // 会话级费用优先(V2 提供 cost()),消息级 cost 兜底(结构未知,宽松读取)
38
+ const sessionCost = context.data.session.cost(sessionID)
39
+ if (Number.isFinite(sessionCost) && sessionCost > 0) cost = sessionCost
40
+ else {
41
+ for (const m of msgs) {
42
+ if (m.type !== "assistant" || m.cost == null) continue
43
+ const c = m.cost as { amount?: unknown; total?: unknown } | { amount?: unknown } | number
44
+ if (typeof c === "number" && Number.isFinite(c)) cost += c
45
+ else {
46
+ const amt = (c as { amount?: unknown }).amount
47
+ if (typeof amt === "number" && Number.isFinite(amt)) cost += amt
48
+ else if (typeof amt === "string") {
49
+ const n = parseFloat(amt)
50
+ if (Number.isFinite(n)) cost += n
51
+ }
52
+ }
53
+ }
54
+ }
55
+ return { input, output, cacheRead, cacheWrite, reasoning, cost, hasData }
56
+ }
57
+
58
+ /** 缓存命中率(0–100):缓存读 /(新鲜输入 + 缓存读 + 缓存写),与 V1 口径一致。 */
59
+ export function hitRate(stats: SessionStats): number {
60
+ const denom = stats.input + stats.cacheRead + stats.cacheWrite
61
+ if (denom <= 0) return 0
62
+ return (stats.cacheRead / denom) * 100
63
+ }
64
+
65
+ /** 输入侧总量(底部栏口径,不含输出)。 */
66
+ export function inputTotal(stats: SessionStats): number {
67
+ return stats.input + stats.cacheRead + stats.cacheWrite
68
+ }
69
+
70
+ /** 单条命中率(V1 底部栏口径):最后一条有 token 的 assistant 消息,
71
+ * 分母含缓存写 read/(input+read+write);prevHitRate 为上一条(趋势用)。 */
72
+ export function collectLastHitRate(context: Context, sessionID: string): {
73
+ hitRate: number
74
+ prevHitRate: number
75
+ input: number
76
+ read: number
77
+ write: number
78
+ } {
79
+ const msgs = context.data.session.message.list(sessionID) ?? []
80
+ const session = context.data.session.get(sessionID) as { tokens?: { input?: number; cache?: { read?: number; write?: number } } } | undefined
81
+ let input = num(session?.tokens?.input)
82
+ let read = num(session?.tokens?.cache?.read)
83
+ let write = num(session?.tokens?.cache?.write)
84
+ // 无 session 聚合字段 → 遍历消息累加(与 V1 fallback 一致)
85
+ if (session?.tokens == null) {
86
+ for (const m of msgs) {
87
+ if (m.type !== "assistant") continue
88
+ const t = m.tokens
89
+ if (!t) continue
90
+ input += num(t.input)
91
+ read += num(t.cache?.read)
92
+ write += num(t.cache?.write)
93
+ }
94
+ }
95
+ let hitRate = -1, prevHitRate = -1
96
+ for (let i = msgs.length - 1; i >= 0; i--) {
97
+ const m = msgs[i]
98
+ if (m.type !== "assistant") continue
99
+ const tk = m.tokens
100
+ if (!tk) continue
101
+ const mit = num(tk.input) + num(tk.cache?.read) + num(tk.cache?.write)
102
+ const mrt = num(tk.cache?.read)
103
+ if (mit <= 0) continue
104
+ const rate = (mrt / mit) * 100
105
+ if (hitRate < 0) { hitRate = rate; continue }
106
+ prevHitRate = rate
107
+ break
108
+ }
109
+ return { hitRate, prevHitRate, input, read, write }
110
+ }
111
+
112
+ export type { MessageInfo }
@@ -0,0 +1,184 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import { createSignal, createEffect, onMount, onCleanup, untrack } from "solid-js"
4
+ import type { Context, PluginModule } from "./types"
5
+ import { createPanelApi } from "./v2-panel-api"
6
+ import { TokenCachePanel } from "../panel/TokenCachePanel"
7
+ import type { BalanceState, PanelApi, PanelSignals } from "../panel/panel-api"
8
+ import { StatusView } from "./status"
9
+ import { mapTheme } from "./theme"
10
+ import { makeCommands, findOpencodeKeyV2 } from "./commands"
11
+ import { getBalanceProvider } from "../balance-providers"
12
+ import { LANG_META, detectLang, type LangCode } from "../i18n"
13
+
14
+ const KV_PREFIX = "cache_panel"
15
+ const BALANCE_POLL_MS = 5 * 60 * 1000 // 5 minutes(对齐 V1)
16
+
17
+ // 环境变量覆盖 + 自动检测(对齐 V1:CACHE_TUI_LANG 优先,其次系统 locale)
18
+ declare const process: { env: Record<string, string | undefined> } | undefined
19
+ const DEBUG_LANG = typeof process !== "undefined" ? process.env?.CACHE_TUI_LANG : undefined
20
+ const INIT_LANG: LangCode = DEBUG_LANG !== undefined && LANG_META.some((m) => m.code === DEBUG_LANG)
21
+ ? (DEBUG_LANG as LangCode)
22
+ : detectLang()
23
+
24
+ /** V2 侧创建面板信号(实验:默认值;偏好持久化经 PanelApi.kv → storage.store)。
25
+ * 返回 PanelSignals + setBalanceState:余额轮询由 PluginRoot 驱动(V1 同构)。 */
26
+ function createPanelSignals(): PanelSignals & { setBalanceState: (v: BalanceState) => void } {
27
+ const [currencySymbol, setCurrencySymbol] = createSignal("$")
28
+ const [exchangeRate, setExchangeRate] = createSignal(1)
29
+ const [langCode, setLangCode] = createSignal(INIT_LANG)
30
+ const [sectionDetail, setSectionDetail] = createSignal(true)
31
+ const [sectionModel, setSectionModel] = createSignal(true)
32
+ const [sectionDist, setSectionDist] = createSignal(true)
33
+ const [sectionSkills, setSectionSkills] = createSignal(true)
34
+ const [sectionBalance, setSectionBalance] = createSignal(true)
35
+ const [sectionBottom, setSectionBottom] = createSignal(true)
36
+ const [balanceRefresh, setBalanceRefresh] = createSignal(0)
37
+ const [balanceProviderId, setBalanceProviderId] = createSignal("")
38
+ const [autoBalance, setAutoBalance] = createSignal(true)
39
+ const [balanceUnsupported, setBalanceUnsupported] = createSignal(false)
40
+ const [balanceState, setBalanceState] = createSignal<BalanceState>({ status: "idle", data: null, lastFetch: 0 })
41
+ const [balanceCurrency, setBalanceCurrency] = createSignal("")
42
+ const [borderVisible, setBorderVisible] = createSignal(true)
43
+ const [overrideSessionId, setOverrideSessionId] = createSignal<string | undefined>(undefined)
44
+ const [sidebarVisible, setSidebarVisible] = createSignal(true)
45
+ return {
46
+ currencySymbol, setCurrencySymbol,
47
+ exchangeRate, setExchangeRate,
48
+ langCode: langCode as PanelSignals["langCode"], setLangCode: setLangCode as PanelSignals["setLangCode"],
49
+ sectionDetail, setSectionDetail,
50
+ sectionModel, setSectionModel,
51
+ sectionDist, setSectionDist,
52
+ sectionSkills, setSectionSkills,
53
+ sectionBalance, setSectionBalance,
54
+ sectionBottom, setSectionBottom,
55
+ balanceRefresh, setBalanceRefresh,
56
+ balanceProviderId, setBalanceProviderId,
57
+ autoBalance, setAutoBalance,
58
+ balanceUnsupported, setBalanceUnsupported,
59
+ balanceState,
60
+ setBalanceState,
61
+ balanceCurrency, setBalanceCurrency,
62
+ borderVisible, setBorderVisible,
63
+ overrideSessionId, setOverrideSessionId,
64
+ sidebarVisible, setSidebarVisible,
65
+ }
66
+ }
67
+
68
+ /** 面板根组件:在组件渲染上下文注册命令 layer(keymap.layer 必须由组件调用),
69
+ * 再渲染共享 TokenCachePanel;同时驱动余额轮询(对齐 V1 tui() 的 pollBalance)。 */
70
+ function PluginRoot(props: {
71
+ context: Context
72
+ api: PanelApi
73
+ signals: PanelSignals & { setBalanceState: (v: BalanceState) => void }
74
+ sessionID: string
75
+ }) {
76
+ // 请求序号:防止定时轮询与手动刷新并发时,慢的旧请求覆盖新结果(对齐 V1)
77
+ let balanceSeq = 0
78
+ // 对齐官方内置插件示例(feature-plugins/system/plugins.tsx):mode 用 global
79
+ props.context.keymap.layer(() => ({
80
+ mode: "global",
81
+ commands: makeCommands(props.context, props.api, props.signals),
82
+ }))
83
+ // 语言偏好恢复(对齐 V1 tui() restoreLang:优先用户 /cache-lang 设置,覆盖自动检测)
84
+ onMount(() => {
85
+ try {
86
+ const saved = props.api.kv.get<string>(`${KV_PREFIX}.lang`)
87
+ if (saved && LANG_META.some((m) => m.code === saved)) {
88
+ props.signals.setLangCode(saved as LangCode)
89
+ }
90
+ } catch {}
91
+ })
92
+
93
+ // ── 余额轮询(对齐 V1 tui() pollBalance):手动 key 优先,缺失时自动复用 OpenCode 已认证 key ──
94
+ const pollBalance = async () => {
95
+ const provider = getBalanceProvider(props.signals.balanceProviderId())
96
+ const key = props.api.kv.get<string>(`${KV_PREFIX}.balance.${provider.id}.key`, "")
97
+ || findOpencodeKeyV2(props.context, provider)
98
+ const set = props.signals.setBalanceState
99
+ if (props.signals.balanceUnsupported()) { set({ status: "idle", data: null, lastFetch: 0, error: undefined, key: undefined }); return }
100
+ if (!key) { set({ status: "idle", data: null, lastFetch: 0, error: undefined, key: undefined }); return }
101
+ const now = Date.now()
102
+ const prev = props.signals.balanceState()
103
+ // key 已更换(重新输入)→ 强制重新查询,绕过缓存
104
+ if (prev.status === "ok" && prev.key === key && now - prev.lastFetch < BALANCE_POLL_MS) return
105
+ const seq = ++balanceSeq
106
+ set({ ...prev, status: "loading", error: undefined, key })
107
+ const controller = new AbortController()
108
+ let timedOut = false
109
+ const timer = setTimeout(() => { timedOut = true; controller.abort() }, 10_000)
110
+ try {
111
+ const data = await provider.fetchBalance(key, controller.signal)
112
+ clearTimeout(timer)
113
+ if (seq !== balanceSeq) return // 已被更新的请求取代,丢弃过期结果
114
+ set({ status: "ok", data, lastFetch: Date.now(), error: undefined, key })
115
+ } catch (err) {
116
+ clearTimeout(timer)
117
+ if (seq !== balanceSeq) return
118
+ const code = timedOut ? "TIMEOUT" : (err instanceof Error ? err.message : "")
119
+ set({ status: "error", data: null, lastFetch: 0, error: code, key })
120
+ }
121
+ }
122
+ // Re-fetch when the API key is (re)configured via /cache-balance-key。
123
+ // 注意:pollBalance 内部读写 balanceState 信号,若不做 untrack 包裹,
124
+ // effect 会追踪 balanceState 的变化并与 setBalanceState 形成无限循环。
125
+ createEffect(() => {
126
+ void props.signals.balanceRefresh()
127
+ untrack(() => { void pollBalance() })
128
+ })
129
+ // 定时轮询(5 分钟);随插件生命周期清理
130
+ const balanceTimer = setInterval(pollBalance, BALANCE_POLL_MS)
131
+ onCleanup(() => clearInterval(balanceTimer))
132
+
133
+ // auto-clear override:用户导航到不同主会话时清除子代理视图(对齐 V1 createSidebarSlot)
134
+ let lastSlotSid = props.sessionID
135
+ createEffect(() => {
136
+ const sid = props.sessionID
137
+ if (sid !== lastSlotSid) {
138
+ lastSlotSid = sid
139
+ if (props.signals.overrideSessionId()) {
140
+ props.signals.setOverrideSessionId(undefined)
141
+ void props.api.kv.set(`${KV_PREFIX}.session`, "")
142
+ }
143
+ }
144
+ })
145
+
146
+ return (
147
+ <TokenCachePanel
148
+ theme={mapTheme(props.context.theme)}
149
+ api={props.api}
150
+ sessionId={props.sessionID}
151
+ signals={props.signals}
152
+ />
153
+ )
154
+ }
155
+
156
+ const mod: PluginModule = {
157
+ id: "opencode-visual-cache",
158
+ setup(context: Context) {
159
+ const api = createPanelApi(context)
160
+ const signals = createPanelSignals()
161
+
162
+ // 侧边栏完整面板(与 V1 同一组件;命令 layer 在组件内注册)。
163
+ // prepend:排在宿主官方信息(问候/Context/用量)之前,紧跟会话标题。
164
+ context.ui.slot({
165
+ prepend: "sidebar.content",
166
+ render: (props) => (
167
+ <PluginRoot context={context} api={api} signals={signals} sessionID={String(props.sessionID ?? "")} />
168
+ ),
169
+ })
170
+
171
+ // 底部状态栏(完整口径与 V1 一致;余额读共享 signals.balanceState)
172
+ context.ui.slot({
173
+ append: "prompt.footer.status",
174
+ render: (props) => (
175
+ <StatusView context={context} signals={signals} sessionID={String(props.sessionID ?? "")} />
176
+ ),
177
+ })
178
+
179
+ // 偏好持久化(实验:storage.store 用法验证)
180
+ context.storage.store("opencode-visual-cache.panel", { initial: { collapsed: false } })
181
+ },
182
+ }
183
+
184
+ export default mod
@@ -0,0 +1,69 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import { createMemo, For, Show } from "solid-js"
4
+ import type { Context } from "./types"
5
+ import { collectSessionStats, hitRate } from "./data"
6
+ import { fmt, fmtCost, progressBar, visualPadEnd } from "../core"
7
+
8
+ const LABEL_GAP = 1
9
+ const BAR_BRACKETS = 2
10
+ const BAR_GAP = 1
11
+ const PCT_FIXED_WIDTH = 5
12
+ const MIN_PANEL_WIDTH = 20
13
+ const DEFAULT_PANEL_WIDTH = 26
14
+
15
+ export function SidebarView(props: { context: Context; sessionID: string }) {
16
+ const stats = createMemo(() => collectSessionStats(props.context, props.sessionID))
17
+ const rate = createMemo(() => hitRate(stats()))
18
+ const theme = props.context.theme
19
+
20
+ const rateColor = () => {
21
+ const r = rate()
22
+ if (r >= 85) return theme.text.feedback.success.default
23
+ if (r >= 70) return theme.text.feedback.warning.default
24
+ return theme.text.feedback.error.default
25
+ }
26
+ const barWidth = () =>
27
+ Math.max(MIN_PANEL_WIDTH, Math.min(DEFAULT_PANEL_WIDTH, props.context.app.version ? DEFAULT_PANEL_WIDTH : DEFAULT_PANEL_WIDTH)) -
28
+ LABEL_GAP - BAR_BRACKETS - BAR_GAP - PCT_FIXED_WIDTH - 1
29
+
30
+ const rows = () => {
31
+ const s = stats()
32
+ return [
33
+ { label: "Hit", value: fmt(s.cacheRead) + " tok", color: rateColor() },
34
+ { label: "Miss", value: fmt(s.input + s.cacheWrite) + " tok", color: theme.text.default },
35
+ { label: "Write", value: fmt(s.cacheWrite) + " tok", color: theme.text.subdued },
36
+ { label: "Out", value: fmt(s.output) + " tok", color: theme.text.subdued },
37
+ ]
38
+ }
39
+
40
+ return (
41
+ <Show when={stats().hasData}>
42
+ <box>
43
+ <box flexDirection="row" gap={LABEL_GAP}>
44
+ <text fg={theme.text.default}>Cache</text>
45
+ <text fg={rateColor()}>
46
+ {"["}
47
+ {progressBar(rate(), barWidth())}
48
+ {"]"}
49
+ </text>
50
+ <text fg={rateColor()}>{rate().toFixed(1) + "%"}</text>
51
+ </box>
52
+ <For each={rows()}>
53
+ {(row) => (
54
+ <box flexDirection="row" gap={LABEL_GAP}>
55
+ <text fg={theme.text.default}>{visualPadEnd(row.label, 5)}</text>
56
+ <text fg={row.color}>{row.value}</text>
57
+ </box>
58
+ )}
59
+ </For>
60
+ <Show when={stats().cost > 0}>
61
+ <box flexDirection="row" gap={LABEL_GAP}>
62
+ <text fg={theme.text.default}>{"Cost"}</text>
63
+ <text fg={theme.text.default}>{fmtCost(stats().cost)}</text>
64
+ </box>
65
+ </Show>
66
+ </box>
67
+ </Show>
68
+ )
69
+ }
@@ -0,0 +1,96 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+
3
+ import { createMemo, For, Show } from "solid-js"
4
+ import type { Context } from "./types"
5
+ import type { PanelSignals } from "../panel/panel-api"
6
+ import { collectLastHitRate } from "./data"
7
+ import { desaturateTo, fmtCompact, formatBalanceText, MAX_SAT, FALLBACK, visualWidth } from "../core"
8
+ import { createT } from "../i18n"
9
+ import { mapTheme } from "./theme"
10
+
11
+ /**
12
+ * 底部状态栏(prompt.footer.status)——对齐 V1 BottomStatusBar 统计段口径:
13
+ * 单条命中率(最后一条有 token 的 assistant 消息)+ 趋势 + Tokens 总量 + 余额。
14
+ * 余额读共享 signals.balanceState(PluginRoot 驱动轮询);provider 不支持余额时隐藏余额段(对齐 V1)。
15
+ * 颜色经 mapTheme(V1 形状)——与侧边栏命中率颜色同源,保证两处一致。
16
+ */
17
+ export function StatusView(props: {
18
+ context: Context
19
+ signals: PanelSignals
20
+ sessionID: string
21
+ }) {
22
+ const t = createT(() => props.signals.langCode())
23
+
24
+ // 与侧边栏 TokenCachePanel 同一颜色来源(mapTheme → desaturateTo)
25
+ const pal = createMemo(() => {
26
+ const th = mapTheme(props.context.theme) as unknown as Record<string, string>
27
+ const sat = (k: string, fb: string) => desaturateTo(th[k], MAX_SAT, fb)
28
+ return {
29
+ text: sat("text", FALLBACK.text),
30
+ muted: sat("textMuted", FALLBACK.muted),
31
+ success: sat("success", FALLBACK.success),
32
+ warning: sat("warning", FALLBACK.warning),
33
+ error: sat("error", FALLBACK.error),
34
+ }
35
+ })
36
+
37
+ const stats = createMemo(() => collectLastHitRate(props.context, props.sessionID))
38
+
39
+ const hitColor = createMemo(() => {
40
+ const r = stats().hitRate
41
+ if (r >= 85) return pal().success
42
+ if (r >= 70) return pal().warning
43
+ return pal().error
44
+ })
45
+
46
+ // 命中率趋势:最后一条与上一条的差值;|Δ| < 0.05 视为无变化(null = 不显示)
47
+ const trend = createMemo(() => {
48
+ const s = stats()
49
+ if (s.prevHitRate < 0 || s.hitRate < 0) return null
50
+ const d = s.hitRate - s.prevHitRate
51
+ return Math.abs(d) < 0.05 ? null : d
52
+ })
53
+
54
+ // 余额文本(对齐 V1):ok → 数值;loading → …;error → ⚠;idle → -
55
+ const balanceText = createMemo(() => {
56
+ const s = props.signals.balanceState()
57
+ if (s.status === "ok" && s.data) return formatBalanceText(s.data, props.signals.balanceCurrency(), props.signals.exchangeRate())
58
+ if (s.status === "loading") return "\u2026"
59
+ if (s.status === "error") return "\u26a0"
60
+ return "-"
61
+ })
62
+
63
+ const segs = createMemo<{ text: string; color: string | undefined }[]>(() => {
64
+ const s = stats()
65
+ const hr = s.hitRate >= 0 ? (Math.floor(s.hitRate * 10) / 10).toFixed(1) + "%" : "--"
66
+ const out: { text: string; color: string | undefined }[] = [
67
+ { text: t("barHit") + " ", color: pal().muted },
68
+ { text: hr, color: hitColor() },
69
+ ]
70
+ const tr = trend()
71
+ if (tr !== null) {
72
+ out.push({ text: " " + (tr > 0 ? "\u2191" : "\u2193") + Math.abs(tr).toFixed(1) + "%", color: tr > 0 ? pal().success : pal().error })
73
+ }
74
+ out.push({ text: " \u00b7 " + t("barTok") + " ", color: pal().muted })
75
+ out.push({ text: s ? fmtCompact(s.input + s.read + s.write) : "--", color: pal().text })
76
+ if (!props.signals.balanceUnsupported()) {
77
+ out.push({ text: " \u00b7 " + t("barBal") + " ", color: pal().muted })
78
+ out.push({ text: balanceText(), color: pal().text })
79
+ }
80
+ out.push({ text: " \u00b7 ", color: pal().muted })
81
+ return out
82
+ })
83
+ const segsW = createMemo(() => {
84
+ let w = 0
85
+ for (const sg of segs()) w += visualWidth(sg.text)
86
+ return w
87
+ })
88
+
89
+ return (
90
+ <Show when={segsW() > 0}>
91
+ <text>
92
+ <For each={segs()}>{(sg) => <span style={{ fg: sg.color }}>{sg.text}</span>}</For>
93
+ </text>
94
+ </Show>
95
+ )
96
+ }
@@ -0,0 +1,19 @@
1
+ import type { TuiThemeCurrent } from "@opencode-ai/plugin/tui"
2
+ import type { Context } from "./types"
3
+
4
+ /** V2 theme → V1 形状映射(组件按 primary/text/textMuted/… 字段消费)。
5
+ * 侧边栏与底部栏共用——保证命中率颜色等两处一致。
6
+ * - V1 primary → V2 interactive(v1-migrate.ts 官方映射:interactive = hues.byToken.primary)
7
+ * - step 取 300:更亮(对齐 V2 暗色强调惯例的亮端),500/400 在暗背景下偏深
8
+ */
9
+ export function mapTheme(theme: Context["theme"]): TuiThemeCurrent {
10
+ return {
11
+ primary: theme.hue.interactive[300],
12
+ text: theme.text.default,
13
+ textMuted: theme.text.subdued,
14
+ success: theme.text.feedback.success.default,
15
+ warning: theme.text.feedback.warning.default,
16
+ error: theme.text.feedback.error.default,
17
+ border: theme.text.subdued,
18
+ } as unknown as TuiThemeCurrent
19
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * V2 (opencode2) TUI plugin API — 最小本地类型(实验版)。
3
+ * 运行时由 opencode2 提供,此处仅用于本地类型检查;
4
+ * 结构对应 v2 分支 packages/plugin/src/tui/context.ts。
5
+ */
6
+
7
+ export interface App {
8
+ readonly version: string
9
+ readonly channel: string
10
+ }
11
+
12
+ export interface Theme {
13
+ readonly hue: {
14
+ /** V1 primary 的 V2 等价(v1-migrate.ts:interactive = hues.byToken.primary)。
15
+ * 取 300:更亮(暗背景下 400/500 偏深)。 */
16
+ readonly interactive: { readonly 300: string }
17
+ /** 主题强调色别名。 */
18
+ readonly accent: { readonly 500: string }
19
+ }
20
+ readonly text: {
21
+ readonly default: string
22
+ readonly subdued: string
23
+ readonly feedback: {
24
+ readonly success: { readonly default: string }
25
+ readonly error: { readonly default: string }
26
+ readonly warning: { readonly default: string }
27
+ }
28
+ }
29
+ }
30
+
31
+ /** token 用量:结构与 V1 的 message.tokens 同构,字段以运行时实际数据为准。 */
32
+ export interface TokenUsage {
33
+ input?: number
34
+ output?: number
35
+ reasoning?: number
36
+ cache?: { read?: number; write?: number }
37
+ }
38
+
39
+ export interface MessageInfo {
40
+ readonly id: string
41
+ readonly type: string
42
+ readonly agent?: string
43
+ readonly model?: string
44
+ readonly time: { readonly created: number; readonly completed?: number }
45
+ readonly cost?: unknown
46
+ readonly tokens?: TokenUsage
47
+ readonly content?: unknown[]
48
+ }
49
+
50
+ export interface SessionInfo {
51
+ readonly id: string
52
+ readonly title?: string
53
+ readonly time?: { readonly created: number; readonly updated: number }
54
+ readonly model?: string
55
+ readonly agent?: string
56
+ readonly parentID?: string
57
+ }
58
+
59
+ export interface Data {
60
+ readonly session: {
61
+ get(sessionID: string): SessionInfo | undefined
62
+ list(): SessionInfo[]
63
+ cost(sessionID: string): number
64
+ status(sessionID: string): string
65
+ readonly message: {
66
+ list(sessionID: string): MessageInfo[]
67
+ sync(sessionID: string): Promise<void>
68
+ }
69
+ }
70
+ readonly location: {
71
+ readonly provider: { list(location?: unknown): unknown[] }
72
+ readonly model: { list(location?: unknown): unknown[] }
73
+ readonly mcp: { readonly server: { list(location?: unknown): unknown[] } }
74
+ }
75
+ readonly on: (type: string, handler: (event: unknown) => void) => () => void
76
+ readonly listen: (handler: (event: unknown) => void) => () => void
77
+ }
78
+
79
+ export interface Storage {
80
+ store<Value extends object>(
81
+ key: string,
82
+ options: { readonly initial: Value },
83
+ ): readonly [Value, (mutation: (draft: Value) => void) => Promise<void>]
84
+ memory<Value extends object>(
85
+ key: string,
86
+ options: { readonly initial: Value },
87
+ ): readonly [Value, (mutation: (draft: Value) => void) => void]
88
+ }
89
+
90
+ export type SlotClaim = {
91
+ readonly render: (input: Record<string, any>) => unknown
92
+ } & (
93
+ | { readonly append: string; readonly prepend?: never; readonly before?: never; readonly after?: never; readonly replace?: never }
94
+ | { readonly prepend: string; readonly append?: never; readonly before?: never; readonly after?: never; readonly replace?: never }
95
+ | { readonly before: string; readonly append?: never; readonly prepend?: never; readonly after?: never; readonly replace?: never }
96
+ | { readonly after: string; readonly append?: never; readonly prepend?: never; readonly before?: never; readonly replace?: never }
97
+ | { readonly replace: string; readonly append?: never; readonly prepend?: never; readonly before?: never; readonly after?: never }
98
+ )
99
+
100
+ export interface KeymapCommand {
101
+ readonly id?: string
102
+ readonly title?: string
103
+ readonly description?: string
104
+ readonly group?: string
105
+ readonly palette?: true
106
+ readonly slash?: { readonly name: string; readonly aliases?: string[]; readonly arguments?: true }
107
+ /** 旧字段(opencode-dcp 兼容写法:palette 可见性 + slash 补全依赖它们) */
108
+ readonly namespace?: string
109
+ readonly name?: string
110
+ readonly desc?: string
111
+ readonly category?: string
112
+ readonly slashName?: string
113
+ readonly slashAliases?: string[]
114
+ readonly run: (input?: string) => void | false | Promise<void>
115
+ }
116
+
117
+ export interface Context {
118
+ readonly app: App
119
+ readonly options: Record<string, any>
120
+ readonly location: { readonly directory?: string } | undefined
121
+ readonly renderer: { readonly terminalWidth: number }
122
+ readonly theme: Theme
123
+ readonly data: Data
124
+ readonly storage: Storage
125
+ readonly ui: {
126
+ slot(claim: SlotClaim): () => void
127
+ readonly toast: {
128
+ show(options: { readonly message: string; readonly title?: string; readonly variant?: string }): void
129
+ }
130
+ readonly dialog: {
131
+ prompt(options: { readonly title: string; readonly message?: string; readonly placeholder?: string }): Promise<string | undefined>
132
+ select<Value>(options: {
133
+ readonly title: string
134
+ readonly placeholder?: string
135
+ readonly options: readonly {
136
+ readonly title: string
137
+ readonly value: Value
138
+ readonly description?: string
139
+ readonly category?: string
140
+ readonly disabled?: boolean
141
+ }[]
142
+ readonly current?: Value
143
+ }): Promise<Value | undefined>
144
+ }
145
+ /** 当前路由:命令需要当前会话 ID(V2 Route = { type: "session", sessionID })。 */
146
+ readonly router: {
147
+ current(): { readonly type?: string; readonly sessionID?: string; readonly params?: Record<string, unknown> }
148
+ }
149
+ }
150
+ readonly keymap: {
151
+ layer(input: () => { readonly commands?: readonly KeymapCommand[] }): void
152
+ shortcuts(id: string): readonly string[]
153
+ }
154
+ }
155
+
156
+ export type PluginModule = {
157
+ readonly id: string
158
+ readonly setup: (context: Context) => void | (() => void | Promise<void>) | Promise<void | (() => void | Promise<void>)>
159
+ }