Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

Add plan start helpers for automating model and config selection

Dane Schneider5ee725f1e466
diff --git a/app/cli/cmd/plan_start_helpers.go b/app/cli/cmd/plan_start_helpers.go
new file mode 100644
index 00000000..0d3cb27a
--- /dev/null
+++ b/app/cli/cmd/plan_start_helpers.go
@@ -0,0 +1,179 @@
+package cmd
+
+import (
+ "fmt"
+ "plandex-cli/api"
+ "plandex-cli/lib"
+ "plandex-cli/term"
+ shared "plandex-shared"
+
+ "github.com/fatih/color"
+ "github.com/spf13/cobra"
+)
+
+var (
+ // Tier flags
+ noAuto bool
+ basicAuto bool
+ plusAuto bool
+ semiAuto bool
+ fullAuto bool
+
+ // Type flags
+ dailyModels bool
+ strongModels bool
+ ossModels bool
+ cheapModels bool
+)
+
+func AddNewPlanFlags(cmd *cobra.Command) {
+ // Add tier flags
+ cmd.Flags().BoolVar(&noAuto, "no-auto", false, shared.AutoModeDescriptions[shared.AutoModeNone])
+ cmd.Flags().BoolVar(&basicAuto, "basic", false, shared.AutoModeDescriptions[shared.AutoModeBasic])
+ cmd.Flags().BoolVar(&plusAuto, "plus", false, shared.AutoModeDescriptions[shared.AutoModePlus])
+ cmd.Flags().BoolVar(&semiAuto, "semi", false, shared.AutoModeDescriptions[shared.AutoModeSemi])
+ cmd.Flags().BoolVar(&fullAuto, "full", false, shared.AutoModeDescriptions[shared.AutoModeFull])
+
+ // Add type flags
+ cmd.Flags().BoolVar(&dailyModels, "daily", false, shared.DailyDriverModelPack.Description)
+ cmd.Flags().BoolVar(&strongModels, "strong", false, shared.StrongModelPack.Description)
+ cmd.Flags().BoolVar(&cheapModels, "cheap", false, shared.CheapModelPack.Description)
+ cmd.Flags().BoolVar(&ossModels, "oss", false, shared.OSSModelPack.Description)
+}
+
+func resolveAutoMode(config *shared.PlanConfig) (bool, *shared.PlanConfig) {
+ didUpdate, updatedConfig, _ := resolveAutoModeWithArgs(config, false)
+ return didUpdate, updatedConfig
+}
+
+func resolveAutoModeSilent(config *shared.PlanConfig) (bool, *shared.PlanConfig, func()) {
+ return resolveAutoModeWithArgs(config, true)
+}
+
+func resolveAutoModeWithArgs(config *shared.PlanConfig, silent bool) (bool, *shared.PlanConfig, func()) {
+ currentAutoMode := config.AutoMode
+ var toSetAutoMode shared.AutoModeType
+ if noAuto {
+ toSetAutoMode = shared.AutoModeNone
+ } else if basicAuto {
+ toSetAutoMode = shared.AutoModeBasic
+ } else if plusAuto {
+ toSetAutoMode = shared.AutoModePlus
+ } else if semiAuto {
+ toSetAutoMode = shared.AutoModeSemi
+ } else if fullAuto {
+ toSetAutoMode = shared.AutoModeFull
+ }
+
+ if toSetAutoMode != "" && toSetAutoMode != currentAutoMode {
+ if !silent {
+ term.StartSpinner("")
+ }
+ _, updatedConfig := updateConfig([]string{"auto-mode", string(toSetAutoMode)}, config)
+ apiErr := api.Client.UpdatePlanConfig(lib.CurrentPlanId, shared.UpdatePlanConfigRequest{
+ Config: updatedConfig,
+ })
+ if !silent {
+ term.StopSpinner()
+ }
+
+ if apiErr != nil {
+ term.OutputErrorAndExit("Error updating config auto-mode: %v", apiErr)
+ }
+
+ fn := func() {
+ fmt.Printf("🚀 Set %s to %s\n", color.New(color.Bold).Sprint("auto-mode"), color.New(color.Bold, term.ColorHiMagenta).Sprint(toSetAutoMode))
+ }
+
+ if !silent {
+ fn()
+ return true, updatedConfig, fn
+ }
+
+ return true, updatedConfig, fn
+ }
+
+ return false, config, nil
+}
+
+func resolveModelPack() {
+ resolveModelPackWithArgs(nil, false)
+}
+
+func resolveModelPackSilent(settings *shared.PlanSettings) (*shared.PlanSettings, func()) {
+ return resolveModelPackWithArgs(settings, true)
+}
+
+func resolveModelPackWithArgs(settings *shared.PlanSettings, silent bool) (*shared.PlanSettings, func()) {
+
+ var originalSettings *shared.PlanSettings
+ var apiErr *shared.ApiError
+ if settings == nil {
+ if !silent {
+ term.StartSpinner("")
+ }
+ originalSettings, apiErr = api.Client.GetSettings(lib.CurrentPlanId, lib.CurrentBranch)
+ } else {
+ originalSettings = settings
+ }
+
+ if apiErr != nil {
+ term.OutputErrorAndExit("Error getting current settings: %v", apiErr)
+ return nil, nil
+ }
+
+ var packName string
+
+ if ossModels {
+ packName = shared.OSSModelPack.Name
+ } else if strongModels {
+ packName = shared.StrongModelPack.Name
+ } else if cheapModels {
+ packName = shared.CheapModelPack.Name
+ } else {
+ packName = shared.DailyDriverModelPack.Name
+ }
+
+ if packName != originalSettings.ModelPack.Name {
+ if !silent {
+ term.StartSpinner("")
+ }
+ updatedSettings := updateModelSettings([]string{packName}, originalSettings)
+ _, apiErr = api.Client.UpdateSettings(lib.CurrentPlanId, lib.CurrentBranch, shared.UpdateSettingsRequest{
+ Settings: updatedSettings,
+ })
+ if !silent {
+ term.StopSpinner()
+ }
+
+ if apiErr != nil {
+ term.OutputErrorAndExit("Error setting model pack: %v", apiErr)
+ return nil, nil
+ }
+
+ fn := func() {
+ fmt.Printf("🧠 Set model pack to %s\n", color.New(color.Bold, term.ColorHiMagenta).Sprint(packName))
+ }
+
+ if !silent {
+ fn()
+ return updatedSettings, fn
+ }
+
+ return updatedSettings, fn
+ } else {
+ if !silent {
+ term.StopSpinner()
+ }
+ fn := func() {
+ fmt.Printf("🧠 Using model pack %s\n", color.New(color.Bold, term.ColorHiMagenta).Sprint(packName))
+ }
+
+ if !silent {
+ fn()
+ return originalSettings, fn
+ }
+
+ return originalSettings, fn
+ }
+}
diff --git a/app/server/model/client_stream.go b/app/server/model/client_stream.go
new file mode 100644
index 00000000..1ccb2a3b
--- /dev/null
+++ b/app/server/model/client_stream.go
@@ -0,0 +1,227 @@
+package model
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "plandex-server/types"
+ shared "plandex-shared"
+ "time"
+)
+
+type OnStreamFn func(chunk string, buffer string) (shouldStop bool)
+
+func CreateChatCompletionWithInternalStream(
+ clients map[string]ClientInfo,
+ modelConfig *shared.ModelRoleConfig,
+ ctx context.Context,
+ req types.ExtendedChatCompletionRequest,
+ onStream OnStreamFn,
+ reqStarted time.Time,
+) (*types.ModelResponse, error) {
+ client, ok := clients[modelConfig.BaseModelConfig.ApiKeyEnvVar]
+ if !ok {
+ return nil, fmt.Errorf("client not found for api key env var: %s", modelConfig.BaseModelConfig.ApiKeyEnvVar)
+ }
+
+ resolveReq(&req, modelConfig)
+
+ // choose the fastest provider by latency/throughput on openrouter
+ if modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenRouter {
+ req.Model += ":nitro"
+ }
+
+ // Force streaming mode since we're using the streaming API
+ req.Stream = true
+
+ return withStreamingRetries[types.ModelResponse](ctx, func() (*types.ModelResponse, error) {
+ return processChatCompletionStream(modelConfig, client, modelConfig.BaseModelConfig.BaseUrl, ctx, req, onStream, reqStarted)
+ })
+}
+
+func processChatCompletionStream(
+ modelConfig *shared.ModelRoleConfig,
+ client ClientInfo,
+ baseUrl string,
+ ctx context.Context,
+ req types.ExtendedChatCompletionRequest,
+ onStream OnStreamFn,
+ reqStarted time.Time,
+) (*types.ModelResponse, error) {
+ streamCtx, cancel := context.WithCancel(ctx)
+ defer cancel()
+
+ stream, err := createChatCompletionStreamExtended(modelConfig, client, baseUrl, streamCtx, req)
+ if err != nil {
+ return nil, fmt.Errorf("error creating chat completion stream: %w", err)
+ }
+ defer stream.Close()
+
+ accumulator := types.NewStreamCompletionAccumulator()
+ // Create a timer that will trigger if no chunk is received within the specified duration
+ timer := time.NewTimer(OPENAI_STREAM_CHUNK_TIMEOUT)
+ defer timer.Stop()
+ streamFinished := false
+
+ receivedFirstChunk := false
+
+ // Process stream until EOF or error
+ for {
+ select {
+ case <-streamCtx.Done():
+ log.Println("Stream canceled")
+ return accumulator.Result(true, streamCtx.Err()), streamCtx.Err()
+ case <-timer.C:
+ log.Println("Stream timed out due to inactivity")
+ if streamFinished {
+ log.Println("Stream finished—timed out waiting for usage chunk")
+ return accumulator.Result(false, nil), nil
+ } else {
+ log.Println("Stream timed out due to inactivity")
+ return accumulator.Result(true, fmt.Errorf("stream timed out due to inactivity. This usually means the model is not responding.")), nil
+ }
+ default:
+ response, err := stream.Recv()
+ if err == io.EOF {
+ if streamFinished {
+ return accumulator.Result(false, nil), nil
+ }
+
+ err = fmt.Errorf("model stream ended unexpectedly: %w", err)
+ return accumulator.Result(true, err), err
+ }
+ if err != nil {
+ err = fmt.Errorf("error receiving stream chunk: %w", err)
+ return accumulator.Result(true, err), err
+ }
+
+ if response.ID != "" {
+ accumulator.SetGenerationId(response.ID)
+ }
+
+ if !receivedFirstChunk {
+ receivedFirstChunk = true
+ accumulator.SetFirstTokenAt(time.Now())
+ }
+
+ if !timer.Stop() {
+ <-timer.C
+ }
+ timer.Reset(OPENAI_STREAM_CHUNK_TIMEOUT)
+
+ // Process the response
+ if response.Usage != nil {
+ accumulator.SetUsage(response.Usage)
+ return accumulator.Result(false, nil), nil
+ }
+
+ if len(response.Choices) == 0 {
+ log.Println("No choices in response")
+ err := fmt.Errorf("no choices in response")
+ return accumulator.Result(false, err), err
+ }
+
+ if len(response.Choices) > 1 {
+ err = fmt.Errorf("stream finished with more than one choice | This usually means the model failed to generate a valid response.")
+ return accumulator.Result(true, err), err
+ }
+
+ choice := response.Choices[0]
+
+ if choice.FinishReason != "" {
+ if choice.FinishReason == "error" {
+ err = fmt.Errorf("model stopped with error status | This usually means the model is not responding.")
+ return accumulator.Result(true, err), err
+ } else {
+ // Reset the timer for the usage chunk
+ if !timer.Stop() {
+ <-timer.C
+ }
+ timer.Reset(OPENAI_USAGE_CHUNK_TIMEOUT)
+ streamFinished = true
+ continue
+ }
+ }
+
+ var content string
+
+ if req.Tools != nil {
+ if choice.Delta.ToolCalls != nil {
+ toolCall := choice.Delta.ToolCalls[0]
+ content = toolCall.Function.Arguments
+ }
+ } else {
+ if choice.Delta.Content != "" {
+ content = choice.Delta.Content
+ }
+ }
+
+ accumulator.AddContent(content)
+ // pass the chunk and the accumulated content to the callback
+ if onStream != nil {
+ shouldReturn := onStream(content, accumulator.Content())
+ if shouldReturn {
+ return accumulator.Result(false, nil), nil
+ }
+ }
+ }
+ }
+}
+
+func withStreamingRetries[T any](
+ ctx context.Context,
+ operation func() (*types.ModelResponse, error),
+) (*types.ModelResponse, error) {
+ var result *types.ModelResponse
+ var numRetry int
+
+ for {
+ if ctx.Err() != nil {
+ if result != nil {
+ // Return partial result with context error
+ result.Stopped = true
+ result.Error = ctx.Err().Error()
+ return result, ctx.Err()
+ }
+ return nil, ctx.Err()
+ }
+
+ resp, err := operation()
+ if err == nil {
+ return resp, nil
+ }
+
+ // Store the partial result for potential return
+ result = resp
+
+ log.Printf("Error in streaming operation: %v, retry: %d\n", err, numRetry)
+
+ if isNonRetriableErr(err) {
+ return result, err
+ }
+
+ if numRetry >= OPENAI_MAX_RETRIES {
+ log.Println("Max retries reached - no retry")
+ return result, err
+ }
+
+ // Handle retry timing
+ if duration := parseRetryAfter(err.Error()); duration != nil {
+ log.Printf("Retry duration found: %v\n", *duration)
+ waitDuration := time.Duration(float64(*duration) * OPENAI_BACKOFF_MULTIPLIER)
+
+ if waitDuration > OPENAI_ABORT_WAIT_DURATION {
+ return result, err
+ } else if waitDuration > OPENAI_MAX_WAIT_DURATION {
+ waitDuration = OPENAI_MAX_WAIT_DURATION
+ }
+
+ time.Sleep(waitDuration)
+ } else {
+ waitBackoff(numRetry)
+ }
+
+ numRetry++
+ }
+}
diff --git a/app/server/model/model_request.go b/app/server/model/model_request.go
new file mode 100644
index 00000000..2d235502
--- /dev/null
+++ b/app/server/model/model_request.go
@@ -0,0 +1,173 @@
+package model
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "plandex-server/db"
+ "plandex-server/hooks"
+ "plandex-server/types"
+ shared "plandex-shared"
+ "time"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+type ModelRequestParams struct {
+ Clients map[string]ClientInfo
+ Auth *types.ServerAuth
+ Plan *db.Plan
+ ModelConfig *shared.ModelRoleConfig
+ Purpose string
+
+ Messages []types.ExtendedChatMessage
+ Prediction string
+ Stop []string
+ Tools []openai.Tool
+ ToolChoice *openai.ToolChoice
+
+ EstimatedOutputTokens int // optional
+
+ ModelStreamId string
+ ConvoMessageId string
+ BuildId string
+ ModelPackName string
+
+ BeforeReq func()
+ AfterReq func()
+
+ OnStream func(string, string) bool
+}
+
+func ModelRequest(
+ ctx context.Context,
+ params ModelRequestParams,
+) (*types.ModelResponse, error) {
+ clients := params.Clients
+ auth := params.Auth
+ plan := params.Plan
+ messages := params.Messages
+ prediction := params.Prediction
+ stop := params.Stop
+ tools := params.Tools
+ toolChoice := params.ToolChoice
+ modelConfig := params.ModelConfig
+ modelStreamId := params.ModelStreamId
+ convoMessageId := params.ConvoMessageId
+ buildId := params.BuildId
+ modelPackName := params.ModelPackName
+ purpose := params.Purpose
+
+ if purpose == "" {
+ return nil, fmt.Errorf("purpose is required")
+ }
+
+ inputTokensEstimate := GetMessagesTokenEstimate(messages...) + TokensPerRequest
+
+ config := modelConfig.GetRoleForInputTokens(inputTokensEstimate)
+ modelConfig = &config
+
+ if params.EstimatedOutputTokens != 0 {
+ config = modelConfig.GetRoleForOutputTokens(params.EstimatedOutputTokens)
+ modelConfig = &config
+ }
+
+ _, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
+ Auth: auth,
+ Plan: plan,
+ WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
+ InputTokens: inputTokensEstimate,
+ OutputTokens: modelConfig.BaseModelConfig.MaxOutputTokens - inputTokensEstimate,
+ ModelName: modelConfig.BaseModelConfig.ModelName,
+ },
+ })
+
+ if apiErr != nil {
+ return nil, apiErr
+ }
+
+ if params.BeforeReq != nil {
+ params.BeforeReq()
+ }
+
+ reqStarted := time.Now()
+
+ req := types.ExtendedChatCompletionRequest{
+ Model: modelConfig.BaseModelConfig.ModelName,
+ Messages: messages,
+ Temperature: modelConfig.Temperature,
+ TopP: modelConfig.TopP,
+ Stop: stop,
+ Tools: tools,
+ ToolChoice: toolChoice,
+ }
+
+ if prediction != "" {
+ req.Prediction = &types.OpenAIPrediction{
+ Type: "content",
+ Content: prediction,
+ }
+ }
+
+ res, err := CreateChatCompletionWithInternalStream(clients, modelConfig, ctx, req, params.OnStream, reqStarted)
+
+ if err != nil {
+ return nil, err
+ }
+
+ if params.AfterReq != nil {
+ params.AfterReq()
+ }
+
+ log.Printf("\n\n**\n\nModel response: %s\n\n**\n\n", res.Content)
+
+ var inputTokens int
+ var outputTokens int
+ var cachedTokens int
+
+ if res.Usage != nil {
+ if res.Usage.PromptTokensDetails != nil {
+ cachedTokens = res.Usage.PromptTokensDetails.CachedTokens
+ }
+ inputTokens = res.Usage.PromptTokens
+ outputTokens = res.Usage.CompletionTokens
+ } else {
+ inputTokens = inputTokensEstimate
+ outputTokens = shared.GetNumTokensEstimate(res.Content)
+ }
+
+ go func() {
+ _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
+ Auth: auth,
+ Plan: plan,
+ DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
+ InputTokens: inputTokens,
+ OutputTokens: outputTokens,
+ CachedTokens: cachedTokens,
+ ModelName: modelConfig.BaseModelConfig.ModelName,
+ ModelProvider: modelConfig.BaseModelConfig.Provider,
+ ModelPackName: modelPackName,
+ ModelRole: shared.ModelRoleBuilder,
+ Purpose: purpose,
+ GenerationId: res.GenerationId,
+ PlanId: plan.Id,
+ ModelStreamId: modelStreamId,
+ ConvoMessageId: convoMessageId,
+ BuildId: buildId,
+
+ RequestStartedAt: reqStarted,
+ Streaming: true,
+ Req: &req,
+ StreamResult: res.Content,
+ ModelConfig: modelConfig,
+ FirstTokenAt: res.FirstTokenAt,
+ },
+ })
+
+ if apiErr != nil {
+ log.Printf("buildWholeFile - error executing DidSendModelRequest hook: %v", apiErr)
+ }
+ }()
+
+ return res, nil
+}
diff --git a/app/server/model/plan/build_validate_and_fix.go b/app/server/model/plan/build_validate_and_fix.go
new file mode 100644
index 00000000..64528033
--- /dev/null
+++ b/app/server/model/plan/build_validate_and_fix.go
@@ -0,0 +1,371 @@
+package plan
+
+import (
+ "context"
+ "fmt"
+ "log"
+ "math/rand"
+ diff_pkg "plandex-server/diff"
+ "plandex-server/model"
+ "plandex-server/model/prompts"
+ "plandex-server/syntax"
+ "plandex-server/types"
+ "plandex-server/utils"
+ shared "plandex-shared"
+ "strings"
+ "time"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+const MaxValidationFixAttempts = 4
+
+type buildValidateLoopParams struct {
+ originalFile string
+ updated string
+ proposedContent string
+ desc string
+ syntaxErrors []string
+ reasons []syntax.NeedsVerifyReason
+ initialPhaseOnStream func(chunk string, buffer string) bool
+}
+
+type buildValidateLoopResult struct {
+ valid bool
+ updated string
+}
+
+func (fileState *activeBuildStreamFileState) buildValidateLoop(
+ ctx context.Context,
+ params buildValidateLoopParams,
+) (buildValidateLoopResult, error) {
+ log.Printf("Starting buildValidateLoop for file: %s", fileState.filePath)
+
+ originalFile := params.originalFile
+ updated := params.updated
+ proposedContent := params.proposedContent
+ desc := params.desc
+
+ syntaxErrors := params.syntaxErrors
+ numAttempts := 0
+
+ for numAttempts < MaxValidationFixAttempts {
+ currentAttempt := numAttempts + 1
+ log.Printf("Starting validation attempt %d/%d", currentAttempt, MaxValidationFixAttempts)
+
+ // check for context cancellation
+ if ctx.Err() != nil {
+ log.Printf("Context cancelled during attempt %d", currentAttempt)
+ return buildValidateLoopResult{}, ctx.Err()
+ }
+
+ // reset retry count for each phase
+ fileState.validationNumRetry = 0
+ log.Printf("Reset validation retry count for attempt %d", currentAttempt)
+
+ var onStream func(chunk string, buffer string) bool
+ if numAttempts == 0 {
+ onStream = params.initialPhaseOnStream
+ log.Printf("Using initial phase onStream handler")
+ } else {
+ onStream = nil
+ log.Printf("No onStream handler for attempt %d", currentAttempt)
+ }
+
+ var reasons []syntax.NeedsVerifyReason
+ if numAttempts == 0 {
+ reasons = params.reasons
+ log.Printf("Using initial reasons for validation")
+ } else {
+ reasons = []syntax.NeedsVerifyReason{}
+ log.Printf("Using empty reasons list for attempt %d", currentAttempt)
+ }
+
+ modelConfig := fileState.settings.ModelPack.Builder
+ // if available, switch to stronger model after the first attempt failed
+ if currentAttempt > 2 && modelConfig.StrongModel != nil {
+ log.Printf("Switching to strong model for attempt %d", currentAttempt)
+ modelConfig = *modelConfig.StrongModel
+ }
+
+ // build validate params
+ validateParams := buildValidateParams{
+ originalFile: originalFile,
+ updated: updated,
+ proposedContent: proposedContent,
+ desc: desc,
+ onStream: onStream,
+ syntaxErrors: syntaxErrors,
+ reasons: reasons,
+ modelConfig: &modelConfig,
+ }
+
+ log.Printf("Calling buildValidate for attempt %d", currentAttempt)
+ valid, res, err := fileState.buildValidate(ctx, validateParams)
+ if err != nil {
+ log.Printf("Error in buildValidate during attempt %d: %v", currentAttempt, err)
+ return buildValidateLoopResult{}, fmt.Errorf("error building validate: %v", err)
+ }
+ updated = res
+
+ if valid {
+ log.Printf("Validation succeeded in attempt %d", currentAttempt)
+ return buildValidateLoopResult{
+ valid: valid,
+ updated: updated,
+ }, nil
+ }
+
+ log.Printf("Validation failed in attempt %d, preparing for next attempt", currentAttempt)
+ syntaxErrors = fileState.validateSyntax(ctx, updated)
+ log.Printf("Found %d syntax errors after attempt %d", len(syntaxErrors), currentAttempt)
+
+ numAttempts++
+ }
+
+ log.Printf("Validation failed after %d attempts", MaxValidationFixAttempts)
+ return buildValidateLoopResult{
+ valid: false,
+ updated: updated,
+ }, nil
+}
+
+type buildValidateParams struct {
+ originalFile string
+ updated string
+ proposedContent string
+ desc string
+ syntaxErrors []string
+ reasons []syntax.NeedsVerifyReason
+ onStream func(chunk string, buffer string) bool
+ phase int
+ modelConfig *shared.ModelRoleConfig
+}
+
+func (fileState *activeBuildStreamFileState) buildValidate(
+ ctx context.Context,
+ params buildValidateParams,
+) (bool, string, error) {
+ log.Printf("Starting buildValidate for phase %d", params.phase)
+
+ auth := fileState.auth
+ filePath := fileState.filePath
+ clients := fileState.clients
+ modelConfig := params.modelConfig
+
+ originalFile := params.originalFile
+ updated := params.updated
+ proposedContent := params.proposedContent
+ desc := params.desc
+ onStream := params.onStream
+ syntaxErrors := params.syntaxErrors
+ reasons := params.reasons
+
+ // Get diff for validation
+ log.Printf("Getting diffs between original and updated content")
+ diff, err := diff_pkg.GetDiffs(originalFile, updated)
+ if err != nil {
+ log.Printf("Error getting diffs: %v", err)
+ return false, "", fmt.Errorf("error getting diffs: %v", err)
+ }
+
+ // Choose prompt and tools based on preferred format
+
+ log.Printf("Building XML validation replacements prompt")
+ promptText := prompts.GetValidationReplacementsXmlPrompt(prompts.ValidationPromptParams{
+ Path: filePath,
+ Original: originalFile,
+ Desc: desc,
+ Proposed: proposedContent,
+ Diff: diff,
+ SyntaxErrors: syntaxErrors,
+ Reasons: reasons,
+ })
+
+ // log.Printf("Prompt to LLM: %s", promptText)
+
+ log.Printf("Creating initial messages for phase 1")
+ messages := []types.ExtendedChatMessage{
+ {
+ Role: openai.ChatMessageRoleSystem,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: promptText,
+ },
+ },
+ },
+ }
+ reqStarted := time.Now()
+ fileState.builderRun.ReplacementStartedAt = reqStarted
+
+ log.Printf("Making validation-replacements model request")
+ // log.Printf("Messages: %v", messages)
+
+ // Use ModelRequest for both formats
+ res, err := model.ModelRequest(ctx, model.ModelRequestParams{
+ Clients: clients,
+ Auth: auth,
+ Plan: fileState.plan,
+ ModelConfig: modelConfig,
+ Purpose: "File edit",
+ Messages: messages,
+ ModelStreamId: fileState.modelStreamId,
+ ConvoMessageId: fileState.convoMessageId,
+ BuildId: fileState.build.Id,
+ ModelPackName: fileState.settings.ModelPack.Name,
+ Stop: []string{"<PlandexFinish/>"},
+ BeforeReq: func() {
+ log.Printf("Starting model request")
+ fileState.builderRun.ReplacementStartedAt = time.Now()
+ },
+ AfterReq: func() {
+ log.Printf("Finished model request")
+ fileState.builderRun.ReplacementFinishedAt = time.Now()
+ },
+ OnStream: onStream,
+ })
+
+ if err != nil {
+ log.Printf("Error calling model: %v", err)
+ return fileState.validationRetryOrError(ctx, params, err)
+ }
+
+ fileState.builderRun.GenerationIds = append(fileState.builderRun.GenerationIds, res.GenerationId)
+ log.Printf("Added generation ID: %s", res.GenerationId)
+
+ // Handle response based on format
+ valid, updated, err := handleXMLResponse(fileState, res.Content, originalFile, updated)
+
+ if err != nil {
+ log.Printf("Error handling response: %v", err)
+ return fileState.validationRetryOrError(ctx, params, err)
+ }
+
+ if valid {
+ log.Printf("Validation result: valid=%v", valid)
+ return valid, updated, nil
+ }
+
+ return false, updated, nil
+}
+
+func handleXMLResponse(
+ fileState *activeBuildStreamFileState,
+ content string,
+ originalFile string,
+ updated string,
+) (bool, string, error) {
+ log.Printf("Handling XML response for file: %s", fileState.filePath)
+
+ if strings.Contains(content, "<PlandexCorrect/>") {
+ log.Printf("XML response indicates changes are correct")
+ fileState.builderRun.ReplacementSuccess = true
+ return true, updated, nil
+ }
+ originalFileLines := strings.Split(originalFile, "\n")
+
+ updated = originalFile
+
+ log.Printf("Processing XML replacement blocks")
+
+ replacementsOuter := utils.GetXMLContent(content, "PlandexReplacements")
+
+ if replacementsOuter == "" {
+ log.Printf("No replacements found in XML response")
+ return false, updated, fmt.Errorf("no replacements found in XML response")
+ }
+
+ replacements := utils.GetAllXMLContent(replacementsOuter, "Replacement")
+
+ for i, replacement := range replacements {
+ log.Printf("Processing replacement: %d/%d", i+1, len(replacements))
+
+ old := utils.GetXMLContent(replacement, "Old")
+ new := utils.GetXMLContent(replacement, "New")
+
+ if old == "" {
+ log.Printf("No old content found for replacement")
+ return false, updated, fmt.Errorf("no old content found for replacement")
+ }
+
+ old = strings.TrimSpace(old)
+
+ log.Printf("Old content trimmed:\n\n%s", old)
+
+ if !strings.HasPrefix(old, "pdx-") {
+ log.Printf("Old content does not have a line number prefix for first line")
+ return false, updated, fmt.Errorf("old content does not have a line number prefix for first line")
+ }
+
+ oldLines := strings.Split(old, "\n")
+
+ var lastLine string
+ var lastLineNum int
+ firstLine := oldLines[0]
+ if len(oldLines) > 1 {
+ lastLine = oldLines[len(oldLines)-1]
+ }
+
+ firstLineNum, err := shared.ExtractLineNumberWithPrefix(firstLine, "pdx-")
+ if err != nil {
+ log.Printf("Error extracting line number from first line: %v", err)
+ return false, updated, fmt.Errorf("error extracting line number from first line: %v", err)
+ }
+
+ if lastLine != "" {
+ lastLineNum, err = shared.ExtractLineNumberWithPrefix(lastLine, "pdx-")
+ if err != nil {
+ log.Printf("Error extracting line number from last line: %v", err)
+ return false, updated, fmt.Errorf("error extracting line number from last line: %v", err)
+ }
+ }
+
+ if lastLineNum == 0 {
+ old = originalFileLines[firstLineNum-1]
+ } else {
+ old = strings.Join(originalFileLines[firstLineNum-1:lastLineNum], "\n")
+ }
+
+ log.Printf("Applying replacement.\n\nOld:\n\n%s\n\nNew:\n\n%s", old, new)
+
+ updated = strings.Replace(updated, old, new, 1)
+
+ log.Printf("Updated content:\n\n%s", updated)
+ }
+
+ return false, updated, nil
+}
+
+func (fileState *activeBuildStreamFileState) validationRetryOrError(buildCtx context.Context, validateParams buildValidateParams, err error) (bool, string, error) {
+ log.Printf("Handling validation error for file: %s", fileState.filePath)
+ if fileState.validationNumRetry < MaxBuildErrorRetries {
+ fileState.validationNumRetry++
+
+ log.Printf("Retrying validation (attempt %d/%d) due to error: %v",
+ fileState.validationNumRetry, MaxBuildErrorRetries, err)
+
+ activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)
+
+ if activePlan == nil {
+ log.Printf("Active plan not found for plan ID %s and branch %s",
+ fileState.plan.Id, fileState.branch)
+ return false, "", fmt.Errorf("active plan not found for plan ID %s and branch %s",
+ fileState.plan.Id, fileState.branch)
+ }
+
+ select {
+ case <-buildCtx.Done():
+ log.Printf("Context canceled during retry wait")
+ return false, "", context.Canceled
+ case <-time.After(time.Duration(fileState.validationNumRetry*fileState.validationNumRetry)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond):
+ log.Printf("Retry wait completed, attempting validation again")
+ break
+ }
+
+ return fileState.buildValidate(buildCtx, validateParams)
+ } else {
+ log.Printf("Max retries (%d) exceeded, returning error", MaxBuildErrorRetries)
+ return false, "", err
+ }
+}
diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.go
index 65d91362..f210ee1d 100644
--- a/app/server/model/plan/tell_summary.go
+++ b/app/server/model/plan/tell_summary.go
@@ -104,13 +104,13 @@ func (state *activeTellStreamState) addConversationMessages() bool {
}
}
- if summary == nil {
+ if summary == nil && tokensBeforeConvo+conversationTokens > state.settings.GetPlannerEffectiveMaxTokens() {
err := errors.New("couldn't get under token limit with conversation summary")
log.Printf("Error: %v\n", err)
active.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeOther,
Status: http.StatusInternalServerError,
- Msg: "Couldn't get under token limit with conversation summary",
+ Msg: "Exceeded token limit",
}
return false
}
@@ -378,7 +378,7 @@ func summarizeConvo(clients map[string]model.ClientInfo, config shared.ModelRole
Auth: params.auth,
Plan: plan,
ModelPackName: params.modelPackName,
- ActivePlan: active,
+ ModelStreamId: active.ModelStreamId,
}, ctx)
if apiErr != nil {
diff --git a/images/plandex-workflow.png b/images/plandex-workflow.png
new file mode 100644
index 00000000..8368402d
Binary files /dev/null and b/images/plandex-workflow.png differ
diff --git a/releases/cli/versions/2.0.0-rc.1.md b/releases/cli/versions/2.0.0-rc.1.md
new file mode 100644
index 00000000..0f23c7da
--- /dev/null
+++ b/releases/cli/versions/2.0.0-rc.1.md
@@ -0,0 +1,52 @@
+Hey, Dane here
+
+I'm excited to announce the beta release of Plandex v2, featuring major improvements in capabilities, user experience, and automation.. This release represents a significant step forward in making AI-powered development more accessible and powerful.
+
+## Key Highlights
+
+### 🧠 Enhanced Model Capabilities
+
+- New default model pack combining Claude 3.5 Sonnet, o3-mini, and Gemini 1.5 Pro
+- 2M token context window for handling larger codebases
+- Improved file editing performance, especially for large files
+- Automatic context selection with smart symbol mapping
+
+### 💻 New Developer Experience
+
+- Introducing the Plandex REPL with fuzzy autocomplete and multi-line editing
+- Chat mode for planning and discussion without code changes
+- GitHub-style UI for reviewing diffs in browser
+- Reduced terminal flickering during plan streaming
+
+### 🚀 Advanced Automation
+
+- Full auto mode for end-to-end task completion
+- Automated debugging with intelligent retry logic
+- Script execution with configurable approval flows
+- Stronger file edit reliability with new algorithms
+
+### 💳 Built-in Payments & Credits
+
+- Native credits system on Plandex Cloud
+- Support for custom API key integration
+- Flexible payment options
+
+For a complete list of new features and improvements, see our What's New in v2 documentation.
+
+Installation
+
+
+bashCopypip install plandex==2.0.0b1
+Getting Started
+
+Update to the latest version
+Configure your preferred model pack with plandex set-model
+Try the new REPL with plandex repl
+
+## Feedback
+
+This is a beta release. I'm actively gathering feedback from the Plandex community. Please share your experiences and suggestions:
+
+- Join the Plandex Discord community
+- Open issues on GitHub
+- Email me at [email protected]
\ No newline at end of file
diff --git a/releases/server/versions/2.0.0-rc.1.md b/releases/server/versions/2.0.0-rc.1.md
new file mode 100644
index 00000000..e69de29b