Skip to content

Support Qwen Cloud personal token plan, and unblock Alibaba Token Plan on Linux#2329

Open
Yach0 wants to merge 2 commits into
steipete:mainfrom
Yach0:qwen-personal-token-plan
Open

Support Qwen Cloud personal token plan, and unblock Alibaba Token Plan on Linux#2329
Yach0 wants to merge 2 commits into
steipete:mainfrom
Yach0:qwen-personal-token-plan

Conversation

@Yach0

@Yach0 Yach0 commented Jul 19, 2026

Copy link
Copy Markdown

Closes #2328.

Adds support for the Qwen Cloud personal/solo token plan, and unblocks the provider on Linux.

Why this isn't just a new region string

The existing alibabatokenplan provider targets the Team Edition (GetSubscriptionSummary,
product=BssOpenAPI-V3) and models a monthly credit pool. The personal plan on
home.qwencloud.com is a different product end to end: different console, different gateway host,
a REST path tunneled through a generic ASPN action, and rolling 5-hour + weekly windows rather
than a credit pool — i.e. the same shape as Claude/Codex.

POST https://cs-data.qwencloud.com/data/api.json
  ?product=sfm_bailian&action=IntlBroadScopeAspnGateway
  &api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/{usage,subscription,quota-config}

Payloads nest at data.DataV2.data.data:

  • usageper5HourPercentage / per1WeekPercentage (fractions of 1.0) plus reset times in
    epoch ms. Required.
  • subscriptionspecCode (lite/standard/pro), status. Best-effort.
  • quota-config — per-tier five_hour / weekly ceilings, joined on specCode to convert the
    percentages into credit counts. Best-effort, and skipped entirely when no tier is known.

sec_token resolves from GET https://home.qwencloud.com/tool/user/info.json — the same
/tool/user/info.json path the team edition already uses, so the existing resolver is reused as is
and cookies alone are sufficient.

Changes

  • New qwen region covering that gateway, with quotaAPIBaseURLString split from the console
    host (Qwen serves them separately) and tokenPlanProductCode made optional since the personal
    gateway takes none.
  • AlibabaTokenPlanPersonalAPI — request builders and parsers for the three endpoints.
  • Quota shape modelled as an enum (creditPool / rollingWindows) instead of four nullable
    fields, so the combinations that were never valid are now unrepresentable. The creditPool path
    is behaviourally identical to before.
  • performGatewayRequest extracted so both editions share the cookie / sec_token / redirect
    machinery. Usage is required; the two enrichment calls are best-effort and cannot abort a
    fetch that already has valid data.
  • Linux gate: exempt the provider from the macOS web-support requirement when cookies are
    configured manually, matching the existing qoder / opencodego / commandcode /
    cursor precedent. The quota fetch is plain URLSession + cookies — only browser cookie
    import needs macOS, so the provider was unreachable on Linux for no reason.

Drive-by fix

URLComponents.percentEncodedQuery leaves + literal, and an
application/x-www-form-urlencoded reader decodes it as a space — so a sec_token containing +
was silently corrupted. This affected the existing team edition too; both body builders now go
through a shared formEncodedBody that escapes it.

Notes / limitations

  • region: "qwen" is manual-cookie only on every platform. Qwen Cloud logs in under its own
    domain with its own ticket cookie (login_qwencloud_ticket), which the shared Alibaba browser
    importer's authentication gate does not recognise. Rather than widen that shared importer — which
    would have leaked qwencloud cookies into the Alibaba Coding Plan's unscoped request header —
    auto-import is rejected up front with a message pointing at the console. Documented in
    docs/alibaba-token-plan.md.
  • Stale sessions return HTTP 200 with an error code in the body, so failures are classified through
    the existing isLoginOrTokenError / isLikelyLoginHTML detectors. Without that they surface as
    .apiError, which is not an isCredentialFailure, and the cookie re-import retry never fires.
  • The window labels still come from static ProviderMetadata (sessionLabel: "Credits",
    weeklyLabel: "Usage"). Those fit the team edition's credit pool but read oddly for 5-hour /
    weekly windows, where "Session" / "Weekly" would be right. Making them region-aware needs
    settings plumbed into metadata resolution, so I left it alone rather than guess at the shape you'd
    want — happy to follow up.
  • API keys are inference-only and cannot report quota: an sk-sp-* key against
    token-plan.ap-southeast-1.maas.aliyuncs.com routes only /compatible-mode/v1/*,
    /apps/anthropic/v1/messages and /api/v1/services/aigc/*; every billing path 404s unrouted,
    successful responses carry no rate-limit headers, and posting the key to the console gateway
    returns ConsoleNeedLogin. Cookie auth is the only option. Recorded in the docs so it isn't
    re-investigated.

Testing

  • swift test309 tests, all passing (Linux). 33 new cases covering the three payload
    parsers, envelope/error classification at every level, cookie scoping, the + encoding, region
    wiring, and the platform gate.
  • Verified end to end on Fedora against a live personal token plan: percentages match the console
    API exactly, and both windows independently agree on absolute credits consumed
    (34.778% × 700 == 9.738% × 2500), which only holds if the tier ceilings are paired with the
    right percentages.
  • Includes regression guards asserting the intl/cn cookie scoping is unchanged.

Not verified: macOS UI/menu rendering and browser cookie import (no macOS machine available), and
the team-edition live path (no team account). Both are untouched by this change beyond the shared
formEncodedBody fix.

Note: swift build -c release crashes the Swift 6.3.2 optimizer on Fedora
(CLICacheCommand.swift, signal 6). I confirmed this reproduces on unmodified main, so it is
unrelated to this PR — debug builds and the full test suite are fine.

The Qwen Cloud personal ("solo") token plan is a different product from the
team edition already supported: it lives on home.qwencloud.com, posts to a
separate gateway host, tunnels a REST path through the generic ASPN action,
and reports rolling 5-hour/weekly windows instead of a monthly credit pool.

Add a qwen region covering that gateway, and model the two quota shapes as an
enum so the invalid mixes of the previous optional fields are unrepresentable.

Also exempt the provider from the macOS web-support gate when cookies are
supplied manually, matching qoder/opencodego/commandcode. The quota fetch is
plain URLSession plus cookies; only browser cookie import needs macOS, so the
provider was unreachable on Linux for no reason.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 73ebb460e5

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +716 to +717
if provider == .alibabatokenplan,
settings?.alibabaTokenPlan?.cookieSource == .manual

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Include ALIBABA_TOKEN_PLAN_COOKIE in Linux bypass

This bypass only covers config snapshots where cookieSource == .manual, but the provider also supports a manually supplied cookie via ALIBABA_TOKEN_PLAN_COOKIE in AlibabaTokenPlanWebFetchStrategy.resolveCookieHeaders. On Linux, a user who sets that existing env var while leaving the config at the default auto mode is still stopped by this gate before the strategy can read the cookie, so the provider remains unusable in that manual-cookie setup; add the same env-cookie check here that other providers such as Sakana use.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch — fixed in b1efecb.

You are right that resolveCookieHeaders reads ALIBABA_TOKEN_PLAN_COOKIE independently of cookieSource, so gating only on cookieSource == .manual blocked a setup that would otherwise have worked. The gate now also opens on the env cookie, mirroring the Sakana check:

if provider == .alibabatokenplan,
   settings?.alibabaTokenPlan?.cookieSource == .manual ||
   environment.map({ AlibabaTokenPlanSettingsReader.cookieHeader(environment: $0) != nil }) == true
{
    return false
}

Since cookieHeader(environment:) goes through cleaned(...), a blank or whitespace-only value still leaves the gate closed rather than letting the provider through to fail later.

Verified on Linux with the config left at the default auto mode:

  • no env var → selected source requires web support and is only supported on macOS (unchanged)
  • ALIBABA_TOKEN_PLAN_COOKIE=... → real usage returned

Added three cases for it (env-only opens the gate, whitespace-only does not, browser-import still gated). Suite is at 311 passing.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

done

The env cookie is honored regardless of the configured cookie source, so a
user setting only that variable was still blocked before the strategy could
read it. Mirrors the existing Sakana env-cookie check.
@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. labels Jul 19, 2026
@clawsweeper

clawsweeper Bot commented Jul 19, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge. Reviewed July 19, 2026, 11:12 AM ET / 15:12 UTC.

Summary
The branch adds Qwen Cloud personal Token Plan usage fetching, permits manual-cookie Alibaba Token Plan access on Linux, and shares request handling with the existing team-plan provider.

Reproducibility: yes. for the Linux gate at source level: the added condition shows that manual cookies and ALIBABA_TOKEN_PLAN_COOKIE were previously rejected before fetching. The Qwen live gateway path is claimed by the contributor but lacks inspectable after-fix output.

Review metrics: 1 noteworthy metric.

  • Patch scope: 13 files affected; 1,005 added and 88 removed. The change spans CLI gating, provider transport, data modeling, tests, and setup documentation, so integration and compatibility review matter more than parser tests alone.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #2328
Summary: This PR is the candidate implementation for the linked Qwen personal-plan and Linux-gate report.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🐚 platinum hermit
Result: blocked until real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add a redacted terminal screenshot, copied live output, or log showing successful Qwen personal-plan retrieval and both rolling windows; remove cookies and other private values.
  • Obtain maintainer confirmation that manual Cookie-header setup is an acceptable supported Qwen workflow.
  • [P1] Preserve the prior public snapshot source API or document and approve the intentional compatibility break.

Proof guidance:

  • [P1] Needs real behavior proof before merge: The PR describes a successful Fedora live run but provides no inspectable redacted terminal transcript, log, recording, or linked artifact showing the changed Qwen gateway behavior after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Risk before merge

  • [P1] The refactor removes the existing public AlibabaTokenPlanUsageSnapshot fields and initializer; any external or cross-target source callers not updated in this branch will fail to compile.
  • [P1] Qwen personal-plan access is intentionally manual-cookie-only, so maintainers need to decide whether DevTools cookie export is an acceptable supported setup path.
  • [P1] The reported Fedora success has no inspectable redacted runtime artifact, leaving the end-to-end cookie, gateway, and window-rendering path unverified for reviewers.

Maintainer options:

  1. Preserve snapshot source compatibility (recommended)
    Keep deprecated computed accessors and a compatibility initializer over the new quota enum, or add focused evidence that CodexBarCore has no supported downstream API callers.
  2. Accept an intentional API break
    Allow the public snapshot API removal only after maintainers explicitly confirm that this module is internal-only and no compatibility promise applies.

Next step before merge

  • [P1] A maintainer must approve the manual-cookie-only product path, and the contributor must supply inspectable real behavior proof before merge.

Maintainer decision needed

  • Question: Should CodexBar officially support Qwen Cloud personal Token Plan as an Alibaba Token Plan region when setup requires users to manually export a browser Cookie header on every platform?
  • Rationale: This is a new provider mode and configuration value, and the PR deliberately declines browser import because Qwen authentication and cookie scope differ from the existing Alibaba flow.
  • Likely owner: steipete — Repository ownership and the new supported authentication workflow make this a product-direction decision.
  • Options:
    • Approve the manual-cookie region (recommended): Treat the documented manual Cookie-header flow as supported, subject to runtime proof and public API compatibility handling.
    • Defer Qwen personal-plan support: Keep the existing team-plan-only provider until a lower-friction and explicitly supported authentication flow is available.

Security
Cleared: The diff adds no dependency, workflow, installer, package-resolution, or secret-permission change; the new fixed Qwen endpoints and cookie handling are within the stated provider integration scope.

Review details

Best possible solution:

If the manual-cookie Qwen workflow is approved, retain or deliberately deprecate the prior public snapshot surface, keep browser import disabled, and land the feature with a redacted Fedora live-run transcript proving both rolling windows.

Do we have a high-confidence way to reproduce the issue?

Yes for the Linux gate at source level: the added condition shows that manual cookies and ALIBABA_TOKEN_PLAN_COOKIE were previously rejected before fetching. The Qwen live gateway path is claimed by the contributor but lacks inspectable after-fix output.

Is this the best way to solve the issue?

Unclear. Reusing the provider and sharing transport logic is a narrow implementation, but accepting a manual-cookie-only Qwen region and removing the prior public snapshot API both need explicit compatibility and product confirmation.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 76772d7d60a5.

Label changes

Label changes:

  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR describes a successful Fedora live run but provides no inspectable redacted terminal transcript, log, recording, or linked artifact showing the changed Qwen gateway behavior after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
  • remove proof: sufficient: Current real behavior proof status is missing, not sufficient.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: 📣 needs proof.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🧂 unranked krab, so this older rating label is no longer current.

Label justifications:

  • P2: This adds a bounded provider capability and fixes a Linux access path, but it is not an urgent regression in an existing default workflow.
  • merge-risk: 🚨 compatibility: The patch replaces public AlibabaTokenPlanUsageSnapshot fields and initializer with a new enum-based API, which may break existing source callers.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs real behavior proof before merge: The PR describes a successful Fedora live run but provides no inspectable redacted terminal transcript, log, recording, or linked artifact showing the changed Qwen gateway behavior after the fix. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

What I checked:

  • Linked implementation candidate: The PR explicitly closes the canonical report and adds the separate Qwen gateway, rolling-window parser, and Linux manual-cookie gate described there. (Sources/CodexBarCore/Providers/Alibaba/AlibabaTokenPlanPersonalAPI.swift:1, b1efecbdb08f)
  • Provider model compatibility: The patch replaces the public used/total/remaining/reset fields and initializer on AlibabaTokenPlanUsageSnapshot with a public quota enum, which can break source callers outside the updated in-repository call sites. (Sources/CodexBarCore/Providers/Alibaba/AlibabaTokenPlanUsageSnapshot.swift:30, b1efecbdb08f)
  • Runtime proof gap: The PR body reports a successful Fedora live run and arithmetic cross-check, but the supplied PR material contains no redacted terminal output, log, recording, or linked artifact that reviewers can inspect as after-fix evidence. (b1efecbdb08f)
  • Canonical issue relationship: The linked issue remains open and describes the same Qwen API shape and Linux gate; this PR is its candidate implementation and should not be treated as a duplicate.

Likely related people:

  • steipete: The change adds a supported provider mode and a user-facing configuration value, so acceptance of the manual-cookie-only workflow needs repository-owner product direction. (role: repository owner and likely product-direction owner; confidence: medium; files: Sources/CodexBarCore/Providers/Alibaba/AlibabaTokenPlanProviderDescriptor.swift, docs/alibaba-token-plan.md)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (1 earlier review cycle)
  • reviewed 2026-07-19T13:02:04.021Z sha b1efecb :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Qwen Cloud Token Plan (Personal/Solo) uses a different API than the Team-edition provider, and Linux gating blocks it

1 participant