release: 1.0.5

This commit is contained in:
wangjinding committed 2026-11-09 16:54:47 +08:00
1 parent 3af30c7580
commit a418866ec5
4 files changed
+138 -33

No files matched your search

+113 -25
View File
@@ -15,7 +15,7 @@
* 「刷新能看到新数」之间的折中。
*/
import { createRequire } from "node:module";
import { realpathSync, readFileSync, existsSync } from "node:fs";
import { realpathSync, readFileSync, existsSync, readdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
export const name = "opencode-usage";
@@ -30,6 +30,8 @@ const DEFAULTS = {
envFile: "",
/** 从 envFile / 进程环境里找的变量名。 */
envKey: "OPENCODE_API_KEY",
/** 都没配时,自动去 dsh 的 .env 层 / 工作空间里找这个键(默认开)。 */
autoDiscover: true,
cacheSeconds: 15,
timeoutMs: 12000,
userAgent: "dsh-opencode-usage/0.1.0",
@@ -66,26 +68,115 @@ function cfgOf(config) {
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;
/** 读一个 .env 文件里的某个键;找不到返回 ""。 */
function readKeyFromFile(file, key) {
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 };
}
if (!file || !existsSync(file)) return "";
for (const line of readFileSync(file, "utf8").split("\n")) {
const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
if (!m || m[1] !== key) continue;
const v = m[2].trim().replace(/^["']|["']$/g, "");
if (v) return v;
}
} catch { /* 读不到就往下试 */ }
const env = process.env[cfg.envKey || DEFAULTS.envKey];
if (env && String(env).trim()) return { token: String(env).trim(), from: "env" };
return { token: "", from: "" };
return "";
}
/** dsh 的 home(优先 DSH_HOME,其次 ~/.dsh)。 */
function dshHomeDir() {
const home = process.env.DSH_HOME;
if (home && String(home).trim()) return String(home).trim();
return process.env.HOME ? `${process.env.HOME}/.dsh` : "";
}
/** dsh 记录的工作空间根目录(读 storages/workspace.json,不依赖任何内部模块)。 */
function workspaceRootsOf() {
const home = dshHomeDir();
if (!home) return [];
const out = [];
try {
const doc = JSON.parse(readFileSync(`${home}/storages/workspace.json`, "utf8"));
const table = doc?.tables?.workspaces ?? {};
for (const ws of Object.values(table)) {
if (ws && typeof ws.path === "string" && ws.path) out.push(ws.path);
}
} catch { /* 没有工作空间记录 */ }
return out;
}
const SKIP_DIRS = new Set(["node_modules", ".git", ".pnpm", "dist", "build", "target", ".venv", "venv", "__pycache__", ".next", ".cache"]);
const ENV_NAME = /^\.env(\.[A-Za-z0-9_-]+)?$/;
/** 在目录里找 .env(限深度、跳过依赖与产物目录,最多 limit 个)。 */
function findEnvFiles(root, maxDepth = 4, limit = 400) {
const out = [];
const walk = (dir, depth) => {
if (out.length >= limit || depth > maxDepth) return;
let entries;
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
for (const e of entries) {
if (out.length >= limit) return;
const p = `${dir}/${e.name}`;
if (e.isFile()) { if (ENV_NAME.test(e.name)) out.push(p); }
else if (e.isDirectory() && !SKIP_DIRS.has(e.name) && !e.name.startsWith(".")) walk(p, depth + 1);
}
};
walk(root, 0);
return out;
}
/** 自动发现的候选 .env:dsh home → 启动目录 → 每个工作空间根及其内部。 */
function candidateEnvFiles() {
const seen = new Set();
const out = [];
const push = (p) => { if (p && !seen.has(p)) { seen.add(p); out.push(p); } };
const home = dshHomeDir();
if (home) push(`${home}/.env`);
push(`${process.cwd()}/.env`);
for (const root of workspaceRootsOf()) {
push(`${root}/.env`);
for (const file of findEnvFiles(root)) push(file);
}
return out;
}
/** 按 apiKey → envFile → dsh launchEnvironment → process.env → 自动发现 的顺序找 token。 */
function resolveToken(cfg, ctx) {
const want = cfg.envKey || DEFAULTS.envKey;
const tried = [];
if (cfg.apiKey && String(cfg.apiKey).trim()) {
return { token: String(cfg.apiKey).trim(), from: "config.apiKey", tried };
}
if (cfg.envFile) {
tried.push(`config.envFile ${cfg.envFile}`);
const v = readKeyFromFile(cfg.envFile, want);
if (v) return { token: v, from: cfg.envFile, tried };
}
try {
const slot = ctx?.get?.("launchEnvironment");
if (slot?.get) {
const v = slot.get(want)?.value;
if (v && String(v).trim()) return { token: String(v).trim(), from: "dsh launchEnvironment", tried };
tried.push("dsh launchEnvironment");
}
} catch { /* 槽不可用就跳过 */ }
const env = process.env[want];
if (env && String(env).trim()) return { token: String(env).trim(), from: "process.env", tried };
tried.push(`process.env ${want}`);
if (cfg.autoDiscover !== false) {
for (const file of candidateEnvFiles()) {
const v = readKeyFromFile(file, want);
if (v) return { token: v, from: file, tried };
}
tried.push("自动发现(DSH_HOME/.env、启动目录、工作空间的 .env)");
}
return { token: "", from: "", tried };
}
/** 把上游的 {usage:{rolling,weekly,monthly}} 归一化,并补上便于展示的字段。 */
@@ -122,18 +213,15 @@ function resetIn(iso) {
}
/** 拉上游用量。命中缓存直接返回,失败抛带 code 的错误。 */
async function fetchUsage(cfg, cache) {
async function fetchUsage(cfg, cache, ctx) {
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);
const { token, from, tried } = resolveToken(cfg, ctx);
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;
@@ -221,7 +309,7 @@ export function apply(ctx, config) {
return;
}
try {
const data = await fetchUsage(cfgNow(), cache);
const data = await fetchUsage(cfgNow(), cache, ctx);
respond(200, { ok: true, ...data });
} catch (e) {
const code = e?.code === "NO_TOKEN" ? 503 : 502;
@@ -273,7 +361,7 @@ export function apply(ctx, config) {
render: (value) => [{ type: "text", text: value?.summary || "" }],
},
async execute() {
const data = await fetchUsage(cfgNow(), cache);
const data = await fetchUsage(cfgNow(), cache, ctx);
const summary = renderText(data);
return {
summary: `OpenCode Go 用量(${new Date((data.fetchedAt || 0) * 1000).toLocaleString("zh-CN")} 抓取):\n${summary}`,