Skip to content
Open
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
15 changes: 15 additions & 0 deletions internal/httpapi/assistant.go
Original file line number Diff line number Diff line change
Expand Up @@ -1743,6 +1743,10 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
var streamFilter assistantStreamFilter
var stderrTail []string
var missingSession, modelStarted, credentialRejected bool
// The CLI sometimes reports the reason (e.g. an unknown model) only in an
// assistant text block and exits with an empty result payload; keep it so
// the failure classification can name the real cause.
var lastAssistantText string
var usageCollector assistantCLIUsage
if engine == assistantEngineCodeBuddy || engine == assistantEngineClaude {
usageCollector.session = newAssistantSessionUsage(root, sessionID, req.Resume, engine)
Expand Down Expand Up @@ -1833,6 +1837,11 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
resetClaudeText := result.Message.ID == "" || result.Message.ID != claudeMessageID
for _, block := range result.Message.Content {
credentialRejected = credentialRejected || isCredentialRejection(block.Text)
if block.Type == "text" {
if text := strings.TrimSpace(block.Text); text != "" && !assistantCLINoticeText(text) {
lastAssistantText = text
}
}
if !captureClaudeText || result.ParentToolUseID != "" || block.Type != "text" {
continue
}
Expand Down Expand Up @@ -1910,6 +1919,12 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U
assistantDiagnosticsFrom(ctx).platform("protocol.result_text_recovered", "Claude Code 本轮成功但结果正文为空,采用已收到的回复", user)
}
out, err := decodeAssistantCLIResult(final, resultError, err, stderrTail)
// A model the account cannot use only shows up in that text block. Append it
// for classification; plain narration keeps the original error so the
// generic "interrupted, retry" reply and its tests are unchanged.
if err != nil && errors.Is(err, errAssistantMissingResult) && assistantProviderRejectionText(lastAssistantText) {
err = fmt.Errorf("%w; assistant=%s", err, truncateRunes(lastAssistantText, 500))
}
if err != nil && req.RunnerLogin && ctx.Err() == nil && !errors.Is(err, runtime.ErrConversationNotStarted) {
text := strings.ToLower(err.Error())
if assistantAuthFailureText(text) || strings.Contains(text, "not logged in") || strings.Contains(text, "login expired") || strings.Contains(text, "please run /login") {
Expand Down
14 changes: 13 additions & 1 deletion internal/httpapi/assistant_failure.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,10 @@ func classifyAssistantFailureParts(f domain.AssistantFailure, err error) (domain
return c, false
}

var assistantModelMissingRe = regexp.MustCompile("(?i)\\bmodel\\s+[`'\"]?[^\\s`'\"]*[`'\"]?\\s*(?:does not exist|not found|is not available)")
// CodeBuddy reports an unknown model as `400 model [id] service info not found`
// and OpenAI-compatible providers as `The model `x` does not exist ...`, so the
// pattern accepts a bracketed, quoted or bare ID plus the provider's wording.
var assistantModelMissingRe = regexp.MustCompile("(?i)\\bmodel\\s*[`'\"]?(?:\\[[^\\]]+\\]|[^\\s`'\"]*)[`'\"]?\\s*(?:does not exist|not found|is not available|service info not found)")

func classifyAssistantFailureText(f domain.AssistantFailure, err error, text string) domain.AssistantFailure {
message := strings.ToLower(text)
Expand Down Expand Up @@ -221,3 +224,12 @@ func classifyAssistantFailureText(f domain.AssistantFailure, err error, text str
// that was missing is reported separately, and a finished install replaces
// both that report and this generic text.
const assistantGenerationFailedMessage = "AI 助手生成失败,请稍后重试"

// assistantProviderRejectionText reports whether an assistant text block is a
// provider rejection (e.g. `400 model [x] service info not found`) rather than
// narration, so only those are carried into the missing-result error.
func assistantProviderRejectionText(text string) bool {
text = strings.TrimSpace(text)
return strings.HasPrefix(text, "400 ") || strings.HasPrefix(text, "403 ") ||
assistantModelMissingRe.MatchString(text) || assistantAuthFailureText(text)
}
53 changes: 53 additions & 0 deletions internal/httpapi/assistant_failure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,56 @@ func TestFailedSharedGenerationSnapshotKeepsCauseAndRetryHistory(t *testing.T) {
})
}
}

func TestAssistantCLIReportsModelRejectionFromAssistantText(t *testing.T) {
// CodeBuddy answers a mistyped model ID with an assistant text block and a
// result whose payload is empty; the model error must survive the decode so
// the connection test can say the model is unavailable instead of "retry".
for _, tc := range []struct {
name, text string
}{
{"bracketed model", "400 model [deepseek-v4.1-flsh] service info not found"},
{"plain model", "400 model deepseek-v4.1-flsh not found"},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, "codebuddy")
script := "#!/bin/sh\ncat <<'RESULT'\n" +
`{"type":"assistant","message":{"content":[{"type":"text","text":"` + tc.text + `"}]}}` + "\n" +
`{"type":"result","subtype":"error_during_execution","is_error":true,"result":""}` + "\nRESULT\n"
if err := os.WriteFile(bin, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin)
_, _, err := runAssistantCLI(context.Background(), assistantCLIRequest{Prompt: "Reply with OK.", SessionRoot: dir}, domain.User{ID: 1, CodeBuddyAPIKey: "test-private-key"}, nil)
if err == nil {
t.Fatal("empty result was accepted")
}
failure := classifyAssistantFailureText(domain.AssistantFailure{}, err, err.Error())
if failure.Code != "MODEL_UNAVAILABLE" {
t.Fatalf("code=%s message=%q err=%v", failure.Code, failure.Message, err)
}
})
}
}

func TestTestCodeBuddyConnectionNamesInvalidModel(t *testing.T) {
dir := t.TempDir()
bin := filepath.Join(dir, "codebuddy")
script := "#!/bin/sh\n" +
"for a in \"$@\"; do case \"$a\" in --help) echo 'Available models:'; echo ' deepseek-v4.1-flash'; exit 0;; esac; done\n" +
"cat <<'RESULT'\n" +
`{"type":"assistant","message":{"content":[{"type":"text","text":"400 model [deepseek-v4.1-flsh] service info not found"}]}}` + "\n" +
`{"type":"result","subtype":"error_during_execution","is_error":true,"result":""}` + "\nRESULT\n"
if err := os.WriteFile(bin, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
t.Setenv("AGENTFLOW_CODEBUDDY_BIN", bin)
result := testOfficialCodeBuddyConnection(context.Background(), "ioa", "test-private-key", "deepseek-v4.1-flsh")
if result.Connected || result.Error == "" {
t.Fatalf("mistyped model reported as connected: %+v", result)
}
if !strings.Contains(result.Error, "deepseek-v4.1-flsh") || strings.Contains(result.Error, "未返回完整回答") {
t.Fatalf("error %q does not name the model", result.Error)
}
}
44 changes: 37 additions & 7 deletions internal/httpapi/assistant_models.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"os"
"os/exec"
"regexp"
Expand Down Expand Up @@ -56,7 +57,7 @@ func prefetchAssistantModels() {}
// CodeBuddy publishes the models available in each network environment in its
// --help output; the list differs between international, internal and iOA.
var (
cliModelPattern = regexp.MustCompile(`Currently supported: \(([^)]*)\)`)
cliModelPattern = regexp.MustCompile(`(?i)Currently\s+supported\s*:\s*\(([^)]*)\)`)
cliModelMu sync.Mutex
cliModelCache = map[string]cliModelEntry{}
cliModelGeneration uint64
Expand Down Expand Up @@ -92,36 +93,65 @@ func cliModelCacheKey(environment, apiKey string) string {
}

func discoverCodeBuddyModels(ctx context.Context, environment, apiKey string) []string {
bin, err := resolveCodeBuddyBin()
if err != nil {
models, _ := readCodeBuddyModels(ctx, environment, apiKey)
if len(models) == 0 {
return nil
}
return models
}

func readCodeBuddyModels(ctx context.Context, environment, apiKey string) ([]string, error) {
bin, err := resolveAssistantEngineBin(assistantEngineCodeBuddy)
if err != nil {
if errors.Is(err, errAssistantCLIMissing) {
return nil, err
}
return nil, errors.New("无法定位 CodeBuddy CLI,请检查平台服务器上的 CLI 配置")
}
dir, err := os.MkdirTemp("", "loopforge-models-")
if err != nil {
return nil
return nil, errors.New("无法为 CodeBuddy CLI 创建临时目录,请检查平台服务器上的目录权限")
}
defer os.RemoveAll(dir)
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, bin, "--help")
cmd.Dir = dir
cmd.WaitDelay = time.Second
cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + dir, "CODEBUDDY_CONFIG_DIR=" + dir, "CODEBUDDY_INTERNET_ENVIRONMENT=" + environment}
if key := strings.TrimSpace(apiKey); key != "" {
cmd.Env = append(cmd.Env, "CODEBUDDY_API_KEY="+key)
}
out, err := cmd.Output()
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, exec.ErrWaitDelay) {
return nil, errors.New("获取 CodeBuddy 模型列表超时,请重试或手动添加模型")
}
if err != nil {
return nil
var exit *exec.ExitError
if errors.As(err, &exit) {
if assistantAuthFailureText(string(exit.Stderr)) || isCredentialRejection(string(out)) {
return nil, errAssistantCredentialRejected
}
return nil, fmt.Errorf("CodeBuddy CLI 获取模型时异常退出(退出码 %d),请检查平台服务器上的 CLI", exit.ExitCode())
}
return nil, errors.New("无法启动 CodeBuddy CLI,请检查平台服务器上的安装与文件权限")
}
models := parseCodeBuddyModels(string(out))
if models == nil {
if isCredentialRejection(string(out)) {
return nil, errAssistantCredentialRejected
}
return nil, errors.New("无法解析 CodeBuddy CLI 的模型列表,请检查 CLI 版本或手动添加模型")
}
return parseCodeBuddyModels(string(out))
return models, nil
}

func parseCodeBuddyModels(help string) []string {
m := cliModelPattern.FindStringSubmatch(help)
if m == nil {
return nil
}
var models []string
models := []string{}
for _, id := range strings.Split(m[1], ",") {
id = strings.TrimSpace(id)
if id == "" || id == "echo" || strings.Contains(id, ":") {
Expand Down
96 changes: 75 additions & 21 deletions internal/httpapi/cli_models_probe.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ type cliModelProbeResult struct {

const assistantAnthropicAPIBase = "https://api.anthropic.com"

// probeCLIModels backs 「获取可用模型」 for a personal model catalog.
// probeCLIModels backs 「获取可用模型」 and 「测试连接」 for a personal model catalog.
// The form's unsaved API Key, Base URL and protocol win over the stored ones
// so a user can probe before saving; nothing is stored. Like
// verifyGitToken it answers 200 with a structured result.
Expand All @@ -56,6 +56,8 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {
// Protocol is the agent CLI's form value; null keeps the stored one.
Protocol *string `json:"protocol"`
Environment *string `json:"environment"`
ConnectOnly bool `json:"connectOnly"`
Model string `json:"model"`
}
if !decode(c, &req) {
return
Expand Down Expand Up @@ -97,27 +99,12 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {
}
}
if engine == assistantEngineCodeBuddy && baseURL == "" {
ctx, cancel := context.WithTimeout(c.Request.Context(), 15*time.Second)
defer cancel()
var models []domain.CLIModel
for _, id := range discoverCLIModels(ctx, environment, apiKey) {
if !codeBuddyIsDefaultModel(id) && assistantValidEngineModel(id) {
models = append(models, domain.CLIModel{ID: id})
}
}
if len(models) == 0 {
if _, err := resolveAssistantEngineBin(engine); errors.Is(err, errAssistantCLIMissing) {
c.JSON(http.StatusOK, cliModelProbeResult{Error: err.Error()})
return
}
c.JSON(http.StatusOK, cliModelProbeResult{Error: "CodeBuddy CLI 没有返回模型,请检查 CLI 和个人凭据"})
return
}
source := "official"
if apiKey == "" {
source = "builtin"
ctx := c.Request.Context()
if req.ConnectOnly {
c.JSON(http.StatusOK, testOfficialCodeBuddyConnection(ctx, environment, apiKey, strings.TrimSpace(req.Model)))
} else {
c.JSON(http.StatusOK, probeOfficialCodeBuddyModels(ctx, environment, apiKey))
}
c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsWithEfforts(engine, models, ""), Source: source})
return
}
if engine == runtime.AgentCLICursor {
Expand Down Expand Up @@ -174,6 +161,73 @@ func (h *usersHandlers) probeCLIModels(c *gin.Context) {
c.JSON(http.StatusOK, cliModelProbeResult{Models: cliModelsWithEfforts(engine, cliModelsOf(models), configuredBaseURL), Source: source, Connected: true})
}

func probeOfficialCodeBuddyModels(ctx context.Context, environment, apiKey string) cliModelProbeResult {
ids, err := readCodeBuddyModels(ctx, environment, apiKey)
if err != nil {
return cliModelProbeResult{Error: err.Error()}
}
var models []domain.CLIModel
for _, id := range ids {
if !codeBuddyIsDefaultModel(id) && assistantValidEngineModel(id) {
models = append(models, domain.CLIModel{ID: id})
}
}
if len(models) == 0 {
return cliModelProbeResult{Error: "CodeBuddy CLI 没有列出可添加的模型,可手动添加模型"}
}
source := "official"
if apiKey == "" {
source = "builtin"
}
return cliModelProbeResult{Models: cliModelsWithEfforts(assistantEngineCodeBuddy, models, ""), Source: source}
}

func testOfficialCodeBuddyConnection(ctx context.Context, environment, apiKey, model string) cliModelProbeResult {
if apiKey == "" {
return cliModelProbeResult{Error: "请先填写 CodeBuddy API Key"}
}
if model == "" || codeBuddyIsDefaultModel(model) {
// This Flash model is available on all three official sites.
model = "deepseek-v4.1-flash"
}
if !assistantValidEngineModel(model) {
return cliModelProbeResult{Error: "用于测试连接的模型 ID 无效"}
}
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
defer cancel()
reply, _, err := runAssistantCLI(ctx, assistantCLIRequest{
Model: assistantEngineCodeBuddy + ":" + model,
Prompt: "Reply with OK.",
SystemPrompt: "Respond briefly to the connection check.",
ReviewOnly: true,
}, domain.User{CodeBuddyAPIKey: apiKey, CodeBuddyInternetEnvironment: environment}, nil)
switch {
case errors.Is(err, context.DeadlineExceeded):
return cliModelProbeResult{Error: "测试 CodeBuddy 连接超时,请检查平台网络后重试"}
case errors.Is(err, errAssistantCLIMissing):
return cliModelProbeResult{Error: err.Error()}
case errors.Is(err, errAssistantCredentialRejected),
assistantAuthFailureText(reply), err != nil && assistantAuthFailureText(err.Error()):
return cliModelProbeResult{Error: errAssistantCredentialRejected.Error()}
case err == nil:
return cliModelProbeResult{Connected: true, Source: "official"}
}
failure := classifyAssistantFailureText(domain.AssistantFailure{}, err, err.Error())
switch failure.Code {
case "MODEL_UNAVAILABLE":
failure.Message = "CodeBuddy 无法使用模型 " + model + ",请确认模型 ID 拼写正确,并在当前网络环境下可用"
case "MISSING_RESULT":
// An empty answer with no recognisable reason is almost always a model
// the current network environment cannot serve, so name the model and
// the way out instead of asking the user to retry blindly.
failure.Message = "CodeBuddy 没有返回回答,请确认模型 " + model + " 在当前网络环境下可用,或换成模型目录里的其他模型"
}
if failure.Message != "" {
return cliModelProbeResult{Error: failure.Message}
}
return cliModelProbeResult{Error: "CodeBuddy 未完成连接测试,请检查平台服务器上的 CLI 或模型服务后重试"}
}

func discoverGeminiModels(ctx context.Context, key, baseURL string) ([]assistantDiscoveredModel, error) {
client := *http.DefaultClient
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
Expand Down
Loading
Loading