Skip to content

feat(alibaba): read Token Plan quota from the official CLI - #269

Open
lucasrochaqw wants to merge 3 commits into
slkiser:mainfrom
lucasrochaqw:feat/alibaba-token-plan-cli
Open

feat(alibaba): read Token Plan quota from the official CLI#269
lucasrochaqw wants to merge 3 commits into
slkiser:mainfrom
lucasrochaqw:feat/alibaba-token-plan-cli

Conversation

@lucasrochaqw

Copy link
Copy Markdown

Summary

Extend the existing Alibaba provider with real Token Plan quota from the official bailian-cli, retaining the Coding Plan request estimate only as an explicitly distinct fallback.

  • Prefer bl usage token-plan --output json with configurable console region/site and binary path. Document the Singapore/international invocation and explicit console login.
  • Parse the CLI's used fractions (0..1) into shared remaining-percentage rows, convert epoch-millisecond reset times, and support weekly-only reports without inventing a five-hour allowance.
  • Recognize the alibaba-token-plan runtime ID and configuration alias while retaining the canonical alibaba-coding-plan provider ID. No new slash command, model API calls, or token-count approximation.
  • Share bounded subprocess execution with the existing Anthropic implementation while preserving its behavior. Alibaba never uses the Windows shell bridge, has forced subprocess termination, bounded output, TTL caching and TTL-independent in-flight deduplication.
  • Emit only fixed safe failure messages and allowlisted diagnostics (alibaba-cli / local-estimate), never arbitrary subprocess stdout/stderr, error messages, binary paths or console credentials.
  • Keep successful CLI probing independent of Coding Plan credential/counter reads. Preserve existing Coding Plan auth sources, tiers, counters and configured request limits on fallback.
  • Update accounting metadata/ledger, provider registration, runtime config propagation, status allowlists, docs and tests.

Linked Issue

Refs #268

The official CLI exposes the console quota source, so the issue's no-endpoint/local-token-estimate alternative is unnecessary here. The CLI contract uses quota fractions; the official console describes its allowance as Credits, not raw token counts. Tests use explicitly synthetic fixtures matching CLI 1.22.0, not captured account data.

Cache and Scope

  • Console authentication is unrelated to the Coding Plan API key. This provider now uses the established uncached/process-local policy rather than persisting real console quota under an unrelated credential identity.
  • Live /quota, status diagnostics, sidebar, compact status, toasts and CLI show consume the same rows. The running TUI's configured JSON export can use its own latest snapshot.
  • show --json remains cache-only by design. A separate CLI process reports Alibaba as unavailable, and threshold mode returns 2, rather than silently fetching live data or reading another account's snapshot. This also means Coding Plan fallback snapshots are no longer durable for this provider. No JSON schema or public export API changes.
  • A Token Plan model API key alone is not sufficient for console quota: users must explicitly authenticate bl with console login. Token Plan credentials/traffic are deliberately not relabeled as Coding Plan request allowances.
  • The alibaba-token-plan-cn runtime is explicitly out of scope pending validation. Windows .cmd/.bat wrappers are not bridged through a shell; a native executable or WSL is required.
  • After changing the CLI's active console account, restart OpenCode or let the 30-second process-local probe cache expire. The plugin never opens a browser or reads/stores console credentials.

OpenCode Validation

  • Installed OpenCode version: 1.18.30, matching the issue's reported version. This branch was not installed into or substituted for the user's running OpenCode plugin.
  • Linux, Node 22.23.1, pnpm 11.0.0, official CLI 1.22.0.
  • Bounded authenticated live command succeeded with --console-region ap-southeast-1 --console-site international --output json; it returned weekly-only quota.
  • The compiled provider independently succeeded with alibaba_quota_source=alibaba-cli, detected version 1.22.0, and produced the expected remaining percentage/reset conversion. No raw credential/error payloads were printed or committed.
  • Automated coverage verifies provider fallback/matching, four-surface rendering and used/remaining direction, CLI show/cache-only JSON, status allowlisting, config validation, cache persistence policy, malformed/no-data responses, missing/auth/network/timeout failures, output bounds and secret sentinel non-disclosure.
  • Manual interactive OpenCode UI verification and native Windows live probing remain unperformed; shared command/TUI/toast boundary and four-surface integration suites pass.

Quality Checklist

  • pnpm verify passed, including typecheck, build, privacy/history, full tests, four-surface parity and package contents.
  • Full suite: 190 files passed, 2,337 tests passed, 1 pre-existing skipped test.
  • Focused four-surface gate: 4 tests passed.
  • All 65 Anthropic tests pass after shared subprocess extraction.
  • Lefthook pre-commit and pre-push hooks ran without bypasses; pre-push reran canonical verification successfully.
  • Updated user-facing provider/configuration/troubleshooting documentation and matching README ledger rows.
  • Provider guidance reviewed. This extends an existing built-in provider with CLI-owned console authentication; the API-key provider template is not applicable to that source.

The repository's existing non-fatal Biome warnings, known TypeScript peer mismatch and JSX/SQLite warnings remain visible; no quality gates were weakened.

@lucasrochaqw

Copy link
Copy Markdown
Author
image

@niheaven

Copy link
Copy Markdown
Contributor

I've made a similar fix for team plan, but it needs cookie to work. bl doesn't support team plan now, right?

image

Detected provider ids are canonical, but OpenCode authenticates providers
under runtime ids (auth.json keys). Declaring the canonical id while a
runtime alias (e.g. alibaba-token-plan) is authenticated left a phantom
provider entry next to the real one in the model picker.

Resolve the declaration key against authenticated auth.json ids, preferring
catalog order (canonical, runtime ids, synonyms), falling back to the
canonical id when nothing is authenticated. The already-declared check keeps
accepting aliases, so existing fixed configs see no churn.
@lucasrochaqw

Copy link
Copy Markdown
Author

@niheaven
Based on what I could verify, that's my understanding as well. I tested this PR with bailian-cli 1.22.0 on a Personal Token Plan account, where bl usage token-plan returned the weekly quota. I haven't found or tested evidence that it exposes the Team Edition subscription or credit pool yet.

Your Team Plan implementation may be complementary. Could you share the branch or PR, including the GetSubscriptionSummary response shape?

If the CLI indeed does not expose Team usage, we could consider keeping it as the preferred source for Personal Token Plan and adding an explicit, opt-in cookie-based source for Team Edition. We would need to review cookie storage, expiration, account binding, endpoint stability, and ensure credentials or raw responses are never logged or persisted by the plugin.

@niheaven

Copy link
Copy Markdown
Contributor

@lucasrochaqw Please look at the branch in my fork:
https://github.com/niheaven/opencode-quota/tree/add-alibaba-token-plan

It needs an alibaba-token-plan.json in ~/.config/opencode/opencode-quota with

{
	"sec_token": "XXXX",
	"login_ticket": "XXXX",
	"account": ["XXXX"] # optional to filter account
}

sec_token is extracted from the request body, while login_ticket comes from the login_aliyunid_ticket cookie in the request headers. Both are obtained from the api.json request made by the Aliyun console.

This method has been tested on the China endpoint for about three weeks. The international endpoint hasn't been tested yet, though it should work the same way.

The tokens are likely valid for several hours, but I haven't verified the exact expiration time.

@lucasrochaqw

Copy link
Copy Markdown
Author

@niheaven Thanks for sharing the implementation. One useful next step would be to test bl usage token-plan against your Team account, using the matching console site and region, and check whether it returns the Team allowance. That would help confirm whether the CLI is missing Team support or exposes a different quota.

Would you be interested in opening a PR from your branch? My suggestion would be to keep #269 focused on the CLI integration and coordinate the Team support as a complementary change.

@slkiser We should also align provider registration before combining the implementations: #269 treats alibaba-token-plan as an alias, while niheaven's branch introduces it as a dedicated provider. We should make source selection explicit enough to distinguish Personal quota from Team seat credits.

@niheaven

Copy link
Copy Markdown
Contributor

bl doesn't work for Team plan, and it said there's no limit for my plan (it's right, I've only monthly quota, not weekly one).

So it must use the cookie to extract quota from console now, and the expiration is long enough (maybe six or eight hours) for the method.

…expires

`bl auth status` reports `authenticated: true` from token presence alone, while
`bl usage token-plan` fails with exit 3 once the console session lapses. Because
availability required an authenticated CLI or a Coding Plan credential, the
provider disappeared from every quota surface as "Unavailable (not detected)"
with no actionable reason.

Treat any Alibaba credential in auth.json (including the alibaba-token-plan
runtime id) as a presence signal so the provider stays visible, and surface the
CLI's fixed safe message as an error. Timeouts and network faults stay
retryable. Presence never grants a Coding Plan request allowance, so the local
estimate fallback and its labels are unchanged. Adds alibaba_runtime_auth to the
status allowlist to separate configured-but-failing from unconfigured.
@lucasrochaqw

Copy link
Copy Markdown
Author

@niheaven Thanks, that helps confirm the behavior.

A couple of notes from my side:

After the latest commit (9a4396d), if the CLI probe fails or returns no quota windows, the provider now stays visible with a clear message instead of disappearing. That should make the fallback to a Team-specific source easier to understand.

I saw similar behavior with the console session expiring after a few hours while bl auth status still reports the token as present. So documenting the cookie re-auth flow will probably be important.

The main open point seems to be provider registration.

This PR currently treats alibaba-token-plan as an alias of alibaba-coding-plan, while your branch registers alibaba-token-plan / alibaba-token-plan-cn separately.

@slkiser, once you decide which direction you prefer, I can adjust #269 so both implementations coexist cleanly without overlapping.

@niheaven, do you prefer to open a separate PR for the Team cookie-based implementation, or would you rather have me use your branch as a reference and integrate that path into #269?

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.

2 participants