* opencode-bru-usage · server 插件入口(OpenCode V2 插件 API)
* - bru_usage 自定义工具:agent 可在会话中查询个人用量 KPI
* - /usage 命令:ctx.command.transform 注入($ARGUMENTS 由 prompt.text 替换)
* - 限额 toast 迁移至 TUI 入口(V2 server 插件无 toast API,session.idle 事件在 TUI 端监听)
*/
import { Plugin } from "@opencode/plugin"
import {
resolveConfig,
fetchKpis,
creditText,
bar,
maskKey,
writeUserBruConfig,
type UsageWindow,
} from "./shared.js"
const WINDOWS: UsageWindow[] = ["today", "week", "month"]
const USAGE_COMMAND_TEMPLATE = [
"调用 bru_usage 工具查询 BlueRegionUsage 个人 API 用量(window 参数使用:$ARGUMENTS,为空则 today)。",
"然后用简洁的 markdown 呈现返回的 KPI,要求:",
"- 标题注明统计窗口(今日 / 本周 / 本月);",
"- KPI 列表:总 Tokens(输入 / 缓存命中 / 输出拆分)、请求数、缓存命中率;",
"- 模型用量 Top3(Tokens 与占比);",
"- Credit 估算与限额:有限额时用文本进度条(如 " + bar(42) + ")展示已用百分比,超限明显标注;",
"- 数据必须严格来自工具返回,禁止编造;字段缺失时显示 --。",
"工具报错时原样转述错误信息(含 code),并提示可能的配置问题(BRU_BASE_URL / BRU_API_KEY)。",
].join("\n")
const BRU_USAGE_INPUT = {
type: "object",
properties: {
action: {
type: "string",
enum: ["query", "login"],
description: "query=查询用量(默认);login=保存个人 API Key / 限额到本用户配置文件",
},
window: { type: "string", enum: ["today", "week", "month"], description: "query:统计窗口,默认 today" },
apiKey: { type: "string", description: "login:个人 API Key(必填)" },
dailyCreditLimit: { type: "number", description: "login:日 Credit 限额(可选)" },
weeklyCreditLimit: { type: "number", description: "login:周 Credit 限额(可选)" },
monthlyCreditLimit: { type: "number", description: "login:月 Credit 限额(可选)" },
},
additionalProperties: false,
}
interface BruUsageArgs {
action?: "query" | "login"
window?: UsageWindow
apiKey?: string
dailyCreditLimit?: number
weeklyCreditLimit?: number
monthlyCreditLimit?: number
}
function snapshotToOutput(snap: any): string {
const limit = snap.creditLimit
const creditBlock =
snap.credit === null
? { credit: null, note: "模型目录未提供 Credit 系数" }
: limit === null
? { credit: Number(snap.credit.toFixed(4)) }
: {
credit: Number(snap.credit.toFixed(4)),
limit,
usedPct: Number(((snap.credit / limit) * 100).toFixed(1)),
over: snap.credit > limit,
}
return JSON.stringify(
{
window: snap.window,
windowLabel: snap.window === "today" ? "今日" : snap.window === "week" ? "本周" : "本月",
consumer: snap.consumer || undefined,
kpi: {
totalTokens: snap.summary.total_tokens,
inputTokens: snap.summary.req_tokens,
cachedTokens: snap.summary.cached_tokens,
outputTokens: snap.summary.rsp_tokens,
requestCount: snap.summary.request_count,
cacheHitRate: snap.summary.cache_hit_rate,
},
comparePreviousPeriod: snap.compare
? {
totalTokens: snap.compare.total_tokens,
requestCount: snap.compare.request_count,
}
: null,
topModels: snap.models.slice(0, 3).map((m: any) => ({
model: m.model,
totalTokens: m.totalTokens,
sharePct: m.share === null ? null : Number((m.share * 100).toFixed(1)),
})),
credit: creditBlock,
hint: "单位:Tokens。cacheHitRate 为 0-1 比例。credit = Σ(每日模型总 Tokens × 当日生效系数) ÷ 1e6(估算)。",
},
null,
2,
)
}
export default Plugin.define({
id: "opencode-bru-usage",
async setup(ctx) {
const options = ctx.options as Record<string, unknown> | undefined
await ctx.command.transform((editor) => {
editor.add({
name: "usage",
description: "BlueRegionUsage 用量 KPI(today/week/month)",
execute: async ({ sessionID, prompt, delivery }) => {
const text = USAGE_COMMAND_TEMPLATE.replace("$ARGUMENTS", prompt.text || "")
await ctx.session.prompt({ sessionID, text, delivery })
},
})
})
await ctx.tool.transform((editor) => {
editor.add({
name: "bru_usage",
description:
"查询蓝区(BlueRegionUsage)个人 LLM API 用量 KPI(总 Tokens、输入/缓存命中/输出拆分、请求数、缓存命中率、模型 Top、Credit 估算与限额进度条)。" +
"多人共用一份 opencode 配置时,每人用自己的 API Key:action=login 保存到 ~/.config/bru-usage/config.json(个人优先于共享配置)。",
input: BRU_USAGE_INPUT,
async execute(raw) {
const args = (raw ?? {}) as BruUsageArgs
if (args.action === "login") {
const key = String(args.apiKey || "").trim()
if (!key) {
return {
content:
'缺少 apiKey。用法:bru_usage {"action":"login","apiKey":"你的Key","dailyCreditLimit":100}(限额可选)',
}
}
let savedPath: string
try {
savedPath = writeUserBruConfig({
apiKey: key,
dailyCreditLimit: args.dailyCreditLimit,
weeklyCreditLimit: args.weeklyCreditLimit,
monthlyCreditLimit: args.monthlyCreditLimit,
})
} catch (e: any) {
return { content: "保存失败:" + (e?.message || e) }
}
const { ok, config, missing } = resolveConfig(options)
const limits = [
args.dailyCreditLimit !== undefined && `日限额 ${args.dailyCreditLimit}`,
args.weeklyCreditLimit !== undefined && `周限额 ${args.weeklyCreditLimit}`,
args.monthlyCreditLimit !== undefined && `月限额 ${args.monthlyCreditLimit}`,
].filter(Boolean)
return {
content:
`已保存个人配置到 ${savedPath}(apiKey ${maskKey(key)}${limits.length ? "," + limits.join("、") : ""})\n` +
(ok
? `配置就绪:baseUrl ${config.baseUrl}`
: `还缺 ${missing.join("、")}(baseUrl 走团队共享配置或环境变量 BRU_BASE_URL),配好后即可查询`),
}
}
const { ok, config, missing } = resolveConfig(options)
if (!ok) {
return {
content:
`蓝区火山用量未配置:缺少 ${missing.join("、")}。\n` +
`推荐:在项目的 opencode.json 里配置蓝区火山网关同源的 provider(含 options.apiKey),插件会自动识别为用量身份。\n` +
`也可以:export BRU_API_KEY="你的Key" 后启动 opencode,或让 agent 执行 bru_usage {"action":"login","apiKey":"你的Key"}。\n` +
`baseUrl 已内置火山网关默认值(options / 环境变量 BRU_BASE_URL 仅用于覆盖,如 mock 联调)。`,
}
}
const window: UsageWindow = WINDOWS.includes(args.window as UsageWindow)
? (args.window as UsageWindow)
: "today"
try {
const snap = await fetchKpis(config, window)
return { content: snapshotToOutput(snap) }
} catch (e: any) {
return {
content:
`查询失败(${e?.code || "error"}):${e?.message || e}\n` +
`可让 agent 执行 bru_usage {"action":"login","apiKey":"你的Key"} 更新个人 Key 后重试。`,
}
}
},
})
})
},
})