Skip to content

Add Kimi Code and Grok Build usage collectors - #6477

Closed
dalmasluca wants to merge 8 commits into
omacom:quattrofrom
dalmasluca:model-usage-kimi-grok
Closed

dalmasluca wants to merge 8 commits into
omacom:quattrofrom
dalmasluca:model-usage-kimi-grok

Conversation

@dalmasluca

@dalmasluca dalmasluca commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds official quota and per-model local token history for Kimi Code and Grok Build to the omarchy.agents plugin, as two standalone collectors that print one display-ready record each:

  • bin/omarchy-agent-usage-kimi
  • bin/omarchy-agent-usage-grok

Both follow the exact shape of bin/omarchy-agent-usage-claude / codex (alone with the record schema, caches, and CLI flags --force / --limits-only / --local-only), and are picked up automatically by bin/omarchy-agent-usage-update by file-name globbing. No QML changes: the panel discovers a provider from its record file and resolves assets/<id>.svg.

  • Official quota
    • Kimi: ~/.kimi-code / KIMI_CODE_HOME credentials + the /usages endpoint (weekly usage summary row + rolling windows under limits[], e.g. 5h), labels and fractions from the CLI's own rendering. Token refresh uses the CLI's OAuth flow under an advisory flock so the CLI and collector never rotate the same refresh token twice.
    • Grok: ~/.grok/auth.json grok-com entry + billing?format=credits (weekly/monthly credit pool, per-product breakdown, on-demand cap), with CLI-style token refresh under auth.json.lock.
  • Local per-model token history (merged into one record, no double counting)
    • Kimi native transcripts (~/.kimi-code/sessions/*/session_*/agents/*/wire.jsonl, per-turn usage.record); model aliases kimi-code/k3, kimi-k3, opencode-go/kimi-k3 collapse into one k3 bucket.
    • Grok native sessions (~/.grok/sessions, turn_started → model map + peak cumulative _meta.totalTokens per turn from updates.jsonl).
    • pi/omp transcripts (~/.pi/agent/sessions, ~/.omp/agent/sessions) for the exact kimi-coding / xai providers.
    • opencode database sessions with providerID exactly kimi / xai (reasoning tokens kept out of input, matching the Anthropic collector).
  • Plugin wiring: manifest.json adds kimi and grok as enabled-by-default providers; assets/kimi.svg, kimi-light.svg, grok.svg, grok-light.svg are copied from the old model-usage plugin.
  • Tests: test/shell.d/agent-usage-kimi-scanner-test.sh and agent-usage-grok-scanner-test.sh, covering native + pi + cross-source dedupe + official quota/billing via a stubbed HTTP server.

Notes

  • Replaces the conflicting PR based on the old model-usage plugin: this branch deletes nothing on quattro, it only adds collectors, tests, assets, and two manifest defaults.
  • Authored by opencode on behalf of the reporter.

Tests

./test/shell.d/agent-usage-kimi-scanner-test.sh
./test/shell.d/agent-usage-grok-scanner-test.sh

Copilot AI balanced review requested due to automatic review settings August 1, 2026 09:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Adds Kimi Code and Grok Build quota and local token-history support to the model-usage plugin.

Changes:

  • Adds quota and transcript scanners for both providers.
  • Integrates providers into the panel, synchronization, and defaults.
  • Adds scanner tests and documentation.

Tip

If you aren't ready for review, convert to a draft PR.
Click "Convert to draft" or run gh pr ready --undo.
Click "Ready for review" or run gh pr ready to reengage.

Reviewed changes

Copilot reviewed 10 out of 10 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
shell/plugins/model-usage/Main.qml Registers and exposes the new providers.
shell/plugins/model-usage/Panel.qml Displays multi-window quotas and provider headers.
shell/plugins/model-usage/README.md Documents Kimi and Grok support.
shell/plugins/model-usage/manifest.json Enables both providers by default.
shell/plugins/model-usage/providers/Kimi.qml Implements the Kimi provider bridge.
shell/plugins/model-usage/providers/Grok.qml Implements the Grok provider bridge.
shell/plugins/model-usage/scripts/kimi_usage.py Fetches Kimi quotas and scans local history.
shell/plugins/model-usage/scripts/grok_usage.py Fetches Grok quotas and scans local history.
test/shell.d/model-usage-kimi-scanner-test.sh Tests Kimi quota and history parsing.
test/shell.d/model-usage-grok-scanner-test.sh Tests Grok quota and history parsing.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +86 to +89
for key, entry in store.items():
if isinstance(entry, dict) and entry.get("key"):
return key, entry
return None, None
"token_type": payload.get("token_type") or token.get("token_type") or "Bearer",
"expires_in": int(expires_in),
})
save_token(merged)
Comment on lines +109 to +111
// Only a successful fetch replaces the limits; a transient network
// failure keeps the last good quota on screen and just reports it.
if (data.available === true) {
Comment on lines +110 to +112
// Only a successful fetch replaces the limits; a transient network
// failure keeps the last good quota on screen and just reports it.
if (data.available === true) {
Comment thread shell/plugins/model-usage/Panel.qml Outdated
Comment on lines +382 to +385
// Kimi and Grok have no shipped mark yet; collapse the icon
// slot so the hero reads as a clean two-line header.
width: source === "" ? 0 : Style.font.display
height: source === "" ? 0 : Style.font.display
Copilot AI review requested due to automatic review settings August 1, 2026 10:02
@dalmasluca

Copy link
Copy Markdown
Contributor Author

Addressed the review comments (commits 358be43, 3119100, 85665dc):

  • grok_usage.py: prefer the grok-com entry when auth.json has multiple credentials, with fallback to a grok client key.
  • kimi_usage.py: refresh tokens under an fcntl lock (no clobbering a rotated refresh token); refresh tokens are only written to disk.
  • Kimi.qml/Grok.qml: clear the quota when auth reaches a terminal state (logout, 401, or no limits) so no stale quota is shown; only network/timeout failures are retried as transient.
  • PanelHero.qml: only reserve the icon margin when an icon is actually rendered, so icon-less providers (Kimi/Grok) no longer show a phantom gap.
  • Tests: assert the transient/terminal behavior for both scanners.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 11 out of 11 changed files in this pull request and generated 1 comment.

Suppressed comments (4)

shell/plugins/model-usage/scripts/grok_usage.py:582

  • The repeated-401 path raises RuntimeError("authorization failed..."), so it falls into this else and is marked transient. Grok.qml consequently keeps displaying the last quota indefinitely even though authentication is terminal. Treat the explicit authorization error (and invalid-grant HTTP 400 responses from refresh) as non-transient.
    if isinstance(exc, urllib.error.HTTPError) and exc.code in (401, 403):
      message = "authorization failed (try: grok login)"
    else:
      # Network, timeout or server error: the last good quota is still valid.
      transient = True

shell/plugins/model-usage/Panel.qml:385

  • Image.source is a QML url value, so strict comparison with the string "" does not reliably detect an empty URL. For Kimi/Grok this can leave the image at display size, making PanelHero.hasIcon true and preserving the blank icon gap this change intends to remove. Convert the URL to a string before comparing.
                width: source === "" ? 0 : Style.font.display
                height: source === "" ? 0 : Style.font.display

shell/plugins/model-usage/scripts/kimi_usage.py:546

  • An expired/revoked refresh token commonly produces OAuth invalid_grant as HTTP 400, but this branch marks every status except 401 as transient. The provider then preserves a stale quota instead of clearing it and asking the user to log in again. Classify terminal OAuth client errors separately from network, rate-limit, and server failures.
    if isinstance(exc, urllib.error.HTTPError) and exc.code == 401:
      message = "authorization failed (try: kimi login)"
    else:
      # Network, timeout or server error: the last good quota is still valid.
      transient = True

shell/plugins/model-usage/scripts/grok_usage.py:5

  • Correct the source/project name typo to “grok-build.”
gork-build crates/codegen/xai-grok-shell/src/extensions/billing.rs):

Comment on lines +159 to +164
fresh = store.get(entry_key)
if not (isinstance(fresh, dict) and fresh.get("key")):
fresh = current
if not force and not token_expired(fresh):
return fresh # the CLI refreshed while we waited
fresh = refresh_entry(fresh)
Copilot AI review requested due to automatic review settings August 1, 2026 10:10

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 11 out of 15 changed files in this pull request and generated no new comments.

Suppressed comments (6)

shell/plugins/model-usage/scripts/grok_usage.py:5

  • Correct the referenced project name from gork-build to grok-build.
gork-build crates/codegen/xai-grok-shell/src/extensions/billing.rs):

shell/plugins/model-usage/scripts/kimi_usage.py:541

  • An expired or revoked refresh token normally makes the OAuth endpoint return HTTP 400 (invalid_grant). This condition treats that as a transient network failure, so Kimi.qml preserves the last quota indefinitely instead of clearing stale data and asking the user to log in again. Treat OAuth/authentication 4xx responses as terminal while retaining transient handling for transport errors, 429s, and 5xx responses.
    if isinstance(exc, urllib.error.HTTPError) and exc.code == 401:
      message = "authorization failed (try: kimi login)"
    else:
      # Network, timeout or server error: the last good quota is still valid.
      transient = True

shell/plugins/model-usage/scripts/grok_usage.py:578

  • Authentication failures are misclassified as transient here. A failed refresh commonly returns HTTP 400, and the explicit second-401 path above raises RuntimeError("authorization failed..."); both enter the else branch, causing Grok.qml to retain stale quota after authentication is definitively invalid. Classify these auth outcomes as terminal and reserve transient for transport errors, 429s, and 5xx responses.
    if isinstance(exc, urllib.error.HTTPError) and exc.code in (401, 403):
      message = "authorization failed (try: grok login)"
    else:
      # Network, timeout or server error: the last good quota is still valid.
      transient = True

test/shell.d/model-usage-kimi-scanner-test.sh:24

  • This fixture deliberately bypasses the newly added OAuth refresh, locking, rotation, and atomic credential-write path. That path modifies the CLI's live credential store and is a core part of this scanner, so add a test with an expired token that serves a refresh response and verifies the refreshed token is persisted with the expected mode and used for /usages; a concurrent-refresh case should also verify that a token rotated under the lock is reused.
# The CLI's FileTokenStorage shape: a non-expired token so the scanner goes
# straight to the /usages endpoint instead of the OAuth refresh flow.

test/shell.d/model-usage-grok-scanner-test.sh:24

  • This fixture deliberately bypasses the newly added OAuth refresh, advisory lock, token rotation, and atomic auth.json update. Because this scanner writes the CLI's credential store, add coverage with an expired entry that serves a refresh response and verifies persistence, permissions, and use of the refreshed token; also cover the forced refresh after a billing 401, which would expose the transient-classification bug.
# The CLI's auth.json shape: an entry with a non-expired token so the scanner
# goes straight to the billing endpoint instead of the OAuth refresh flow.

shell/Ui/PanelHero.qml:43

  • This changes the shared hero geometry used by multiple panels, while the PR reports only scanner tests and there is no model-usage or PanelHero acceptance coverage. Verify the iconless and icon-present states in the running shell, including the new four-provider switch and both light/dark icons, and inspect screenshots for spacing, clipping, and overlap before merging.
    anchors.left: root.hasIcon ? iconLoader.right : parent.left
    anchors.leftMargin: root.hasIcon ? Style.space(14) : 0

@rlimberger rlimberger mentioned this pull request Aug 6, 2026
4 of 7 tasks
@dhh

dhh commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

Heads up: #6603 just landed on quattro and restructured this whole area, so this PR needs a rework before it can merge.

The model-usage plugin is gone. It's been renamed to omarchy.agents (shell/plugins/agents/), and the panel is now strictly a display: it watches JSON records under ~/.local/state/omarchy/agents/usage/ and draws whatever appears there. All the in-plugin machinery this PR touches — providers/*.qml adapters and scripts/*_usage_scanner.py — no longer exists.

Usage collection now lives in standalone collectors in bin/. One omarchy-agent-usage-<agent> script per agent prints a complete, display-ready usage record (identity, tier, status, rate limits, today/week/all-time stats), and omarchy-agent-usage-update runs every collector it finds and writes the records atomically to the state directory.

The upside: adding an agent no longer touches the panel at all. Ship a collector that prints the record contract, optionally add an assets/<id>.svg mark (with an -light twin if it needs one for light surfaces), and the panel gains a tab on its own. See shell/plugins/agents/README.md for the contract and the claude/codex collectors in bin/ as reference implementations — #6604 (Cursor) is a good example of a provider PR in the new style.

If you'd like to update this PR to the new structure, rebase on quattro and reshape the scanner into a collector. Happy to answer questions here.

— Claude Fable 5, written on behalf of @dhh

@dalmasluca
dalmasluca force-pushed the model-usage-kimi-grok branch from 25f6fe0 to 169f2cc Compare August 9, 2026 16:52
Copilot AI review requested due to automatic review settings August 9, 2026 16:52
@dalmasluca dalmasluca changed the title Add Kimi Code and Grok Build support to model usage Add Kimi Code and Grok Build usage collectors Aug 9, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 5 out of 11 changed files in this pull request and generated no new comments.

Suppressed comments (2)

test/shell.d/agent-usage-kimi-scanner-test.sh:23

  • This hard-coded timestamp is considered “today” only on 2026-08-09. On later runs, the pi usage drops out of todayTotalTokens, so the assertion expecting 2800 becomes permanently failing. Generate the timestamp from now_ms, as the Grok test does.
{"type":"message","id":"pi-1","timestamp":"2026-08-09T12:00:00Z","message":{"role":"assistant","provider":"kimi-coding","model":"k3","usage":{"input":400,"output":100,"cacheRead":50,"cacheWrite":0,"totalTokens":550}}}

shell/plugins/agents/manifest.json:26

  • The PR description says the README is updated, but enabling these providers leaves shell/plugins/agents/README.md listing only Claude, Codex, and Fireworks in both its collector table and provider-settings example. Add Kimi/Grok limits, local-source, auth/home-variable, and settings documentation so the enabled defaults are discoverable and the PR description matches the change.
        "fireworks": { "enabled": true },
        "kimi": { "enabled": true },
        "grok": { "enabled": true }

Copilot AI review requested due to automatic review settings August 9, 2026 18:01

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 6 out of 12 changed files in this pull request and generated no new comments.

@bjarneo

bjarneo commented Sep 20, 2026

Copy link
Copy Markdown
Member

Automated duplication check: this pull request looks similar to #9498, which covers the same Grok usage collector. I keep that one open and close this one to consolidate review.

If you feel this is the wrong decision, please open the PR again with a note on the difference.

@bjarneo bjarneo closed this Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants