@cad0p/pi-usage 0.11.3 → 0.11.4-20261103.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.
@@ -0,0 +1,33 @@
1
+ import QtQuick
2
+ import Quickshell.Io
3
+
4
+ // One usage record, read straight off its data file. Carried over unchanged
5
+ // from Omarchy's built-in Agents plugin (plugins/agents/Agent.qml, MIT): a
6
+ // record that appears in the usage directory is a provider, whoever wrote it.
7
+ Item {
8
+ id: root
9
+ visible: false
10
+
11
+ property string agentId: ""
12
+ property string path: ""
13
+ property var record: null
14
+
15
+ FileView {
16
+ path: root.path
17
+ watchChanges: true
18
+ printErrors: false
19
+ onFileChanged: reload()
20
+ onLoaded: root.parse(text())
21
+ onLoadFailed: root.record = null
22
+ }
23
+
24
+ function parse(content) {
25
+ try {
26
+ var parsed = JSON.parse(String(content || ""))
27
+ root.record = parsed && typeof parsed === "object" ? parsed : null
28
+ } catch (e) {
29
+ console.warn("cad0p.pi-usage", "Ignoring bad usage record", root.path, e)
30
+ root.record = null
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,333 @@
1
+ import QtQuick
2
+ import Quickshell
3
+ import Quickshell.Io
4
+ import "UsageLogic.js" as Logic
5
+
6
+ // The data side of the AI Usage panel: discover every usage record in
7
+ // Omarchy's usage directory (pi-usage's pi-*.json and Omarchy's own
8
+ // claude/codex/fireworks records alike), watch them, keep the per-section
9
+ // expansion state, and trigger the publishers on demand.
10
+ //
11
+ // Discovery and the per-record watcher follow Omarchy's built-in Agents plugin
12
+ // (plugins/agents/Main.qml, MIT, by Omarchy).
13
+ Item {
14
+ id: root
15
+ visible: false
16
+
17
+ property var settings: ({})
18
+ // Live bar, used only to see whether the built-in Agents widget is also on
19
+ // it (see collectorsWanted).
20
+ property QtObject bar: null
21
+ // file:// URL of the plugin directory, so the panel can find the pi-usage
22
+ // CLI of the package it ships in.
23
+ property string pluginDir: ""
24
+
25
+ readonly property string home: Quickshell.env("HOME") || ""
26
+ readonly property string stateHome: Quickshell.env("XDG_STATE_HOME") || (home + "/.local/state")
27
+ // PI_QUOTA_OMARCHY_DIR is the writer's own override; honoring it here keeps
28
+ // the two ends pointed at the same directory.
29
+ readonly property string usageDir: Quickshell.env("PI_QUOTA_OMARCHY_DIR") || (stateHome + "/omarchy/agents/usage")
30
+ readonly property string uiStateDir: Logic.uiStateDirectory(stateHome, Quickshell.env("PI_USAGE_PANEL_STATE_DIR"))
31
+ readonly property string uiStatePath: uiStateDir + "/cad0p.pi-usage.json"
32
+
33
+ function setting(name, fallback) {
34
+ var value = settings ? settings[name] : undefined
35
+ return value === undefined || value === null ? fallback : value
36
+ }
37
+
38
+ // ------------------------------------------------------------- discovery
39
+
40
+ property var recordIds: []
41
+ property var agents: []
42
+ property int dataRevision: 0
43
+
44
+ Process {
45
+ id: listProcess
46
+ running: false
47
+ command: ["find", root.usageDir, "-maxdepth", "1", "-name", "*.json", "-printf", "%f\n"]
48
+
49
+ stdout: StdioCollector {
50
+ waitForEnd: true
51
+ onStreamFinished: root.applyListing(text)
52
+ }
53
+ }
54
+
55
+ // New records are found by listing the directory again on a slow timer and
56
+ // after every publisher run; each record's content is watched by its own
57
+ // FileView, which is what actually moves the numbers.
58
+ Timer {
59
+ interval: 60000
60
+ running: true
61
+ repeat: true
62
+ triggeredOnStart: true
63
+ onTriggered: root.rescan()
64
+ }
65
+
66
+ function rescan() {
67
+ if (!listProcess.running) listProcess.running = true
68
+ }
69
+
70
+ function applyListing(output) {
71
+ var ids = []
72
+ var lines = String(output || "").split("\n")
73
+ for (var i = 0; i < lines.length; i++) {
74
+ var name = lines[i].trim()
75
+ if (name.slice(-5) === ".json") ids.push(name.slice(0, -5))
76
+ }
77
+ ids.sort()
78
+ if (JSON.stringify(ids) !== JSON.stringify(recordIds)) recordIds = ids
79
+ }
80
+
81
+ Instantiator {
82
+ id: agentInstantiator
83
+ model: root.recordIds
84
+
85
+ delegate: Agent {
86
+ required property var modelData
87
+ agentId: modelData
88
+ path: root.usageDir + "/" + modelData + ".json"
89
+ onRecordChanged: root.recordsChanged()
90
+ }
91
+
92
+ onObjectAdded: (index, object) => root.rebuildAgents()
93
+ onObjectRemoved: (index, object) => root.rebuildAgents()
94
+ }
95
+
96
+ function rebuildAgents() {
97
+ var result = []
98
+ for (var i = 0; i < agentInstantiator.count; i++) {
99
+ var agent = agentInstantiator.objectAt(i)
100
+ if (agent) result.push(agent)
101
+ }
102
+ agents = result
103
+ recordsChanged()
104
+ }
105
+
106
+ function recordsChanged() {
107
+ dataRevision++
108
+ scheduleLimitsRetry()
109
+ }
110
+
111
+ property var retryAgentIds: []
112
+ property string pendingUpdateKind: ""
113
+ property bool pendingPublisher: false
114
+
115
+ Timer {
116
+ id: limitsRetry
117
+ interval: 30000
118
+ repeat: false
119
+ // A retry is a collector run like any other: the same switch that gates the
120
+ // interval timer gates this one, even if it flips while the retry waits.
121
+ onTriggered: if (root.collectorsWanted) root.runCollectors("limits", root.retryAgentIds)
122
+ }
123
+
124
+ function scheduleLimitsRetry() {
125
+ var records = []
126
+ for (var i = 0; i < agents.length; i++) {
127
+ var record = agents[i] ? agents[i].record : null
128
+ if (record) records.push(record)
129
+ }
130
+ retryAgentIds = Logic.advisedRetryIds(records, settings, collectorsWanted)
131
+ if (retryAgentIds.length > 0) limitsRetry.restart()
132
+ else limitsRetry.stop()
133
+ }
134
+
135
+ // Turning the collectors off (or putting the built-in widget back on the
136
+ // bar) cancels a retry that is already waiting.
137
+ onCollectorsWantedChanged: scheduleLimitsRetry()
138
+
139
+ readonly property var providers: {
140
+ var rev = dataRevision
141
+ var records = []
142
+ for (var i = 0; i < agents.length; i++) if (agents[i] && agents[i].record) records.push(agents[i].record)
143
+ return Logic.visibleProviders(records, settings)
144
+ }
145
+
146
+ readonly property string newestUpdate: {
147
+ var rev = dataRevision
148
+ var best = ""
149
+ for (var i = 0; i < agents.length; i++) {
150
+ var record = agents[i] ? agents[i].record : null
151
+ var at = record && record.updatedAt ? String(record.updatedAt) : ""
152
+ if (at !== "" && (best === "" || new Date(at).getTime() > new Date(best).getTime())) best = at
153
+ }
154
+ return best
155
+ }
156
+
157
+ // ------------------------------------------------------------ expansion
158
+
159
+ property var expandedOverrides: ({})
160
+
161
+ FileView {
162
+ id: uiStateFile
163
+ path: root.uiStatePath
164
+ watchChanges: false
165
+ atomicWrites: true
166
+ printErrors: false
167
+ onLoaded: root.expandedOverrides = Logic.parseUiState(text()).expanded
168
+ }
169
+
170
+ Process {
171
+ id: uiStateMkdir
172
+ running: false
173
+ command: ["mkdir", "-p", root.uiStateDir]
174
+ onExited: function(exitCode) {
175
+ if (exitCode === 0) uiStateFile.setText(Logic.serializeUiState({ expanded: root.expandedOverrides }))
176
+ }
177
+ }
178
+
179
+ Timer {
180
+ id: uiStateSave
181
+ interval: 400
182
+ repeat: false
183
+ onTriggered: if (!uiStateMkdir.running) uiStateMkdir.running = true
184
+ }
185
+
186
+ function setExpanded(id, expanded) {
187
+ expandedOverrides = Logic.withExpanded(expandedOverrides, String(id), expanded)
188
+ uiStateSave.restart()
189
+ }
190
+
191
+ // --------------------------------------------------------------- refresh
192
+ //
193
+ // pi-usage's records already have two writers: the systemd user timer
194
+ // (./install.sh --omarchy-timer) and the Pi extension on every quota
195
+ // refresh. A third periodic writer would only multiply the calls to the
196
+ // usage endpoints, so the panel never schedules piquota itself; it runs it
197
+ // when you ask for a refresh.
198
+ //
199
+ // Omarchy's own collectors are different: the built-in Agents widget is what
200
+ // runs them. "Auto" runs them here only while that widget is not on the bar,
201
+ // so replacing it keeps claude/codex/fireworks fresh and keeping both never
202
+ // doubles the work.
203
+
204
+ property string collectorsSetting: String(setting("omarchyCollectors", "Auto"))
205
+ property int refreshIntervalSec: Math.max(30, Number(setting("refreshIntervalSec", 900)))
206
+ property bool builtinOnBar: false
207
+ readonly property bool collectorsWanted: Logic.collectorsWanted(collectorsSetting, builtinOnBar)
208
+ readonly property bool refreshing: collectorProcess.running || publisherProcess.running
209
+
210
+ function updateBuiltinOnBar() {
211
+ var widgets = bar && typeof bar.moduleWidgets === "function" ? bar.moduleWidgets("omarchy.agents") : []
212
+ builtinOnBar = !!widgets && widgets.length > 0
213
+ }
214
+
215
+ Timer {
216
+ interval: root.refreshIntervalSec * 1000
217
+ running: root.collectorsSetting !== "Off"
218
+ repeat: true
219
+ triggeredOnStart: true
220
+ onTriggered: {
221
+ root.updateBuiltinOnBar()
222
+ if (root.collectorsWanted) root.runCollectors("normal")
223
+ }
224
+ }
225
+
226
+ Process {
227
+ id: collectorProcess
228
+ running: false
229
+ onExited: {
230
+ root.rescan()
231
+ if (root.pendingUpdateKind !== "") {
232
+ var kind = root.pendingUpdateKind
233
+ root.pendingUpdateKind = ""
234
+ root.runCollectors(kind)
235
+ }
236
+ }
237
+ stderr: StdioCollector {
238
+ waitForEnd: true
239
+ onStreamFinished: if (text.trim() !== "") console.warn("cad0p.pi-usage", text.trim())
240
+ }
241
+ }
242
+
243
+ function collectorCommand(kind, agentIds) {
244
+ var args = []
245
+ if (kind === "force") args.push("--force")
246
+ if (kind === "limits") args.push("--limits-only")
247
+ var providerSettings = settings && settings.providers ? settings.providers : {}
248
+ for (var id in providerSettings) {
249
+ if (id.indexOf("pi-") === 0) continue
250
+ if (providerSettings[id] && providerSettings[id].enabled === false) args.push("--except", id)
251
+ }
252
+ if (agentIds) {
253
+ for (var i = 0; i < agentIds.length; i++) args.push(agentIds[i])
254
+ }
255
+ // Absent on a machine without Omarchy's collectors: nothing to run.
256
+ return ["bash", "-c", "command -v omarchy-agent-usage-update >/dev/null 2>&1 || exit 0; exec omarchy-agent-usage-update \"$@\"", "omarchy-agent-usage-update"].concat(args)
257
+ }
258
+
259
+ function runCollectors(kind, agentIds) {
260
+ // The one choke point every collector run passes through: the interval
261
+ // timer, an explicit refresh and the retryAdvised retry.
262
+ if (!collectorsWanted) return
263
+ if (collectorProcess.running) {
264
+ pendingUpdateKind = Logic.queueUpdateKind(pendingUpdateKind, kind)
265
+ return
266
+ }
267
+ collectorProcess.command = collectorCommand(kind, agentIds)
268
+ collectorProcess.running = true
269
+ }
270
+
271
+ Process {
272
+ id: publisherProcess
273
+ running: false
274
+ onExited: {
275
+ root.rescan()
276
+ if (root.pendingPublisher) {
277
+ root.pendingPublisher = false
278
+ root.runPublisher()
279
+ }
280
+ }
281
+ stderr: StdioCollector {
282
+ waitForEnd: true
283
+ onStreamFinished: if (text.trim() !== "") console.warn("cad0p.pi-usage", text.trim())
284
+ }
285
+ }
286
+
287
+ function localPath(url) {
288
+ var text = String(url || "")
289
+ if (text.indexOf("file://") === 0) text = decodeURIComponent(text.slice(7))
290
+ return text.replace(/\/+$/, "")
291
+ }
292
+
293
+ // The user's timer unit first, so a manual refresh runs with exactly the
294
+ // environment the periodic one does (PI_QUOTA_CLAUDE_SOURCE and friends);
295
+ // then the CLI of the package this plugin ships in; then piquota on PATH.
296
+ function publisherCommand() {
297
+ var script = [
298
+ "if command -v systemctl >/dev/null 2>&1 && systemctl --user cat piquota-omarchy.service >/dev/null 2>&1; then",
299
+ " exec systemctl --user start piquota-omarchy.service",
300
+ "fi",
301
+ "cli=\"$(readlink -f \"$1\" 2>/dev/null)/../../bin/piquota.js\"",
302
+ "if [ -f \"$cli\" ] && command -v node >/dev/null 2>&1; then exec node \"$cli\" omarchy; fi",
303
+ "if command -v piquota >/dev/null 2>&1; then exec piquota omarchy; fi",
304
+ "if [ -x \"$HOME/.local/bin/piquota\" ]; then exec \"$HOME/.local/bin/piquota\" omarchy; fi",
305
+ "exit 0"
306
+ ].join("\n")
307
+ return ["bash", "-c", script, "pi-usage-refresh", localPath(pluginDir)]
308
+ }
309
+
310
+ function runPublisher() {
311
+ if (publisherProcess.running) {
312
+ pendingPublisher = true
313
+ return
314
+ }
315
+ publisherProcess.command = publisherCommand()
316
+ publisherProcess.running = true
317
+ }
318
+
319
+ // r, middle click, IPC refresh: everything, now.
320
+ function refreshAll() {
321
+ updateBuiltinOnBar()
322
+ runPublisher()
323
+ if (collectorsWanted) runCollectors("force")
324
+ }
325
+
326
+ // Opening the panel wants the numbers that go stale on the wire; Omarchy's
327
+ // collectors reuse their recent transcript scans in this mode.
328
+ function refreshOnOpen() {
329
+ updateBuiltinOnBar()
330
+ rescan()
331
+ if (collectorsWanted) runCollectors("limits")
332
+ }
333
+ }
@@ -0,0 +1,136 @@
1
+ import QtQuick
2
+ import Quickshell
3
+ import Quickshell.Io
4
+ import qs.Commons
5
+ import qs.Ui
6
+ import "UsageLogic.js" as Logic
7
+
8
+ // AI Usage: one bar icon and one popup for every AI subscription that has a
9
+ // usage record, each provider a collapsible section of a single scrolling
10
+ // list. Derived from Omarchy's built-in Agents panel (plugins/agents, MIT, by
11
+ // Omarchy): the same records, rows and type, with the tab switch replaced by
12
+ // sections and multi-account providers drawn account by account.
13
+ Panel {
14
+ id: root
15
+ moduleName: "cad0p.pi-usage"
16
+ ipcTarget: "cad0p.pi-usage"
17
+ manageIpc: false
18
+
19
+ readonly property color foreground: bar ? bar.foreground : Color.foreground
20
+ readonly property color urgent: bar ? bar.urgent : Color.urgent
21
+ readonly property string fontFamily: bar ? bar.fontFamily : Style.font.family
22
+ readonly property string glyph: "󱚣"
23
+
24
+ readonly property var providers: usage.providers
25
+
26
+ // The icon lights up when any headline window is at 90% or a prepaid
27
+ // balance is down to its last 10%, the built-in's alarm thresholds.
28
+ readonly property bool alarming: {
29
+ for (var i = 0; i < providers.length; i++) {
30
+ var h = Logic.headline(providers[i])
31
+ if ((h && h.percent >= 0.9) || Logic.balanceAlarming(providers[i].balance)) return true
32
+ }
33
+ return false
34
+ }
35
+
36
+ // Countdowns and "updated" read this instead of Date.now() so the panel
37
+ // keeps telling the truth while it sits open.
38
+ property double nowMs: Date.now()
39
+
40
+ function refreshNow() { usage.refreshAll() }
41
+
42
+ function launchAgent() {
43
+ if (root.bar) root.bar.run("omarchy-agent --pick")
44
+ root.close()
45
+ }
46
+
47
+ // Nothing to report, nothing in the bar, as with the built-in widget.
48
+ visible: Logic.pluginVisible(providers)
49
+ implicitWidth: button.implicitWidth
50
+ implicitHeight: button.implicitHeight
51
+
52
+ onOpenedChanged: if (opened) {
53
+ nowMs = Date.now()
54
+ content.resetView()
55
+ usage.refreshOnOpen()
56
+ Qt.callLater(function() { keyCatcher.forceActiveFocus() })
57
+ }
58
+
59
+ Main {
60
+ id: usage
61
+ settings: root.settings
62
+ bar: root.bar
63
+ pluginDir: Qt.resolvedUrl(".")
64
+ }
65
+
66
+ Timer {
67
+ interval: 30000
68
+ running: root.opened
69
+ repeat: true
70
+ onTriggered: root.nowMs = Date.now()
71
+ }
72
+
73
+ IpcHandler {
74
+ target: root.ipcTarget
75
+ function open(): void { root.open() }
76
+ function close(): void { root.close() }
77
+ function show(): void { root.open() }
78
+ function hide(): void { root.close() }
79
+ function toggle(): void { root.toggle() }
80
+ function refresh(): string { root.refreshNow(); return "ok" }
81
+ function expand(id: string): string { usage.setExpanded(id, true); return "ok" }
82
+ function collapse(id: string): string { usage.setExpanded(id, false); return "ok" }
83
+ }
84
+
85
+ BarIconButton {
86
+ id: button
87
+ anchors.fill: parent
88
+ bar: root.bar
89
+ text: root.glyph
90
+ active: root.alarming
91
+ onPressed: function(buttonCode) {
92
+ if (buttonCode === Qt.RightButton) root.launchAgent()
93
+ else if (buttonCode === Qt.MiddleButton) root.refreshNow()
94
+ else root.toggle()
95
+ }
96
+ }
97
+
98
+ KeyboardPanel {
99
+ id: panel
100
+ anchorItem: button
101
+ owner: root
102
+ bar: root.bar
103
+ open: root.opened
104
+ focusTarget: keyCatcher
105
+ contentWidth: panel.fittedContentWidth(Style.space(380))
106
+ contentHeight: panel.fittedContentHeight(content.contentImplicitHeight, Style.space(640))
107
+
108
+ PanelKeyCatcher {
109
+ id: keyCatcher
110
+ anchors.fill: parent
111
+
112
+ // j/k or arrows walk the section headers (paging through an open one
113
+ // taller than the panel), Enter/Space fold or unfold, l/h unfold and
114
+ // fold, r refreshes, Tab moves to the neighboring bar panel.
115
+ onMoveRequested: function(dx, dy) {
116
+ if (dy !== 0) content.moveCursor(dy)
117
+ if (dx !== 0) content.setCursorExpanded(dx > 0)
118
+ }
119
+ onActivateRequested: content.toggleCursor()
120
+ onCloseRequested: root.close()
121
+ onTabRequested: function(direction) { root.switchPanel(direction) }
122
+ onTextKey: function(t) { if (t === "r" || t === "R") root.refreshNow() }
123
+
124
+ UsageContent {
125
+ id: content
126
+ anchors.fill: parent
127
+ usage: usage
128
+ foreground: root.foreground
129
+ urgent: root.urgent
130
+ fontFamily: root.fontFamily
131
+ nowMs: root.nowMs
132
+ fallbackGlyph: root.glyph
133
+ }
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,40 @@
1
+ # AI Usage (`cad0p.pi-usage`)
2
+
3
+ One Omarchy bar icon and one scrolling panel for every AI subscription that has
4
+ a usage record in `${XDG_STATE_HOME:-~/.local/state}/omarchy/agents/usage/`:
5
+ pi-usage's `pi-*.json` and Omarchy's own `claude`, `codex` and `fireworks`
6
+ records alike. Every provider is a collapsible section instead of a tab; a
7
+ multi-account provider shows every window of every account.
8
+
9
+ The plugin does **not** support the built-in Agents widget's synced cross-device
10
+ aggregation (`syncMode`, `syncDir`, `syncFileName`, `syncDeviceId`). Users who
11
+ rely on synced aggregation should keep the built-in widget; this plugin is not a
12
+ full replacement for it.
13
+
14
+ Omarchy's own collectors follow the `omarchyCollectors` setting: `Off` never
15
+ runs them, `Auto` only while the built-in Agents widget is off the bar — the
16
+ `retryAdvised` retry included.
17
+
18
+ Part of [`@cad0p/pi-usage`](../../README.md#the-ai-usage-bar-plugin), which
19
+ documents installation, keys, settings and IPC. Install with
20
+ `./install.sh --omarchy-plugin`, then `omarchy plugin enable cad0p.pi-usage`.
21
+
22
+ The installer links the plugin directory; Omarchy loads that symlink, but
23
+ `omarchy plugin validate` rejects symlinked plugin folders. Validate the real
24
+ package path instead, for example
25
+ `omarchy plugin validate ~/.pi/agent/npm/node_modules/@cad0p/pi-usage/omarchy/cad0p.pi-usage`,
26
+ or validate the directory in a source checkout—not the
27
+ `~/.config/omarchy/plugins/cad0p.pi-usage` link.
28
+
29
+ | File | Role |
30
+ |---|---|
31
+ | `Panel.qml` | Bar button, popup, keyboard and IPC (`omarchy-shell cad0p.pi-usage …`) |
32
+ | `UsageContent.qml` | The scrolling list of provider sections and their rows |
33
+ | `Main.qml` | Record discovery and watching, expansion state, refresh |
34
+ | `Agent.qml` | Per-record file watcher |
35
+ | `UsageLogic.js` | Pure logic (headline, ordering, formatting), tested with `node --test` |
36
+ | `assets/` | Provider marks, `<family>.svg` with a `-light` twin where needed |
37
+
38
+ Derived from Omarchy's built-in Agents plugin (`shell/plugins/agents`, MIT,
39
+ by Omarchy): its record contract, rows, meters, type scale and the Claude,
40
+ Codex and Fireworks marks. MIT, like the package.