diff --git a/README.md b/README.md index a3e4d1a..be83e89 100644 --- a/README.md +++ b/README.md @@ -42,13 +42,29 @@ pnpm add file:/path/to/dsh-opencode-usage ## 配置凭证 -三选一,按优先级: +五级查找,从上到下第一个命中即用: -| 顺序 | 来源 | +| 顺序 | 来源 | 说明 | +|---|---|---| +| 1 | `config.apiKey` | 显式配置,优先级最高 | +| 2 | `config.envFile` 指向的 `.env` | 文件里的 `OPENCODE_API_KEY` | +| 3 | DSH 的 launchEnvironment | DSH 启动时读的 `.env` 层(process / project-env / user-env) | +| 4 | 进程环境变量 `OPENCODE_API_KEY` | 由 DSH 或你的 shell 注入 | +| 5 | **自动发现** | 见下 | + +### 自动发现(默认开启) + +第 1–4 级全落空时,插件自己去找,范围是**有界**的: + +| 顺序 | 位置 | |---|---| -| 1 | `config.apiKey` | -| 2 | `config.envFile` 指向的 `.env` 里的 `OPENCODE_API_KEY` | -| 3 | 进程环境变量 `OPENCODE_API_KEY` | +| 1 | `$DSH_HOME/.env`(通常 `~/.dsh/.env`) | +| 2 | DSH 启动目录的 `.env` | +| 3 | 每个 DSH 工作空间根目录下的 `.env`(工作空间来自 `$DSH_HOME/storages/workspace.json`) | +| 4 | 工作空间内递归查找 `.env*`,深度 ≤ 4,跳过 `node_modules` / `.git` / `.pnpm` / `dist` / `build` / `target` / `.venv` 等,最多 400 个 | + +只读文件名匹配 `.env*` 的文件,只取 `OPENCODE_API_KEY` 这一行;值不写日志、不进接口响应(响应里只有百分比和 `source` 路径)。 +想关掉:`config.autoDiscover: false`。 写在**你自己 profile 的** `cordis.patch.yml`(不要改本包): @@ -75,6 +91,7 @@ pnpm add file:/path/to/dsh-opencode-usage cacheSeconds: 15 # 缓存秒数 timeoutMs: 12000 # 单次请求超时 envKey: OPENCODE_API_KEY # 变量名 + autoDiscover: true # 是否自动发现 .env(默认 true) ``` ## 实现要点 diff --git a/lib/index.js b/lib/index.js index bf1f865..5f41dd4 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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}`, diff --git a/market-index.json b/market-index.json index cad0f67..ed864de 100644 --- a/market-index.json +++ b/market-index.json @@ -45,8 +45,8 @@ }, "versions": [ { - "version": "1.0.4", - "publishTimestamp": 1794212137, + "version": "1.0.5", + "publishTimestamp": 1794214485, "source": { "type": "npm" }, diff --git a/package.json b/package.json index 42b994d..14ab9d7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@wangjinding/dsh-opencode-go-usage", - "version": "1.0.4", + "version": "1.0.5", "description": "OpenCode Go 套餐用量查看:DSH 左侧栏卡片(滚动/本周/本月三条配额进度条 + 重置倒计时 + 刷新按钮),并提供 opencode_usage 工具与 /plugin/opencode-usage 接口。直连 opencode.ai,API Key 不经过浏览器。", "type": "module", "license": "MIT",