ollama-cloud-usage 0.0.0 → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ BSD 2-Clause License
2
+
3
+ Copyright (c) [2026], [Beeno Tung (Tung Cheung Leong)]
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
17
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
20
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md ADDED
@@ -0,0 +1,76 @@
1
+ # ollama-cloud-usage
2
+
3
+ Monitor your Ollama Cloud session/weekly quota from the terminal. Reads quota
4
+ state from `/api/balance` (session and weekly remaining percentages plus
5
+ authoritative reset times) and request counts from `/api/usage`, shows a live
6
+ dashboard, and logs history to a JSONL file.
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ npm install -g ollama-cloud-usage
12
+ ```
13
+
14
+ ## Usage
15
+
16
+ ```sh
17
+ ollama-cloud-usage [--baseline <sec>] [--fine <sec>] [--window <min>]
18
+ ```
19
+
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`)
25
+
26
+ ### Interactive commands
27
+
28
+ | key | action |
29
+ |-----|--------|
30
+ | `r` | refresh usage now |
31
+ | `q` | quit |
32
+ | `?` | show help |
33
+
34
+ ## API key
35
+
36
+ The key is resolved by precedence:
37
+
38
+ 1. `OLLAMA_API_KEY` env var
39
+ 2. `~/.local/share/opencode/auth.json` → `ollama-cloud.key` (opencode users)
40
+
41
+ The key is never logged or written to disk by this tool.
42
+
43
+ ## Quota and reset times
44
+
45
+ Quota state comes from `/api/balance`, which reports `remaining_percent` and
46
+ `resets_at` for the session and weekly windows. The reset times are
47
+ server-authoritative — the tool does not infer them.
48
+
49
+ - **Session**: rolling 5-hour window (the anchor drifts through the day, since
50
+ 24h is not divisible by 5h).
51
+ - **Weekly**: Monday 00:00 UTC.
52
+
53
+ Accounts on credit plans (no session/weekly limits) instead get
54
+ `balance_usd` / `allowance_usd`, which the dashboard shows as remaining credit.
55
+
56
+ ## Log
57
+
58
+ Snapshots are appended to `./ollama-usage.jsonl` (one JSON object per line), or
59
+ the path in `OLLAMA_USAGE_LOG`. Each line:
60
+
61
+ ```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}}}
63
+ ```
64
+
65
+ The log never contains the API key or per-request content.
66
+
67
+ ## License
68
+
69
+ This project is licensed with [BSD-2-Clause](./LICENSE)
70
+
71
+ This is free, libre, and open-source software. It comes down to four essential freedoms [[ref]](https://seirdy.one/2021/01/27/whatsapp-and-the-domestication-of-users.html#fnref:2):
72
+
73
+ - The freedom to run the program as you wish, for any purpose
74
+ - The freedom to study how the program works, and change it so it does your computing as you wish
75
+ - The freedom to redistribute copies so you can help others
76
+ - The freedom to distribute copies of your modified versions to others
package/bin.js ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ require('./dist/cli.js').main().catch((error) => {
3
+ console.error(error)
4
+ process.exit(1)
5
+ })
package/dist/api.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ export interface UsageMetrics {
2
+ request_count: number;
3
+ usage_usd?: number;
4
+ input_tokens?: number;
5
+ cached_input_tokens?: number;
6
+ output_tokens?: number;
7
+ }
8
+ export interface UsageBucket extends UsageMetrics {
9
+ from: string;
10
+ until: string;
11
+ partial?: boolean;
12
+ }
13
+ export interface UsageReport {
14
+ range: "24h" | "7d" | "30d";
15
+ scope: "self" | "team";
16
+ granularity: "hour" | "day";
17
+ from: string;
18
+ until: string;
19
+ totals: UsageMetrics;
20
+ buckets: UsageBucket[];
21
+ }
22
+ export interface PlanLimit {
23
+ remaining_percent: number;
24
+ resets_at: string;
25
+ }
26
+ export interface Balance {
27
+ included: {
28
+ session?: PlanLimit;
29
+ weekly?: PlanLimit;
30
+ balance_usd?: number;
31
+ allowance_usd?: number;
32
+ period?: {
33
+ from: string;
34
+ until: string;
35
+ };
36
+ };
37
+ purchased?: {
38
+ balance_usd: number;
39
+ };
40
+ }
41
+ export declare function fetchUsage(key: string, range?: string): Promise<UsageReport>;
42
+ export declare function fetchBalance(key: string): Promise<Balance>;
43
+ export declare function hasLimits(balance: Balance): boolean;
package/dist/api.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchUsage = fetchUsage;
4
+ exports.fetchBalance = fetchBalance;
5
+ exports.hasLimits = hasLimits;
6
+ async function fetchUsage(key, range = "7d") {
7
+ let res = await fetch(`https://ollama.com/api/usage?range=${range}`, {
8
+ headers: { Authorization: `Bearer ${key}` },
9
+ });
10
+ if (!res.ok)
11
+ throw new Error(`API returned ${res.status}: ${await res.text()}`);
12
+ return res.json();
13
+ }
14
+ async function fetchBalance(key) {
15
+ let res = await fetch("https://ollama.com/api/balance", {
16
+ headers: { Authorization: `Bearer ${key}` },
17
+ });
18
+ if (!res.ok)
19
+ throw new Error(`API returned ${res.status}: ${await res.text()}`);
20
+ return res.json();
21
+ }
22
+ // true when the plan has session/weekly limits (legacy plans). Credit plans
23
+ // report balance_usd / allowance_usd instead.
24
+ function hasLimits(balance) {
25
+ return Boolean(balance && balance.included && balance.included.session && balance.included.weekly);
26
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function main(): Promise<void>;
package/dist/cli.js ADDED
@@ -0,0 +1,166 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.main = main;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const readline_1 = __importDefault(require("readline"));
10
+ const key_1 = require("./key");
11
+ const api_1 = require("./api");
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;
21
+ for (let i = 2; i < process.argv.length; i++) {
22
+ let arg = process.argv[i];
23
+ 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);
34
+ i++;
35
+ }
36
+ }
37
+ // Log file for usage history (append-only JSONL). Never contains the key.
38
+ let logFile = process.env.OLLAMA_USAGE_LOG || path_1.default.join(process.cwd(), "ollama-usage.jsonl");
39
+ function iso(d) {
40
+ let pad = (n, w = 2) => String(n).padStart(w, "0");
41
+ return (`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
42
+ `T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}+08:00`);
43
+ }
44
+ function logQuota(options) {
45
+ let included = options.balance.included;
46
+ let toLimit = (limit) => ({
47
+ used_percent: Math.round((100 - limit.remaining_percent) * 1e6) / 1e6,
48
+ remaining_percent: limit.remaining_percent,
49
+ resets_at: limit.resets_at,
50
+ });
51
+ let row = {
52
+ timestamp: options.now.toISOString(),
53
+ session: toLimit(included.session),
54
+ weekly: toLimit(included.weekly),
55
+ };
56
+ if (options.balance.purchased)
57
+ row.purchased = options.balance.purchased;
58
+ if (options.usage) {
59
+ row.usage = {
60
+ range: options.usage.range,
61
+ totals: options.usage.totals,
62
+ };
63
+ }
64
+ fs_1.default.appendFileSync(logFile, JSON.stringify(row) + "\n");
65
+ }
66
+ async function main() {
67
+ let key = (0, key_1.loadKey)();
68
+ let prevUsage = null;
69
+ console.log(`ollama-cloud-usage monitor`);
70
+ console.log(`quota from /api/balance (authoritative reset times)`);
71
+ console.log(`log -> ${logFile}`);
72
+ console.log(`commands:`);
73
+ console.log(` r refresh now`);
74
+ console.log(` q quit`);
75
+ console.log(` ? show this help`);
76
+ while (true) {
77
+ let now = new Date();
78
+ let balance = await (0, api_1.fetchBalance)(key);
79
+ let usage = await (0, api_1.fetchUsage)(key, "7d");
80
+ if ((0, api_1.hasLimits)(balance)) {
81
+ // Legacy plans: session/weekly remaining % plus exact reset times.
82
+ let session = balance.included.session;
83
+ let weekly = balance.included.weekly;
84
+ let sessionUsage = 100 - session.remaining_percent;
85
+ let weeklyUsage = 100 - weekly.remaining_percent;
86
+ let sessionReset = new Date(session.resets_at);
87
+ let weeklyReset = new Date(weekly.resets_at);
88
+ logQuota({ now, balance, usage });
89
+ if (prevUsage !== null && sessionUsage < prevUsage) {
90
+ console.log(`RESET ${now.toTimeString().slice(0, 8)}: ${prevUsage.toFixed(1)}% -> ${sessionUsage.toFixed(1)}% used`);
91
+ }
92
+ prevUsage = sessionUsage;
93
+ (0, display_1.printStatus)({
94
+ sessionUsage,
95
+ weeklyUsage,
96
+ sessionReset,
97
+ weeklyReset,
98
+ now,
99
+ });
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);
103
+ continue;
104
+ }
105
+ // Credit plans (or unexpected shape): show remaining allowance.
106
+ console.log("");
107
+ console.log(`[${(0, display_1.hhmm)(now)}] quota limits unavailable`);
108
+ if (typeof balance.included.balance_usd === "number") {
109
+ let balanceUsd = balance.included.balance_usd;
110
+ let allowance = balance.included.allowance_usd;
111
+ let pct = allowance ? (balanceUsd / allowance) * 100 : null;
112
+ console.log(` included $${balanceUsd.toFixed(2)}` +
113
+ (allowance ? ` / $${allowance.toFixed(2)} (${pct.toFixed(1)}%)` : ""));
114
+ if (balance.included.period) {
115
+ console.log(` period until ${balance.included.period.until}`);
116
+ }
117
+ }
118
+ console.log(` requests ${usage.totals.request_count.toLocaleString()} over ${usage.range}`);
119
+ await waitForIntervalOrKeypress(baselineSec);
120
+ }
121
+ }
122
+ // Resolve when the interval elapses, or when the user types a command + enter.
123
+ // r -> refresh now (recompute interval)
124
+ // q -> quit
125
+ // ? -> show command list (keep waiting)
126
+ // The readline interface is created once and reused, so listeners don't
127
+ // accumulate across polls. The handlers act on the *current* poll's timer and
128
+ // finish via module-level refs, so they stay correct across polls.
129
+ let rl = null;
130
+ let currentTimer = null;
131
+ let currentFinish = null;
132
+ function waitForIntervalOrKeypress(intervalSec) {
133
+ return new Promise((resolve) => {
134
+ let done = false;
135
+ let finish = () => {
136
+ if (done)
137
+ return;
138
+ done = true;
139
+ if (currentTimer)
140
+ clearTimeout(currentTimer);
141
+ resolve();
142
+ };
143
+ currentFinish = finish;
144
+ currentTimer = setTimeout(finish, intervalSec * 1000);
145
+ if (!rl) {
146
+ rl = readline_1.default.createInterface({ input: process.stdin });
147
+ rl.on("line", (line) => {
148
+ let cmd = line.trim().toLowerCase();
149
+ if (cmd === "r") {
150
+ currentFinish?.();
151
+ }
152
+ else if (cmd === "q") {
153
+ if (currentTimer)
154
+ clearTimeout(currentTimer);
155
+ process.exit(0);
156
+ }
157
+ else if (cmd === "?") {
158
+ console.log("commands:");
159
+ console.log(" r refresh now");
160
+ console.log(" q quit");
161
+ console.log(" ? show this help");
162
+ }
163
+ });
164
+ }
165
+ });
166
+ }
@@ -0,0 +1,9 @@
1
+ export declare function hhmm(d: Date): string;
2
+ export interface StatusInput {
3
+ sessionUsage: number;
4
+ weeklyUsage: number;
5
+ sessionReset: Date | null;
6
+ weeklyReset: Date;
7
+ now: Date;
8
+ }
9
+ export declare function printStatus(input: StatusInput): void;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.hhmm = hhmm;
4
+ exports.printStatus = printStatus;
5
+ // Window lengths, used to compute how much of each window has elapsed.
6
+ const SESSION_MS = 5 * 3600_000;
7
+ const WEEKLY_MS = 7 * 24 * 3600_000;
8
+ const GREEN = "\x1b[32m";
9
+ const ORANGE = "\x1b[33m";
10
+ const RED = "\x1b[31m";
11
+ const RESET = "\x1b[0m";
12
+ function rateColor(rate) {
13
+ if (rate === null)
14
+ return "";
15
+ if (rate > 1)
16
+ return RED;
17
+ if (rate > 0.8)
18
+ return ORANGE;
19
+ return GREEN;
20
+ }
21
+ function bar(length, percent) {
22
+ let filled = Math.round((length * percent) / 100);
23
+ return "█".repeat(filled) + "░".repeat(length - filled);
24
+ }
25
+ function countdown(ms) {
26
+ let s = Math.round(ms / 1000);
27
+ let m = Math.floor(s / 60);
28
+ let h = Math.floor(m / 60);
29
+ let days = Math.floor(h / 24);
30
+ if (days >= 1)
31
+ return `${days}d ${h % 24}h`;
32
+ if (h >= 1)
33
+ return `${h}h ${m % 60}m`;
34
+ if (m >= 1)
35
+ return `${m}m ${s % 60}s`;
36
+ return `${s}s`;
37
+ }
38
+ function hhmm(d) {
39
+ return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
40
+ }
41
+ function printStatus(input) {
42
+ let { sessionUsage: sp, weeklyUsage: wp, sessionReset, weeklyReset, now } = input;
43
+ let sLine = sessionReset
44
+ ? `reset in ${countdown(sessionReset.getTime() - now.getTime())} (${hhmm(sessionReset)})`
45
+ : "observing first reset…";
46
+ let wLine = `reset in ${countdown(weeklyReset.getTime() - now.getTime())} (${weeklyReset.toDateString().slice(0, 3)} ${hhmm(weeklyReset)})`;
47
+ // time elapsed within each window
48
+ let sElapsed = sessionReset
49
+ ? Math.min(100, Math.max(0, ((now.getTime() - (sessionReset.getTime() - SESSION_MS)) / SESSION_MS) * 100))
50
+ : null;
51
+ let wElapsed = Math.min(100, Math.max(0, ((now.getTime() - (weeklyReset.getTime() - WEEKLY_MS)) / WEEKLY_MS) * 100));
52
+ // burn rate = usage% / elapsed% (1.0x = on track to hit 100% at reset)
53
+ let sRate = sElapsed ? sp / sElapsed : null;
54
+ let wRate = wElapsed ? wp / wElapsed : null;
55
+ console.log("");
56
+ console.log(`[${hhmm(now)}] 5H:${sp.toFixed(1)}% W:${wp.toFixed(1)}%`);
57
+ console.log(` ${"5-hour".padEnd(6)} ${bar(18, sp)} ${sp.toFixed(1).padStart(5)}% ${"used".padEnd(7)} rate ${rateColor(sRate)}${sRate ? sRate.toFixed(1) + "x" : "?"}${RESET}`);
58
+ if (sElapsed !== null) {
59
+ console.log(` ${"time".padEnd(6)} ${bar(18, sElapsed)} ${sElapsed.toFixed(1).padStart(5)}% ${"elapsed".padEnd(7)} ${sLine}`);
60
+ }
61
+ else {
62
+ console.log(` ${"time".padEnd(6)} ${"".padEnd(18)} ${"".padStart(5)} ${"".padEnd(7)} ${sLine}`);
63
+ }
64
+ console.log("");
65
+ console.log(` ${"Weekly".padEnd(6)} ${bar(18, wp)} ${wp.toFixed(1).padStart(5)}% ${"used".padEnd(7)} rate ${rateColor(wRate)}${wRate ? wRate.toFixed(1) + "x" : "?"}${RESET}`);
66
+ console.log(` ${"time".padEnd(6)} ${bar(18, wElapsed)} ${wElapsed.toFixed(1).padStart(5)}% ${"elapsed".padEnd(7)} ${wLine}`);
67
+ }
package/dist/key.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare function loadKey(): string;
package/dist/key.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.loadKey = loadKey;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const os_1 = __importDefault(require("os"));
9
+ const path_1 = __importDefault(require("path"));
10
+ // Resolve the ollama cloud API key by precedence:
11
+ // 1. OLLAMA_API_KEY env var (works for anyone, CI, etc.)
12
+ // 2. ~/.local/share/opencode/auth.json -> ollama-cloud.key (opencode users)
13
+ // The key is never logged or written to disk by this tool.
14
+ function loadKey() {
15
+ let env = process.env.OLLAMA_API_KEY;
16
+ if (env)
17
+ return env;
18
+ let authPath = path_1.default.join(os_1.default.homedir(), ".local", "share", "opencode", "auth.json");
19
+ try {
20
+ let auth = JSON.parse(fs_1.default.readFileSync(authPath, "utf8"));
21
+ let key = auth["ollama-cloud"] && auth["ollama-cloud"].key;
22
+ if (key)
23
+ return key;
24
+ }
25
+ catch {
26
+ // fall through to error below
27
+ }
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");
30
+ }
package/package.json CHANGED
@@ -1,11 +1,22 @@
1
1
  {
2
2
  "name": "ollama-cloud-usage",
3
- "version": "0.0.0",
3
+ "version": "0.1.0",
4
4
  "type": "commonjs",
5
- "description": "",
6
- "keywords": [],
7
- "author": "",
8
- "license": "ISC",
5
+ "description": "Monitor your Ollama Cloud session/weekly quota from the terminal",
6
+ "keywords": [
7
+ "ollama",
8
+ "ollama-cloud",
9
+ "quota",
10
+ "usage",
11
+ "monitor",
12
+ "cli"
13
+ ],
14
+ "author": {
15
+ "name": "Beeno Tung",
16
+ "email": "aabbcc1241@yahoo.com.hk",
17
+ "url": "https://beeno-tung.surge.sh"
18
+ },
19
+ "license": "BSD-2-Clause",
9
20
  "repository": {
10
21
  "type": "git",
11
22
  "url": "git+https://github.com/beenotung/ollama-cloud-usage.git"
@@ -14,10 +25,14 @@
14
25
  "bugs": {
15
26
  "url": "https://github.com/beenotung/ollama-cloud-usage/issues"
16
27
  },
17
- "main": "dist/index.js",
18
- "types": "dist/index.d.ts",
28
+ "main": "dist/cli.js",
29
+ "types": "dist/cli.d.ts",
30
+ "bin": {
31
+ "ollama-cloud-usage": "bin.js"
32
+ },
19
33
  "files": [
20
- "dist"
34
+ "dist",
35
+ "bin.js"
21
36
  ],
22
37
  "scripts": {
23
38
  "test": "tsc --noEmit",