Skip to content

Commit 178ae20

Browse files
committed
feat(opencode-zen): pay-as-you-go balance via billing-page scrape
OpenCode Zen's PAYG account has no JSON usage endpoint yet (anomalyco/opencode#10448), so this vendor scrapes the workspace billing page with the session `auth` cookie and parses the embedded SolidStart data. It complements the existing `opencode-go` vendor: Go-plan percentage windows stay there; Zen here reports the prepaid balance in USD. - Parser: anchored field scan after the `billing.get[` anchor plus a rendered `data-slot` fallback. Unit handling learned from a live capture (2026-08): balance/usage/payments are billing units where 1 USD = 1e8 units, but reloadAmount/reloadTrigger are plain dollars. Missing fields are legal (monthlyLimit is null on most accounts); a missing balance is schema drift -> AppError::Schema, never $0.00. No new dependencies — hand-rolled byte scanners, fully unit-tested. - Fetch: lock -> fresh cache (300s TTL; the HTML console must not be hit on every Waybar tick) -> live scrape -> stale fallback (7d). Error paths are terse by construction: fixed status messages and a hashed workspace id keep the cookie out of every rendered surface. - Render: bar shows `$balance` (DeepSeek-style balance vendor). With a dashboard monthly limit set, severity follows consumed %; without one, absolute bands driven by configurable low_balance_warn_usd. Tooltip adds spend, auto-reload state and last top-up. - Config `[opencode-zen]`: enabled/workspace_id/auth_cookie/ low_balance_warn_usd. No env var on purpose — OPENCODE_* collides with the opencode client's own variables. A non-empty cookie auto-tightens the config file to 0600. Verified against a live workspace capture and via the new #[ignore]d `opencode_zen_live` smoke test (make smoke).
1 parent 526ea17 commit 178ae20

17 files changed

Lines changed: 1867 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ come from environment variables or `config.toml`.
144144
| Kiro CLI | Existing kiro-cli login | Opt in and run `kiro-cli login` once. ai-usagebar refreshes the session when needed. |
145145
| Nous Research | OAuth device flow | Enable `[nous]`, click **Log in with Nous Research** in the Omarchy settings panel, or run `ai-usagebar auth nous login`. Credentials are kept in ai-usagebar's separate platform config directory (`~/.config/ai-usagebar/credentials.json` on Linux). |
146146
| OpenCode Go | API key (`OPENCODE_GO_API_KEY` env or `[opencode-go] api_key` in config) | Enable `[opencode-go]`, then enter the key in the Omarchy settings panel or set the environment variable. |
147+
| OpenCode Zen | Session cookie (`[opencode-zen] auth_cookie` in config) | Opt in. Copy the workspace id from your billing URL and the `auth` session cookie from your browser (DevTools → Cookies); both live under `[opencode-zen]`. Reports the pay-as-you-go balance, not Go-plan quotas. |
147148

148149
### Nous credits and OpenCode Go
149150

‎config.example.toml‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
# is selected when the TUI opens. Comment out to default to Anthropic.
1111
# Valid: anthropic | anthropic_api | openai | zai | openrouter | deepseek
1212
# | kimi | kilo | novita | moonshot | grok | supergrok | antigravity
13-
# | cursor | minimax | kiro | nous | opencode-go
13+
# | cursor | minimax | kiro | nous | opencode-go | opencode-zen
1414
# When unset, the TUI opens on the Overview (all vendors at once); set this to
1515
# open directly on a vendor's tab instead.
1616
# primary = "anthropic"
@@ -294,3 +294,20 @@ enabled = false
294294
enabled = false
295295
api_key_env = "OPENCODE_GO_API_KEY"
296296
# api_key = "[REDACTED]" # optional inline fallback; prefer the environment
297+
298+
# OpenCode Zen — pay-as-you-go balance, scraped from the workspace billing
299+
# page (there is no JSON endpoint for it yet, anomalyco/opencode#10448).
300+
# workspace_id: from your billing URL — opencode.ai/workspace/<id>/billing
301+
# auth_cookie: the `auth` session cookie for opencode.ai (DevTools →
302+
# Storage → Cookies). Valid roughly a year; re-copy when
303+
# requests start failing with HTTP 401. There is deliberately
304+
# no environment-variable fallback: OPENCODE_* collides with
305+
# the opencode client's own variables. A non-empty cookie here
306+
# auto-tightens this file to 0600.
307+
# low_balance_warn_usd: without a dashboard monthly limit, the widget turns
308+
# warn-orange once the remaining balance drops below this.
309+
[opencode-zen]
310+
enabled = false
311+
workspace_id = ""
312+
auth_cookie = ""
313+
low_balance_warn_usd = 5.0

‎docs/vendor-endpoints.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ defensive and includes opt-in live tests for catching response changes.
2424
| **Kiro CLI** | `codewhisperer.<region>.amazonaws.com` `GetUsageLimits` (undocumented; the same call kiro-cli's own `/usage` slash command makes) | Single credit pool this cycle — used/limit/%, plan, reset | No — widget/TUI only |
2525
| **Nous Research** | `portal.nousresearch.com/api/oauth/account` (OAuth-authenticated Portal account response) | Subscription usage %, subscription credits, top-up/purchased credits, total usable credits, renewal | Yes |
2626
| **OpenCode Go** | `opencode.ai/zen/go/v1/usage` | Rolling, weekly, and monthly `percent` windows with absolute reset timestamps | Yes |
27+
| **OpenCode Zen** | `opencode.ai/workspace/{id}/billing` HTML (undocumented; the web console's own page, scraped with the session `auth` cookie — no JSON endpoint exists yet, anomalyco/opencode#10448) | Pay-as-you-go balance ($), monthly usage vs optional limit, auto-reload config, last top-up | No — widget/TUI only |
2728

2829

2930
## Stability notes

‎src/active.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ fn parse_slug(s: &str) -> Option<VendorId> {
117117
"kiro" => Some(VendorId::Kiro),
118118
"nous" => Some(VendorId::NousResearch),
119119
"opencode-go" => Some(VendorId::OpenCodeGo),
120+
"opencode-zen" => Some(VendorId::OpenCodeZen),
120121
_ => None,
121122
}
122123
}

‎src/config.rs‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,8 @@ pub struct Config {
5757
pub nous: NousConfig,
5858
#[serde(rename = "opencode-go")]
5959
pub opencode_go: OpenCodeGoConfig,
60+
#[serde(rename = "opencode-zen")]
61+
pub opencode_zen: OpenCodeZenConfig,
6062
}
6163

6264
/// UI / dispatch preferences. Currently just `primary` — which vendor the
@@ -497,6 +499,41 @@ impl Default for OpenCodeGoConfig {
497499
}
498500
}
499501

502+
/// OpenCode Zen pay-as-you-go account. Unlike Go (an API key against a JSON
503+
/// endpoint) Zen's balance is only reachable by scraping the workspace
504+
/// billing page with the console's session cookie, so the credentials here
505+
/// are a workspace id plus that cookie — no env var, deliberately, to avoid
506+
/// colliding with the opencode client's own `OPENCODE_*` variables.
507+
///
508+
/// Opt-in (`enabled` defaults to `false`): it sends a session secret to a web
509+
/// page and scrapes HTML, so it stays off until explicitly turned on.
510+
#[derive(Debug, Clone, Deserialize, Serialize)]
511+
#[serde(default)]
512+
pub struct OpenCodeZenConfig {
513+
pub enabled: bool,
514+
/// Workspace id from the billing URL — `opencode.ai/workspace/<id>/billing`.
515+
pub workspace_id: String,
516+
/// The `auth` session cookie from opencode.ai (DevTools → Storage →
517+
/// Cookies). Valid roughly a year; re-copy when requests start failing.
518+
/// Treated like an inline `api_key`: the config file is auto-tightened to
519+
/// 0600 while this holds a value.
520+
pub auth_cookie: String,
521+
/// Without a dashboard monthly limit, severity colors come from absolute
522+
/// balance bands; this is the warn-band floor in USD.
523+
pub low_balance_warn_usd: f64,
524+
}
525+
526+
impl Default for OpenCodeZenConfig {
527+
fn default() -> Self {
528+
Self {
529+
enabled: false,
530+
workspace_id: String::new(),
531+
auth_cookie: String::new(),
532+
low_balance_warn_usd: crate::opencode_zen::vendor::DEFAULT_LOW_BALANCE_WARN_USD,
533+
}
534+
}
535+
}
536+
500537
#[derive(Debug, Clone, Deserialize, Serialize)]
501538
#[serde(default)]
502539
pub struct ZaiConfig {
@@ -913,6 +950,21 @@ fn resolve_api_key_in_section(
913950
)))
914951
}
915952

953+
/// Resolve the OpenCode Zen scrape credentials: both fields are required and
954+
/// there is deliberately no env-var fallback (see [`OpenCodeZenConfig`]).
955+
pub fn resolve_opencode_zen(cfg: &OpenCodeZenConfig) -> crate::error::Result<(String, String)> {
956+
let workspace_id = cfg.workspace_id.trim();
957+
let auth_cookie = cfg.auth_cookie.trim();
958+
if workspace_id.is_empty() || auth_cookie.is_empty() {
959+
return Err(crate::error::AppError::Credentials(format!(
960+
"OpenCode Zen: set `workspace_id` (from the billing URL) and `auth_cookie` \
961+
(the opencode.ai session cookie) under [opencode-zen] in {}.",
962+
config_path_hint()
963+
)));
964+
}
965+
Ok((workspace_id.to_string(), auth_cookie.to_string()))
966+
}
967+
916968
fn is_valid_env_var_name(name: &str) -> bool {
917969
let mut chars = name.chars();
918970
let Some(first) = chars.next() else {
@@ -991,6 +1043,9 @@ impl Config {
9911043
.iter()
9921044
.map(|account| account.api_key.as_deref()),
9931045
)
1046+
.chain(std::iter::once(Some(
1047+
self.opencode_zen.auth_cookie.as_str(),
1048+
)))
9941049
.any(|key| key.is_some_and(|key| !key.is_empty()))
9951050
}
9961051

@@ -1037,6 +1092,7 @@ impl Config {
10371092
VendorId::Kiro => self.kiro.enabled,
10381093
VendorId::NousResearch => self.nous.enabled,
10391094
VendorId::OpenCodeGo => self.opencode_go.enabled,
1095+
VendorId::OpenCodeZen => self.opencode_zen.enabled,
10401096
}
10411097
}
10421098

@@ -1091,6 +1147,29 @@ impl Config {
10911147
"[supergrok] grok_binary must not be empty".into(),
10921148
));
10931149
}
1150+
if self.opencode_zen.enabled {
1151+
if self.opencode_zen.workspace_id.trim().is_empty() {
1152+
return Err(AppError::Other(
1153+
"[opencode-zen] enabled but workspace_id is empty — copy the id from \
1154+
your billing URL (opencode.ai/workspace/<id>/billing)"
1155+
.into(),
1156+
));
1157+
}
1158+
if self.opencode_zen.auth_cookie.trim().is_empty() {
1159+
return Err(AppError::Other(
1160+
"[opencode-zen] enabled but auth_cookie is empty — copy the `auth` \
1161+
cookie for opencode.ai from your browser (DevTools → Storage → Cookies)"
1162+
.into(),
1163+
));
1164+
}
1165+
}
1166+
if !self.opencode_zen.low_balance_warn_usd.is_finite()
1167+
|| self.opencode_zen.low_balance_warn_usd < 0.0
1168+
{
1169+
return Err(AppError::Other(
1170+
"[opencode-zen] low_balance_warn_usd must be finite and non-negative".into(),
1171+
));
1172+
}
10941173
let mut labels = HashSet::new();
10951174
for account in &self.anthropic.accounts {
10961175
validate_account_label(&account.label)?;

‎src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ pub mod nous;
3333
pub mod novita;
3434
pub mod openai;
3535
pub mod opencode_go;
36+
pub mod opencode_zen;
3637
pub mod openrouter;
3738
pub mod pacing;
3839
pub mod pango;

0 commit comments

Comments
 (0)