Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
no more streaming function call requirement for builds, meaning non-OpenAI models that support non-streaming function calls can now be used... some refactoring to support this, and a model selection fix
Dane Schneiderd90bd612703a
diff --git a/app/cli/cmd/model_packs.go b/app/cli/cmd/model_packs.goindex 035450b2..18ef2a07 100644--- a/app/cli/cmd/model_packs.go+++ b/app/cli/cmd/model_packs.go@@ -5,6 +5,7 @@ import ("os""plandex/api""plandex/auth"+ "plandex/lib""plandex/term""strconv"@@ -277,127 +278,5 @@ func getPlannerRoleConfig(customModels []*shared.AvailableModel) shared.PlannerRfunc getModelForRole(customModels []*shared.AvailableModel, role shared.ModelRole) *shared.AvailableModel {color.New(color.Bold).Printf("Select a model for the %s role π\n", role)- return selectModelForRole(customModels, role, false)-}--func selectModelForRole(customModels []*shared.AvailableModel, role shared.ModelRole, includeProviderGoBack bool) *shared.AvailableModel {- var providers []string- addedProviders := map[string]bool{}-- builtInModels := shared.FilterCompatibleModels(shared.AvailableModels, role)-- for _, m := range builtInModels {- var p string- if m.Provider == shared.ModelProviderCustom {- p = *m.CustomProvider- } else {- p = string(m.Provider)- }-- if !addedProviders[p] {- providers = append(providers, p)- addedProviders[p] = true- }- }-- customModels = shared.FilterCompatibleModels(customModels, role)-- for _, m := range customModels {- var p string- if m.Provider == shared.ModelProviderCustom {- p = *m.CustomProvider- } else {- p = string(m.Provider)- }-- if !addedProviders[p] {- providers = append(providers, p)- addedProviders[p] = true- }- }-- for {- var opts []string- opts = append(opts, providers...)- if includeProviderGoBack {- opts = append(opts, goBack)- }- provider, err := term.SelectFromList("Select a provider:", opts)- if err != nil {- if err.Error() == "interrupt" {- return nil- }-- term.OutputErrorAndExit("Error selecting provider: %v", err)- return nil- }-- if provider == goBack {- break- }-- var selectableModels []*shared.AvailableModel- opts = []string{}-- for _, m := range shared.AvailableModels {- var p string- if m.Provider == shared.ModelProviderCustom {- p = *m.CustomProvider- } else {- p = string(m.Provider)- }-- if p == provider {- label := fmt.Sprintf("%s β %s | max %d πͺ", m.Provider, m.ModelName, m.MaxTokens)- opts = append(opts, label)- selectableModels = append(selectableModels, m)- }- }-- for _, m := range customModels {- var p string- if m.Provider == shared.ModelProviderCustom {- p = *m.CustomProvider- } else {- p = string(m.Provider)- }-- if p == provider {- label := fmt.Sprintf("%s β %s | max %d πͺ", p, m.ModelName, m.MaxTokens)- opts = append(opts, label)- selectableModels = append(selectableModels, m)- }- }-- opts = append(opts, goBack)-- selection, err := term.SelectFromList("Select a model:", opts)-- if err != nil {- if err.Error() == "interrupt" {- return nil- }-- term.OutputErrorAndExit("Error selecting model: %v", err)- return nil- }-- if selection == goBack {- continue- }-- var idx int- for i := range opts {- if opts[i] == selection {- idx = i- break- }- }-- return selectableModels[idx]-- }-- return nil-+ return lib.SelectModelForRole(customModels, role, false)}diff --git a/app/cli/cmd/set_model.go b/app/cli/cmd/set_model.goindex 479e2844..9d5fbb21 100644--- a/app/cli/cmd/set_model.go+++ b/app/cli/cmd/set_model.go@@ -15,8 +15,6 @@ import ("github.com/spf13/cobra")-const goBack = "β Go back"-var provider stringfunc init() {@@ -217,7 +215,7 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings) *opts = append(opts, "Custom | "+ms.Name)}- opts = append(opts, goBack)+ opts = append(opts, lib.GoBack)selection, err := term.SelectFromList("Select a model pack:", opts)if err != nil {@@ -229,7 +227,7 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings) *return nil}- if selection == goBack {+ if selection == lib.GoBack {return updateModelSettings([]string{}, originalSettings)}@@ -359,7 +357,7 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings) *"Set top-p",}- opts = append(opts, goBack)+ opts = append(opts, lib.GoBack)selection, err := term.SelectFromList("Select a property to update:", opts)if err != nil {@@ -371,7 +369,7 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings) *return nil}- if selection == goBack {+ if selection == lib.GoBack {return updateModelSettings([]string{}, originalSettings)}@@ -384,7 +382,7 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings) *term.OutputErrorAndExit("Error fetching models: %v", apiErr)}- selectedModel = selectModelForRole(customModels, role, true)+ selectedModel = lib.SelectModelForRole(customModels, role, true)if selectedModel != nil {break Outerdiff --git a/app/cli/lib/model_settings.go b/app/cli/lib/model_settings.goindex e5a8530f..4a461ed1 100644--- a/app/cli/lib/model_settings.go+++ b/app/cli/lib/model_settings.go@@ -7,8 +7,133 @@ import ("plandex/term""github.com/fatih/color"+ "github.com/plandex/plandex/shared")+const GoBack = "β Go back"++func SelectModelForRole(customModels []*shared.AvailableModel, role shared.ModelRole, includeProviderGoBack bool) *shared.AvailableModel {+ var providers []string+ addedProviders := map[string]bool{}++ builtInModels := shared.FilterCompatibleModels(shared.AvailableModels, role)++ for _, m := range builtInModels {+ var p string+ if m.Provider == shared.ModelProviderCustom {+ p = *m.CustomProvider+ } else {+ p = string(m.Provider)+ }++ if !addedProviders[p] {+ providers = append(providers, p)+ addedProviders[p] = true+ }+ }++ customModels = shared.FilterCompatibleModels(customModels, role)++ for _, m := range customModels {+ var p string+ if m.Provider == shared.ModelProviderCustom {+ p = *m.CustomProvider+ } else {+ p = string(m.Provider)+ }++ if !addedProviders[p] {+ providers = append(providers, p)+ addedProviders[p] = true+ }+ }++ for {+ var opts []string+ opts = append(opts, providers...)+ if includeProviderGoBack {+ opts = append(opts, GoBack)+ }+ provider, err := term.SelectFromList("Select a provider:", opts)+ if err != nil {+ if err.Error() == "interrupt" {+ return nil+ }++ term.OutputErrorAndExit("Error selecting provider: %v", err)+ return nil+ }++ if provider == GoBack {+ break+ }++ var selectableModels []*shared.AvailableModel+ opts = []string{}++ for _, m := range builtInModels {+ var p string+ if m.Provider == shared.ModelProviderCustom {+ p = *m.CustomProvider+ } else {+ p = string(m.Provider)+ }++ if p == provider {+ label := fmt.Sprintf("%s β %s | max %d πͺ", m.Provider, m.ModelName, m.MaxTokens)+ opts = append(opts, label)+ selectableModels = append(selectableModels, m)+ }+ }++ for _, m := range customModels {+ var p string+ if m.Provider == shared.ModelProviderCustom {+ p = *m.CustomProvider+ } else {+ p = string(m.Provider)+ }++ if p == provider {+ label := fmt.Sprintf("%s β %s | max %d πͺ", p, m.ModelName, m.MaxTokens)+ opts = append(opts, label)+ selectableModels = append(selectableModels, m)+ }+ }++ opts = append(opts, GoBack)++ selection, err := term.SelectFromList("Select a model:", opts)++ if err != nil {+ if err.Error() == "interrupt" {+ return nil+ }++ term.OutputErrorAndExit("Error selecting model: %v", err)+ return nil+ }++ if selection == GoBack {+ continue+ }++ var idx int+ for i := range opts {+ if opts[i] == selection {+ idx = i+ break+ }+ }++ return selectableModels[idx]++ }++ return nil++}+func MustVerifyApiKeys() map[string]string {return mustVerifyApiKeys(false)}diff --git a/app/cli/stream_tui/model.go b/app/cli/stream_tui/model.goindex b1b52766..77015f10 100644--- a/app/cli/stream_tui/model.go+++ b/app/cli/stream_tui/model.go@@ -36,9 +36,10 @@ type streamUIModel struct {mainViewport viewport.Model- processing bool- starting bool- spinner spinner.Model+ processing bool+ starting bool+ spinner spinner.Model+ buildSpinner spinner.Modelbuilding booltokensByPath map[string]int@@ -93,6 +94,9 @@ func initialModel(prestartReply, prompt string, buildOnly bool) *streamUIModel {s.Spinner = spinner.Pointss.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))+ buildSpinner := spinner.New()+ buildSpinner.Spinner = spinner.MiniDot+initialState := streamUIModel{buildOnly: buildOnly,prompt: prompt,@@ -157,6 +161,7 @@ func initialModel(prestartReply, prompt string, buildOnly bool) *streamUIModel {tokensByPath: make(map[string]int),finishedByPath: make(map[string]bool),spinner: s,+ buildSpinner: buildSpinner,atScrollBottom: true,starting: true,}diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.goindex 7209a4b9..cd0f1eb8 100644--- a/app/cli/stream_tui/update.go+++ b/app/cli/stream_tui/update.go@@ -25,11 +25,18 @@ func (m streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {switch msg := msg.(type) {case spinner.TickMsg:+ var cmds []tea.Cmdif m.processing || m.starting {spinnerModel, cmd := m.spinner.Update(msg)m.spinner = spinnerModel- return m, cmd+ cmds = append(cmds, cmd)}+ if m.building {+ buildSpinnerModel, cmd := m.buildSpinner.Update(msg)+ m.buildSpinner = buildSpinnerModel+ cmds = append(cmds, cmd)+ }+ return m, tea.Batch(cmds...)case tea.WindowSizeMsg:m.windowResized(msg.Width, msg.Height)@@ -316,13 +323,22 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.m.updateViewportDimensions()+ cmds := []tea.Cmd{m.buildSpinner.Tick}if m.processing && !m.finished {- return m, m.spinner.Tick+ cmds = append(cmds, m.spinner.Tick)}+ return m, tea.Batch(cmds...)case shared.StreamMessageDescribing:m.processing = true- return m, m.spinner.Tick++ cmds := []tea.Cmd{m.spinner.Tick}++ if m.building {+ cmds = append(cmds, m.buildSpinner.Tick)+ }++ return m, tea.Batch(cmds...)case shared.StreamMessageError:m.apiErr = msg.Error@@ -340,6 +356,9 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.case shared.StreamMessageRepliesFinished:m.processing = false+ if m.building {+ return m, m.buildSpinner.Tick+ }}return m, nildiff --git a/app/cli/stream_tui/view.go b/app/cli/stream_tui/view.goindex 977f9ac9..376c4cc7 100644--- a/app/cli/stream_tui/view.go+++ b/app/cli/stream_tui/view.go@@ -133,7 +133,10 @@ func (m streamUIModel) getRows(static bool) []string {block += " β "} else if tokens > 0 {block += fmt.Sprintf(" %d πͺ", tokens)+ } else {+ block += " " + m.buildSpinner.View()}+maybeBlockWidth := lipgloss.Width(block)if maybeBlockWidth > m.width {diff --git a/app/server/handlers/client_helper.go b/app/server/handlers/client_helper.goindex 6256d910..7441f3ae 100644--- a/app/server/handlers/client_helper.go+++ b/app/server/handlers/client_helper.go@@ -48,23 +48,38 @@ func initClients(params initClientsParams) map[string]*openai.Client {continue}- if planSettings.ModelPack.Planner.BaseModelConfig.ApiKeyEnvVar == envVar {- endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.Planner.BaseModelConfig.BaseUrl+ if planSettings.ModelPack.PlanSummary.BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.PlanSummary.BaseModelConfig.BaseUrlcontinue}- if planSettings.ModelPack.Planner.BaseModelConfig.ApiKeyEnvVar == envVar {- endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.Planner.BaseModelConfig.BaseUrl+ if planSettings.ModelPack.Builder.BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.Builder.BaseModelConfig.BaseUrlcontinue}- if planSettings.ModelPack.Planner.BaseModelConfig.ApiKeyEnvVar == envVar {- endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.Planner.BaseModelConfig.BaseUrl+ if planSettings.ModelPack.Namer.BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.Namer.BaseModelConfig.BaseUrlcontinue}- if planSettings.ModelPack.Planner.BaseModelConfig.ApiKeyEnvVar == envVar {- endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.Planner.BaseModelConfig.BaseUrl+ if planSettings.ModelPack.CommitMsg.BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.CommitMsg.BaseModelConfig.BaseUrl+ continue+ }++ if planSettings.ModelPack.ExecStatus.BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.ExecStatus.BaseModelConfig.BaseUrl+ continue+ }++ if planSettings.ModelPack.GetVerifier().BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.GetVerifier().BaseModelConfig.BaseUrl+ continue+ }++ if planSettings.ModelPack.GetAutoFix().BaseModelConfig.ApiKeyEnvVar == envVar {+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.GetAutoFix().BaseModelConfig.BaseUrlcontinue}}diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.goindex 6c856b18..3750751d 100644--- a/app/server/model/plan/build_exec.go+++ b/app/server/model/plan/build_exec.go@@ -1,6 +1,7 @@package planimport (+ "encoding/json""fmt""log""plandex-server/db"@@ -9,6 +10,7 @@ import ("plandex-server/syntax""plandex-server/types"+ "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai")@@ -343,12 +345,56 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {envVar := config.BaseModelConfig.ApiKeyEnvVarclient := clients[envVar]- stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)- if err != nil {- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)- fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))- return+ if config.BaseModelConfig.HasStreamingFunctionCalls {+ stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)+ if err != nil {+ log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)+ fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))+ return+ }++ go fileState.listenStreamChangesWithLineNums(stream)+ } else {++ log.Println("request:")+ log.Println(spew.Sdump(modelReq))++ resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)++ if err != nil {+ log.Printf("Error building file '%s': %v\n", filePath, err)+ fileState.onBuildFileError(fmt.Errorf("error building file '%s': %v", filePath, err))+ return+ }++ var s string+ var res types.ChangesWithLineNums++ for _, choice := range resp.Choices {+ if len(choice.Message.ToolCalls) == 1 &&+ choice.Message.ToolCalls[0].Function.Name == prompts.ListReplacementsFn.Name {+ fnCall := choice.Message.ToolCalls[0].Function+ s = fnCall.Arguments+ break+ }+ }++ if s == "" {+ log.Println("no ListReplacements function call found in response")+ fileState.lineNumsRetryOrError(fmt.Errorf("no ListReplacements function call found in response"))+ return+ }++ bytes := []byte(s)++ err = json.Unmarshal(bytes, &res)+ if err != nil {+ log.Printf("Error unmarshalling build response: %v\n", err)+ fileState.lineNumsRetryOrError(fmt.Errorf("error unmarshalling build response: %v", err))+ return+ }++ fileState.onBuildResult(res)}- go fileState.listenStreamChangesWithLineNums(stream)}diff --git a/app/server/model/plan/build_fix.go b/app/server/model/plan/build_fix.goindex 8456a7b9..36a67401 100644--- a/app/server/model/plan/build_fix.go+++ b/app/server/model/plan/build_fix.go@@ -1,12 +1,15 @@package planimport (+ "encoding/json""fmt""log""plandex-server/model""plandex-server/model/prompts"+ "plandex-server/types""strings"+ "github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai")@@ -95,12 +98,62 @@ func (fileState *activeBuildStreamFileState) fixFileLineNums() {envVar := config.BaseModelConfig.ApiKeyEnvVarclient := clients[envVar]- stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)- if err != nil {- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)- fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))- return- }+ if config.BaseModelConfig.HasStreamingFunctionCalls {++ stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)+ if err != nil {+ log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)+ fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))+ return+ }++ go fileState.listenStreamFixChanges(stream)+ } else {+ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: false,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })++ resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)++ if err != nil {+ log.Printf("Error building file '%s': %v\n", filePath, err)+ fileState.onBuildFileError(fmt.Errorf("error building file '%s': %v", filePath, err))+ return+ }- go fileState.listenStreamFixChanges(stream)+ var s string+ var res types.ChangesWithLineNums++ for _, choice := range resp.Choices {+ if len(choice.Message.ToolCalls) == 1 &&+ choice.Message.ToolCalls[0].Function.Name == prompts.ListReplacementsFn.Name {+ fnCall := choice.Message.ToolCalls[0].Function+ s = fnCall.Arguments+ break+ }+ }++ if s == "" {+ log.Println("no ListReplacements function call found in response")+ fileState.fixRetryOrAbort(fmt.Errorf("no ListReplacements function call found in response"))+ return+ }++ bytes := []byte(s)++ err = json.Unmarshal(bytes, &res)+ if err != nil {+ log.Printf("Error unmarshalling fix response: %v\n", err)+ fileState.fixRetryOrAbort(fmt.Errorf("error unmarshalling fix response: %v", err))+ return+ }++ fileState.onFixResult(res)+ }}diff --git a/app/server/model/plan/build_fix_result.go b/app/server/model/plan/build_fix_result.gonew file mode 100644index 00000000..1d3b7b13--- /dev/null+++ b/app/server/model/plan/build_fix_result.go@@ -0,0 +1,178 @@+package plan++import (+ "fmt"+ "log"+ "math/rand"+ "plandex-server/types"+ "sort"+ "time"++ "github.com/davecgh/go-spew/spew"+ "github.com/plandex/plandex/shared"+)++func (fileState *activeBuildStreamFileState) onFixResult(res types.ChangesWithLineNums) {++ filePath := fileState.filePath+ build := fileState.build+ currentOrgId := fileState.currentOrgId+ planId := fileState.plan.Id+ branch := fileState.branch++ activePlan := GetActivePlan(planId, branch)++ if activePlan == nil {+ log.Printf("listenStreamFixChanges - Active plan not found for plan ID %s on branch %s\n", planId, branch)+ return+ }+ sorted := []*shared.StreamedChangeWithLineNums{}++ // Sort the changes by start line+ for _, change := range res.Changes {+ if change.HasChange {+ sorted = append(sorted, change)+ }+ }++ // Sort the changes by start line+ sort.Slice(sorted, func(i, j int) bool {+ var iStartLine int+ var jStartLine int++ // Convert the line number part to an integer+ iStartLine, _, err := sorted[i].GetLines()++ if err != nil {+ log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[i], err)+ fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[i], err))+ return false+ }++ jStartLine, _, err = sorted[j].GetLines()++ if err != nil {+ log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[j], err)+ fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[j], err))+ return false+ }++ return iStartLine < jStartLine+ })++ fileState.streamedChangesWithLineNums = sorted++ var overlapStrategy OverlapStrategy = OverlapStrategyError+ if fileState.fixFileNumRetry > 1 {+ overlapStrategy = OverlapStrategySkip+ }++ planFileResult, updated, allSucceeded, err := GetPlanResult(+ activePlan.Ctx,+ PlanResultParams{+ OrgId: currentOrgId,+ PlanId: planId,+ PlanBuildId: build.Id,+ ConvoMessageId: build.ConvoMessageId,+ FilePath: filePath,+ PreBuildState: fileState.updated,+ ChangesWithLineNums: res.Changes,+ OverlapStrategy: overlapStrategy,++ IsFix: true,+ IsSyntaxFix: fileState.isFixingSyntax,+ IsOtherFix: fileState.isFixingOther,++ FixEpoch: fileState.syntaxNumEpoch,++ CheckSyntax: true,+ },+ )++ if err != nil {+ log.Println("listenStreamFixChanges - Error getting plan result:", err)+ fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - error getting plan result for file '%s': %v", filePath, err))+ return+ }++ if !allSucceeded {+ log.Println("listenStreamFixChanges - Failed replacements:")+ for _, replacement := range planFileResult.Replacements {+ if replacement.Failed {+ spew.Dump(replacement)+ }+ }++ // no retry here as this should never happen+ fileState.onBuildFileError(fmt.Errorf("listenStreamFixChanges - replacements failed for file '%s'", filePath))+ return++ }++ log.Println("listenStreamFixChanges - Plan file result:")+ // spew.Dump(planFileResult)++ // reset fix state+ fileState.isFixingSyntax = false+ fileState.isFixingOther = false++ // if we are below the number of FixSyntaxRetries, and the syntax is invalid, short-circuit here and retry+ // otherwise if the syntax is invalid but we're out of retries, continue to onFinishBuildFile, which will handle epoch-based retries (i.e. running additional fixes on top of this failed fix) if applicable+ if planFileResult.WillCheckSyntax && !planFileResult.SyntaxValid {+ if fileState.syntaxNumRetry < FixSyntaxRetries {+ fileState.isFixingSyntax = true+ fileState.syntaxNumRetry+++ go fileState.fixFileLineNums()+ return+ }+ }++ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: true,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })+ time.Sleep(50 * time.Millisecond)++ fileState.onFinishBuildFile(planFileResult, updated)+}++func (fileState *activeBuildStreamFileState) fixRetryOrAbort(err error) {+ if fileState.fixFileNumRetry < MaxBuildStreamErrorRetries {+ fileState.fixFileNumRetry+++ fileState.activeBuild.FixBuffer = ""+ fileState.activeBuild.FixBufferTokens = 0+ log.Printf("Retrying fix file '%s' due to error: %v\n", fileState.filePath, err)++ // Exponential backoff+ time.Sleep(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)++ fileState.fixFileLineNums()+ } else {+ log.Printf("Aborting fix file '%s' due to error: %v\n", fileState.filePath, err)++ activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)++ if activePlan == nil {+ log.Println("fixRetryOrAbort - Active plan not found")+ return+ }++ buildInfo := &shared.BuildInfo{+ Path: fileState.filePath,+ NumTokens: 0,+ Finished: true,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })+ time.Sleep(50 * time.Millisecond)++ fileState.onFinishBuildFile(nil, "")+ }+}diff --git a/app/server/model/plan/build_fix_stream.go b/app/server/model/plan/build_fix_stream.goindex 0788874c..fc24ae98 100644--- a/app/server/model/plan/build_fix_stream.go+++ b/app/server/model/plan/build_fix_stream.go@@ -6,22 +6,17 @@ import ("fmt""log""math"- "math/rand""plandex-server/model""plandex-server/types"- "sort""strings""time"- "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai")func (fileState *activeBuildStreamFileState) listenStreamFixChanges(stream *openai.ChatCompletionStream) {filePath := fileState.filePath- build := fileState.build- currentOrgId := fileState.currentOrgIdplanId := fileState.plan.Idbranch := fileState.branch@@ -117,126 +112,13 @@ func (fileState *activeBuildStreamFileState) listenStreamFixChanges(stream *open}}- var streamed types.StreamedChangesWithLineNums+ var streamed types.ChangesWithLineNumserr = json.Unmarshal([]byte(fileState.activeBuild.FixBuffer), &streamed)if err == nil {log.Printf("listenStreamFixChanges - File %s: Parsed streamed replacements\n", filePath)- spew.Dump(streamed)-- sorted := []*shared.StreamedChangeWithLineNums{}-- // Sort the streamed changes by start line- for _, change := range streamed.Changes {- if change.HasChange {- sorted = append(sorted, change)- }- }-- // Sort the streamed changes by start line- sort.Slice(sorted, func(i, j int) bool {- var iStartLine int- var jStartLine int-- // Convert the line number part to an integer- iStartLine, _, err := sorted[i].GetLines()-- if err != nil {- log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[i], err)- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[i], err))- return false- }-- jStartLine, _, err = sorted[j].GetLines()-- if err != nil {- log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[j], err)- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[j], err))- return false- }-- return iStartLine < jStartLine- })-- fileState.streamedChangesWithLineNums = sorted-- var overlapStrategy OverlapStrategy = OverlapStrategyError- if fileState.fixFileNumRetry > 1 {- overlapStrategy = OverlapStrategySkip- }-- planFileResult, updated, allSucceeded, err := GetPlanResult(- activePlan.Ctx,- PlanResultParams{- OrgId: currentOrgId,- PlanId: planId,- PlanBuildId: build.Id,- ConvoMessageId: build.ConvoMessageId,- FilePath: filePath,- PreBuildState: fileState.updated,- StreamedChangesWithLineNums: streamed.Changes,- OverlapStrategy: overlapStrategy,-- IsFix: true,- IsSyntaxFix: fileState.isFixingSyntax,- IsOtherFix: fileState.isFixingOther,-- FixEpoch: fileState.syntaxNumEpoch,-- CheckSyntax: true,- },- )-- if err != nil {- log.Println("listenStreamFixChanges - Error getting plan result:", err)- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - error getting plan result for file '%s': %v", filePath, err))- return- }-- if !allSucceeded {- log.Println("listenStreamFixChanges - Failed replacements:")- for _, replacement := range planFileResult.Replacements {- if replacement.Failed {- spew.Dump(replacement)- }- }-- // no retry here as this should never happen- fileState.onBuildFileError(fmt.Errorf("listenStreamFixChanges - replacements failed for file '%s'", filePath))- return-- }-- log.Println("listenStreamFixChanges - Plan file result:")- // spew.Dump(planFileResult)-- // reset fix state- fileState.isFixingSyntax = false- fileState.isFixingOther = false-- // if we are below the number of FixSyntaxRetries, and the syntax is invalid, short-circuit here and retry- // otherwise if the syntax is invalid but we're out of retries, continue to onFinishBuildFile, which will handle epoch-based retries (i.e. running additional fixes on top of this failed fix) if applicable- if planFileResult.WillCheckSyntax && !planFileResult.SyntaxValid {- if fileState.syntaxNumRetry < FixSyntaxRetries {- fileState.isFixingSyntax = true- fileState.syntaxNumRetry++- go fileState.fixFileLineNums()- return- }- }-- buildInfo := &shared.BuildInfo{- Path: filePath,- NumTokens: 0,- Finished: true,- }- activePlan.Stream(shared.StreamMessage{- Type: shared.StreamMessageBuildInfo,- BuildInfo: buildInfo,- })- time.Sleep(50 * time.Millisecond)-- fileState.onFinishBuildFile(planFileResult, updated)+ // spew.Dump(streamed)+ fileState.onFixResult(streamed)return} else if len(delta.ToolCalls) == 0 {log.Println("listenStreamFixChanges - Stream chunk missing function call.")@@ -247,39 +129,3 @@ func (fileState *activeBuildStreamFileState) listenStreamFixChanges(stream *open}}}--func (fileState *activeBuildStreamFileState) fixRetryOrAbort(err error) {- if fileState.fixFileNumRetry < MaxBuildStreamErrorRetries {- fileState.fixFileNumRetry++- fileState.activeBuild.FixBuffer = ""- fileState.activeBuild.FixBufferTokens = 0- log.Printf("Retrying fix file '%s' due to error: %v\n", fileState.filePath, err)-- // Exponential backoff- time.Sleep(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)-- fileState.fixFileLineNums()- } else {- log.Printf("Aborting fix file '%s' due to error: %v\n", fileState.filePath, err)-- activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)-- if activePlan == nil {- log.Println("fixRetryOrAbort - Active plan not found")- return- }-- buildInfo := &shared.BuildInfo{- Path: fileState.filePath,- NumTokens: 0,- Finished: true,- }- activePlan.Stream(shared.StreamMessage{- Type: shared.StreamMessageBuildInfo,- BuildInfo: buildInfo,- })- time.Sleep(50 * time.Millisecond)-- fileState.onFinishBuildFile(nil, "")- }-}diff --git a/app/server/model/plan/build_result.go b/app/server/model/plan/build_result.goindex 88e5ae8f..65e6d4a7 100644--- a/app/server/model/plan/build_result.go+++ b/app/server/model/plan/build_result.go@@ -4,9 +4,13 @@ import ("context""fmt""log"+ "math/rand""plandex-server/db""plandex-server/syntax"+ "plandex-server/types"+ "sort""strings"+ "time""github.com/davecgh/go-spew/spew""github.com/google/uuid"@@ -21,14 +25,14 @@ const ()type PlanResultParams struct {- OrgId string- PlanId string- PlanBuildId string- ConvoMessageId string- FilePath string- PreBuildState string- OverlapStrategy OverlapStrategy- StreamedChangesWithLineNums []*shared.StreamedChangeWithLineNums+ OrgId string+ PlanId string+ PlanBuildId string+ ConvoMessageId string+ FilePath string+ PreBuildState string+ OverlapStrategy OverlapStrategy+ ChangesWithLineNums []*shared.StreamedChangeWithLineNumsCheckSyntax bool@@ -44,7 +48,7 @@ func GetPlanResult(ctx context.Context, params PlanResultParams) (*db.PlanFileReplanBuildId := params.PlanBuildIdfilePath := params.FilePathpreBuildState := params.PreBuildState- streamedChangesWithLineNums := params.StreamedChangesWithLineNums+ streamedChangesWithLineNums := params.ChangesWithLineNumspreBuildState = shared.AddLineNums(preBuildState)@@ -208,3 +212,140 @@ func GetPlanResult(ctx context.Context, params PlanResultParams) (*db.PlanFileRereturn &res, updated, allSucceeded, nil}++func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWithLineNums) {+ filePath := fileState.filePath+ build := fileState.build+ currentOrgId := fileState.currentOrgId+ planId := fileState.plan.Id+ branch := fileState.branch+ preBuildState := fileState.preBuildState++ activePlan := GetActivePlan(planId, branch)++ if activePlan == nil {+ log.Printf("listenStream - Active plan not found for plan ID %s on branch %s\n", planId, branch)+ return+ }++ sorted := []*shared.StreamedChangeWithLineNums{}++ // Sort the streamed changes by start line+ for _, change := range res.Changes {+ if change.HasChange {+ sorted = append(sorted, change)+ }+ }++ // Sort the streamed changes by start line+ sort.Slice(sorted, func(i, j int) bool {+ var iStartLine int+ var jStartLine int++ // Convert the line number part to an integer+ iStartLine, _, err := sorted[i].GetLines()++ if err != nil {+ log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[i], err)+ fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[i], err))+ return false+ }++ jStartLine, _, err = sorted[j].GetLines()++ if err != nil {+ log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[j], err)+ fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[j], err))+ return false+ }++ return iStartLine < jStartLine+ })++ fileState.streamedChangesWithLineNums = sorted++ var overlapStrategy OverlapStrategy = OverlapStrategyError+ if fileState.lineNumsNumRetry > 1 {+ overlapStrategy = OverlapStrategySkip+ }++ planFileResult, updatedFile, allSucceeded, err := GetPlanResult(+ activePlan.Ctx,+ PlanResultParams{+ OrgId: currentOrgId,+ PlanId: planId,+ PlanBuildId: build.Id,+ ConvoMessageId: build.ConvoMessageId,+ FilePath: filePath,+ PreBuildState: preBuildState,+ ChangesWithLineNums: res.Changes,+ OverlapStrategy: overlapStrategy,+ CheckSyntax: false,+ },+ )++ if err != nil {+ log.Println("listenStream - Error getting plan result:", err)+ fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting plan result for file '%s': %v", filePath, err))+ return+ }++ if !allSucceeded {+ log.Println("listenStream - Failed replacements:")+ for _, replacement := range planFileResult.Replacements {+ if replacement.Failed {+ spew.Dump(replacement)+ }+ }++ // no retry here as this should never happen+ fileState.onBuildFileError(fmt.Errorf("listenStream - replacements failed for file '%s'", filePath))+ return+ }++ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: true,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })+ time.Sleep(50 * time.Millisecond)++ fileState.updated = updatedFile++ log.Println("build stream - Plan file result:", planFileResult != nil)+ log.Printf("updatedFile exists: %v\n", updatedFile != "")++ fileState.onFinishBuildFile(planFileResult, updatedFile)+}++func (fileState *activeBuildStreamFileState) lineNumsRetryOrError(err error) {+ if fileState.lineNumsNumRetry < MaxBuildStreamErrorRetries {+ fileState.lineNumsNumRetry+++ fileState.activeBuild.WithLineNumsBuffer = ""+ fileState.activeBuild.WithLineNumsBufferTokens = 0+ log.Printf("Retrying line nums build file '%s' due to error: %v\n", fileState.filePath, err)++ activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)++ if activePlan == nil {+ log.Println("lineNumsRetryOrError - Active plan not found")+ return+ }++ select {+ case <-activePlan.Ctx.Done():+ log.Println("lineNumsRetryOrError - Context canceled. Exiting.")+ return+ case <-time.After(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond):+ break+ }++ fileState.buildFileLineNums()+ } else {+ fileState.onBuildFileError(err)+ }+}diff --git a/app/server/model/plan/build_stream_line_nums.go b/app/server/model/plan/build_stream_line_nums.goindex 373b4382..429305e5 100644--- a/app/server/model/plan/build_stream_line_nums.go+++ b/app/server/model/plan/build_stream_line_nums.go@@ -6,25 +6,19 @@ import ("fmt""log""math"- "math/rand""plandex-server/model""plandex-server/types"- "sort""strings""time"- "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai")func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(stream *openai.ChatCompletionStream) {filePath := fileState.filePath- build := fileState.build- currentOrgId := fileState.currentOrgIdplanId := fileState.plan.Idbranch := fileState.branch- preBuildState := fileState.preBuildStateactivePlan := GetActivePlan(planId, branch)@@ -122,105 +116,14 @@ func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(str}}- var streamed types.StreamedChangesWithLineNums+ var streamed types.ChangesWithLineNumserr = json.Unmarshal([]byte(fileState.activeBuild.WithLineNumsBuffer), &streamed)if err == nil {log.Printf("listenStream - File %s: Parsed streamed replacements\n", filePath)// spew.Dump(streamed)- sorted := []*shared.StreamedChangeWithLineNums{}-- // Sort the streamed changes by start line- for _, change := range streamed.Changes {- if change.HasChange {- sorted = append(sorted, change)- }- }-- // Sort the streamed changes by start line- sort.Slice(sorted, func(i, j int) bool {- var iStartLine int- var jStartLine int-- // Convert the line number part to an integer- iStartLine, _, err := sorted[i].GetLines()-- if err != nil {- log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[i], err)- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[i], err))- return false- }-- jStartLine, _, err = sorted[j].GetLines()-- if err != nil {- log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[j], err)- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[j], err))- return false- }-- return iStartLine < jStartLine- })-- fileState.streamedChangesWithLineNums = sorted-- var overlapStrategy OverlapStrategy = OverlapStrategyError- if fileState.lineNumsNumRetry > 1 {- overlapStrategy = OverlapStrategySkip- }-- planFileResult, updatedFile, allSucceeded, err := GetPlanResult(- activePlan.Ctx,- PlanResultParams{- OrgId: currentOrgId,- PlanId: planId,- PlanBuildId: build.Id,- ConvoMessageId: build.ConvoMessageId,- FilePath: filePath,- PreBuildState: preBuildState,- StreamedChangesWithLineNums: streamed.Changes,- OverlapStrategy: overlapStrategy,- CheckSyntax: false,- },- )-- if err != nil {- log.Println("listenStream - Error getting plan result:", err)- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting plan result for file '%s': %v", filePath, err))- return- }-- if !allSucceeded {- log.Println("listenStream - Failed replacements:")- for _, replacement := range planFileResult.Replacements {- if replacement.Failed {- spew.Dump(replacement)- }- }-- // no retry here as this should never happen- fileState.onBuildFileError(fmt.Errorf("listenStream - replacements failed for file '%s'", filePath))- return- }-- buildInfo := &shared.BuildInfo{- Path: filePath,- NumTokens: 0,- Finished: true,- }- activePlan.Stream(shared.StreamMessage{- Type: shared.StreamMessageBuildInfo,- BuildInfo: buildInfo,- })- time.Sleep(50 * time.Millisecond)-- fileState.updated = updatedFile-- log.Println("build stream - Plan file result:", planFileResult != nil)- log.Printf("updatedFile exists: %v\n", updatedFile != "")-- fileState.onFinishBuildFile(planFileResult, updatedFile)+ fileState.onBuildResult(streamed)return} else if len(delta.ToolCalls) == 0 {log.Println("listenStream - Stream chunk missing function call.")@@ -236,31 +139,3 @@ func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(str}}}--func (fileState *activeBuildStreamFileState) lineNumsRetryOrError(err error) {- if fileState.lineNumsNumRetry < MaxBuildStreamErrorRetries {- fileState.lineNumsNumRetry++- fileState.activeBuild.WithLineNumsBuffer = ""- fileState.activeBuild.WithLineNumsBufferTokens = 0- log.Printf("Retrying line nums build file '%s' due to error: %v\n", fileState.filePath, err)-- activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)-- if activePlan == nil {- log.Println("lineNumsRetryOrError - Active plan not found")- return- }-- select {- case <-activePlan.Ctx.Done():- log.Println("lineNumsRetryOrError - Context canceled. Exiting.")- return- case <-time.After(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond):- break- }-- fileState.buildFileLineNums()- } else {- fileState.onBuildFileError(err)- }-}diff --git a/app/server/model/plan/build_verify.go b/app/server/model/plan/build_verify.goindex ec565b59..d0b9daaf 100644--- a/app/server/model/plan/build_verify.go+++ b/app/server/model/plan/build_verify.go@@ -1,12 +1,15 @@package planimport (+ "encoding/json""fmt""log""plandex-server/db""plandex-server/model""plandex-server/model/prompts"+ "plandex-server/types"+ "github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai")@@ -112,13 +115,62 @@ func (fileState *activeBuildStreamFileState) verifyFileBuild() {envVar := config.BaseModelConfig.ApiKeyEnvVarclient := clients[envVar]- stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)- if err != nil {- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)- fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))- return- }+ if config.BaseModelConfig.HasStreamingFunctionCalls {+ stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)+ if err != nil {+ log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)+ fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))+ return+ }++ go fileState.listenStreamVerifyOutput(stream)+ } else {+ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: false,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })++ resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)++ if err != nil {+ log.Printf("Error verifying file '%s': %v\n", filePath, err)+ fileState.onBuildFileError(fmt.Errorf("error verifying file '%s': %v", filePath, err))+ return+ }- go fileState.listenStreamVerifyOutput(stream)+ var s string+ var res types.VerifyResult++ for _, choice := range resp.Choices {+ if len(choice.Message.ToolCalls) == 1 &&+ choice.Message.ToolCalls[0].Function.Name == prompts.VerifyOutputFn.Name {+ fnCall := choice.Message.ToolCalls[0].Function+ s = fnCall.Arguments+ break+ }+ }++ if s == "" {+ log.Println("no VerifyOutput function call found in response")+ fileState.verifyRetryOrAbort(fmt.Errorf("no Verify Output function call found in response"))+ return+ }++ bytes := []byte(s)++ err = json.Unmarshal(bytes, &res)+ if err != nil {+ log.Printf("Error unmarshalling verify response: %v\n", err)+ fileState.verifyRetryOrAbort(fmt.Errorf("error unmarshalling verify response: %v", err))+ return+ }++ fileState.onVerifyResult(res)+ }}diff --git a/app/server/model/plan/build_verify_result.go b/app/server/model/plan/build_verify_result.gonew file mode 100644index 00000000..31e5241d--- /dev/null+++ b/app/server/model/plan/build_verify_result.go@@ -0,0 +1,78 @@+package plan++import (+ "log"+ "math/rand"+ "plandex-server/types"+ "time"++ "github.com/plandex/plandex/shared"+)++func (fileState *activeBuildStreamFileState) onVerifyResult(res types.VerifyResult) {++ filePath := fileState.filePath+ planId := fileState.plan.Id+ branch := fileState.branch++ activePlan := GetActivePlan(planId, branch)++ if activePlan == nil {+ log.Printf("listenStreamVerifyOutput - Active plan not found for plan ID %s on branch %s\n", planId, branch)+ return+ }++ if res.IsCorrect() {+ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: true,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })+ log.Println("build verify - res.IsCorrect")++ time.Sleep(50 * time.Millisecond)++ fileState.onFinishBuildFile(nil, "")+ } else {++ log.Printf("listenStreamVerifyOutput - File %s: Streamed verify result is incorrect\n", filePath)++ fileState.verificationErrors = res.GetReasoning()+ fileState.isFixingOther = true++ // log.Println("Verification errors:")+ // log.Println(fileState.verificationErrors)++ select {+ case <-activePlan.Ctx.Done():+ log.Println("listenStreamVerifyOutput - Context canceled. Exiting.")+ return+ case <-time.After(time.Duration(rand.Intn(1001)) * time.Millisecond):+ break+ }+ fileState.fixFileLineNums()+ }++}++func (fileState *activeBuildStreamFileState) verifyRetryOrAbort(err error) {+ if fileState.verifyFileNumRetry < MaxBuildStreamErrorRetries {+ fileState.verifyFileNumRetry+++ fileState.activeBuild.VerifyBuffer = ""+ fileState.activeBuild.VerifyBufferTokens = 0+ log.Printf("Retrying verify file '%s' due to error: %v\n", fileState.filePath, err)++ // Exponential backoff+ time.Sleep(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)++ fileState.verifyFileBuild()+ } else {+ log.Printf("Aborting verify file '%s' due to error: %v\n", fileState.filePath, err)++ fileState.onFinishBuildFile(nil, "")+ }+}diff --git a/app/server/model/plan/build_verify_stream.go b/app/server/model/plan/build_verify_stream.goindex 83d05350..21718125 100644--- a/app/server/model/plan/build_verify_stream.go+++ b/app/server/model/plan/build_verify_stream.go@@ -5,7 +5,6 @@ import ("encoding/json""fmt""log"- "math/rand""plandex-server/model""plandex-server/types""strings"@@ -99,47 +98,14 @@ func (fileState *activeBuildStreamFileState) listenStreamVerifyOutput(stream *opfileState.activeBuild.VerifyBufferTokens++}- var streamed types.StreamedVerifyResult+ var streamed types.VerifyResulterr = json.Unmarshal([]byte(fileState.activeBuild.VerifyBuffer), &streamed)if err == nil {log.Printf("listenStreamVerifyOutput - File %s: Parsed streamed verify result\n", filePath)// spew.Dump(streamed)- if streamed.IsCorrect() {- buildInfo := &shared.BuildInfo{- Path: filePath,- NumTokens: 0,- Finished: true,- }- activePlan.Stream(shared.StreamMessage{- Type: shared.StreamMessageBuildInfo,- BuildInfo: buildInfo,- })- log.Println("build verify - streamed.IsCorrect")-- time.Sleep(50 * time.Millisecond)-- fileState.onFinishBuildFile(nil, "")- } else {-- log.Printf("listenStreamVerifyOutput - File %s: Streamed verify result is incorrect\n", filePath)-- fileState.verificationErrors = streamed.GetReasoning()- fileState.isFixingOther = true-- // log.Println("Verification errors:")- // log.Println(fileState.verificationErrors)-- select {- case <-activePlan.Ctx.Done():- log.Println("listenStreamVerifyOutput - Context canceled. Exiting.")- return- case <-time.After(time.Duration(rand.Intn(1001)) * time.Millisecond):- break- }- fileState.fixFileLineNums()- }+ fileState.onVerifyResult(streamed)return} else if len(delta.ToolCalls) == 0 {log.Println("listenStreamVerifyOutput - Stream chunk missing function call.")@@ -151,21 +117,3 @@ func (fileState *activeBuildStreamFileState) listenStreamVerifyOutput(stream *op}}--func (fileState *activeBuildStreamFileState) verifyRetryOrAbort(err error) {- if fileState.verifyFileNumRetry < MaxBuildStreamErrorRetries {- fileState.verifyFileNumRetry++- fileState.activeBuild.VerifyBuffer = ""- fileState.activeBuild.VerifyBufferTokens = 0- log.Printf("Retrying verify file '%s' due to error: %v\n", fileState.filePath, err)-- // Exponential backoff- time.Sleep(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)-- fileState.verifyFileBuild()- } else {- log.Printf("Aborting verify file '%s' due to error: %v\n", fileState.filePath, err)-- fileState.onFinishBuildFile(nil, "")- }-}diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.goindex 6e55a496..15d61c86 100644--- a/app/server/model/plan/tell_exec.go+++ b/app/server/model/plan/tell_exec.go@@ -371,9 +371,9 @@ func execTellPlan(}}, state.messages[len(state.messages)-1:]...)...)}- for _, message := range state.messages {- log.Printf("%s: %s\n", message.Role, message.Content)- }+ // for _, message := range state.messages {+ // log.Printf("%s: %s\n", message.Role, message.Content)+ // }modelReq := openai.ChatCompletionRequest{Model: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,diff --git a/app/server/model/prompts/build.go b/app/server/model/prompts/build.goindex 8dce241a..53045a35 100644--- a/app/server/model/prompts/build.go+++ b/app/server/model/prompts/build.go@@ -152,7 +152,7 @@ The 'listChangesWithLineNums' function MUST be called *valid JSON*. Double quote`const commentsPrompt = `-The 'comments' key is an array of objects with two properties: 'txt' and 'reference'. 'txt' is the exact text of a code comment. 'reference' is a boolean that indicates whether the comment is a placeholder of or reference to the original code, like "// rest of the function..." or "# existing init code...", or "// rest of the main function" or "// rest of your function..." or "// Existing methods..." or "// Remaining methods" or "// Existing code..." or "// ... existing setup code ..."" or other comments which reference code from the original file. References DO NOT need to exactly match any of the previous examples. Use your judgement to determine whether each comment is a reference. If 'reference' is true, the comment is a placeholder or reference to the original code. If 'reference' is false, the comment is not a placeholder or reference to the original code.+The 'comments' key is an array of objects with two properties: 'txt' and 'reference'. 'txt' is the exact text of a code comment. 'reference' is a boolean that indicates whether the comment is a placeholder of or reference to the original code, like "// rest of the function..." or "# existing init code...", or "// rest of the main function" or "// rest of your function..." or "// Existing methods..." or "// Remaining methods" or "// Existing code..." or "// ... existing setup code ..." or "// ... existing code ..." or "// ..." or other comments which reference code from the original file. References DO NOT need to exactly match any of the previous examples. Use your judgement to determine whether each comment is a reference. If 'reference' is true, the comment is a placeholder or reference to the original code. If 'reference' is false, the comment is not a placeholder or reference to the original code.In 'comments', you must list EVERY comment included in the proposed updates. Only list *code comments* that are valid comments for the programming language being used. Do not list logging statements or any other non-comment text that is not a valid code comment. If there are no code comments in the proposed updates, 'comments' must be an empty array.@@ -395,7 +395,7 @@ Based on supplied diffs, you must list EVERY code section that was removed or ov'hasDuplicationErrors': A boolean that indicates whether any code was *incorrectly* duplicated in the updated file, based on the reasoning provided in 'duplicationErrorsReasoning'. If code was *incorrectly* duplicated, set 'hasDuplicationErrors' to true. If code was *correctly* duplicated, consistent with the intention of the plan, set 'hasDuplicationErrors' to false.-'comments': an array of objects with two properties: 'txt' and 'reference'. 'txt' is the exact text of a code comment. 'reference' is a boolean that indicates whether the comment is a placeholder of or reference to the original code, like "// rest of the function..." or "# existing init code...", or "// rest of the main function" or "// rest of your function..." or "// Existing methods..." or "// Remaining methods" or "// Existing code..." or "// ... existing setup code ..."" or other comments which reference code from the original file. References DO NOT need to exactly match any of the previous examples. Use your judgement to determine whether each comment is a reference. If 'reference' is true, the comment is a placeholder or reference to the original code. If 'reference' is false, the comment is not a placeholder or reference to the original code.+'comments': an array of objects with two properties: 'txt' and 'reference'. 'txt' is the exact text of a code comment. 'reference' is a boolean that indicates whether the comment is a placeholder of or reference to the original code, like "// rest of the function..." or "# existing init code...", or "// rest of the main function" or "// rest of your function..." or "// Existing methods..." or "// Remaining methods" or "// Existing code..." or "// ... existing setup code ..." or "// ... existing code ..." or "// ..." or other comments which reference code from the original file. References DO NOT need to exactly match any of the previous examples. Use your judgement to determine whether each comment is a reference. If 'reference' is true, the comment is a placeholder or reference to the original code. If 'reference' is false, the comment is not a placeholder or reference to the original code.In 'comments', you must list EVERY comment included in the *updated file*. Only list *code comments* that are valid comments for the programming language being used. Do not list logging statements or any other non-comment text that is not a valid code comment. If there are no code comments in the *updated file*, 'comments' must be an empty array.diff --git a/app/server/types/model.go b/app/server/types/model.goindex ae066bde..3759ae21 100644--- a/app/server/types/model.go+++ b/app/server/types/model.go@@ -11,7 +11,7 @@ type StreamedFile struct {Content string `json:"content"`}-type StreamedChangesWithLineNums struct {+type ChangesWithLineNums struct {Comments []struct {Txt string `json:"txt"`Reference bool `json:"reference"`@@ -24,7 +24,7 @@ type StreamedChangesWithLineNums struct {// Changes []*shared.StreamedChangeFull `json:"changes"`// }-type StreamedVerifyResult struct {+type VerifyResult struct {SyntaxErrorsReasoning string `json:"syntaxErrorsReasoning"`HasSyntaxErrors bool `json:"hasSyntaxErrors"`Removed []struct {@@ -44,11 +44,11 @@ type StreamedVerifyResult struct {HasReferenceErrors bool `json:"hasReferenceErrors"`}-func (s *StreamedVerifyResult) IsCorrect() bool {+func (s *VerifyResult) IsCorrect() bool {return !s.HasRemovedCodeErrors && !s.HasDuplicationErrors && !s.HasReferenceErrors && !s.HasSyntaxErrors}-func (s *StreamedVerifyResult) GetReasoning() string {+func (s *VerifyResult) GetReasoning() string {res := []string{}if s.HasSyntaxErrors {diff --git a/app/shared/ai_models.go b/app/shared/ai_models.goindex 51911b1a..d1756e0d 100644--- a/app/shared/ai_models.go+++ b/app/shared/ai_models.go@@ -145,25 +145,6 @@ var AvailableModels = []*AvailableModel{BaseUrl: BaseUrlByProvider[ModelProviderOpenRouter],},},- {- Description: "Anthropic Claude Opus via OpenRouter",- DefaultMaxConvoTokens: 15000,- DefaultReservedOutputTokens: 4096,- BaseModelConfig: BaseModelConfig{- Provider: ModelProviderOpenRouter,- ModelName: "anthropic/claude-3-opus",- MaxTokens: 200000,- ApiKeyEnvVar: ApiKeyByProvider[ModelProviderOpenRouter],- ModelCompatibility: ModelCompatibility{- IsOpenAICompatible: true,- HasJsonResponseMode: true,- HasStreaming: true,- HasFunctionCalling: true,- HasStreamingFunctionCalls: false,- },- BaseUrl: BaseUrlByProvider[ModelProviderOpenRouter],- },- },{Description: "Anthropic Claude Sonnet via OpenRouter",DefaultMaxConvoTokens: 15000,@@ -240,6 +221,25 @@ var AvailableModels = []*AvailableModel{BaseUrl: BaseUrlByProvider[ModelProviderTogether],},},+ {+ Description: "CodeLLama-34b via Together.ai",+ DefaultMaxConvoTokens: 10000,+ DefaultReservedOutputTokens: 4096,+ BaseModelConfig: BaseModelConfig{+ Provider: ModelProviderTogether,+ ModelName: "togethercomputer/CodeLlama-34b-Instruct",+ MaxTokens: 16384,+ ApiKeyEnvVar: ApiKeyByProvider[ModelProviderTogether],+ ModelCompatibility: ModelCompatibility{+ IsOpenAICompatible: true,+ HasJsonResponseMode: true,+ HasStreaming: true,+ HasFunctionCalling: true,+ HasStreamingFunctionCalls: false,+ },+ BaseUrl: BaseUrlByProvider[ModelProviderTogether],+ },+ },{Description: "Google Gemini Pro 1.5 preview via OpenRouter",DefaultMaxConvoTokens: 100000,@@ -265,6 +265,7 @@ var AvailableModelsByName = map[string]*AvailableModel{}var Gpt4TurboLatestModelPack ModelPackvar OpenRouterClaudeOpusGPT4TurboModelPack ModelPack+var OpenRouterClaudeOpusModelPack ModelPackvar TogetherMixtral8x22BModelPack ModelPackvar Gpt4oLatestModelPack ModelPack@@ -272,6 +273,7 @@ var BuiltInModelPacks = []*ModelPack{&Gpt4oLatestModelPack,&Gpt4TurboLatestModelPack,&OpenRouterClaudeOpusGPT4TurboModelPack,+ &OpenRouterClaudeOpusModelPack,&TogetherMixtral8x22BModelPack,}@@ -329,10 +331,10 @@ var RequiredCompatibilityByRole = map[ModelRole]ModelCompatibility{HasStreaming: true,},ModelRoleBuilder: {- IsOpenAICompatible: true,- HasStreaming: true,- HasFunctionCalling: true,- HasStreamingFunctionCalls: true,+ IsOpenAICompatible: true,+ HasStreaming: true,+ HasFunctionCalling: true,+ // HasStreamingFunctionCalls: true -- no longer required},ModelRoleName: {IsOpenAICompatible: true,@@ -346,16 +348,16 @@ var RequiredCompatibilityByRole = map[ModelRole]ModelCompatibility{HasFunctionCalling: true,},ModelRoleVerifier: {- IsOpenAICompatible: true,- HasStreaming: true,- HasFunctionCalling: true,- HasStreamingFunctionCalls: true,+ IsOpenAICompatible: true,+ HasStreaming: true,+ HasFunctionCalling: true,+ // HasStreamingFunctionCalls: true -- no longer required},ModelRoleAutoFix: {- IsOpenAICompatible: true,- HasStreaming: true,- HasFunctionCalling: true,- HasStreamingFunctionCalls: true,+ IsOpenAICompatible: true,+ HasStreaming: true,+ HasFunctionCalling: true,+ // HasStreamingFunctionCalls: true -- no longer required},}@@ -465,8 +467,8 @@ func init() {}OpenRouterClaudeOpusGPT4TurboModelPack = ModelPack{- Name: "claude-opus/gpt-4o",- Description: "Uses Anthropic's Claude Opus model (via OpenRouter) for planning, Claude Sonnet for summarization, gpt-4o for builds and auto-continue, and gpt-3.5-turbo for lighter tasks.",+ Name: "claude-opus/gpt-4-turbo",+ Description: "Uses Anthropic's Claude Opus model (via OpenRouter) for planning, Claude Sonnet for summarization, gpt-4-turbo for builds and auto-continue, and gpt-3.5-turbo for lighter tasks.",Planner: PlannerRoleConfig{ModelRoleConfig: ModelRoleConfig{Role: ModelRolePlanner,@@ -484,7 +486,7 @@ func init() {},Builder: ModelRoleConfig{Role: ModelRoleBuilder,- BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,+ BaseModelConfig: AvailableModelsByName[openai.GPT4Turbo].BaseModelConfig,Temperature: DefaultConfigByRole[ModelRoleBuilder].Temperature,TopP: DefaultConfigByRole[ModelRoleBuilder].TopP,},@@ -502,7 +504,51 @@ func init() {},ExecStatus: ModelRoleConfig{Role: ModelRoleExecStatus,- BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,+ BaseModelConfig: AvailableModelsByName[openai.GPT4Turbo].BaseModelConfig,+ Temperature: DefaultConfigByRole[ModelRoleBuilder].Temperature,+ TopP: DefaultConfigByRole[ModelRoleBuilder].TopP,+ },+ }++ OpenRouterClaudeOpusModelPack = ModelPack{+ Name: "anthropic-claude",+ Description: "Uses Anthropic's Claude Opus model (via OpenRouter) for planning, builds, and auto-continue, Claude Sonnet for summarization, and Claude Haiku for lighter tasks.",+ Planner: PlannerRoleConfig{+ ModelRoleConfig: ModelRoleConfig{+ Role: ModelRolePlanner,+ BaseModelConfig: AvailableModelsByName["anthropic/claude-3-opus"].BaseModelConfig,+ Temperature: DefaultConfigByRole[ModelRolePlanner].Temperature,+ TopP: DefaultConfigByRole[ModelRolePlanner].TopP,+ },+ PlannerModelConfig: getPlannerModelConfig("anthropic/claude-3-opus"),+ },+ PlanSummary: ModelRoleConfig{+ Role: ModelRolePlanSummary,+ BaseModelConfig: AvailableModelsByName["anthropic/claude-3-sonnet"].BaseModelConfig,+ Temperature: DefaultConfigByRole[ModelRolePlanSummary].Temperature,+ TopP: DefaultConfigByRole[ModelRolePlanSummary].TopP,+ },+ Builder: ModelRoleConfig{+ Role: ModelRoleBuilder,+ BaseModelConfig: AvailableModelsByName["anthropic/claude-3-opus"].BaseModelConfig,+ Temperature: DefaultConfigByRole[ModelRoleBuilder].Temperature,+ TopP: DefaultConfigByRole[ModelRoleBuilder].TopP,+ },+ Namer: ModelRoleConfig{+ Role: ModelRoleName,+ BaseModelConfig: AvailableModelsByName["anthropic/claude-3-haiku"].BaseModelConfig,+ Temperature: DefaultConfigByRole[ModelRoleName].Temperature,+ TopP: DefaultConfigByRole[ModelRoleName].TopP,+ },+ CommitMsg: ModelRoleConfig{+ Role: ModelRoleCommitMsg,+ BaseModelConfig: AvailableModelsByName["anthropic/claude-3-haiku"].BaseModelConfig,+ Temperature: DefaultConfigByRole[ModelRoleName].Temperature,+ TopP: DefaultConfigByRole[ModelRoleName].TopP,+ },+ ExecStatus: ModelRoleConfig{+ Role: ModelRoleExecStatus,+ BaseModelConfig: AvailableModelsByName["anthropic/claude-3-opus"].BaseModelConfig,Temperature: DefaultConfigByRole[ModelRoleBuilder].Temperature,TopP: DefaultConfigByRole[ModelRoleBuilder].TopP,},diff --git a/releases/cli/versions/1.0.2.md b/releases/cli/versions/1.0.2.mdindex b998df07..114c3025 100644--- a/releases/cli/versions/1.0.2.md+++ b/releases/cli/versions/1.0.2.md@@ -4,5 +4,7 @@- Remove 'gpt-4-turbo-preview' from list of built-in models and model packs- Better help text if `plandex load` is run with incorrect arguments- `plandex rm` can now accept a range of indices to remove (e.g. `plandex rm 1-5`)+- Non-OpenAI models can now be used for *all* roles, including the builder, verifier, and auto-fix roles, since streaming function calls are no longer required for these roles.- Fix for `plandex load` issue loading paths that begin with `./`-- Fixes for some occasional rendering issues when streaming plans and build counts\ No newline at end of file+- Fixes for some occasional rendering issues when streaming plans and build counts+- Fix for `plandex set-model` model selection showing built-in model options that aren't compatible with the selected role--now only compatible models are shown\ No newline at end of file