Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog/unreleased/codearts-credit-only.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
### English

- Huawei Cloud CodeArts (码道) now uses the credit-only model catalog: the retired free-benefit gateway is no longer queried and `maas_type: benefit` is never sent. Unknown model ids are rejected locally before a billable chat request, and daily check-in claims only campaigns the server marks eligible. The remote-image inlining behaviour is preserved.

### 中文

- 华为云码道改为仅使用积分模型目录:不再查询已下线的免费权益网关,也不再发送 `maas_type: benefit` 头。未知模型 ID 会在发送计费请求前本地拒绝,每日签到只领取服务端标记可领的活动。远程图片内联行为保持不变。
165 changes: 30 additions & 135 deletions internal/providers/codearts/catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,29 +27,25 @@ type modelRecord struct {
Reasoning []string
}

// fetchModels merges the three official sources for one account. A source that
// fails is skipped; only an empty merge is an error.
// fetchModels reads the account's currently billable models. Since 2026-10
// CodeArts has a single credit channel: /v1/model/builtin is authoritative.
// Agent-center records are kept only as a fallback for accounts where the
// builtin endpoint is temporarily unavailable. The retired benefit gateway is
// never queried and never advertised.
func (c *Client) fetchModels(ctx context.Context, accountID string) ([]providers.ModelInfo, map[string]bool, error) {
credential, err := c.credential(ctx, accountID)
if err != nil {
return nil, nil, err
}
merged := map[string]modelRecord{}
benefit := map[string]bool{}
if records, fetchErr := c.fetchAgentModels(ctx, accountID, credential); fetchErr == nil {
builtinOK := false
if records, fetchErr := c.fetchBuiltinModels(ctx, accountID, credential); fetchErr == nil && len(records) > 0 {
mergeRecords(merged, records)
builtinOK = true
}
if records, fetchErr := c.fetchBuiltinModels(ctx, accountID, credential); fetchErr == nil {
mergeRecords(merged, records)
}
// Benefit discovery is additive. A failed claim/config (the normal state
// for credit-only trial accounts) must not hide agent models: the same
// model works over the credit path without maas_type: benefit.
if records, fetchErr := c.fetchBenefitModels(ctx, accountID, credential); fetchErr == nil {
for _, record := range records {
record.Benefit = true
benefit[strings.ToLower(record.ID)] = true
mergeRecords(merged, []modelRecord{record})
if !builtinOK {
if records, fetchErr := c.fetchAgentModels(ctx, accountID, credential); fetchErr == nil {
mergeRecords(merged, records)
}
}
if len(merged) == 0 {
Expand Down Expand Up @@ -81,7 +77,9 @@ func (c *Client) fetchModels(ctx context.Context, accountID string) ([]providers
for _, record := range records {
models = append(models, toModelInfo(record))
}
return models, benefit, nil
// The retired benefit channel is always empty; the map is kept in the
// catalog signature for the existing cache/tests but never populated.
return models, map[string]bool{}, nil
}

// fetchThinkingVariants asks the PromptCenter endpoint for the reasoning
Expand Down Expand Up @@ -297,31 +295,33 @@ func cloneBoolMap(in map[string]bool) map[string]bool {
}

// canonicalModel returns the exact catalog spelling for a client-supplied id.
func (c *Client) canonicalModel(accountID, model string) string {
// A non-empty catalog is authoritative: every real call bills credits, so a
// guessed model name must fail instead of silently charging for a different
// model or hitting a dead channel.
func canonicalModel(models []providers.ModelInfo, model string) (string, bool) {
want := strings.ToLower(strings.TrimSpace(model))
if want == "" {
return ""
}
models, _, ok := c.cachedCatalog(accountID)
if !ok {
return model
return "", false
}
for _, info := range models {
if strings.ToLower(info.NativeModel) == want || strings.ToLower(info.PublicModel) == want {
return info.NativeModel
return info.NativeModel, true
}
}
return model
return "", false
}

// isBenefitModel reports whether the account's catalog routes this model
// through the limited-benefit gateway.
func (c *Client) isBenefitModel(accountID, model string) bool {
_, benefit, ok := c.cachedCatalog(accountID)
// displayModel is used only for response labels. It never changes the model id
// sent upstream; doChat performs the strict routing validation.
func (c *Client) displayModel(accountID, model string) string {
models, _, ok := c.cachedCatalog(accountID)
if !ok {
return false
return strings.TrimSpace(strings.TrimPrefix(model, "codearts/"))
}
if canonical, found := canonicalModel(models, model); found {
return canonical
}
return benefit[strings.ToLower(strings.TrimSpace(model))]
return strings.TrimSpace(strings.TrimPrefix(model, "codearts/"))
}

// fetchAgentModels reads the CodeAgent detail's gpts.models.
Expand Down Expand Up @@ -465,111 +465,6 @@ func (c *Client) fetchBuiltinModels(ctx context.Context, accountID string, crede
return records, nil
}

// fetchBenefitModels reads the limited-benefit gateway config and, matching the
// official client opening the model menu, claims the benefit idempotently.
func (c *Client) fetchBenefitModels(ctx context.Context, accountID string, credential Credential) ([]modelRecord, error) {
if err := c.claimBenefit(ctx, accountID, credential); err != nil {
// Match the official client: do not load benefit models when claim
// failed. The same model may still be callable over the credit path,
// and fetchModels keeps the agent/builtin records for that case.
return nil, err
}
requestCtx, cancel := context.WithTimeout(ctx, metadataTimeout)
defer cancel()
req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, c.benefitBase+benefitConfig, nil)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Language", Language)
signRequest(req, nil, credential.Sign())
client, err := c.httpClient(ctx, accountID)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if resp.StatusCode >= 400 {
return nil, newProviderError(resp.StatusCode, string(raw))
}
var out struct {
ErrorCode string `json:"error_code"`
Result struct {
Models []struct {
ModelID string `json:"model_id"`
ModelName string `json:"model_name"`
ModelDesc string `json:"model_desc"`
ContextWindow int64 `json:"context_window"`
MaxTokens int64 `json:"max_tokens"`
SupportsImages bool `json:"supports_images"`
} `json:"models"`
} `json:"result"`
}
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("parse codearts benefit config: %w", err)
}
if out.ErrorCode != "" && out.ErrorCode != "0000" {
return nil, fmt.Errorf("codearts benefit config error %s", out.ErrorCode)
}
records := make([]modelRecord, 0, len(out.Result.Models))
for _, model := range out.Result.Models {
id := firstNonEmpty(model.ModelID, model.ModelName)
if id == "" {
continue
}
records = append(records, modelRecord{
ID: id, Name: firstNonEmpty(model.ModelName, id), Description: model.ModelDesc,
ContextWindow: model.ContextWindow, MaxTokens: model.MaxTokens,
Images: model.SupportsImages, Benefit: true,
})
}
return records, nil
}

func (c *Client) claimBenefit(ctx context.Context, accountID string, credential Credential) error {
body := []byte("{}")
requestCtx, cancel := context.WithTimeout(ctx, metadataTimeout)
defer cancel()
req, err := http.NewRequestWithContext(requestCtx, http.MethodPost, c.benefitBase+benefitClaim, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("Agent-Type", "PromptCenter")
req.Header.Set("X-Language", Language)
signRequest(req, body, credential.Sign())
client, err := c.httpClient(ctx, accountID)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if resp.StatusCode >= 400 {
return newProviderError(resp.StatusCode, string(raw))
}
var envelope struct {
ErrorCode string `json:"error_code"`
ErrorMsg string `json:"error_msg"`
}
if err := json.Unmarshal(raw, &envelope); err != nil {
return fmt.Errorf("parse codearts benefit claim: %w", err)
}
if envelope.ErrorCode != "" && envelope.ErrorCode != "0000" {
return fmt.Errorf("codearts benefit claim error %s: %s", envelope.ErrorCode, envelope.ErrorMsg)
}
return nil
}

// signedGet sends a signed GET and returns the body.
func (c *Client) signedGet(ctx context.Context, accountID, endpoint string, credential Credential, agentCenter bool) ([]byte, error) {
requestCtx, cancel := context.WithTimeout(ctx, metadataTimeout)
Expand Down
44 changes: 30 additions & 14 deletions internal/providers/codearts/chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
Expand All @@ -30,7 +31,7 @@ func (c *Client) ChatStream(ctx context.Context, accountID string, req translate
return nil, providers.ResolvedChat{}, err
}
pr, pw := io.Pipe()
model := c.canonicalModel(accountID, req.Model)
model := c.displayModel(accountID, req.Model)
go func() {
defer upstream.Body.Close()
defer pw.Close()
Expand Down Expand Up @@ -66,7 +67,7 @@ func (c *Client) ChatNonStream(ctx context.Context, accountID string, req transl
return providers.ChatOutcome{}, err
}
outcome := providers.ChatOutcome{
Model: c.canonicalModel(accountID, req.Model),
Model: c.displayModel(accountID, req.Model),
Content: completion.Content,
Reasoning: completion.Reasoning,
FinishReason: completion.Finish,
Expand Down Expand Up @@ -104,11 +105,13 @@ func (c *Client) doChat(ctx context.Context, accountID string, req translate.Cha
if err != nil {
return nil, "", err
}
if _, _, ok := c.cachedCatalog(accountID); !ok {
// The benefit header and exact model spelling depend on the account
// catalog. A failed discovery is not fatal: chat still carries the
// client's model id and the upstream will answer with a clear error.
models, _, catalogOK := c.cachedCatalog(accountID)
if !catalogOK {
// The exact model spelling depends on the account catalog. A failed
// discovery is not fatal: chat still carries the client's model id and
// the upstream will answer with a clear error.
_, _ = c.Models(ctx, accountID)
models, _, catalogOK = c.cachedCatalog(accountID)
}
model := strings.TrimSpace(req.Model)
model = strings.TrimPrefix(model, "codearts/")
Expand All @@ -119,20 +122,34 @@ func (c *Client) doChat(ctx context.Context, accountID string, req translate.Cha
Message: "codearts model is required",
}
}
model = c.canonicalModel(accountID, model)
if catalogOK && len(models) > 0 {
canonical, found := canonicalModel(models, model)
if !found {
return nil, "", &providers.Error{
Kind: accounts.KindModelNotAvailable,
Status: http.StatusNotFound,
Message: fmt.Sprintf("codearts model %q is not available for this account", model),
}
}
model = canonical
} else {
model = strings.TrimSpace(model)
}
// Inline remote image URLs as data URLs before the billable call, matching
// the official client (kept from upstream #548).
if err := c.inlineMessageImages(ctx, accountID, req.Messages); err != nil {
return nil, "", err
}
level, caps := c.resolveLevel(ctx, accountID, model, requestedLevel(req))
body, err := buildChatBody(req, model, level, caps.Images, c.isBenefitModel(accountID, model))
body, err := buildChatBody(req, model, level, caps.Images)
if err != nil {
return nil, "", err
}
raw, err := json.Marshal(body)
if err != nil {
return nil, "", err
}
resp, err := c.sendChat(ctx, accountID, credential, raw, model, c.isBenefitModel(accountID, model))
resp, err := c.sendChat(ctx, accountID, credential, raw, model)
if err != nil {
return nil, "", err
}
Expand All @@ -147,7 +164,7 @@ func (c *Client) doChat(ctx context.Context, accountID string, req translate.Cha
if refreshErr != nil {
return nil, "", refreshErr
}
resp, err = c.sendChat(ctx, accountID, refreshed, raw, model, c.isBenefitModel(accountID, model))
resp, err = c.sendChat(ctx, accountID, refreshed, raw, model)
if err != nil {
return nil, "", err
}
Expand All @@ -165,7 +182,7 @@ func (c *Client) doChat(ctx context.Context, accountID string, req translate.Cha
}

// sendChat performs the signed request and enforces the TTFB deadline.
func (c *Client) sendChat(ctx context.Context, accountID string, credential Credential, body []byte, model string, benefit bool) (*http.Response, error) {
func (c *Client) sendChat(ctx context.Context, accountID string, credential Credential, body []byte, model string) (*http.Response, error) {
base := c.apiBase(credential)
requestCtx, cancel := context.WithCancel(ctx)
req, err := http.NewRequestWithContext(requestCtx, http.MethodPost, base+chatPath, bytes.NewReader(body))
Expand All @@ -180,9 +197,8 @@ func (c *Client) sendChat(ctx context.Context, accountID string, credential Cred
req.Header.Set("X-Language", Language)
req.Header.Set("app-id", AppID)
req.Header.Set("is_confidential", "false")
if benefit {
req.Header.Set(HeaderMaasType, MaasBenefit)
}
// CodeArts removed the limited free benefit channel in 2026-10. Every
// model now bills through the credit path, so never send maas_type.
signRequest(req, body, credential.Sign())
// Tip headers after sign so they stay out of SignedHeaders (hub #723 / tip 28527f4).
applyOTSessionHeaders(req.Header, credential.UserID)
Expand Down
24 changes: 9 additions & 15 deletions internal/providers/codearts/checkin.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,10 @@ func (c *Client) Checkin(ctx context.Context, accountID string) (providers.Check
total := 0.0
allOK := true
for _, campaign := range campaigns {
if campaign.ID != 1 && campaign.ID != 4 {
continue
}
if campaign.BenefitUnit != "" && campaign.BenefitUnit != "CREDIT" {
// The server marks the activities an account may actually claim. Only
// time-triggered credit rewards are automatic: student verification and
// invite campaigns are never claimed on the user's behalf.
if !campaign.Claimable || campaign.BenefitUnit != "" && campaign.BenefitUnit != "CREDIT" {
continue
}
claim := c.claimCampaign(ctx, accountID, credential, campaign)
Expand Down Expand Up @@ -115,11 +115,6 @@ func (c *Client) claimCampaign(ctx context.Context, accountID string, credential
case "CLAIMED":
// Already delivered; only the confirm step may be missing.
case "ELIGIBLE":
if !campaign.Claimable {
claim.OK = false
claim.Message = "not claimable yet"
return claim
}
if _, err := c.creditRequest(ctx, accountID, credential, http.MethodPost, creditClaimPath, map[string]any{
"campaignId": campaign.ID, "channel": creditChannel,
"idempotentKey": fmt.Sprintf("claim_%d_%d", campaign.ID, now.UnixMilli()),
Expand All @@ -141,15 +136,14 @@ func (c *Client) claimCampaign(ctx context.Context, accountID string, credential
claim.Message = "unknown campaign status: " + campaign.Status
return claim
}
if _, err := c.creditRequest(ctx, accountID, credential, http.MethodPost, creditConfirmPath, map[string]any{"campaignId": campaign.ID}); err != nil {
claim.OK = false
claim.Message = "claimed but confirmation failed: " + err.Error()
return claim
}
// The current ops API has no confirm step: a successful claim is final.
// Older builds polled /v1/ops/confirm, which now just returns 404 and made
// successful daily check-ins look like failures.
claim.Status = "CONFIRMED"
claim.Message = "confirmed"
if claim.Credits > 0 {
claim.Message = fmt.Sprintf("claimed %g credits", claim.Credits)
} else {
claim.Message = "claimed"
}
return claim
}
Expand Down
Loading
Loading