Skip to content

Commit 942f4db

Browse files
fix: key lookup from the opencode data dir, surface read errors, tests, README (#27) (#28)
1 parent bd16253 commit 942f4db

7 files changed

Lines changed: 126 additions & 56 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
11
# Changelog
22

3+
## 0.1.1 — 2026-11-14
4+
- fix: read auth.json from the opencode data dir (`$XDG_DATA_HOME/opencode`, default `~/.local/share/opencode`) first; state dir is the fallback
5+
- fix: unreadable key files show `KEY ERROR <code>` instead of `NO KEY`
6+
- test: precedence covered with competing keys in every source
7+
- docs: README describes the key lookup and status messages
8+
39
## 0.1.0 — 2026-06-11
410
- Initial release: DeepSeek API balance meter in TUI sidebar

‎GUIDELINES.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,5 +44,5 @@ src/
4444
All new source files must include:
4545
```typescript
4646
// SPDX-License-Identifier: Apache-2.0
47-
// Copyright (c) 2026 Four Bytes / Four Flames GmbH & Co. KG
47+
// Copyright (c) 2026 Four Flames GmbH & Co. KG
4848
```

‎README.md‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
## Why?
1010

11-
DeepSeek API has usage-based billing. This TUI sidebar shows your balance in real-time so you never hit zero unexpectedly. Auto-detects DeepSeek provider from opencode config. Color-coded warnings when balance drops below thresholds.
11+
DeepSeek API has usage-based billing. This TUI sidebar shows your balance in real-time so you never hit zero unexpectedly. Reads the DeepSeek key from opencode's auth.json (see Configuration). Color-coded warnings when balance drops below thresholds.
1212

1313
## Quickstart
1414

@@ -35,11 +35,20 @@ Restart opencode.
3535
└──────────────────────┘
3636
```
3737

38-
Auto-refreshes after each assistant message (min 10s interval). Shows "no key" if DeepSeek provider not configured.
38+
Auto-refreshes after each assistant message (min 10s interval).
39+
40+
Status messages: `NO KEY` (no key found), `KEY ERROR <code>` (a key file exists but cannot be read, e.g. `EACCES`), `INVALID KEY` (rejected by DeepSeek), `API <status>` (other API errors).
3941

4042
## Configuration
4143

42-
No config file needed — reads API key from opencode provider config. Ensure DeepSeek is configured in opencode's model providers.
44+
No config file needed. The API key is taken from the first source that has one:
45+
46+
1. `auth.json` in the opencode data dir — `$XDG_DATA_HOME/opencode/auth.json`, default `~/.local/share/opencode/auth.json` (written by `opencode auth login`)
47+
2. `auth.json` in the opencode state dir (fallback)
48+
3. `~/.secrets/deepseek-key` (plain text file)
49+
4. Environment variable `DEEPSEEK_API_KEY`
50+
51+
A malformed `auth.json` is skipped.
4352

4453
## Contributing
4554

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@four-bytes/four-opencode-deepseek-meter",
3-
"version": "0.1.0",
3+
"version": "0.1.1",
44
"description": "opencode Plugin: shows DeepSeek API balance in the TUI sidebar",
55
"license": "Apache-2.0",
66
"type": "module",

‎src/key-resolver.test.ts‎

Lines changed: 50 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// Copyright (c) 2026 Four Flames GmbH & Co. KG
13
import { afterAll, describe, expect, test } from "bun:test";
2-
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
4+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
35
import os from "node:os";
46
import path from "node:path";
5-
import { findDeepSeekKey, parseAuthKey } from "./key-resolver.js";
7+
import { findDeepSeekKey, opencodeDataDir, parseAuthKey } from "./key-resolver.js";
68

79
const dirs: string[] = [];
810

@@ -52,30 +54,47 @@ describe("parseAuthKey", () => {
5254
});
5355

5456
describe("findDeepSeekKey", () => {
55-
test("auth.json (stateDir) primär", () => {
56-
const d = tmpDir();
57-
writeAuth(d, "sk-state");
58-
expect(findDeepSeekKey({ stateDir: d })).toBe("sk-state");
57+
/** Every source holds a different key, so each precedence step is observable. */
58+
function allSources() {
59+
const dataDir = tmpDir();
60+
const stateDir = tmpDir();
61+
const secretsDir = tmpDir();
62+
writeAuth(dataDir, "sk-data");
63+
writeAuth(stateDir, "sk-state");
64+
writeSecret(secretsDir, "sk-secret");
65+
return { dataDir, stateDir, secretsDir, env: { DEEPSEEK_API_KEY: "sk-env" } };
66+
}
67+
68+
test("dataDir gewinnt über alle anderen Quellen", () => {
69+
expect(findDeepSeekKey(allSources())).toBe("sk-data");
5970
});
6071

61-
test("stateDir gewinnt über alle anderen Quellen", () => {
62-
const d = tmpDir();
63-
writeAuth(d, "sk-state");
64-
expect(
65-
findDeepSeekKey({ stateDir: d, secretsDir: tmpDir(), env: { DEEPSEEK_API_KEY: "sk-env" } }),
66-
).toBe("sk-state");
72+
test("stateDir vor secrets und env", () => {
73+
const s = allSources();
74+
expect(findDeepSeekKey({ ...s, dataDir: undefined })).toBe("sk-state");
6775
});
6876

69-
test("fallback auf opencodeDir", () => {
70-
const d = tmpDir();
71-
writeAuth(d, "sk-open");
72-
expect(findDeepSeekKey({ opencodeDir: d })).toBe("sk-open");
77+
test("secrets vor env", () => {
78+
const s = allSources();
79+
expect(findDeepSeekKey({ ...s, dataDir: undefined, stateDir: undefined })).toBe("sk-secret");
80+
});
81+
82+
test("auth.json ohne deepseek-Key fällt auf die nächste Quelle zurück", () => {
83+
const s = allSources();
84+
writeAuth(s.dataDir, undefined);
85+
expect(findDeepSeekKey(s)).toBe("sk-state");
7386
});
7487

7588
test("kaputtes auth.json wird übersprungen", () => {
7689
const d = tmpDir();
7790
writeFileSync(path.join(d, "auth.json"), "{not json");
78-
expect(findDeepSeekKey({ stateDir: d, env: { DEEPSEEK_API_KEY: "sk-env" } })).toBe("sk-env");
91+
expect(findDeepSeekKey({ dataDir: d, env: { DEEPSEEK_API_KEY: "sk-env" } })).toBe("sk-env");
92+
});
93+
94+
test("nicht lesbares auth.json wirft statt 'kein Key'", () => {
95+
const d = tmpDir();
96+
mkdirSync(path.join(d, "auth.json"));
97+
expect(() => findDeepSeekKey({ dataDir: d, env: { DEEPSEEK_API_KEY: "sk-env" } })).toThrow();
7998
});
8099

81100
test("fallback auf secrets", () => {
@@ -96,3 +115,17 @@ describe("findDeepSeekKey", () => {
96115
expect(findDeepSeekKey({})).toBeUndefined();
97116
});
98117
});
118+
119+
describe("opencodeDataDir", () => {
120+
test("nutzt XDG_DATA_HOME", () => {
121+
expect(opencodeDataDir({ XDG_DATA_HOME: "/xdg/data" }, "/home/u")).toBe(path.join("/xdg/data", "opencode"));
122+
});
123+
124+
test("Default ~/.local/share/opencode", () => {
125+
expect(opencodeDataDir({}, "/home/u")).toBe(path.join("/home/u", ".local", "share", "opencode"));
126+
});
127+
128+
test("leeres XDG_DATA_HOME → Default", () => {
129+
expect(opencodeDataDir({ XDG_DATA_HOME: " " }, "/home/u")).toBe(path.join("/home/u", ".local", "share", "opencode"));
130+
});
131+
});

‎src/key-resolver.ts‎

Lines changed: 41 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,48 @@
1+
// SPDX-License-Identifier: Apache-2.0
2+
// Copyright (c) 2026 Four Flames GmbH & Co. KG
13
import { readFileSync } from "node:fs";
4+
import os from "node:os";
25
import path from "node:path";
36

47
export interface DeepSeekKeySources {
5-
/** opencode state dir (api.state.path.state) — primary auth.json location */
8+
/** opencode data dir containing auth.json — primary location ($XDG_DATA_HOME/opencode) */
9+
dataDir?: string;
10+
/** opencode state dir (api.state.path.state) — fallback location for auth.json */
611
stateDir?: string;
7-
/** fallback dir containing auth.json (e.g. ~/.local/share/opencode) */
8-
opencodeDir?: string;
912
/** dir containing the deepseek-key file (e.g. ~/.secrets) */
1013
secretsDir?: string;
1114
/** environment variables */
1215
env?: Record<string, string | undefined>;
1316
}
1417

18+
/** opencode data dir: $XDG_DATA_HOME/opencode, default ~/.local/share/opencode */
19+
export function opencodeDataDir(
20+
env: Record<string, string | undefined> = process.env,
21+
home: string = os.homedir(),
22+
): string {
23+
const xdg = env.XDG_DATA_HOME?.trim();
24+
return path.join(xdg ? xdg : path.join(home, ".local", "share"), "opencode");
25+
}
26+
1527
function clean(key: unknown): string | undefined {
1628
if (typeof key !== "string") return undefined;
1729
const trimmed = key.trim();
1830
return trimmed ? trimmed : undefined;
1931
}
2032

33+
/**
34+
* Reads a file; a missing file yields undefined. Any other error (permissions,
35+
* a directory instead of a file, …) is rethrown so it is not reported as "no key".
36+
*/
37+
function readOptional(file: string): string | undefined {
38+
try {
39+
return readFileSync(file, "utf8");
40+
} catch (err) {
41+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return undefined;
42+
throw err;
43+
}
44+
}
45+
2146
export function parseAuthKey(json: string): string | undefined {
2247
try {
2348
const parsed = JSON.parse(json) as { deepseek?: { key?: unknown } };
@@ -27,42 +52,31 @@ export function parseAuthKey(json: string): string | undefined {
2752
}
2853
}
2954

30-
export function readAuthKey(stateDir: string): string | undefined {
31-
try {
32-
return parseAuthKey(readFileSync(path.join(stateDir, "auth.json"), "utf8"));
33-
} catch {
34-
return undefined;
35-
}
55+
export function readAuthKey(dir: string): string | undefined {
56+
const content = readOptional(path.join(dir, "auth.json"));
57+
return content === undefined ? undefined : parseAuthKey(content);
3658
}
3759

3860
export function readSecretsKey(secretsDir: string): string | undefined {
39-
try {
40-
return clean(readFileSync(path.join(secretsDir, "deepseek-key"), "utf8"));
41-
} catch {
42-
return undefined;
43-
}
61+
return clean(readOptional(path.join(secretsDir, "deepseek-key")));
4462
}
4563

64+
/**
65+
* Lookup order: auth.json in the data dir → auth.json in the state dir →
66+
* ~/.secrets/deepseek-key → DEEPSEEK_API_KEY. A malformed auth.json is skipped;
67+
* an unreadable file throws.
68+
*/
4669
export function findDeepSeekKey(sources: DeepSeekKeySources): string | undefined {
47-
// 1. opencode auth.json (primär, konfigurationsfrei)
48-
if (sources.stateDir) {
49-
const key = readAuthKey(sources.stateDir);
50-
if (key) return key;
51-
}
52-
if (sources.opencodeDir) {
53-
const key = readAuthKey(sources.opencodeDir);
70+
for (const dir of [sources.dataDir, sources.stateDir]) {
71+
if (!dir) continue;
72+
const key = readAuthKey(dir);
5473
if (key) return key;
5574
}
5675

57-
// 2. ~/.secrets/deepseek-key
5876
if (sources.secretsDir) {
5977
const key = readSecretsKey(sources.secretsDir);
6078
if (key) return key;
6179
}
6280

63-
// 3. Env DEEPSEEK_API_KEY
64-
const envKey = clean(sources.env?.DEEPSEEK_API_KEY);
65-
if (envKey) return envKey;
66-
67-
return undefined;
81+
return clean(sources.env?.DEEPSEEK_API_KEY);
6882
}

‎src/tui.tsx‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** @jsxImportSource @opentui/solid */
22
import { createEffect, createMemo, createSignal, onMount } from "solid-js";
33
import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui";
4-
import { findDeepSeekKey } from "./key-resolver.js";
4+
import { findDeepSeekKey, opencodeDataDir } from "./key-resolver.js";
55
import os from "node:os";
66
import path from "node:path";
77

@@ -22,12 +22,20 @@ function DeepseekView(props: { api: TuiPluginApi; session_id?: string }) {
2222
let lastFetch = 0;
2323

2424
const fetchBalance = async () => {
25-
const apiKey = findDeepSeekKey({
26-
stateDir: props.api.state?.path?.state,
27-
opencodeDir: path.join(os.homedir(), ".local", "share", "opencode"),
28-
secretsDir: path.join(os.homedir(), ".secrets"),
29-
env: process.env,
30-
});
25+
let apiKey: string | undefined;
26+
try {
27+
apiKey = findDeepSeekKey({
28+
dataDir: opencodeDataDir(process.env),
29+
stateDir: props.api.state?.path?.state,
30+
secretsDir: path.join(os.homedir(), ".secrets"),
31+
env: process.env,
32+
});
33+
} catch (err) {
34+
// unreadable key file (permissions etc.) — not the same as a missing key
35+
setStatus(`KEY ERROR ${(err as NodeJS.ErrnoException).code ?? ""}`.trim());
36+
setStatusColor(theme().error);
37+
return;
38+
}
3139
if (!apiKey) {
3240
setStatus("NO KEY");
3341
setStatusColor(theme().error);

0 commit comments

Comments
 (0)