ollama-cloud-usage 0.0.0 → 1.0.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 +25 -0
- package/README.md +87 -0
- package/bin.js +5 -0
- package/dist/api.d.ts +43 -0
- package/dist/api.js +26 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +152 -0
- package/dist/display.d.ts +9 -0
- package/dist/display.js +67 -0
- package/dist/key.d.ts +1 -0
- package/dist/key.js +92 -0
- package/package.json +23 -8
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,87 @@
|
|
|
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
|
+
## 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
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
npm install -g ollama-cloud-usage
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Usage
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
ollama-cloud-usage [--interval <sec>]
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
- `--interval <sec>` — polling interval (default `300` = 5 min)
|
|
33
|
+
|
|
34
|
+
### Interactive commands
|
|
35
|
+
|
|
36
|
+
| key | action |
|
|
37
|
+
|-----|--------|
|
|
38
|
+
| `r` | refresh usage now |
|
|
39
|
+
| `q` | quit |
|
|
40
|
+
| `?` | show help |
|
|
41
|
+
|
|
42
|
+
## API key
|
|
43
|
+
|
|
44
|
+
The key is resolved by precedence:
|
|
45
|
+
|
|
46
|
+
1. `OLLAMA_API_KEY` env var
|
|
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)
|
|
51
|
+
|
|
52
|
+
The key is never logged or written to disk by this tool.
|
|
53
|
+
|
|
54
|
+
## Quota and reset times
|
|
55
|
+
|
|
56
|
+
Quota state comes from `/api/balance`, which reports `remaining_percent` and
|
|
57
|
+
`resets_at` for the session and weekly windows. The reset times are
|
|
58
|
+
server-authoritative — the tool does not infer them.
|
|
59
|
+
|
|
60
|
+
- **Session**: rolling 5-hour window (the anchor drifts through the day, since
|
|
61
|
+
24h is not divisible by 5h).
|
|
62
|
+
- **Weekly**: Monday 00:00 UTC.
|
|
63
|
+
|
|
64
|
+
Accounts on credit plans (no session/weekly limits) instead get
|
|
65
|
+
`balance_usd` / `allowance_usd`, which the dashboard shows as remaining credit.
|
|
66
|
+
|
|
67
|
+
## Log
|
|
68
|
+
|
|
69
|
+
Snapshots are appended to `./ollama-usage.jsonl` (one JSON object per line), or
|
|
70
|
+
the path in `OLLAMA_USAGE_LOG`. Each line:
|
|
71
|
+
|
|
72
|
+
```json
|
|
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":29012}}}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The log never contains the API key or per-request content.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
This project is licensed with [BSD-2-Clause](./LICENSE)
|
|
81
|
+
|
|
82
|
+
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):
|
|
83
|
+
|
|
84
|
+
- The freedom to run the program as you wish, for any purpose
|
|
85
|
+
- The freedom to study how the program works, and change it so it does your computing as you wish
|
|
86
|
+
- The freedom to redistribute copies so you can help others
|
|
87
|
+
- The freedom to distribute copies of your modified versions to others
|
package/bin.js
ADDED
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,152 @@
|
|
|
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 [--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;
|
|
17
|
+
for (let i = 2; i < process.argv.length; i++) {
|
|
18
|
+
let arg = process.argv[i];
|
|
19
|
+
let value = process.argv[i + 1];
|
|
20
|
+
if (arg === "--interval" && value) {
|
|
21
|
+
intervalSec = parseInt(value, 10);
|
|
22
|
+
i++;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Log file for usage history (append-only JSONL). Never contains the key.
|
|
26
|
+
let logFile = process.env.OLLAMA_USAGE_LOG || path_1.default.join(process.cwd(), "ollama-usage.jsonl");
|
|
27
|
+
function iso(d) {
|
|
28
|
+
let pad = (n, w = 2) => String(n).padStart(w, "0");
|
|
29
|
+
return (`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
|
|
30
|
+
`T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}+08:00`);
|
|
31
|
+
}
|
|
32
|
+
function logQuota(options) {
|
|
33
|
+
let included = options.balance.included;
|
|
34
|
+
let toLimit = (limit) => ({
|
|
35
|
+
used_percent: Math.round((100 - limit.remaining_percent) * 1e6) / 1e6,
|
|
36
|
+
remaining_percent: limit.remaining_percent,
|
|
37
|
+
resets_at: limit.resets_at,
|
|
38
|
+
});
|
|
39
|
+
let row = {
|
|
40
|
+
timestamp: options.now.toISOString(),
|
|
41
|
+
session: toLimit(included.session),
|
|
42
|
+
weekly: toLimit(included.weekly),
|
|
43
|
+
};
|
|
44
|
+
if (options.balance.purchased)
|
|
45
|
+
row.purchased = options.balance.purchased;
|
|
46
|
+
if (options.usage) {
|
|
47
|
+
row.usage = {
|
|
48
|
+
range: options.usage.range,
|
|
49
|
+
totals: options.usage.totals,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
fs_1.default.appendFileSync(logFile, JSON.stringify(row) + "\n");
|
|
53
|
+
}
|
|
54
|
+
async function main() {
|
|
55
|
+
let key = (0, key_1.loadKey)();
|
|
56
|
+
let prevUsage = null;
|
|
57
|
+
console.log(`ollama-cloud-usage monitor`);
|
|
58
|
+
console.log(`quota from /api/balance (authoritative reset times)`);
|
|
59
|
+
console.log(`log -> ${logFile}`);
|
|
60
|
+
console.log(`commands:`);
|
|
61
|
+
console.log(` r refresh now`);
|
|
62
|
+
console.log(` q quit`);
|
|
63
|
+
console.log(` ? show this help`);
|
|
64
|
+
while (true) {
|
|
65
|
+
let now = new Date();
|
|
66
|
+
let balance = await (0, api_1.fetchBalance)(key);
|
|
67
|
+
let usage = await (0, api_1.fetchUsage)(key, "7d");
|
|
68
|
+
if ((0, api_1.hasLimits)(balance)) {
|
|
69
|
+
// Legacy plans: session/weekly remaining % plus exact reset times.
|
|
70
|
+
let session = balance.included.session;
|
|
71
|
+
let weekly = balance.included.weekly;
|
|
72
|
+
let sessionUsage = 100 - session.remaining_percent;
|
|
73
|
+
let weeklyUsage = 100 - weekly.remaining_percent;
|
|
74
|
+
let sessionReset = new Date(session.resets_at);
|
|
75
|
+
let weeklyReset = new Date(weekly.resets_at);
|
|
76
|
+
logQuota({ now, balance, usage });
|
|
77
|
+
if (prevUsage !== null && sessionUsage < prevUsage) {
|
|
78
|
+
console.log(`RESET ${now.toTimeString().slice(0, 8)}: ${prevUsage.toFixed(1)}% -> ${sessionUsage.toFixed(1)}% used`);
|
|
79
|
+
}
|
|
80
|
+
prevUsage = sessionUsage;
|
|
81
|
+
(0, display_1.printStatus)({
|
|
82
|
+
sessionUsage,
|
|
83
|
+
weeklyUsage,
|
|
84
|
+
sessionReset,
|
|
85
|
+
weeklyReset,
|
|
86
|
+
now,
|
|
87
|
+
});
|
|
88
|
+
await waitForIntervalOrKeypress(intervalSec);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
// Credit plans (or unexpected shape): show remaining allowance.
|
|
92
|
+
console.log("");
|
|
93
|
+
console.log(`[${(0, display_1.hhmm)(now)}] quota limits unavailable`);
|
|
94
|
+
if (typeof balance.included.balance_usd === "number") {
|
|
95
|
+
let balanceUsd = balance.included.balance_usd;
|
|
96
|
+
let allowance = balance.included.allowance_usd;
|
|
97
|
+
let pct = allowance ? (balanceUsd / allowance) * 100 : null;
|
|
98
|
+
console.log(` included $${balanceUsd.toFixed(2)}` +
|
|
99
|
+
(allowance ? ` / $${allowance.toFixed(2)} (${pct.toFixed(1)}%)` : ""));
|
|
100
|
+
if (balance.included.period) {
|
|
101
|
+
console.log(` period until ${balance.included.period.until}`);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
console.log(` requests ${usage.totals.request_count.toLocaleString()} over ${usage.range}`);
|
|
105
|
+
await waitForIntervalOrKeypress(intervalSec);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Resolve when the interval elapses, or when the user types a command + enter.
|
|
109
|
+
// r -> refresh now (recompute interval)
|
|
110
|
+
// q -> quit
|
|
111
|
+
// ? -> show command list (keep waiting)
|
|
112
|
+
// The readline interface is created once and reused, so listeners don't
|
|
113
|
+
// accumulate across polls. The handlers act on the *current* poll's timer and
|
|
114
|
+
// finish via module-level refs, so they stay correct across polls.
|
|
115
|
+
let rl = null;
|
|
116
|
+
let currentTimer = null;
|
|
117
|
+
let currentFinish = null;
|
|
118
|
+
function waitForIntervalOrKeypress(intervalSec) {
|
|
119
|
+
return new Promise((resolve) => {
|
|
120
|
+
let done = false;
|
|
121
|
+
let finish = () => {
|
|
122
|
+
if (done)
|
|
123
|
+
return;
|
|
124
|
+
done = true;
|
|
125
|
+
if (currentTimer)
|
|
126
|
+
clearTimeout(currentTimer);
|
|
127
|
+
resolve();
|
|
128
|
+
};
|
|
129
|
+
currentFinish = finish;
|
|
130
|
+
currentTimer = setTimeout(finish, intervalSec * 1000);
|
|
131
|
+
if (!rl) {
|
|
132
|
+
rl = readline_1.default.createInterface({ input: process.stdin });
|
|
133
|
+
rl.on("line", (line) => {
|
|
134
|
+
let cmd = line.trim().toLowerCase();
|
|
135
|
+
if (cmd === "r") {
|
|
136
|
+
currentFinish?.();
|
|
137
|
+
}
|
|
138
|
+
else if (cmd === "q") {
|
|
139
|
+
if (currentTimer)
|
|
140
|
+
clearTimeout(currentTimer);
|
|
141
|
+
process.exit(0);
|
|
142
|
+
}
|
|
143
|
+
else if (cmd === "?") {
|
|
144
|
+
console.log("commands:");
|
|
145
|
+
console.log(" r refresh now");
|
|
146
|
+
console.log(" q quit");
|
|
147
|
+
console.log(" ? show this help");
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
package/dist/display.js
ADDED
|
@@ -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,92 @@
|
|
|
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 1)
|
|
13
|
+
// 3. ~/.local/share/opencode/opencode.db -> credential row (OpenCode 2)
|
|
14
|
+
// 4. anything else: clear error
|
|
15
|
+
// The key is never logged or written to disk by this tool.
|
|
16
|
+
function loadKey() {
|
|
17
|
+
let env = process.env.OLLAMA_API_KEY;
|
|
18
|
+
if (env)
|
|
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() {
|
|
31
|
+
let authPath = path_1.default.join(os_1.default.homedir(), ".local", "share", "opencode", "auth.json");
|
|
32
|
+
try {
|
|
33
|
+
let auth = JSON.parse(fs_1.default.readFileSync(authPath, "utf8"));
|
|
34
|
+
let key = auth["ollama-cloud"] && auth["ollama-cloud"].key;
|
|
35
|
+
if (typeof key === "string" && key)
|
|
36
|
+
return key;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
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
|
|
90
|
+
}
|
|
91
|
+
return value || null;
|
|
92
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ollama-cloud-usage",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"type": "commonjs",
|
|
5
|
-
"description": "",
|
|
6
|
-
"keywords": [
|
|
7
|
-
|
|
8
|
-
|
|
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/
|
|
18
|
-
"types": "dist/
|
|
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",
|