feat: OpenCode Go 用量插件 v1.0.0

DSH 左侧栏底部常驻卡片,显示 OpenCode Go 套餐的三条配额用量:
- 滚动窗口 / 本周 / 本月 的已用百分比 + 进度条
- 每条配额的重置倒计时(X小时Y分后重置)
- 标题旁显示本月重置日期
- 百分比按档位变色(<70% 绿 / 70-89% 橙 / ≥90% 红)
- SVG 圆形刷新按钮,加载时旋转;60 秒自动刷新

另有 opencode_usage 工具(供 agent 查询)与 GET /plugin/opencode-usage 接口。
服务端直连 opencode.ai/zen/go/v1/usage,API Key 不经过浏览器。
纯 JS 实现,无需构建。
This commit is contained in:
wangjinding committed 2026-11-09 15:04:53 +08:00
commit 2994a20bb0
7 files changed
+767

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
node_modules/
*.tgz
*.log
.DS_Store
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 dsh-opencode-usage contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+95
View File
@@ -0,0 +1,95 @@
# dsh-opencode-usage
在 DSH 左侧栏看 OpenCode Go 套餐用量:滚动窗口 / 本周 / 本月 三条配额的已用百分比与重置倒计时。
服务端直连 `https://opencode.ai/zen/go/v1/usage`,API Key 不经过浏览器。
![位置](https://img.shields.io/badge/%E4%BD%8D%E7%BD%AE-%E5%B7%A6%E4%BE%A7%E6%A0%8F%E5%BA%95%E9%83%A8-16a34a)
## 功能
| 能力 | 说明 |
|---|---|
| **左侧栏卡片** | 三条配额的百分比、进度条、重置倒计时;标题旁显示本月重置日 |
| **刷新按钮** | SVG 圆形箭头,加载时旋转;60 秒自动刷新 |
| **颜色分档** | `<70%` 绿 / `70–89%` 橙 / `≥90%` 红 |
| **`opencode_usage` 工具** | 让 agent 也能查(「opencode 用了多少」)|
| **`GET /plugin/opencode-usage`** | JSON 接口,15 秒缓存 |
返回结构:
```json
{
"ok": true,
"fetchedAt": 1794204531,
"source": "config.apiKey",
"buckets": [
{ "key": "rolling", "label": "滚动窗口", "status": "ok", "percent": 2,
"resetsAt": "2026-11-09T11:01:12.000Z", "resetInSeconds": 17539 }
],
"cached": false
}
```
## 安装
```bash
cd ~/.dsh/profiles/<你的 profile>
pnpm add file:/path/to/dsh-opencode-usage
```
然后在 profile 的 `dsh.profile.bundles` 里加上 `dsh-opencode-usage`,重启 DSH。
## 配置凭证
三选一,按优先级:
| 顺序 | 来源 |
|---|---|
| 1 | `config.apiKey` |
| 2 | `config.envFile` 指向的 `.env` 里的 `OPENCODE_API_KEY` |
| 3 | 进程环境变量 `OPENCODE_API_KEY` |
写在**你自己 profile 的** `cordis.patch.yml`(不要改本包):
```yaml
- id: opencode-usage
config:
apiKey: oc_sk_xxx
```
或者从 `.env` 文件读:
```yaml
- id: opencode-usage
config:
envFile: /path/to/.env
```
### 其他可选配置
```yaml
- id: opencode-usage
config:
baseUrl: https://opencode.ai/zen/go/v1 # 上游地址
cacheSeconds: 15 # 缓存秒数
timeoutMs: 12000 # 单次请求超时
envKey: OPENCODE_API_KEY # 变量名
```
## 实现要点
- **纯 JS,无需构建**:客户端通过 `window.__ModuleLoader__.load()` 注册,服务端是标准 ESM `apply(ctx, config)`。
- **凭证不落浏览器**:前端只拿到三条百分比,Bearer 只在服务端拼。
- **`defineTool` 动态解析**:插件装在 profile 的 `local/` 下,模块解析链上找不到 `@deepseek-ai/dsh-tools`,
所以用 `realpath(argv[1])` 建 `createRequire`,从 DSH 自己的依赖树里取。
- **value schema DSL 有约束**:不吃 `required: [...]` 数组、不吃 `type: ["number","null"]` 这类 union、
`additionalProperties` 必须显式。所以未知值用哨兵(`-1` / `""`)。
## 隐私
本包**不含任何凭证、个人路径或主机名**。凭证只在你自己的 profile 配置或环境变量里。
## License
MIT
+24
View File
@@ -0,0 +1,24 @@
# dsh-opencode-usage bundle patch
#
# 挂载 OpenCode Go 用量查看插件:
# ① 服务端:GET /plugin/opencode-usage(代理 opencode.ai 的 /usage,带 15 秒缓存)
# ② 服务端:opencode_usage 工具(让 agent 也能查)
# ③ 客户端:左侧栏底部「OpenCode Go」卡片(三条配额进度条 + 刷新按钮)
#
# 凭证(三选一,按优先级):
# config.apiKey > config.envFile 里的 OPENCODE_API_KEY > 进程环境变量 OPENCODE_API_KEY
#
# 用法示例(在你自己 profile 的 cordis.patch.yml 里覆盖,别写进本包):
# - id: opencode-usage
# config:
# apiKey: oc_sk_xxx
# 或者:
# - id: opencode-usage
# config:
# envFile: /path/to/.env
#
# 回滚:从 ~/.dsh/profiles/<profile>/package.json 的 dsh.profile.bundles 里删掉本包,再 pnpm install。
- insert:
- id: opencode-usage
name: "dsh-opencode-usage"
+285
View File
@@ -0,0 +1,285 @@
// dsh-opencode-usage — 左侧栏「OpenCode Go 用量」卡片。
//
// 只注册一个位置:sidebar.footer.action(DSH 渲染在 .footerActions 里,位于左侧栏底部)。
// 设置页不再有对应分区 —— 用量这类"随时瞟一眼"的指标放在侧栏比埋进设置页直观得多。
//
// window.__ModuleLoader__.load 是 DSH 客户端的插件注册入口(纯 JS,不需要构建):
// factory(require) 里 require("react") 拿到的就是宿主那份 React,所以插件
// 不会引入第二份 React 实例(否则 hooks 会报 invalid hook call)。
//
// 数据从 /plugin/opencode-usage 取 —— 同源、由本插件的服务端代理上游,
// 既避开了浏览器直连 opencode.ai 的 CORS,也不把 API Key 暴露给页面。
window.__ModuleLoader__.load({
id: "dsh-opencode-usage",
factory: (require) => {
const module = { exports: {} };
const exports = module.exports;
const react = require("react");
const h = react.createElement;
const { useCallback, useEffect, useMemo, useRef, useState } = react;
const PLUGIN_NAME = "dsh-opencode-usage";
/** 左侧栏底部 actions 区(DSH 的 .footerActions 容器)。 */
const SLOT_SIDEBAR_FOOTER = "sidebar.footer.action";
const ENDPOINT = "/plugin/opencode-usage";
/** 自动刷新间隔:用量是分钟级指标,60 秒足够,也不会给上游添麻烦。 */
const AUTO_REFRESH_MS = 60000;
const PLUGIN_CSS = `
.ocu-card {
display: flex; flex-direction: column; gap: 9px;
width: 100%; min-width: 0; padding: 10px 10px 9px;
border-radius: 10px;
border: 1px solid rgba(127,127,127,.20);
background: rgba(127,127,127,.06);
box-sizing: border-box;
}
.ocu-head { display: flex; align-items: center; gap: 6px; }
.ocu-title { font-size: 11.5px; font-weight: 600; opacity: .85; letter-spacing: .2px; }
.ocu-head-spacer { flex: 1; }
.ocu-refresh {
display: inline-flex; align-items: center; justify-content: center;
width: 21px; height: 21px; padding: 0; flex: none;
border: 1px solid rgba(127,127,127,.26); border-radius: 6px;
background: transparent; color: inherit; cursor: pointer;
opacity: .70;
transition: opacity .15s, background .15s, border-color .15s;
}
.ocu-refresh:hover:not(:disabled) { opacity: 1; background: rgba(127,127,127,.14); border-color: rgba(127,127,127,.5); }
.ocu-refresh:disabled { cursor: default; opacity: .72; }
/* 加载态:图标本体常驻(不再换成文字),只有旋转;
按钮整体不降透明度,避免"变灰=不可用"和"正在转=正在刷新"两种语义打架。 */
.ocu-refresh.is-loading { border-color: rgba(127,127,127,.45); background: rgba(127,127,127,.10); opacity: 1; }
.ocu-spin { display: block; transform-origin: 50% 50%; }
.ocu-spin.is-spinning { animation: ocu-spin .75s linear infinite; }
@keyframes ocu-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
/* 标题右侧的月份重置标记 */
.ocu-month {
font-size: 9.5px; opacity: .45; white-space: nowrap;
font-variant-numeric: tabular-nums; margin-left: 2px;
}
.ocu-bucket { display: flex; flex-direction: column; gap: 3px; }
/* 一行放下「名字 + 倒计时 + 百分比」:倒计时占中间剩余空间,超长用省略号,
这样每个分桶只要 2 行(标题行 + 进度条),比原来 3 行紧凑。 */
.ocu-row { display: flex; align-items: baseline; gap: 5px; min-width: 0; }
.ocu-label { font-size: 11px; opacity: .62; flex: none; }
.ocu-pct { margin-left: auto; font-size: 12px; font-weight: 700; font-variant-numeric: tabular-nums; letter-spacing: -.2px; flex: none; }
.ocu-pct.ok { color: #16a34a; }
.ocu-pct.warn { color: #d97706; }
.ocu-pct.hot { color: #dc2626; }
.ocu-track { position: relative; height: 5px; border-radius: 999px; background: rgba(127,127,127,.22); overflow: hidden; }
.ocu-fill { position: absolute; inset: 0 auto 0 0; border-radius: 999px; transition: width .35s ease; }
.ocu-fill.ok { background: #16a34a; }
.ocu-fill.warn { background: #d97706; }
.ocu-fill.hot { background: #dc2626; }
.ocu-fill.unknown { background: rgba(127,127,127,.5); }
.ocu-reset {
font-size: 10px; opacity: .5; font-variant-numeric: tabular-nums;
flex: 1 1 auto; min-width: 0;
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.ocu-foot {
display: flex; align-items: center; gap: 5px;
padding-top: 2px; font-size: 9.5px; opacity: .42;
font-variant-numeric: tabular-nums;
}
.ocu-err {
font-size: 10.5px; line-height: 1.55; color: #b91c1c;
word-break: break-all;
}
.ocu-dim { font-size: 10.5px; opacity: .55; }
@media (prefers-color-scheme: dark) {
.ocu-err { color: #fca5a5; }
}
`;
/** 百分比 → 颜色档位:<70 绿、70-89 橙、>=90 红。 */
function tier(pct) {
if (pct === null || pct === undefined) return "unknown";
if (pct >= 90) return "hot";
if (pct >= 70) return "warn";
return "ok";
}
/** 秒 → 紧凑的"还剩多久"(侧栏窄,尽量用最短写法)。 */
function humanDuration(sec) {
if (sec === null || sec === undefined || sec < 0) return "";
if (sec >= 86400) {
const d = Math.floor(sec / 86400);
const hr = Math.floor((sec % 86400) / 3600);
return hr > 0 ? `${d}天${hr}小时` : `${d}天`;
}
if (sec >= 3600) {
const hr = Math.floor(sec / 3600);
const mi = Math.floor((sec % 3600) / 60);
return mi > 0 ? `${hr}小时${mi}分` : `${hr}小时`;
}
return `${Math.max(1, Math.floor(sec / 60))}分钟`;
}
function formatClock(epochSec) {
if (!epochSec) return "";
const d = new Date(epochSec * 1000);
const p = (n) => String(n).padStart(2, "0");
return `${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
}
/** ISO 时间 → "MM-DD"(侧栏宽度有限,只保留月日)。 */
function formatMonthDay(iso) {
if (!iso) return "";
const t = Date.parse(iso);
if (!Number.isFinite(t)) return "";
const d = new Date(t);
const p = (n) => String(n).padStart(2, "0");
return `${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
/** 标准 refresh 图标(圆弧 + 箭头):静态是"可刷新",加载态整体旋转。
* 用 SVG 而不是 ↻ 字符,是因为字符在不同字体下大小/基线不一致,
* 而且旋转一个字形会有轻微的抖动感。 */
function RefreshIcon({ spinning }) {
return h("svg", {
className: `ocu-spin${spinning ? " is-spinning" : ""}`,
viewBox: "0 0 24 24", width: 13, height: 13,
fill: "none", stroke: "currentColor",
strokeWidth: 2.2, strokeLinecap: "round", strokeLinejoin: "round",
"aria-hidden": "true",
},
h("path", { d: "M20.5 12a8.5 8.5 0 1 1-2.49-6.01" }),
h("path", { d: "M20.5 3.5v5.5h-5.5" }),
);
}
/** 短标签:滚动 / 本周 / 本月;未知分桶回退到上游给的 label。 */
function shortLabel(b) {
if (b.key === "rolling") return "滚动";
if (b.key === "weekly") return "本周";
if (b.key === "monthly") return "本月";
return b.label || b.key;
}
function SidebarCard() {
const [state, setState] = useState({ loading: true, error: null, data: null });
const [spinning, setSpinning] = useState(false);
const timerRef = useRef(null);
const aliveRef = useRef(true);
const load = useCallback(async (manual) => {
if (manual) setSpinning(true);
try {
const resp = await fetch(ENDPOINT, { headers: { Accept: "application/json" }, cache: "no-store" });
const body = await resp.json().catch(() => ({}));
if (!resp.ok || body.ok === false) {
throw new Error(body.error || `接口返回 HTTP ${resp.status}`);
}
if (aliveRef.current) setState({ loading: false, error: null, data: body });
} catch (e) {
if (aliveRef.current) {
setState({ loading: false, error: String(e && e.message ? e.message : e), data: null });
}
} finally {
if (manual && aliveRef.current) setSpinning(false);
}
}, []);
useEffect(() => {
aliveRef.current = true;
load(true);
timerRef.current = setInterval(() => load(false), AUTO_REFRESH_MS);
return () => {
aliveRef.current = false;
if (timerRef.current) clearInterval(timerRef.current);
};
}, [load]);
const onRefresh = useCallback((ev) => {
if (ev && typeof ev.stopPropagation === "function") ev.stopPropagation();
load(true);
}, [load]);
const buckets = state.data && Array.isArray(state.data.buckets) ? state.data.buckets : [];
// 月份重置日:从 monthly 分桶取(上游给的是 ISO 时间),侧栏只显示 MM-DD
const monthly = buckets.find((b) => b.key === "monthly") || null;
const monthReset = monthly ? formatMonthDay(monthly.resetsAt) : "";
const head = h("div", { className: "ocu-head" },
h("span", { className: "ocu-title" }, "OpenCode Go"),
monthReset
? h("span", { className: "ocu-month", title: `本月额度 ${monthly.resetsAt} 重置` }, `${monthReset} 重置`)
: null,
h("span", { className: "ocu-head-spacer" }),
h("button", {
className: `ocu-refresh${spinning ? " is-loading" : ""}`,
disabled: spinning,
title: spinning ? "正在刷新…" : "刷新用量",
onClick: onRefresh,
}, h(RefreshIcon, { spinning })),
);
if (state.error) {
return h("div", { className: "ocu-card" },
head,
h("div", { className: "ocu-err" }, state.error),
);
}
const body = buckets.length
? buckets.map((b) => {
const pct = typeof b.percent === "number" ? Math.max(0, Math.min(100, b.percent)) : null;
const t = tier(pct);
const left = humanDuration(b.resetInSeconds);
return h("div", { className: "ocu-bucket", key: b.key },
h("div", { className: "ocu-row" },
h("span", { className: "ocu-label" }, shortLabel(b)),
// 倒计时紧跟名字后面,只占一行的中间空隙;放不下时省略号收尾
h("span", { className: "ocu-reset", title: left ? `${left}后重置` : "重置时间未知" },
left ? `${left}后重置` : "重置未知"),
h("span", { className: `ocu-pct ${t}` }, pct === null ? "—" : `${pct}%`),
),
h("div", { className: "ocu-track" },
h("div", { className: `ocu-fill ${t}`, style: { width: `${pct === null ? 0 : pct}%` } }),
),
);
})
: [h("div", { className: "ocu-dim", key: "empty" }, state.loading ? "读取中…" : "上游未返回用量数据")];
// 底栏只留抓取时间:实时/缓存这个提示对使用者没有决策价值
// (要不要重拉是自动+手动刷新决定的事),去掉后底栏更干净。
const foot = h("div", { className: "ocu-foot" },
h("span", null, state.data ? `${formatClock(state.data.fetchedAt)} 更新` : ""),
);
return h("div", { className: "ocu-card" }, head, ...body, foot);
}
const injectList = ["slots"];
function apply(ctx) {
ctx.effect(() => {
const style = document.createElement("style");
style.dataset.plugin = PLUGIN_NAME;
style.textContent = PLUGIN_CSS;
document.head.appendChild(style);
return () => style.remove();
}, `${PLUGIN_NAME}: styles`);
// 唯一出口:左侧栏底部
ctx.slots.inject(SLOT_SIDEBAR_FOOTER, () => {
return ctx.slots.register({
name: SLOT_SIDEBAR_FOOTER,
id: "opencode-usage-footer",
order: 20,
}, () => h(SidebarCard));
});
}
exports.apply = apply;
exports.inject = injectList;
exports.name = PLUGIN_NAME;
return module.exports;
},
});
+295
View File
@@ -0,0 +1,295 @@
/**
* dsh-opencode-usage — OpenCode Go 套餐用量查看(服务端)。
*
* 两个出口:
* ① GET /plugin/opencode-usage —— 给设置页卡片用(同源,免鉴权,只依赖 DSH 自身的
* loopback ∪ trustedHost 网络栅栏;前端拿到的是三条百分比,不含任何凭证)。
* ② opencode_usage 工具 —— 让 agent 也能查(用户直接问「opencode 用了多少」)。
*
* 数据源:直连 https://opencode.ai/zen/go/v1/usage(Bearer + UA),不依赖任何中间服务。
* 凭证按 apiKey → envFile 里的 OPENCODE_API_KEY → 进程环境变量 的顺序找,
* 找到就用;一个都没有时接口回 503 并把三条搜索路径写清楚,方便排查。
*
* 缓存:默认 15 秒。用量是分钟级刷新的指标,没必要每次点开都打一次上游;
* 但也不能太长 —— 用户点「刷新」时期待看到变化,15s 是「连点不重复打」和
* 「刷新能看到新数」之间的折中。
*/
import { createRequire } from "node:module";
import { realpathSync, readFileSync, existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
export const name = "opencode-usage";
/** 只依赖两个 seam:注册 HTTP 路由 + 注册工具。 */
export const inject = ["webServer", "tools"];
const DEFAULTS = {
baseUrl: "https://opencode.ai/zen/go/v1",
/** 可选的 .env 文件路径(形如 KEY=VALUE 逐行)。默认不读文件,只认 config.apiKey 与环境变量;
* 想从某个 .env 里取 key,用 config.envFile 指向它,或把 key 直接放进环境变量。 */
envFile: "",
/** 从 envFile / 进程环境里找的变量名。 */
envKey: "OPENCODE_API_KEY",
cacheSeconds: 15,
timeoutMs: 12000,
userAgent: "dsh-opencode-usage/0.1.0",
};
/* ── defineTool:从运行中的 dsh 安装里解析 ────────────────────────────────
* 插件装在 ~/.dsh/profiles/web/local/ 下,模块解析链上找不到 @deepseek-ai/dsh-tools
* (它只在 dsh 自己的 node_modules 里)。所以拿 dsh 进程的入口做 realpath,
* 用它的真实位置建 createRequire,就能解析到 dsh 依赖树里的所有 @deepseek-ai 包。
* 失败时返回 undefined,调用方降级成「只有 HTTP 路由、没有工具」。 */
function loadDefineTool() {
const entry = process.argv[1];
const candidates = [];
if (entry) {
candidates.push(entry);
try { candidates.push(realpathSync(entry)); } catch { /* 入口不存在就算了 */ }
}
for (const c of candidates) {
try {
const req = createRequire(`file://${c}`);
const mod = req("@deepseek-ai/dsh-tools");
if (mod?.defineTool) return mod.defineTool;
} catch { /* 换下一条 */ }
}
return undefined;
}
/** 读配置:兼容 cordis 的 Ref 包装(`.get()`)与裸对象。 */
function cfgOf(config) {
if (!config) return {};
if (typeof config.get === "function") {
try { return config.get() ?? {}; } catch { return {}; }
}
return config;
}
/** 按 apiKey → envFile → 环境变量 的顺序找 token;返回 {token, from}。 */
function resolveToken(cfg) {
if (cfg.apiKey && String(cfg.apiKey).trim()) {
return { token: String(cfg.apiKey).trim(), from: "config.apiKey" };
}
const envFile = cfg.envFile || DEFAULTS.envFile;
try {
if (existsSync(envFile)) {
const want = cfg.envKey || DEFAULTS.envKey;
for (const line of readFileSync(envFile, "utf8").split("\n")) {
const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
if (!m || m[1] !== want) continue;
const v = m[2].trim().replace(/^["']|["']$/g, "");
if (v) return { token: v, from: envFile };
}
}
} catch { /* 读不到就往下试 */ }
const env = process.env[cfg.envKey || DEFAULTS.envKey];
if (env && String(env).trim()) return { token: String(env).trim(), from: "env" };
return { token: "", from: "" };
}
/** 把上游的 {usage:{rolling,weekly,monthly}} 归一化,并补上便于展示的字段。 */
function normalize(raw) {
const usage = raw?.usage ?? raw ?? {};
const order = [
["rolling", "滚动窗口"],
["weekly", "本周"],
["monthly", "本月"],
];
const buckets = [];
for (const [key, label] of order) {
const b = usage[key];
if (!b || typeof b !== "object") continue;
const percent = Number(b.percent);
buckets.push({
key,
label,
status: typeof b.status === "string" ? b.status : "unknown",
percent: Number.isFinite(percent) ? percent : null,
resetsAt: typeof b.resetsAt === "string" ? b.resetsAt : null,
resetInSeconds: resetIn(b.resetsAt),
});
}
return buckets;
}
/** 距离重置还有多少秒;解析不了返回 null。 */
function resetIn(iso) {
if (!iso) return null;
const t = Date.parse(iso);
if (!Number.isFinite(t)) return null;
return Math.max(0, Math.round((t - Date.now()) / 1000));
}
/** 拉上游用量。命中缓存直接返回,失败抛带 code 的错误。 */
async function fetchUsage(cfg, cache) {
const now = Date.now();
const ttl = Math.max(0, Number(cfg.cacheSeconds ?? DEFAULTS.cacheSeconds)) * 1000;
if (cache.data && now - cache.at < ttl) {
return { ...cache.data, cached: true };
}
const { token, from } = resolveToken(cfg);
if (!token) {
const tried = ["config.apiKey"];
if (cfg.envFile) tried.push(`${cfg.envFile} 里的 ${cfg.envKey || DEFAULTS.envKey}`);
tried.push(`环境变量 ${cfg.envKey || DEFAULTS.envKey}`);
const err = new Error(`OpenCode Go 未配置 API Key(已尝试:${tried.join("、")})`);
err.code = "NO_TOKEN";
throw err;
}
const base = String(cfg.baseUrl || DEFAULTS.baseUrl).replace(/\/+$/, "");
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), Number(cfg.timeoutMs ?? DEFAULTS.timeoutMs));
let resp;
try {
resp = await fetch(`${base}/usage`, {
headers: {
Authorization: `Bearer ${token}`,
"User-Agent": cfg.userAgent || DEFAULTS.userAgent,
Accept: "application/json",
},
signal: ctrl.signal,
});
} catch (e) {
const err = new Error(
e?.name === "AbortError" ? "查询 OpenCode Go 用量超时" : `查询 OpenCode Go 用量失败:${e?.message || e}`,
);
err.code = "UPSTREAM";
throw err;
} finally {
clearTimeout(timer);
}
if (!resp.ok) {
const err = new Error(`OpenCode Go 用量接口返回 HTTP ${resp.status}`);
err.code = "UPSTREAM";
err.status = resp.status;
throw err;
}
const raw = await resp.json();
const data = {
fetchedAt: Math.floor(now / 1000),
source: from,
buckets: normalize(raw),
raw,
};
cache.at = now;
cache.data = data;
return { ...data, cached: false };
}
/** 把桶数组渲染成一段人类可读文本(工具返回 / 命令行调试都用它)。 */
function renderText(data) {
if (!data?.buckets?.length) return "(上游没有返回任何用量分桶)";
const lines = [];
for (const b of data.buckets) {
const pct = b.percent === null ? "—" : `${b.percent}%`;
const reset = b.resetInSeconds === null ? "" : `,${formatDuration(b.resetInSeconds)}后重置`;
lines.push(`${b.label}:${pct}${reset}`);
}
return lines.join("\n");
}
function formatDuration(sec) {
if (sec >= 86400) return `${Math.floor(sec / 86400)} 天 ${Math.floor((sec % 86400) / 3600)} 小时`;
if (sec >= 3600) return `${Math.floor(sec / 3600)} 小时 ${Math.floor((sec % 3600) / 60)} 分`;
return `${Math.max(1, Math.floor(sec / 60))} 分钟`;
}
export function apply(ctx, config) {
const cache = { at: 0, data: null };
const cfgNow = () => ({ ...DEFAULTS, ...cfgOf(config) });
/* ① HTTP 路由:给设置页卡片用 */
ctx.webServer.register({
kind: "exact",
path: "/plugin/opencode-usage",
async handler(req, res) {
const respond = (code, body) => {
const text = JSON.stringify(body);
res.writeHead(code, {
"Content-Type": "application/json; charset=utf-8",
"Cache-Control": "no-store",
"Content-Length": Buffer.byteLength(text),
});
res.end(text);
};
if (req.method !== "GET" && req.method !== "HEAD") {
respond(405, { ok: false, error: "只支持 GET" });
return;
}
try {
const data = await fetchUsage(cfgNow(), cache);
respond(200, { ok: true, ...data });
} catch (e) {
const code = e?.code === "NO_TOKEN" ? 503 : 502;
ctx.logger?.warn?.("opencode-usage: 查询失败 %s", e?.message || e);
respond(code, { ok: false, error: String(e?.message || e), code: e?.code || "UNKNOWN" });
}
},
});
/* ② 工具:让 agent 也能查 */
const defineTool = loadDefineTool();
if (!defineTool) {
ctx.logger?.warn?.("opencode-usage: 未能解析 @deepseek-ai/dsh-tools,跳过工具注册(HTTP 路由仍可用)");
return;
}
ctx.tools.register(defineTool({
name: "opencode_usage",
description:
"查询 OpenCode Go 套餐的用量(滚动窗口 / 本周 / 本月三条配额的已用百分比与重置时间)。直连 opencode.ai,不依赖任何中间服务。",
parameters: {},
// 注意:dsh-tools 的 value schema DSL 是**受约束子集**,不吃 `required: [...]`
// 数组(会抛 JsonSchemaError: schema.required is not supported),也不吃
// `type: ["number","null"]` 这种 union。所以这里只用纯类型,
// 未知值用哨兵表示:percent = -1、resetsAt = ""、resetInSeconds = -1。
output: {
schema: {
type: "object",
additionalProperties: false,
properties: {
summary: { type: "string", description: "人类可读的用量摘要,直接可以回复给用户" },
fetchedAt: { type: "integer", description: "数据抓取时间(epoch 秒)" },
buckets: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
key: { type: "string" },
label: { type: "string" },
status: { type: "string" },
percent: { type: "number", description: "-1 表示上游没给百分比" },
resetsAt: { type: "string", description: "ISO 时间;空串表示未知" },
resetInSeconds: { type: "integer", description: "-1 表示未知" },
},
},
},
},
},
render: (value) => [{ type: "text", text: value?.summary || "" }],
},
async execute() {
const data = await fetchUsage(cfgNow(), cache);
const summary = renderText(data);
return {
summary: `OpenCode Go 用量(${new Date((data.fetchedAt || 0) * 1000).toLocaleString("zh-CN")} 抓取):\n${summary}`,
fetchedAt: data.fetchedAt || 0,
// 与上面的 schema 对齐:null → 哨兵,避免结构化输出校验失败
buckets: (data.buckets || []).map((b) => ({
key: b.key,
label: b.label,
status: b.status || "unknown",
percent: b.percent === null || b.percent === undefined ? -1 : b.percent,
resetsAt: b.resetsAt || "",
resetInSeconds: b.resetInSeconds === null || b.resetInSeconds === undefined ? -1 : b.resetInSeconds,
})),
};
},
}));
ctx.logger?.info?.("opencode-usage: 已注册 /plugin/opencode-usage 与 opencode_usage 工具");
}
+43
View File
@@ -0,0 +1,43 @@
{
"name": "dsh-opencode-usage",
"version": "1.0.0",
"description": "OpenCode Go 套餐用量查看:DSH 左侧栏卡片(滚动/本周/本月三条配额进度条 + 重置倒计时 + 刷新按钮),并提供 opencode_usage 工具与 /plugin/opencode-usage 接口。直连 opencode.ai,API Key 不经过浏览器。",
"type": "module",
"license": "MIT",
"keywords": [
"dsh",
"dsh-plugin",
"opencode",
"usage",
"quota",
"sidebar"
],
"engines": {
"node": "^22.19.0 || >=24.0.0"
},
"main": "./lib/index.js",
"exports": {
".": "./lib/index.js",
"./client": "./lib/client.js",
"./cordis.patch.yml": "./cordis.patch.yml",
"./package.json": "./package.json"
},
"files": [
"lib",
"cordis.patch.yml",
"README.md",
"LICENSE"
],
"dsh": {
"bundle": {
"patch": "./cordis.patch.yml"
},
"client": {
"inject": [
"@deepseek-ai/dsh-client-connection",
"@deepseek-ai/dsh-client-ui-settings"
],
"platform": "web"
}
}
}