Skip to content

Commit ab0856d

Browse files
committed
feat(aiquotas): add opencode provider for OpenCode Go subscription quotas
Reads the OpenCode Go plan usage windows and emits one canonical quota record, so the Go subscription shows up in the status bar next to the other coding-plan providers. Endpoint: GET https://opencode.ai/zen/go/v1/usage, Bearer auth with the Zen API key. Key resolution prefers OPENCODE_API_KEY (opencode's own variable for it) and falls back to ["opencode-go"].key in opencode's auth store, the same way the openai adapter reads the Codex OAuth file. The key is long-lived, so unlike claudecode there is no refresh treadmill. The endpoint is undocumented: opencode.ai/docs/go points users at the web console and documents no usage API. It was verified against the live service instead, which answers a JSON AuthError on 401 where every sibling path under /zen/ falls through to the marketing site's 404. Two upstream feature requests (anomalyco/opencode#16017, #31084) propose a dollar-denominated shape with usageDollars/limitDollars/resetInSec; that is the issue authors' invention and is not what the service returns. The real shape is: {usage:{rolling:{status,percent,resetsAt}, weekly:{...}, monthly:{...}}} percent is % consumed, with no dollar figures and no limits, so this is a pure 0-100 scale. Modelled as ONE quota record like zai, kimicode and claudecode: rolling is the record, weekly rides along in weekly_remaining_percent, which is what the dual-window compact renderer and the weekly health escalation both read. Carries no compatibility promise, so normalization degrades to unsupported rather than guessing if the shape changes. The monthly window is dropped, the same way emit_claudecode drops weekly_scoped: the canonical record holds exactly one interval plus one weekly percentage and the plan meters three windows. Monthly is arguably the window that governs a $10/month plan, so surfacing it needs either a second record or a monthly_remaining_percent dimension, both contract-level changes left as a follow-up. The per-window status string is deliberately not interpreted. Only "ok" has been observed, so mapping the others would be guesswork; health comes from percent through the shared threshold evaluator like every other provider. Not added to the default providers list, so this is opt-in. 21 tests covering normalization, the monthly drop, the weekly-only fallback, clamping, unparseable timestamps, the uninterpreted status field, the speculative upstream shape, both key sources, the ~/ expansion, an auth store with no Go entry, 401 / 429 / unsupported outcomes, both render formats, and weekly health escalation.
1 parent 22e9540 commit ab0856d

9 files changed

Lines changed: 812 additions & 5 deletions

File tree

‎src/plugins/aiquotas.sh‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
# * _metrics.sh — _aiquotas_metrics_document (canonical jq document builder)
2929
# * _render.sh — record→text render helpers (compact / detailed)
3030
# * _health.sh — _aiquotas_worst_health / _aiquotas_threshold_health
31-
# * <provider>.sh — per-adapter files (anthropic, openai, deepseek, minimax, zai, kimicode, claudecode, xiaomi_mimo)
31+
# * <provider>.sh — per-adapter files (anthropic, openai, deepseek, minimax, zai, kimicode, claudecode, opencode, xiaomi_mimo)
3232
#
3333
# HTTP collection uses _aiquotas_http_get, a single seam that can be intercepted
3434
# by an HTTP shim in tests/helpers/shims/curl (Todo 2) without modifying this file.
@@ -50,6 +50,7 @@ declare -gA AIQUOTAS_LABELS=(
5050
[zai]="zai"
5151
[kimicode]="Kimi"
5252
[claudecode]="Claude Code"
53+
[opencode]="OpenCode Go"
5354
)
5455

5556
# Default URLs per provider endpoint. URL can be overridden via plugin options.
@@ -66,6 +67,7 @@ declare -gA AIQUOTAS_DEFAULT_URLS=(
6667
[zai_quota]="https://api.z.ai/api/monitor/usage/quota/limit"
6768
[kimicode_usage]="https://api.kimi.com/coding/v1/usages"
6869
[claudecode_usage]="https://api.anthropic.com/api/oauth/usage"
70+
[opencode_usage]="https://opencode.ai/zen/go/v1/usage"
6971
)
7072

7173
# =============================================================================
@@ -137,6 +139,7 @@ _aiquotas_load_all_providers() {
137139
_aiquotas_load_provider zai
138140
_aiquotas_load_provider kimicode
139141
_aiquotas_load_provider claudecode
142+
_aiquotas_load_provider opencode
140143
}
141144

142145
# =============================================================================
@@ -219,6 +222,12 @@ plugin_declare_options() {
219222
declare_option "claudecode_usage_url" "string" "${AIQUOTAS_DEFAULT_URLS[claudecode_usage]}" "Claude subscription usage endpoint"
220223
declare_option "claudecode_credentials_file" "path" "${HOME}/.claude/.credentials.json" "Claude Code OAuth credentials file (used when CLAUDE_CODE_OAUTH_TOKEN is unset)"
221224

225+
# OpenCode Go subscription. The endpoint is undocumented upstream; see the
226+
# header of src/plugins/aiquotas/opencode.sh for what was verified and how
227+
# it degrades if the shape changes.
228+
declare_option "opencode_usage_url" "string" "${AIQUOTAS_DEFAULT_URLS[opencode_usage]}" "OpenCode Go usage endpoint"
229+
declare_option "opencode_auth_file" "path" "${XDG_DATA_HOME:-${HOME}/.local/share}/opencode/auth.json" "OpenCode auth store (used when OPENCODE_API_KEY is unset)"
230+
222231
declare_option "icon" "icon" $'\uEE9C' "Plugin icon (brain)"
223232
declare_option "cache_ttl" "number" "300" "Cache duration in seconds"
224233
}
@@ -241,9 +250,9 @@ plugin_get_presence() { printf 'conditional'; }
241250
_aiquotas_collect_provider() {
242251
# Dispatches one provider's collection through its dedicated adapter
243252
# (anthropic / openai / deepseek / minimax / zai / kimicode / claudecode /
244-
# xiaomi_mimo). Each adapter returns the canonical metrics document on
245-
# stdout (or an empty string on hard transport failure). Does NOT touch
246-
# plugin_data.
253+
# opencode / xiaomi_mimo). Each adapter returns the canonical metrics
254+
# document on stdout (or an empty string on hard transport failure). Does
255+
# NOT touch plugin_data.
247256
local provider="$1"
248257
local timeout
249258
timeout=$(get_option "timeout")
@@ -261,6 +270,7 @@ _aiquotas_collect_provider() {
261270
zai) _aiquotas_collect_zai 2>/dev/null ;;
262271
kimicode) _aiquotas_collect_kimicode 2>/dev/null ;;
263272
claudecode) _aiquotas_collect_claudecode 2>/dev/null ;;
273+
opencode) _aiquotas_collect_opencode 2>/dev/null ;;
264274
*) return 64 ;;
265275
esac
266276
}
@@ -288,7 +298,7 @@ plugin_collect() {
288298
[[ -n "$provider" ]] || continue
289299

290300
case "$provider" in
291-
anthropic | openai | deepseek | minimax | zai | kimicode | claudecode)
301+
anthropic | openai | deepseek | minimax | zai | kimicode | claudecode | opencode)
292302
# Unified dispatch: every adapter owns its own HTTP+normalization
293303
# and returns a canonical metrics document on stdout (or empty
294304
# on hard transport failure). See _aiquotas_collect_provider.

‎src/plugins/aiquotas/_metrics.sh‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,73 @@ _aiquotas_metrics_document() {
434434
)
435435
end;
436436

437+
def emit_opencode:
438+
# OpenCode Go plan usage:
439+
# {usage:{rolling:{status,percent,resetsAt},
440+
# weekly:{...}, monthly:{...}}}
441+
#
442+
# percent is % CONSUMED and there are no dollar figures or limits in
443+
# the response, so this is a pure 0-100 scale. Modelled as ONE quota
444+
# record like zai, kimicode and claudecode: the rolling window is the
445+
# record and the weekly window rides along in weekly_remaining_percent,
446+
# which is what the dual-window compact renderer and the weekly health
447+
# escalation in _health.sh both read.
448+
#
449+
# monthly is deliberately ignored: the canonical record holds exactly
450+
# one interval and one weekly percentage and the plan meters three
451+
# windows, so it has nowhere to go. See the adapter header.
452+
#
453+
# The per-window `status` string is not interpreted. Only "ok" has been
454+
# observed, so mapping the others would be guesswork; health comes from
455+
# percent through the shared threshold evaluator instead.
456+
(.usage // null) as $u |
457+
if ($u | type) != "object"
458+
then error("unknown schema")
459+
else
460+
($u.rolling.percent? // null) as $pct5 |
461+
($u.weekly.percent? // null) as $pctwk |
462+
($u.rolling.resetsAt? // null) as $reset5 |
463+
($u.weekly.resetsAt? // null) as $resetwk |
464+
if (($pct5 | type) != "number") and (($pctwk | type) != "number")
465+
then error("unknown schema")
466+
else
467+
(($pct5 | type) == "number") as $has5 |
468+
# Prefer the rolling window, fall back to weekly, mirroring
469+
# emit_zai and emit_claudecode. Labelled "5h" rather than
470+
# "rolling" to match the sibling adapters: the plan documents
471+
# it as a five-hour window.
472+
(if $has5 then "5h" else "weekly" end) as $label |
473+
(if $has5 then $pct5 else $pctwk end) as $raw |
474+
(if $has5 then $reset5 else $resetwk end) as $reset |
475+
# Window length, so window_start can be derived from the reset.
476+
(if $has5 then 18000 else 604800 end) as $span |
477+
($raw | clamp_pct) as $pct |
478+
reset_epoch($reset) as $epoch |
479+
(if $epoch != null then ($epoch | todate) else null end) as $we_iso |
480+
(if $epoch != null then (($epoch - $span) | todate) else null end) as $ws_iso |
481+
record(
482+
"quota";
483+
$pct;
484+
100;
485+
(100 - $pct);
486+
"percent";
487+
null;
488+
$ws_iso;
489+
$we_iso;
490+
$we_iso;
491+
"official";
492+
({resource: "subscription", line_item: $label} +
493+
{interval_remaining_percent: (100 - $pct)} +
494+
# Only when rolling is the primary. With weekly already
495+
# the record, a weekly dimension would duplicate it and
496+
# the renderer would print the same number twice.
497+
(if $has5 and (($pctwk | type) == "number")
498+
then {weekly_remaining_percent: (100 - ($pctwk | clamp_pct))}
499+
else {} end))
500+
)
501+
end
502+
end;
503+
437504
# ---- top-level dispatch -------------------------------------------
438505
. as $root |
439506
if (type != "object") or has("error")
@@ -484,6 +551,13 @@ _aiquotas_metrics_document() {
484551
then doc([]; "official"; "unsupported"; "unknown schema")
485552
else doc([ $rec ]; "official"; "ok"; null)
486553
end
554+
elif ($provider == "opencode") and ($schema == "")
555+
then
556+
(try emit_opencode catch null) as $rec |
557+
if $rec == null
558+
then doc([]; "official"; "unsupported"; "unknown schema")
559+
else doc([ $rec ]; "official"; "ok"; null)
560+
end
487561
elif (($provider == "xiaomi_mimo") or ($provider == "minimax")) and ($schema != "")
488562
then
489563
(try apply_schema($root; $schema) catch null) as $mapped |

‎src/plugins/aiquotas/_render.sh‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ _aiquotas_render_label() {
9696
zai) printf 'zai' ;;
9797
kimicode) printf 'KM' ;;
9898
claudecode) printf 'CC' ;;
99+
opencode) printf 'OC' ;;
99100
*) printf '%s' "$provider" ;;
100101
esac
101102
return

‎src/plugins/aiquotas/opencode.sh‎

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
#!/usr/bin/env bash
2+
# =============================================================================
3+
# aiquotas adapter — opencode (OpenCode Go subscription)
4+
# =============================================================================
5+
# Companion adapter for the aiquotas plugin. Provides _aiquotas_collect_opencode
6+
# which emits a canonical metrics document for the OpenCode Go plan usage
7+
# windows.
8+
#
9+
# Loaded lazily by _aiquotas_load_provider in the entry point. NEVER source this
10+
# file directly — go through the loader.
11+
#
12+
# Endpoint: GET https://opencode.ai/zen/go/v1/usage
13+
# Auth: Authorization: Bearer <OpenCode Zen API key, "sk-...">
14+
# Shape: {usage:{rolling:{status,percent,resetsAt},
15+
# weekly :{status,percent,resetsAt},
16+
# monthly:{status,percent,resetsAt}}}
17+
# percent = % CONSUMED; remaining% = 100 - percent.
18+
#
19+
# --- On the endpoint being undocumented -------------------------------------
20+
#
21+
# https://opencode.ai/docs/go/ documents no usage API at all and points users at
22+
# the web console instead. The route nonetheless exists and was verified against
23+
# the live service: it answers 401 with a JSON AuthError when unauthenticated,
24+
# where every sibling path under /zen/ falls through to the marketing site's
25+
# 404. Two upstream feature requests (anomalyco/opencode#16017, #31084) propose
26+
# a *different*, dollar-denominated shape; that shape is the issue authors'
27+
# invention and does not match what the service returns. The normalization in
28+
# emit_opencode follows the observed response and degrades to `unsupported`
29+
# rather than guessing if the shape changes, which is the right outcome for an
30+
# endpoint carrying no compatibility promise.
31+
#
32+
# Only status "ok" has been observed in the wild, so the per-window `status`
33+
# field is deliberately not interpreted; health comes from `percent` via the
34+
# shared threshold evaluator like every other provider.
35+
#
36+
# --- The monthly window ------------------------------------------------------
37+
#
38+
# The plan meters three windows but a canonical record holds exactly one
39+
# interval plus one weekly percentage, so `monthly` is dropped, the same way
40+
# emit_claudecode drops weekly_scoped. Monthly is arguably the window that
41+
# actually governs a $10/month plan, so surfacing it needs either a second
42+
# record or a monthly_remaining_percent dimension — both contract-level changes,
43+
# deliberately left as a follow-up.
44+
# =============================================================================
45+
46+
POWERKIT_ROOT="${POWERKIT_ROOT:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)}"
47+
. "${POWERKIT_ROOT}/src/core/guard.sh"
48+
source_guard "aiquotas_opencode" && return 0
49+
50+
# -----------------------------------------------------------------------------
51+
# Key resolution
52+
# -----------------------------------------------------------------------------
53+
# OPENCODE_API_KEY wins when set. That is opencode's own environment variable
54+
# for the Zen key, not one invented here, so exporting it in a shell profile is
55+
# the configuration that works everywhere tmux inherits the environment.
56+
# Otherwise read ["opencode-go"].key out of opencode's auth store, the same way
57+
# the openai adapter reads the Codex OAuth file.
58+
#
59+
# Unlike the Claude OAuth access token, this is a long-lived API key, so there
60+
# is no refresh treadmill and no expected intermittent unauthorized window.
61+
#
62+
# Prints the key on stdout, or nothing when none can be resolved.
63+
_aiquotas_opencode_key() {
64+
if [[ -n "${OPENCODE_API_KEY:-}" ]]; then
65+
printf '%s' "$OPENCODE_API_KEY"
66+
return 0
67+
fi
68+
69+
local auth
70+
auth=$(get_option "opencode_auth_file")
71+
# tmux option values are not shell-expanded, so a leading ~/ is literal.
72+
# Only the bare-home form is expanded; ~user/... is left untouched rather
73+
# than being silently rewritten under the current $HOME.
74+
if [[ "$auth" == "~" ]]; then
75+
auth="$HOME"
76+
elif [[ "$auth" == \~/* ]]; then
77+
auth="${HOME}/${auth#\~/}"
78+
fi
79+
[[ -n "$auth" && -r "$auth" ]] || return 0
80+
81+
jq -r '.["opencode-go"].key // empty' "$auth" 2>/dev/null
82+
}
83+
84+
# -----------------------------------------------------------------------------
85+
# OpenCode Go adapter
86+
# -----------------------------------------------------------------------------
87+
#
88+
# Reads the Go plan usage endpoint and emits one quota record for the rolling
89+
# window, with the weekly window as a dimension. Treats the data as `official`
90+
# only when a key could be resolved.
91+
#
92+
# Returns the canonical JSON document on stdout. Exits 0 even on partial
93+
# failure (the provider_outcomes entry carries the error); exits non-zero only
94+
# when jq cannot assemble the envelope at all.
95+
#
96+
_aiquotas_collect_opencode() {
97+
local key
98+
key=$(_aiquotas_opencode_key)
99+
100+
if [[ -z "$key" ]]; then
101+
jq -nc '
102+
{schema_version:1, records:[],
103+
provider_outcomes:[{provider:"opencode",source:"official",
104+
status:"unconfigured",
105+
error:"no OpenCode key: set OPENCODE_API_KEY or subscribe to Go in opencode"}]}
106+
'
107+
return 0
108+
fi
109+
110+
local url timeout body status
111+
url=$(get_option "opencode_usage_url")
112+
timeout=$(get_option "timeout")
113+
timeout="${timeout:-5}"
114+
115+
if [[ -z "$url" ]]; then
116+
jq -nc '
117+
{schema_version:1, records:[],
118+
provider_outcomes:[{provider:"opencode",source:"official",
119+
status:"unconfigured",
120+
error:"opencode usage URL not configured"}]}
121+
'
122+
return 0
123+
fi
124+
125+
# The credential travels via stdin so it never appears in argv.
126+
body=$(_aiquotas_http_get_meta_authed \
127+
"$url" "$timeout" \
128+
"Authorization" "Bearer $key" \
129+
-H "Accept: application/json") || body=""
130+
status=$(_aiquotas_last_status)
131+
132+
if [[ -z "$body" ]]; then
133+
jq -nc '
134+
{schema_version:1, records:[],
135+
provider_outcomes:[{provider:"opencode",source:"official",
136+
status:"unavailable",
137+
error:"usage fetch transport failure"}]}
138+
'
139+
return 0
140+
fi
141+
142+
# A revoked or mistyped key answers 401 with {"type":"error",...}; the
143+
# shared mapper turns that into `unauthorized` rather than a blank segment.
144+
if [[ "$status" != 2* ]]; then
145+
local canonical_status canonical_error
146+
canonical_status=$(_aiquotas_http_status_to_canonical "$status")
147+
canonical_error=$(_aiquotas_http_status_error_message "$body" "usage")
148+
jq -nc \
149+
--arg st "$canonical_status" \
150+
--arg er "$canonical_error" \
151+
'
152+
{schema_version:1, records:[],
153+
provider_outcomes:[{provider:"opencode",source:"official",
154+
status:$st, error:$er}]}
155+
'
156+
return 0
157+
fi
158+
159+
if ! _aiquotas_metrics_document "opencode" "$body" 2>/dev/null; then
160+
jq -nc '
161+
{schema_version:1, records:[],
162+
provider_outcomes:[{provider:"opencode",source:"official",
163+
status:"malformed",
164+
error:"usage payload normalization failed"}]}
165+
'
166+
return 0
167+
fi
168+
}

0 commit comments

Comments
 (0)