ollama-cloud-usage 0.1.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,6 +5,18 @@ state from `/api/balance` (session and weekly remaining percentages plus
5
5
  authoritative reset times) and request counts from `/api/usage`, shows a live
6
6
  dashboard, and logs history to a JSONL file.
7
7
 
8
+ ## Features
9
+
10
+ - **Live quota dashboard** — session and weekly usage with bars, burn rate, and
11
+ reset countdowns.
12
+ - **Authoritative reset times** — read from `/api/balance`, not inferred.
13
+ - **Configurable polling interval** — 5 minutes by default.
14
+ - **Keyboard shortcuts** — refresh on demand without restarting.
15
+ - **History log** — append-only JSONL you can analyse later.
16
+ - **Credit-plan aware** — shows remaining credit when session/weekly limits are
17
+ not used.
18
+ - **Zero runtime dependencies** — Node built-ins only.
19
+
8
20
  ## Install
9
21
 
10
22
  ```sh
@@ -14,14 +26,10 @@ npm install -g ollama-cloud-usage
14
26
  ## Usage
15
27
 
16
28
  ```sh
17
- ollama-cloud-usage [--baseline <sec>] [--fine <sec>] [--window <min>]
29
+ ollama-cloud-usage [--interval <sec>]
18
30
  ```
19
31
 
20
- All flags are named and can be given in any order.
21
-
22
- - `--baseline <sec>` — idle polling interval (default `300` = 5 min)
23
- - `--fine <sec>` — near-boundary polling interval (default `30`)
24
- - `--window <min>` — half-window around each reset boundary (default `5`)
32
+ - `--interval <sec>` — polling interval (default `300` = 5 min)
25
33
 
26
34
  ### Interactive commands
27
35
 
@@ -36,7 +44,10 @@ All flags are named and can be given in any order.
36
44
  The key is resolved by precedence:
37
45
 
38
46
  1. `OLLAMA_API_KEY` env var
39
- 2. `~/.local/share/opencode/auth.json` → `ollama-cloud.key` (opencode users)
47
+ 2. `~/.local/share/opencode/auth.json` → `ollama-cloud.key` (OpenCode 1)
48
+ 3. `~/.local/share/opencode/opencode.db` → `credential` row with
49
+ `integration_id = 'ollama-cloud'` (OpenCode 2, read via Node's built-in
50
+ SQLite, falling back to the `sqlite3` CLI if needed)
40
51
 
41
52
  The key is never logged or written to disk by this tool.
42
53
 
@@ -59,9 +70,13 @@ Snapshots are appended to `./ollama-usage.jsonl` (one JSON object per line), or
59
70
  the path in `OLLAMA_USAGE_LOG`. Each line:
60
71
 
61
72
  ```json
62
- {"timestamp":"...","session":{"used_percent":3.91,"remaining_percent":96.09,"resets_at":"2026-10-27T08:00:00Z"},"weekly":{"used_percent":16.67,"remaining_percent":83.33,"resets_at":"2026-11-02T00:00:00Z"},"purchased":{"balance_usd":0},"usage":{"range":"7d","totals":{"request_count":29012}}}
73
+ {"timestamp":"...","session":{"used_percent":3.91,"remaining_percent":96.09,"resets_at":"2026-10-27T08:00:00Z"},"weekly":{"used_percent":16.67,"remaining_percent":83.33,"resets_at":"2026-11-02T00:00:00Z"},"purchased":{"balance_usd":0},"usage":{"range":"7d","totals":{"request_count":37796,"groups":[{"model":"deepseek-v4.1-flash:1017","request_count":32964},{"model":"glm-5.3-flash","request_count":4588}]}}}
63
74
  ```
64
75
 
76
+ `usage.totals.groups` holds the per-model request counts (`group_by=model`,
77
+ top 10). The monitor only logs these — it does not display or interpret them;
78
+ cost analysis can be done later from the log.
79
+
65
80
  The log never contains the API key or per-request content.
66
81
 
67
82
  ## License
package/dist/api.d.ts CHANGED
@@ -5,7 +5,14 @@ export interface UsageMetrics {
5
5
  cached_input_tokens?: number;
6
6
  output_tokens?: number;
7
7
  }
8
- export interface UsageBucket extends UsageMetrics {
8
+ export interface UsageGroup extends UsageMetrics {
9
+ model: string;
10
+ }
11
+ export interface UsageSummary extends UsageMetrics {
12
+ groups?: UsageGroup[];
13
+ remainder?: UsageMetrics;
14
+ }
15
+ export interface UsageBucket extends UsageSummary {
9
16
  from: string;
10
17
  until: string;
11
18
  partial?: boolean;
@@ -14,9 +21,10 @@ export interface UsageReport {
14
21
  range: "24h" | "7d" | "30d";
15
22
  scope: "self" | "team";
16
23
  granularity: "hour" | "day";
24
+ group_by?: "model";
17
25
  from: string;
18
26
  until: string;
19
- totals: UsageMetrics;
27
+ totals: UsageSummary;
20
28
  buckets: UsageBucket[];
21
29
  }
22
30
  export interface PlanLimit {
@@ -38,6 +46,9 @@ export interface Balance {
38
46
  balance_usd: number;
39
47
  };
40
48
  }
41
- export declare function fetchUsage(key: string, range?: string): Promise<UsageReport>;
49
+ export declare function fetchUsage(key: string, options?: {
50
+ range?: string;
51
+ groupBy?: "model";
52
+ }): Promise<UsageReport>;
42
53
  export declare function fetchBalance(key: string): Promise<Balance>;
43
54
  export declare function hasLimits(balance: Balance): boolean;
package/dist/api.js CHANGED
@@ -3,8 +3,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.fetchUsage = fetchUsage;
4
4
  exports.fetchBalance = fetchBalance;
5
5
  exports.hasLimits = hasLimits;
6
- async function fetchUsage(key, range = "7d") {
7
- let res = await fetch(`https://ollama.com/api/usage?range=${range}`, {
6
+ async function fetchUsage(key, options = {}) {
7
+ let range = options.range || "7d";
8
+ let url = `https://ollama.com/api/usage?range=${range}`;
9
+ if (options.groupBy)
10
+ url += `&group_by=${options.groupBy}`;
11
+ let res = await fetch(url, {
8
12
  headers: { Authorization: `Bearer ${key}` },
9
13
  });
10
14
  if (!res.ok)
package/dist/cli.js CHANGED
@@ -10,27 +10,15 @@ const readline_1 = __importDefault(require("readline"));
10
10
  const key_1 = require("./key");
11
11
  const api_1 = require("./api");
12
12
  const display_1 = require("./display");
13
- // CLI: ollama-cloud-usage [--baseline <sec>] [--fine <sec>] [--window <min>]
14
- // --baseline <sec> = idle polling interval (default 300 = 5 min)
15
- // --fine <sec> = near-boundary polling interval (default 30)
16
- // --window <min> = half-window around each boundary (default 5)
17
- // All flags are named so they can be given in any order.
18
- let baselineSec = 300;
19
- let fineSec = 30;
20
- let windowMin = 5;
13
+ // CLI: ollama-cloud-usage [--interval <sec>]
14
+ // --interval <sec> = polling interval (default 300 = 5 min)
15
+ // Reset times come from the API, so there is no boundary-aware polling.
16
+ let intervalSec = 300;
21
17
  for (let i = 2; i < process.argv.length; i++) {
22
18
  let arg = process.argv[i];
23
19
  let value = process.argv[i + 1];
24
- if (arg === "--baseline" && value) {
25
- baselineSec = parseInt(value, 10);
26
- i++;
27
- }
28
- else if (arg === "--fine" && value) {
29
- fineSec = parseInt(value, 10);
30
- i++;
31
- }
32
- else if (arg === "--window" && value) {
33
- windowMin = parseInt(value, 10);
20
+ if (arg === "--interval" && value) {
21
+ intervalSec = parseInt(value, 10);
34
22
  i++;
35
23
  }
36
24
  }
@@ -76,7 +64,7 @@ async function main() {
76
64
  while (true) {
77
65
  let now = new Date();
78
66
  let balance = await (0, api_1.fetchBalance)(key);
79
- let usage = await (0, api_1.fetchUsage)(key, "7d");
67
+ let usage = await (0, api_1.fetchUsage)(key, { range: "7d", groupBy: "model" });
80
68
  if ((0, api_1.hasLimits)(balance)) {
81
69
  // Legacy plans: session/weekly remaining % plus exact reset times.
82
70
  let session = balance.included.session;
@@ -97,9 +85,7 @@ async function main() {
97
85
  weeklyReset,
98
86
  now,
99
87
  });
100
- let nearest = Math.min(Math.abs(sessionReset.getTime() - now.getTime()), Math.abs(weeklyReset.getTime() - now.getTime()));
101
- let interval = nearest <= windowMin * 60000 ? fineSec : baselineSec;
102
- await waitForIntervalOrKeypress(interval);
88
+ await waitForIntervalOrKeypress(intervalSec);
103
89
  continue;
104
90
  }
105
91
  // Credit plans (or unexpected shape): show remaining allowance.
@@ -116,7 +102,7 @@ async function main() {
116
102
  }
117
103
  }
118
104
  console.log(` requests ${usage.totals.request_count.toLocaleString()} over ${usage.range}`);
119
- await waitForIntervalOrKeypress(baselineSec);
105
+ await waitForIntervalOrKeypress(intervalSec);
120
106
  }
121
107
  }
122
108
  // Resolve when the interval elapses, or when the user types a command + enter.
package/dist/key.js CHANGED
@@ -9,22 +9,84 @@ const os_1 = __importDefault(require("os"));
9
9
  const path_1 = __importDefault(require("path"));
10
10
  // Resolve the ollama cloud API key by precedence:
11
11
  // 1. OLLAMA_API_KEY env var (works for anyone, CI, etc.)
12
- // 2. ~/.local/share/opencode/auth.json -> ollama-cloud.key (opencode users)
12
+ // 2. ~/.local/share/opencode/auth.json -> ollama-cloud.key (OpenCode 1)
13
+ // 3. ~/.local/share/opencode/opencode.db -> credential row (OpenCode 2)
14
+ // 4. anything else: clear error
13
15
  // The key is never logged or written to disk by this tool.
14
16
  function loadKey() {
15
17
  let env = process.env.OLLAMA_API_KEY;
16
18
  if (env)
17
19
  return env;
20
+ let fromAuthJson = keyFromAuthJson();
21
+ if (fromAuthJson)
22
+ return fromAuthJson;
23
+ let fromDb = keyFromOpenCodeDb();
24
+ if (fromDb)
25
+ return fromDb;
26
+ throw new Error("No ollama cloud API key found. Set OLLAMA_API_KEY, or store it in " +
27
+ "~/.local/share/opencode/auth.json ('ollama-cloud'.key) or the " +
28
+ "OpenCode database (credential where integration_id = 'ollama-cloud').");
29
+ }
30
+ function keyFromAuthJson() {
18
31
  let authPath = path_1.default.join(os_1.default.homedir(), ".local", "share", "opencode", "auth.json");
19
32
  try {
20
33
  let auth = JSON.parse(fs_1.default.readFileSync(authPath, "utf8"));
21
34
  let key = auth["ollama-cloud"] && auth["ollama-cloud"].key;
22
- if (key)
35
+ if (typeof key === "string" && key)
23
36
  return key;
24
37
  }
25
38
  catch {
26
- // fall through to error below
39
+ // fall through
40
+ }
41
+ return null;
42
+ }
43
+ // OpenCode 2 stores credentials in SQLite. Prefer the built-in node:sqlite
44
+ // (Node >= 22, no external binary); fall back to the sqlite3 CLI if present.
45
+ function keyFromOpenCodeDb() {
46
+ let dbPath = path_1.default.join(os_1.default.homedir(), ".local", "share", "opencode", "opencode.db");
47
+ if (!fs_1.default.existsSync(dbPath))
48
+ return null;
49
+ let query = "select value from credential where integration_id = 'ollama-cloud' " +
50
+ "order by time_updated desc limit 1";
51
+ try {
52
+ let { DatabaseSync } = require("node:sqlite");
53
+ let db = new DatabaseSync(dbPath, { readOnly: true });
54
+ try {
55
+ let row = db.prepare(query).get();
56
+ if (row && row.value)
57
+ return extractKey(row.value);
58
+ }
59
+ finally {
60
+ db.close();
61
+ }
62
+ }
63
+ catch {
64
+ // node:sqlite unavailable; try the CLI below
65
+ }
66
+ try {
67
+ let { execFileSync } = require("child_process");
68
+ let out = execFileSync("sqlite3", ["-readonly", "-json", dbPath, query], {
69
+ encoding: "utf8",
70
+ });
71
+ let rows = JSON.parse(out || "[]");
72
+ if (rows.length > 0 && rows[0].value)
73
+ return extractKey(rows[0].value);
74
+ }
75
+ catch {
76
+ // no sqlite3 binary either
77
+ }
78
+ return null;
79
+ }
80
+ // The stored value is JSON like {"type":"api_key","key":"..."}; older entries
81
+ // may be the raw key.
82
+ function extractKey(value) {
83
+ try {
84
+ let parsed = JSON.parse(value);
85
+ if (parsed && typeof parsed.key === "string" && parsed.key)
86
+ return parsed.key;
87
+ }
88
+ catch {
89
+ // not JSON: treat as a raw key
27
90
  }
28
- throw new Error("No ollama cloud API key found. Set OLLAMA_API_KEY, or add it to " +
29
- "~/.local/share/opencode/auth.json under 'ollama-cloud'.key");
91
+ return value || null;
30
92
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ollama-cloud-usage",
3
- "version": "0.1.0",
3
+ "version": "1.0.1",
4
4
  "type": "commonjs",
5
5
  "description": "Monitor your Ollama Cloud session/weekly quota from the terminal",
6
6
  "keywords": [