diff --git a/changelog/unreleased/codearts-credit-only.md b/changelog/unreleased/codearts-credit-only.md new file mode 100644 index 00000000..86157ac2 --- /dev/null +++ b/changelog/unreleased/codearts-credit-only.md @@ -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 会在发送计费请求前本地拒绝,每日签到只领取服务端标记可领的活动。远程图片内联行为保持不变。 diff --git a/internal/providers/codearts/catalog.go b/internal/providers/codearts/catalog.go index f1ebc144..740a3234 100644 --- a/internal/providers/codearts/catalog.go +++ b/internal/providers/codearts/catalog.go @@ -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 { @@ -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 @@ -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. @@ -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) diff --git a/internal/providers/codearts/chat.go b/internal/providers/codearts/chat.go index 4f9187a4..d299faa5 100644 --- a/internal/providers/codearts/chat.go +++ b/internal/providers/codearts/chat.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "fmt" "io" "net/http" "strings" @@ -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() @@ -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, @@ -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/") @@ -119,12 +122,26 @@ 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 } @@ -132,7 +149,7 @@ func (c *Client) doChat(ctx context.Context, accountID string, req translate.Cha 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 } @@ -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 } @@ -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)) @@ -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) diff --git a/internal/providers/codearts/checkin.go b/internal/providers/codearts/checkin.go index 56daa74e..6b0af9e1 100644 --- a/internal/providers/codearts/checkin.go +++ b/internal/providers/codearts/checkin.go @@ -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) @@ -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()), @@ -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 } diff --git a/internal/providers/codearts/codearts_test.go b/internal/providers/codearts/codearts_test.go index 7bbd396e..81439e56 100644 --- a/internal/providers/codearts/codearts_test.go +++ b/internal/providers/codearts/codearts_test.go @@ -98,6 +98,16 @@ func newTestClient(t *testing.T, server *httptest.Server) (*Client, *memoryStore return client, store } +func TestCanonicalModelRejectsUnknownModel(t *testing.T) { + models := []providers.ModelInfo{{NativeModel: "GLM-5.2", PublicModel: "GLM-5.2"}} + if got, ok := canonicalModel(models, "glm-5.2"); !ok || got != "GLM-5.2" { + t.Fatalf("canonicalModel = %q, %v", got, ok) + } + if _, ok := canonicalModel(models, "not-a-model"); ok { + t.Fatal("unknown model accepted") + } +} + func TestValidateCredential(t *testing.T) { valid, _ := testCredential().Encode() if err := ValidateCredential(valid); err != nil { @@ -318,7 +328,7 @@ func TestResolveMaxReasoningHonorsRequestedLevel(t *testing.T) { } body, err := buildChatBody(translate.ChatRequest{ Model: "GLM-5.2", Messages: []translate.ChatMessage{{Role: "user", Content: "hi"}}, - }, "GLM-5.2", level, caps.Images, false) + }, "GLM-5.2", level, caps.Images) if err != nil { t.Fatal(err) } @@ -416,10 +426,6 @@ func TestModelsAndQuota(t *testing.T) { _, _ = io.WriteString(w, `{"builtinModels":[{"model_id":"GLM-5.2","model_name":"GLM-5.2","context_window":200000,"max_tokens":131072}]}`) case "/v1/agent-center/agents/useragents": http.NotFound(w, r) - case "/api/v1/benefit/claim": - _, _ = io.WriteString(w, `{"error_code":"0000"}`) - case "/api/v1/gateway/config": - _, _ = io.WriteString(w, `{"error_code":"0000","result":{"models":[{"model_id":"glm-5.3-flash","context_window":1048576,"max_tokens":393216}]}}`) case statisticsPath: _, _ = io.WriteString(w, `{"end_date":"2026-12-31","package":{"spec_code":"free","package_name_en":"Free"},"metrics":[{"name":"usageTotalPackageCredit","show":true,"package_credit_amount":500,"package_credit_used":100,"package_credit_remain":400,"value":20},{"name":"usageTokenChatMessages","show":true,"usage_token_num":1000,"package_token_amount":10000,"value":10}]}`) default: @@ -433,7 +439,7 @@ func TestModelsAndQuota(t *testing.T) { if err != nil { t.Fatalf("Models: %v", err) } - if len(models) != 2 { + if len(models) != 1 { t.Fatalf("models = %+v", models) } found := false @@ -448,9 +454,6 @@ func TestModelsAndQuota(t *testing.T) { if !found { t.Fatal("GLM-5.2 missing") } - if !client.isBenefitModel("acct-1", "glm-5.3-flash") { - t.Fatal("benefit model not marked") - } quota, err := client.Quota(context.Background(), "acct-1") if err != nil { t.Fatalf("Quota: %v", err) diff --git a/internal/providers/codearts/doc.go b/internal/providers/codearts/doc.go index c658c1e8..1e02cdf0 100644 --- a/internal/providers/codearts/doc.go +++ b/internal/providers/codearts/doc.go @@ -47,19 +47,18 @@ // // # Catalog and quota // -// The catalog is per account and merges three upstream sources: the CodeAgent -// detail's gpts.models, GET /v1/model/builtin (Agent-Type: PromptCenter), and -// the limited-benefit gateway config. Each record declares its exact model id -// plus context/output limits; those declarations are the only capability -// source. The adapter declares tools because the chat endpoint natively -// accepts them, and forwards image_url content parts for models whose catalog -// entry advertises supports_images. A text-only model rejects image input with -// a 400 instead of silently dropping it. GET /v1/model/thinking-variants -// supplies each model's allowed reasoning strengths; the adapter exposes them -// as ReasoningOptions and forwards the selected level as reasoning_effort. -// Benefits models are marked and routed with maas_type: benefit; the adapter -// claims the benefit idempotently while discovering the catalog, mirroring the -// official client opening its model menu. +// The catalog is per account. Since 2026-10 CodeArts has a single credit +// channel: GET /v1/model/builtin (Agent-Type: PromptCenter) is authoritative, +// with the CodeAgent detail's gpts.models kept only as a fallback. The retired +// free benefit gateway is never queried and maas_type is never sent. Each +// record declares its exact model id plus context/output limits; those +// declarations are the only capability source. The adapter declares tools +// because the chat endpoint natively accepts them, and forwards image_url +// content parts for models whose catalog entry advertises supports_images. A +// text-only model rejects image input with a 400 instead of silently dropping +// it. GET /v1/model/thinking-variants supplies each model's allowed reasoning +// strengths; the adapter exposes them as ReasoningOptions and forwards the +// selected level as reasoning_effort. // // The discovered list is not the same as the display list: CodeArts' agent // and builtin catalogs are keyed by model_parameters.model_id, while @@ -67,14 +66,9 @@ // GLM-5.2-ArkTS-SPARK instead of glm-5.2-sft-harmony) returns 002002009. The // adapter keeps model_id as NativeModel and model_name only as DisplayName. // -// Benefits are a separate routing path. A model advertised by a successful -// benefit gateway/config is marked and sent with maas_type: benefit. A -// credit-only trial account has no benefit group: claim/config answer 4000 -// invalid channel/group not found, and adding maas_type: benefit to the same -// model returns 4004.200 benefit not found. Crucially, the same model works -// over the credit path without that header. Therefore benefit discovery is -// additive and a failed claim/config never hides agent/builtin models. Only a -// real 002002009/4004.200 chat answer marks that model unusable for 30 minutes +// A non-empty catalog is authoritative: an unknown client model id is rejected +// locally before a billable request is sent. Only a real 002002009/4004.200 +// chat answer marks that model unusable for 30 minutes // and removes it from /v1/models; the account stays ready because this is an // entitlement failure, not auth. // diff --git a/internal/providers/codearts/payload.go b/internal/providers/codearts/payload.go index cbcd6ef7..32288b74 100644 --- a/internal/providers/codearts/payload.go +++ b/internal/providers/codearts/payload.go @@ -16,7 +16,7 @@ import ( // buildChatBody maps the internal request to the native CodeArts // chat-completions shape. The upstream accepts the OpenAI wire format, with two // deviations: tool_choice must be a string, and max_tokens is the only cap. -func buildChatBody(req translate.ChatRequest, model, level string, allowImages, benefit bool) (map[string]any, error) { +func buildChatBody(req translate.ChatRequest, model, level string, allowImages bool) (map[string]any, error) { tools, choice, err := nativeTools(req.Tools, req.ToolChoice) if err != nil { return nil, err @@ -61,7 +61,6 @@ func buildChatBody(req translate.ChatRequest, model, level string, allowImages, body["tool_choice"] = choice } } - _ = benefit // benefit routing is a header, not a body field return body, nil }