Skip to content

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

Refactor plan state management and chat interface handling with improved stage transitions and context management

Dane Schneiderc126542d8ac4
diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.go
index 8aa2420f..7929303d 100644
--- a/app/server/model/plan/build_exec.go
+++ b/app/server/model/plan/build_exec.go
@@ -3,7 +3,9 @@ package plan
import (
"fmt"
"log"
+ "path/filepath"
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/model"
"plandex-server/types"
"time"
@@ -143,6 +145,12 @@ func (buildState *activeBuildStreamState) execPlanBuild(activeBuild *types.Activ
activeBuildStreamState: buildState,
filePath: filePath,
activeBuild: activeBuild,
+ builderRun: hooks.DidFinishBuilderRunParams{
+ StartedAt: time.Now(),
+ PlanId: activePlan.Id,
+ FilePath: filePath,
+ FileExt: filepath.Ext(filePath),
+ },
}
log.Printf("execPlanBuild - %s - calling fileState.loadBuildFile()\n", filePath)
@@ -194,9 +202,7 @@ func (fileState *activeBuildStreamFileState) buildFile() {
}
log.Printf("Building file %s\n", filePath)
-
log.Printf("%d files in context\n", len(activePlan.ContextsByPath))
-
// log.Println("activePlan.ContextsByPath files:")
// for k := range activePlan.ContextsByPath {
// log.Println(k)
diff --git a/app/server/model/plan/build_finish.go b/app/server/model/plan/build_finish.go
index 353692b1..be260463 100644
--- a/app/server/model/plan/build_finish.go
+++ b/app/server/model/plan/build_finish.go
@@ -5,8 +5,10 @@ import (
"log"
"net/http"
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/types"
"strings"
+ "time"
shared "plandex-shared"
)
@@ -86,7 +88,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {
defer func() {
if err != nil {
log.Printf("Finish build error: %v\n", err)
- err = db.GitClearUncommittedChanges(currentOrgId, planId)
+ err = db.GitClearUncommittedChanges(currentOrgId, planId, branch)
if err != nil {
log.Printf("Error clearing uncommitted changes: %v\n", err)
}
@@ -242,7 +244,7 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanF
defer func() {
if err != nil {
log.Printf("Error storing plan result: %v\n", err)
- err = db.GitClearUncommittedChanges(currentOrgId, planId)
+ err = db.GitClearUncommittedChanges(currentOrgId, planId, branch)
if err != nil {
log.Printf("Error clearing uncommitted changes: %v\n", err)
}
@@ -285,6 +287,13 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanF
return
}
+ fileState.builderRun.FinishedAt = time.Now()
+ hooks.ExecHook(hooks.DidFinishBuilderRun, hooks.HookParams{
+ Auth: fileState.auth,
+ Plan: fileState.plan,
+ DidFinishBuilderRunParams: &fileState.builderRun,
+ })
+
log.Printf("Finished building file %s - setting activeBuild.Success to true\n", filePath)
// log.Println(spew.Sdump(activeBuild))
@@ -363,7 +372,7 @@ func (fileState *activeBuildStreamFileState) onBuildFileError(err error) {
}
// rollback repo in case there are uncommitted builds
- err = db.GitClearUncommittedChanges(currentOrgId, planId)
+ err = db.GitClearUncommittedChanges(currentOrgId, planId, branch)
if err != nil {
log.Printf("Error clearing uncommitted changes: %v\n", err)
diff --git a/app/server/model/plan/build_load.go b/app/server/model/plan/build_load.go
index dbe9ee93..d64895ed 100644
--- a/app/server/model/plan/build_load.go
+++ b/app/server/model/plan/build_load.go
@@ -145,6 +145,8 @@ func (state *activeBuildStreamFileState) loadBuildFile(activeBuild *types.Active
state.language = validationRes.Lang
state.parser = validationRes.Parser
+ state.builderRun.Lang = string(validationRes.Lang)
+
if validationRes.TimedOut {
state.syntaxCheckTimedOut = true
} else if !validationRes.Valid {
diff --git a/app/server/model/plan/build_state.go b/app/server/model/plan/build_state.go
index 8b02d81f..6c8d1913 100644
--- a/app/server/model/plan/build_state.go
+++ b/app/server/model/plan/build_state.go
@@ -2,6 +2,7 @@ package plan
import (
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/model"
"plandex-server/types"
@@ -41,4 +42,6 @@ type activeBuildStreamFileState struct {
wholeFileNumRetry int
isNewFile bool
contextPart *db.Context
+
+ builderRun hooks.DidFinishBuilderRunParams
}
diff --git a/app/server/model/plan/build_structured_edits.go b/app/server/model/plan/build_structured_edits.go
index 459b6666..3626ad25 100644
--- a/app/server/model/plan/build_structured_edits.go
+++ b/app/server/model/plan/build_structured_edits.go
@@ -10,6 +10,7 @@ import (
"plandex-server/model"
"plandex-server/model/prompts"
"plandex-server/syntax"
+ "plandex-server/types"
"strings"
"time"
@@ -66,8 +67,8 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
fileState.language,
activePlan.Ctx,
)
- log.Println("buildStructuredEdits - applyRes.NewFile:")
- log.Println(applyRes.NewFile)
+ // log.Println("buildStructuredEdits - applyRes.NewFile:")
+ // log.Println(applyRes.NewFile)
log.Println("buildStructuredEdits - applyRes.NeedsVerifyReasons:")
log.Println(applyRes.NeedsVerifyReasons)
@@ -92,6 +93,16 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
isValid := len(applyRes.NeedsVerifyReasons) == 0 && len(syntaxErrors) == 0
+ if isValid {
+ fileState.builderRun.AutoApplySuccess = true
+ } else {
+ fileState.builderRun.AutoApplyValidationReasons = make([]string, len(applyRes.NeedsVerifyReasons))
+ for i, reason := range applyRes.NeedsVerifyReasons {
+ fileState.builderRun.AutoApplyValidationReasons[i] = string(reason)
+ }
+ fileState.builderRun.AutoApplyValidationSyntaxErrors = syntaxErrors
+ }
+
log.Printf("buildStructuredEdits - %s - initial isValid: %t\n", filePath, isValid)
// var buildStage BuildStage = BuildStageInitial
@@ -140,14 +151,19 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
// log.Printf("buildStructuredEdits - %s - validateSysPrompt:\n%s\n", filePath, validateSysPrompt)
- validateFileMessages := []openai.ChatCompletionMessage{
+ validateFileMessages := []types.ExtendedChatMessage{
{
- Role: openai.ChatMessageRoleSystem,
- Content: validateSysPrompt,
+ Role: openai.ChatMessageRoleSystem,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: validateSysPrompt,
+ },
+ },
},
}
- inputTokens := shared.GetMessagesTokenEstimate(validateFileMessages...) + shared.TokensPerRequest
+ inputTokens := model.GetMessagesTokenEstimate(validateFileMessages...) + model.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -165,13 +181,17 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
log.Println("buildStructuredEdits - calling model for applied changes validation")
- modelReq := openai.ChatCompletionRequest{
+ modelReq := types.ExtendedChatCompletionRequest{
Model: config.BaseModelConfig.ModelName,
Messages: validateFileMessages,
Temperature: config.Temperature,
TopP: config.TopP,
Stop: []string{"<PlandexFinish/>"},
}
+ reqStarted := time.Now()
+
+ fileState.builderRun.ValidateModelConfig = &config
+ fileState.builderRun.AutoApplyValidationStartedAt = time.Now()
resp, err := model.CreateChatCompletionWithRetries(clients, &config, activePlan.Ctx, modelReq)
@@ -181,6 +201,8 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
return
}
+ fileState.builderRun.GenerationIds = append(fileState.builderRun.GenerationIds, resp.ID)
+
log.Println("buildStructuredEdits - usage:")
log.Println(spew.Sdump(resp.Usage))
@@ -201,6 +223,12 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
ModelStreamId: fileState.tellState.activePlan.ModelStreamId,
ConvoMessageId: fileState.convoMessageId,
BuildId: fileState.build.Id,
+
+ RequestStartedAt: reqStarted,
+ Streaming: false,
+ Req: &modelReq,
+ Res: &resp,
+ ModelConfig: &config,
},
})
@@ -286,6 +314,13 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
} else if buildStage == BuildStageValidateOnly {
isValid = strings.Contains(content, "<PlandexCorrect/>")
+
+ fileState.builderRun.AutoApplyValidationFinishedAt = time.Now()
+ if isValid {
+ fileState.builderRun.AutoApplyValidationPassed = true
+ } else {
+ fileState.builderRun.AutoApplyValidationFailureResponse = content
+ }
}
}
diff --git a/app/server/model/plan/build_whole_file.go b/app/server/model/plan/build_whole_file.go
index a19513d8..67f58b2a 100644
--- a/app/server/model/plan/build_whole_file.go
+++ b/app/server/model/plan/build_whole_file.go
@@ -9,6 +9,7 @@ import (
"plandex-server/hooks"
"plandex-server/model"
"plandex-server/model/prompts"
+ "plandex-server/types"
"strings"
"time"
@@ -37,17 +38,22 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(proposedCont
sysPrompt := prompts.GetWholeFilePrompt(filePath, originalFile, desc, proposedContent)
- messages := []openai.ChatCompletionMessage{
+ messages := []types.ExtendedChatMessage{
{
- Role: openai.ChatMessageRoleSystem,
- Content: sysPrompt,
+ Role: openai.ChatMessageRoleSystem,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: sysPrompt,
+ },
+ },
},
}
maxExpectedOutputTokens := shared.GetNumTokensEstimate(originalFile + proposedContent)
modelConfig := config.GetRoleForOutputTokens(maxExpectedOutputTokens)
- inputTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
+ inputTokens := model.GetMessagesTokenEstimate(messages...) + model.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -68,21 +74,14 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(proposedCont
var resp openai.ChatCompletionResponse
var err error
- modelReq := &openai.ChatCompletionRequest{
- Model: modelConfig.BaseModelConfig.ModelName,
- Messages: messages,
- Temperature: modelConfig.Temperature,
- TopP: modelConfig.TopP,
- }
-
log.Println("buildWholeFile - modelConfig.BaseModelConfig.PredictedOutputEnabled:", modelConfig.BaseModelConfig.PredictedOutputEnabled)
+ var prediction *types.OpenAIPrediction
+
if modelConfig.BaseModelConfig.PredictedOutputEnabled {
- extendedReq := &model.ExtendedChatCompletionRequest{
- ChatCompletionRequest: modelReq,
- Prediction: &model.OpenAIPrediction{
- Type: "content",
- Content: `
+ prediction = &types.OpenAIPrediction{
+ Type: "content",
+ Content: `
## Comments
No comments
@@ -91,19 +90,32 @@ No comments
` + originalFile + `
</PlandexWholeFile>
`,
- },
}
- resp, err = model.CreateChatCompletionWithRetries(clients, &config, activePlan.Ctx, *extendedReq)
- } else {
- resp, err = model.CreateChatCompletionWithRetries(clients, &config, activePlan.Ctx, *modelReq)
}
+ extendedReq := &types.ExtendedChatCompletionRequest{
+ Model: modelConfig.BaseModelConfig.ModelName,
+ Messages: messages,
+ Temperature: modelConfig.Temperature,
+ TopP: modelConfig.TopP,
+ Prediction: prediction,
+ }
+
+ reqStarted := time.Now()
+ fileState.builderRun.BuiltWholeFile = true
+ fileState.builderRun.BuildWholeFileStartedAt = reqStarted
+
+ resp, err = model.CreateChatCompletionWithRetries(clients, &config, activePlan.Ctx, *extendedReq)
+
if err != nil {
log.Printf("buildWholeFile - error calling model: %v\n", err)
fileState.wholeFileRetryOrError(proposedContent, desc, fmt.Errorf("error calling model: %v", err))
return
}
+ fileState.builderRun.GenerationIds = append(fileState.builderRun.GenerationIds, resp.ID)
+ fileState.builderRun.BuildWholeFileFinishedAt = time.Now()
+
log.Println("buildWholeFile - usage:")
log.Println(spew.Sdump(resp.Usage))
@@ -124,6 +136,12 @@ No comments
ModelStreamId: fileState.tellState.activePlan.ModelStreamId,
ConvoMessageId: fileState.convoMessageId,
BuildId: fileState.build.Id,
+
+ RequestStartedAt: reqStarted,
+ Streaming: false,
+ Req: extendedReq,
+ Res: &resp,
+ ModelConfig: &config,
},
})
diff --git a/app/server/model/plan/tell_context.go b/app/server/model/plan/tell_context.go
index 0a91ce84..05a9150a 100644
--- a/app/server/model/plan/tell_context.go
+++ b/app/server/model/plan/tell_context.go
@@ -4,6 +4,7 @@ import (
"fmt"
"log"
"net/http"
+ "plandex-server/types"
"regexp"
"strings"
@@ -12,16 +13,41 @@ import (
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees, isImplementationStage, smartContextEnabled, execEnabled bool) (string, error) {
+type formatModelContextParams struct {
+ includeMaps bool
+ smartContextEnabled bool
+ execEnabled bool
+ basicOnly bool
+ cache bool
+ activeOnly bool
+ autoOnly bool
+ activatedPaths map[string]bool
+}
+
+func (state *activeTellStreamState) formatModelContext(params formatModelContextParams) *types.ExtendedChatMessagePart {
log.Println("Tell plan - formatModelContext")
+ includeMaps := params.includeMaps
+ smartContextEnabled := params.smartContextEnabled
+ execEnabled := params.execEnabled
+ currentStage := state.currentStage
+
+ basicOnly := params.basicOnly
+ activeOnly := params.activeOnly
+ autoOnly := params.autoOnly
+ activatedPaths := params.activatedPaths
+
+ if activatedPaths == nil {
+ activatedPaths = map[string]bool{}
+ }
+
var contextMessages []string = []string{
"### LATEST PLAN CONTEXT ###",
}
addedFilesSet := map[string]bool{}
uses := map[string]bool{}
- if isImplementationStage && smartContextEnabled && state.currentSubtask != nil {
+ if currentStage.TellStage == shared.TellStageImplementation && smartContextEnabled && state.currentSubtask != nil {
log.Println("Tell plan - formatModelContext - implementation stage - smart context enabled for current subtask")
for _, path := range state.currentSubtask.UsesFiles {
uses[path] = true
@@ -30,7 +56,19 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
}
for _, part := range state.modelContext {
- if isImplementationStage && smartContextEnabled && state.currentSubtask != nil && part.ContextType == shared.ContextFileType && !uses[part.FilePath] {
+ if basicOnly && part.AutoLoaded {
+ continue
+ }
+
+ if autoOnly && !part.AutoLoaded {
+ continue
+ }
+
+ if currentStage.TellStage == shared.TellStageImplementation && smartContextEnabled && state.currentSubtask != nil && part.ContextType == shared.ContextFileType && !uses[part.FilePath] {
+ continue
+ }
+
+ if activeOnly && !activatedPaths[part.FilePath] {
continue
}
@@ -39,9 +77,6 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
var args []any
if part.ContextType == shared.ContextDirectoryTreeType {
- if !includeTrees {
- continue
- }
fmtStr = "\n\n- %s | directory tree:\n\n```\n%s\n```"
args = append(args, part.FilePath, part.Body)
} else if part.ContextType == shared.ContextFileType {
@@ -88,7 +123,7 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
for filePath, body := range state.currentPlanState.CurrentPlanFiles.Files {
if !addedFilesSet[filePath] {
- if isImplementationStage && smartContextEnabled && !uses[filePath] {
+ if currentStage.TellStage == shared.TellStageImplementation && smartContextEnabled && !uses[filePath] {
continue
}
@@ -96,6 +131,10 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
continue
}
+ if activeOnly && !activatedPaths[filePath] {
+ continue
+ }
+
contextMessages = append(contextMessages, fmt.Sprintf("\n\n- %s:\n\n```\n%s\n```", filePath, body))
log.Printf("Tell plan - formatModelContext - added current plan file - %s\n", filePath)
@@ -115,7 +154,7 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
if execEnabled &&
// don't show _apply.sh history and content if smart context is enabled and the current subtask doesn't use it
- !(isImplementationStage && smartContextEnabled && state.currentSubtask != nil && !uses["_apply.sh"]) {
+ !(currentStage.TellStage == shared.TellStageImplementation && smartContextEnabled && state.currentSubtask != nil && !uses["_apply.sh"]) {
execHistory := state.currentPlanState.ExecHistory()
@@ -131,7 +170,7 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
contextMessages = append(contextMessages, "*Current* state of _apply.sh script:")
contextMessages = append(contextMessages, fmt.Sprintf("\n\n- _apply.sh:\n\n```\n%s\n```", scriptContent))
- if isEmpty && state.isPlanningStage && !state.isContextStage {
+ if isEmpty && currentStage.TellStage == shared.TellStagePlanning && currentStage.PlanningPhase != shared.PlanningPhaseContext {
contextMessages = append(contextMessages, "The _apply.sh script is *empty*. You ABSOLUTELY MUST include a '### Commands' section in your response prior to the '### Tasks' section that evaluates whether any commands should be written to _apply.sh during the plan. This is MANDATORY. Do NOT UNDER ANY CIRCUMSTANCES omit this section. If you determine that commands should be added or updated in _apply.sh, you MUST also create a subtask referencing _apply.sh in the '### Tasks' section.")
if execHistory != "" {
@@ -140,26 +179,40 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees
}
}
- return strings.Join(contextMessages, "\n\n") + "\n\n### END OF CONTEXT ###\n\n", nil
+ s := strings.Join(contextMessages, "\n\n") + "\n\n### END OF CONTEXT ###\n\n"
+
+ res := &types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: s,
+ }
+
+ if params.cache {
+ res.CacheControl = &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ }
+ }
+
+ return res
}
var pathRegex = regexp.MustCompile("`(.+?)`")
-func (state *activeTellStreamState) checkAutoLoadContext() []string {
+type checkAutoLoadContextResult struct {
+ autoLoadPaths []string
+ activatePaths map[string]bool
+}
+
+func (state *activeTellStreamState) checkAutoLoadContext() checkAutoLoadContextResult {
req := state.req
activePlan := state.activePlan
contextsByPath := activePlan.ContextsByPath
+ currentStage := state.currentStage
- if !activePlan.AutoContext {
- return nil
- }
-
- if state.req.IsChatOnly && state.iteration > 0 {
- return nil
- }
-
- if !(state.isContextStage || state.isPlanningStage || state.req.IsChatOnly) {
- return nil
+ // can only auto load context in planning stage
+ // context phase is primary loading phase
+ // planning phase can still load additional context files as a backup
+ if currentStage.TellStage != shared.TellStagePlanning {
+ return checkAutoLoadContextResult{}
}
log.Printf("%d existing contexts by path\n", len(contextsByPath))
@@ -167,7 +220,8 @@ func (state *activeTellStreamState) checkAutoLoadContext() []string {
// pick out all potential file paths within backticks
matches := pathRegex.FindAllStringSubmatch(activePlan.CurrentReplyContent, -1)
- files := []string{}
+ toAutoLoad := []string{}
+ toActivate := map[string]bool{}
for _, match := range matches {
trimmed := strings.TrimSpace(match[1])
@@ -175,14 +229,21 @@ func (state *activeTellStreamState) checkAutoLoadContext() []string {
continue
}
- if req.ProjectPaths[trimmed] && contextsByPath[trimmed] == nil {
- files = append(files, trimmed)
+ if req.ProjectPaths[trimmed] {
+ toActivate[trimmed] = true
+ if contextsByPath[trimmed] == nil {
+ toAutoLoad = append(toAutoLoad, trimmed)
+ }
}
}
- log.Printf("Tell plan - checkAutoLoadContext - files: %v\n", files)
+ log.Printf("Tell plan - checkAutoLoadContext - toAutoLoad: %v\n", toAutoLoad)
+ log.Printf("Tell plan - checkAutoLoadContext - toActivate: %v\n", toActivate)
- return files
+ return checkAutoLoadContextResult{
+ autoLoadPaths: toAutoLoad,
+ activatePaths: toActivate,
+ }
}
func (state *activeTellStreamState) addImageContext() (int, bool) {
@@ -205,9 +266,9 @@ func (state *activeTellStreamState) addImageContext() (int, bool) {
imageContextTokens += context.NumTokens
- imageMessage := openai.ChatCompletionMessage{
+ imageMessage := types.ExtendedChatMessage{
Role: openai.ChatMessageRoleUser,
- MultiContent: []openai.ChatMessagePart{
+ Content: []types.ExtendedChatMessagePart{
{
Type: openai.ChatMessagePartTypeText,
Text: fmt.Sprintf("Image: %s", context.Name),
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index 207de4be..8d65d890 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -9,7 +9,6 @@ import (
"plandex-server/db"
"plandex-server/hooks"
"plandex-server/model"
- "plandex-server/model/prompts"
"plandex-server/types"
shared "plandex-shared"
@@ -52,19 +51,16 @@ func Tell(clients map[string]model.ClientInfo, plan *db.Plan, branch string, aut
}
type execTellPlanParams struct {
- clients map[string]model.ClientInfo
- plan *db.Plan
- branch string
- auth *types.ServerAuth
- req *shared.TellPlanRequest
- iteration int
- missingFileResponse shared.RespondMissingFileChoice
- shouldBuildPending bool
- numErrorRetry int
- shouldLoadFollowUpContext bool
- didLoadFollowUpContext bool
- didMakeFollowUpPlan bool
- didLoadChatOnlyContext bool
+ clients map[string]model.ClientInfo
+ plan *db.Plan
+ branch string
+ auth *types.ServerAuth
+ req *shared.TellPlanRequest
+ iteration int
+ missingFileResponse shared.RespondMissingFileChoice
+ shouldBuildPending bool
+ numErrorRetry int
+ unfinishedSubtaskReasoning string
}
func execTellPlan(params execTellPlanParams) {
@@ -76,9 +72,7 @@ func execTellPlan(params execTellPlanParams) {
iteration := params.iteration
missingFileResponse := params.missingFileResponse
shouldBuildPending := params.shouldBuildPending
- shouldLoadFollowUpContext := params.shouldLoadFollowUpContext
- didLoadFollowUpContext := params.didLoadFollowUpContext
- didMakeFollowUpPlan := params.didMakeFollowUpPlan
+ unfinishedSubtaskReasoning := params.unfinishedSubtaskReasoning
log.Printf("[TellExec] Starting iteration %d for plan %s on branch %s", iteration, plan.Id, branch)
currentUserId := auth.User.Id
@@ -92,23 +86,24 @@ func execTellPlan(params execTellPlanParams) {
}
// Load existing subtasks to log their state
- subtasks, err := db.GetPlanSubtasks(currentOrgId, plan.Id)
- if err != nil {
- log.Printf("[TellExec] Error loading subtasks: %v", err)
- } else {
- var unfinished []string
- var finished []string
- for _, task := range subtasks {
- if task.IsFinished {
- finished = append(finished, task.Title)
- } else {
- unfinished = append(unfinished, task.Title)
- }
- }
- log.Printf("[TellExec] Current subtask state - Total: %d, Finished: %d, Unfinished: %d", len(subtasks), len(finished), len(unfinished))
- log.Printf("[TellExec] Finished tasks: %v", finished)
- log.Printf("[TellExec] Unfinished tasks: %v", unfinished)
- }
+ // subtasks, err := db.GetPlanSubtasks(currentOrgId, plan.Id)
+ // if err != nil {
+ // log.Printf("[TellExec] Error loading subtasks: %v", err)
+ // } else {
+ // var unfinished []string
+ // var finished []string
+ // for _, task := range subtasks {
+ // if task.IsFinished {
+ // finished = append(finished, task.Title)
+ // } else {
+ // unfinished = append(unfinished, task.Title)
+ // }
+ // }
+ // log.Printf("[TellExec] Current subtask state - Total: %d, Finished: %d, Unfinished: %d", len(subtasks), len(finished), len(unfinished))
+ // log.Printf("[TellExec] Finished tasks: %v", finished)
+ // log.Printf("[TellExec] Unfinished tasks: %v", unfinished)
+ // log.Printf("[TellExec] Unfinished subtask reasoning: %s", unfinishedSubtaskReasoning)
+ // }
if missingFileResponse == "" {
log.Println("Executing WillExecPlanHook")
@@ -126,7 +121,7 @@ func execTellPlan(params execTellPlanParams) {
planId := plan.Id
log.Println("execTellPlan - Setting plan status to replying")
- err = db.SetPlanStatus(planId, branch, shared.PlanStatusReplying, "")
+ err := db.SetPlanStatus(planId, branch, shared.PlanStatusReplying, "")
if err != nil {
log.Printf("Error setting plan %s status to replying: %v\n", planId, err)
active.StreamDoneCh <- &shared.ApiError{
@@ -160,98 +155,56 @@ func execTellPlan(params execTellPlanParams) {
}
log.Println("execTellPlan - Tell plan loaded")
- log.Printf(`
- iteration: %d
- req.AutoContext: %t,
- req.IsChatOnly: %t,
- req.ExecEnabled: %t,
- req.BuildMode: %s,
- req.IsUserContinue: %t,
- req.IsUserDebug: %t,
- req.IsApplyDebug: %t,
- shouldLoadFollowUpContext: %t,
- didLoadFollowUpContext: %t,
- didMakeFollowUpPlan: %t,
- didLoadChatOnlyContext: %t,
- state.hasContextMap: %t,
- state.hasAssistantReply: %t,
- len(state.subtasks): %d,
- `,
- iteration,
- req.AutoContext,
- req.IsChatOnly,
- req.ExecEnabled,
- req.BuildMode,
- req.IsUserContinue,
- req.IsUserDebug,
- req.IsApplyDebug,
- shouldLoadFollowUpContext,
- didLoadFollowUpContext,
- didMakeFollowUpPlan,
- params.didLoadChatOnlyContext,
- state.hasContextMap,
- state.hasAssistantReply,
- len(state.subtasks),
- )
-
- var lastConvoMsg *db.ConvoMessage
- if len(state.convo) > 0 {
- lastConvoMsg = state.convo[len(state.convo)-1]
- }
-
- wasContextStage := lastConvoMsg != nil && lastConvoMsg.Flags.IsContextStage
- didMakePlan := lastConvoMsg != nil && lastConvoMsg.Flags.DidMakePlan
- wasImplementationStage := lastConvoMsg != nil && lastConvoMsg.Flags.IsImplementationStage
-
- isTrueUserContinue := iteration == 0 && req.IsUserContinue && lastConvoMsg != nil && lastConvoMsg.Role == openai.ChatMessageRoleAssistant
- isUserPrompt := iteration == 0 && (!req.IsChatOnly || !isTrueUserContinue)
-
- hasSubtasks := len(state.subtasks) > 0
-
- autoContextEnabled := req.AutoContext && state.hasContextMap
- smartContextEnabled := req.AutoContext
-
- isFollowUp := iteration == 0 && !isTrueUserContinue && (hasSubtasks || (req.IsChatOnly && state.hasAssistantReply))
-
- isPlanningStage := req.IsChatOnly ||
- lastConvoMsg == nil ||
- isUserPrompt ||
- (!didMakePlan && !wasImplementationStage)
-
- isImplementationStage := !req.IsChatOnly && !isPlanningStage
-
- isContextStage := autoContextEnabled && isPlanningStage && (req.IsChatOnly || !isFollowUp) && !state.contextMapEmpty && !wasContextStage && (isUserPrompt || shouldLoadFollowUpContext)
+ activatedPaths := state.resolveCurrentStage()
- log.Printf("isPlanningStage: %t, isImplementationStage: %t, isContextStage: %t, isFollowUp: %t\n", isPlanningStage, isImplementationStage, isContextStage, isFollowUp)
+ var basicContextMsg *types.ExtendedChatMessagePart
+ var autoContextMsg *types.ExtendedChatMessagePart
+ var smartContextMsg *types.ExtendedChatMessagePart
- state.isFollowUp = isFollowUp
- state.willLoadFollowUpContext = shouldLoadFollowUpContext
- state.isPlanningStage = isPlanningStage
- state.isImplementationStage = isImplementationStage
- state.isContextStage = isContextStage
-
- // if auto context is enabled, we only include maps on the first iteration, which is the context-gathering step, and the second iteration, which is the planning step
- var (
- includeMaps = true
- )
- if req.AutoContext && iteration > 1 {
- includeMaps = false
- }
-
- modelContextText, err := state.formatModelContext(includeMaps, true, isImplementationStage, smartContextEnabled, req.ExecEnabled)
- if err != nil {
- err = fmt.Errorf("error formatting model modelContext: %v", err)
- log.Println(err)
+ if state.currentStage.TellStage == shared.TellStageImplementation {
+ smartContextMsg = state.formatModelContext(formatModelContextParams{
+ includeMaps: false,
+ smartContextEnabled: req.SmartContext,
+ execEnabled: req.ExecEnabled,
+ })
+ } else if state.currentStage.TellStage == shared.TellStagePlanning {
+ basicContextMsg = state.formatModelContext(formatModelContextParams{
+ includeMaps: true,
+ smartContextEnabled: req.SmartContext,
+ execEnabled: req.ExecEnabled,
+ basicOnly: true,
+ cache: true,
+ })
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error formatting model modelContext",
+ if state.currentStage.PlanningPhase == shared.PlanningPhasePlanning {
+ if req.AutoContext {
+ autoContextMsg = state.formatModelContext(formatModelContextParams{
+ includeMaps: false,
+ smartContextEnabled: req.SmartContext,
+ execEnabled: req.ExecEnabled,
+ activeOnly: true,
+ activatedPaths: activatedPaths,
+ })
+ } else {
+ // if auto context is disabled, just dump in everything, both basic and auto, that may have accumulated
+ autoContextMsg = state.formatModelContext(formatModelContextParams{
+ includeMaps: false,
+ smartContextEnabled: req.SmartContext,
+ execEnabled: req.ExecEnabled,
+ autoOnly: true,
+ })
+ }
}
- return
}
- sysPrompt, err := state.getTellSysPrompt(autoContextEnabled, smartContextEnabled, req.IsChatOnly && params.didLoadChatOnlyContext, modelContextText)
+ getTellSysPromptParams := getTellSysPromptParams{
+ autoContextEnabled: state.currentStage.TellStage == shared.TellStagePlanning && state.currentStage.PlanningPhase == shared.PlanningPhaseContext,
+ smartContextEnabled: req.SmartContext,
+ basicContextMsg: basicContextMsg,
+ autoContextMsg: autoContextMsg,
+ smartContextMsg: smartContextMsg,
+ }
+ sysParts, err := state.getTellSysPrompt(getTellSysPromptParams)
if err != nil {
log.Printf("Error getting tell sys prompt: %v\n", err)
active.StreamDoneCh <- &shared.ApiError{
@@ -262,12 +215,12 @@ func execTellPlan(params execTellPlanParams) {
return
}
- // log.Println("**sysPrompt:**\n", sysPrompt)
+ // log.Println("**sysPrompt:**\n", spew.Sdump(sysParts))
- state.messages = []openai.ChatCompletionMessage{
+ state.messages = []types.ExtendedChatMessage{
{
Role: openai.ChatMessageRoleSystem,
- Content: sysPrompt,
+ Content: sysParts,
},
}
@@ -277,26 +230,19 @@ func execTellPlan(params execTellPlanParams) {
return
}
- var applyScriptSummary string
- if req.ExecEnabled {
- if isPlanningStage {
- applyScriptSummary = prompts.ApplyScriptPlanningPromptSummary
- } else {
- applyScriptSummary = prompts.ApplyScriptImplementationPromptSummary
- }
- }
-
- promptMessage, ok := state.resolvePromptMessage(isPlanningStage, isContextStage, req.IsChatOnly && params.didLoadChatOnlyContext, applyScriptSummary)
+ promptMessage, ok := state.resolvePromptMessage(unfinishedSubtaskReasoning)
if !ok {
return
}
+ // log.Println("promptMessage:", spew.Sdump(promptMessage))
+
state.tokensBeforeConvo =
- shared.GetMessagesTokenEstimate(state.messages...) +
- shared.GetMessagesTokenEstimate(*promptMessage) +
+ model.GetMessagesTokenEstimate(state.messages...) +
+ model.GetMessagesTokenEstimate(*promptMessage) +
state.latestSummaryTokens +
imageContextTokens +
- shared.TokensPerRequest
+ model.TokensPerRequest
// print out breakdown of token usage
log.Printf("Image context tokens: %d\n", imageContextTokens)
@@ -324,7 +270,7 @@ func execTellPlan(params execTellPlanParams) {
if missingFileResponse == "" {
state.messages = append(state.messages, *promptMessage)
- } else if !state.handleMissingFileResponse(applyScriptSummary) {
+ } else if !state.handleMissingFileResponse(unfinishedSubtaskReasoning) {
return
}
@@ -333,19 +279,19 @@ func execTellPlan(params execTellPlanParams) {
// log.Printf("%s: %s\n", message.Role, message.Content)
// }
- requestTokens := shared.GetMessagesTokenEstimate(state.messages...) + imageContextTokens + shared.TokensPerRequest
+ requestTokens := model.GetMessagesTokenEstimate(state.messages...) + imageContextTokens + model.TokensPerRequest
state.totalRequestTokens = requestTokens
stop := []string{"<PlandexFinish/>"}
var modelConfig shared.ModelRoleConfig
- if isPlanningStage {
+ if state.currentStage.TellStage == shared.TellStagePlanning {
plannerConfig := state.settings.ModelPack.Planner.GetRoleForTokens(requestTokens)
modelConfig = plannerConfig.ModelRoleConfig
- if isContextStage {
+ if state.currentStage.PlanningPhase == shared.PlanningPhaseContext {
log.Println("Tell plan - isContextStage - setting modelConfig to context loader")
modelConfig = state.settings.ModelPack.GetArchitect().GetRoleForInputTokens(requestTokens)
}
- } else if isImplementationStage {
+ } else if state.currentStage.TellStage == shared.TellStageImplementation {
modelConfig = state.settings.ModelPack.GetCoder().GetRoleForInputTokens(requestTokens)
}
@@ -370,7 +316,7 @@ func execTellPlan(params execTellPlanParams) {
log.Println("modelConfig:", spew.Sdump(modelConfig))
- modelReq := openai.ChatCompletionRequest{
+ modelReq := types.ExtendedChatCompletionRequest{
Model: modelConfig.BaseModelConfig.ModelName,
Messages: state.messages,
Stream: true,
@@ -382,6 +328,10 @@ func execTellPlan(params execTellPlanParams) {
Stop: stop,
}
+ state.requestStartedAt = time.Now()
+ state.originalReq = &modelReq
+ state.modelConfig = &modelConfig
+
// output the modelReq to a json file
// if jsonData, err := json.MarshalIndent(modelReq, "", " "); err == nil {
// timestamp := time.Now().Format("2006-01-02-150405")
diff --git a/app/server/model/plan/tell_load.go b/app/server/model/plan/tell_load.go
index 995f537b..2a863635 100644
--- a/app/server/model/plan/tell_load.go
+++ b/app/server/model/plan/tell_load.go
@@ -258,7 +258,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
defer func() {
if err != nil {
log.Printf("Error: %v\n", err)
- err = db.GitClearUncommittedChanges(auth.OrgId, planId)
+ err = db.GitClearUncommittedChanges(auth.OrgId, planId, branch)
if err != nil {
log.Printf("Error clearing uncommitted changes: %v\n", err)
}
@@ -326,6 +326,9 @@ func (state *activeTellStreamState) loadTellPlan() error {
}
}
+ log.Printf("[TellLoad] Subtasks: %+v", state.subtasks)
+ log.Printf("[TellLoad] Current subtask: %+v", state.currentSubtask)
+
state.hasContextMap = false
state.contextMapEmpty = true
for _, context := range state.modelContext {
diff --git a/app/server/model/plan/tell_missing_file.go b/app/server/model/plan/tell_missing_file.go
index 97af88e6..1b270a11 100644
--- a/app/server/model/plan/tell_missing_file.go
+++ b/app/server/model/plan/tell_missing_file.go
@@ -10,13 +10,11 @@ import (
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) handleMissingFileResponse(applyScriptSummary string) bool {
+func (state *activeTellStreamState) handleMissingFileResponse(unfinishedSubtaskReasoning string) bool {
missingFileResponse := state.missingFileResponse
planId := state.plan.Id
branch := state.branch
req := state.req
- isFollowUp := state.isFollowUp
- isPlanningStage := state.isPlanningStage
active := GetActivePlan(planId, branch)
@@ -60,9 +58,14 @@ func (state *activeTellStreamState) handleMissingFileResponse(applyScriptSummary
}
}
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: active.CurrentReplyContent,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: active.CurrentReplyContent,
+ },
+ },
})
if missingFileResponse == shared.RespondMissingFileChoiceSkip {
@@ -71,21 +74,27 @@ func (state *activeTellStreamState) handleMissingFileResponse(applyScriptSummary
params := prompts.UserPromptParams{
CreatePromptParams: prompts.CreatePromptParams{
- ExecMode: req.ExecEnabled,
- AutoContext: req.AutoContext,
+ ExecMode: req.ExecEnabled,
+ AutoContext: req.AutoContext,
+ IsUserDebug: req.IsUserDebug,
+ IsApplyDebug: req.IsApplyDebug,
},
- Prompt: skipPrompt,
- OsDetails: req.OsDetails,
- IsPlanningStage: isPlanningStage,
- IsFollowUp: isFollowUp,
- ApplyScriptSummary: applyScriptSummary,
+ Prompt: skipPrompt,
+ OsDetails: req.OsDetails,
+ CurrentStage: state.currentStage,
+ UnfinishedSubtaskReasoning: unfinishedSubtaskReasoning,
}
prompt := prompts.GetWrappedPrompt(params) + "\n\n" + skipPrompt // repetition of skip prompt to improve instruction following
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompt,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: prompt,
+ },
+ },
})
} else {
@@ -93,21 +102,27 @@ func (state *activeTellStreamState) handleMissingFileResponse(applyScriptSummary
params := prompts.UserPromptParams{
CreatePromptParams: prompts.CreatePromptParams{
- ExecMode: req.ExecEnabled,
- AutoContext: req.AutoContext,
+ ExecMode: req.ExecEnabled,
+ AutoContext: req.AutoContext,
+ IsUserDebug: req.IsUserDebug,
+ IsApplyDebug: req.IsApplyDebug,
},
- Prompt: missingPrompt,
- OsDetails: req.OsDetails,
- IsPlanningStage: isPlanningStage,
- IsFollowUp: isFollowUp,
- ApplyScriptSummary: applyScriptSummary,
+ Prompt: missingPrompt,
+ OsDetails: req.OsDetails,
+ CurrentStage: state.currentStage,
+ UnfinishedSubtaskReasoning: unfinishedSubtaskReasoning,
}
prompt := prompts.GetWrappedPrompt(params) + "\n\n" + missingPrompt // repetition of missing prompt to improve instruction following
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompt,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: prompt,
+ },
+ },
})
}
diff --git a/app/server/model/plan/tell_prompt_message.go b/app/server/model/plan/tell_prompt_message.go
index 324b7784..aa81c048 100644
--- a/app/server/model/plan/tell_prompt_message.go
+++ b/app/server/model/plan/tell_prompt_message.go
@@ -4,26 +4,22 @@ import (
"log"
"net/http"
"plandex-server/model/prompts"
-
+ "plandex-server/types"
shared "plandex-shared"
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isContextStage, didLoadChatOnlyContext bool, applyScriptSummary string) (*openai.ChatCompletionMessage, bool) {
+func (state *activeTellStreamState) resolvePromptMessage(
+ unfinishedSubtaskReasoning string,
+) (*types.ExtendedChatMessage, bool) {
req := state.req
- iteration := state.iteration
active := state.activePlan
- isFollowUp := state.isFollowUp
-
- if isFollowUp && (req.IsApplyDebug) {
- log.Println("resolvePromptMessage: IsApplyDebug or IsUserDebug - setting isFollowUp to false")
- isFollowUp = false
- }
+ iteration := state.iteration
- var promptMessage *openai.ChatCompletionMessage
+ var promptMessage *types.ExtendedChatMessage
- var lastMessage *openai.ChatCompletionMessage
+ var lastMessage *types.ExtendedChatMessage
if req.IsUserContinue {
if len(state.messages) == 0 {
@@ -46,8 +42,9 @@ func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isCont
if req.IsUserContinue {
if lastMessage.Role == openai.ChatMessageRoleUser {
log.Println("User is continuing plan in chat only mode. Last message was user message. Using last user message as prompt")
- prompt = lastMessage.Content
- state.userPrompt = prompt
+ content := lastMessage.ToOpenAI().Content
+ prompt = content
+ state.userPrompt = content
state.messages = state.messages[:len(state.messages)-1]
} else {
log.Println("User is continuing plan in chat only mode. Last message was assistant message. Using user continue prompt")
@@ -59,17 +56,23 @@ func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isCont
wrapped := prompts.GetWrappedChatOnlyPrompt(prompts.ChatUserPromptParams{
CreatePromptParams: prompts.CreatePromptParams{
- AutoContext: req.AutoContext,
- ExecMode: req.ExecEnabled,
- LastResponseLoadedContext: didLoadChatOnlyContext,
+ AutoContext: req.AutoContext,
+ ExecMode: req.ExecEnabled,
+ // no need to pass in IsUserDebug or IsApplyDebug here because it's a chat message
},
Prompt: prompt,
OsDetails: req.OsDetails,
+ // no current task for chat only mode
})
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: wrapped,
+ promptMessage = &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: wrapped,
+ },
+ },
}
state.messages = append(state.messages, *promptMessage)
@@ -82,23 +85,31 @@ func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isCont
state.messages = state.messages[:len(state.messages)-1]
+ content := lastMessage.ToOpenAI().Content
+
params := prompts.UserPromptParams{
CreatePromptParams: prompts.CreatePromptParams{
ExecMode: req.ExecEnabled,
AutoContext: req.AutoContext,
+ // no need to pass in IsUserDebug or IsApplyDebug here because we're continuing
},
- Prompt: lastMessage.Content,
- OsDetails: req.OsDetails,
- IsPlanningStage: isPlanningStage,
- IsFollowUp: isFollowUp,
+ Prompt: content,
+ OsDetails: req.OsDetails,
+ CurrentStage: state.currentStage,
+ UnfinishedSubtaskReasoning: unfinishedSubtaskReasoning,
}
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompts.GetWrappedPrompt(params),
+ promptMessage = &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: prompts.GetWrappedPrompt(params),
+ },
+ },
}
- state.userPrompt = lastMessage.Content
+ state.userPrompt = content
} else {
// if the last message was an assistant message, we'll use the user continue prompt
@@ -108,17 +119,22 @@ func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isCont
CreatePromptParams: prompts.CreatePromptParams{
ExecMode: req.ExecEnabled,
AutoContext: req.AutoContext,
+ // no need to pass in IsUserDebug or IsApplyDebug here because we're continuing
},
- Prompt: prompts.UserContinuePrompt,
- OsDetails: req.OsDetails,
- IsPlanningStage: isPlanningStage,
- IsFollowUp: isFollowUp,
- ApplyScriptSummary: applyScriptSummary,
+ Prompt: prompts.UserContinuePrompt,
+ OsDetails: req.OsDetails,
+ CurrentStage: state.currentStage,
+ UnfinishedSubtaskReasoning: unfinishedSubtaskReasoning,
}
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompts.GetWrappedPrompt(params),
+ promptMessage = &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: prompts.GetWrappedPrompt(params),
+ },
+ },
}
}
@@ -126,43 +142,42 @@ func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isCont
} else {
var prompt string
if iteration == 0 {
- if req.IsUserDebug {
- prompt = req.Prompt + prompts.DebugPrompt
- } else if req.IsApplyDebug {
- prompt = req.Prompt + prompts.ApplyDebugPrompt
- } else {
- prompt = req.Prompt
- }
+ prompt = req.Prompt
} else {
prompt = prompts.AutoContinuePrompt
}
- state.userPrompt = prompt
+ if state.currentStage.TellStage == shared.TellStageImplementation {
+ prompt = prompts.AutoContinuePrompt
+ }
- var finalPrompt string
- if isContextStage {
- finalPrompt = prompt
- } else {
- params := prompts.UserPromptParams{
- CreatePromptParams: prompts.CreatePromptParams{
- ExecMode: req.ExecEnabled,
- AutoContext: req.AutoContext,
- },
- Prompt: prompt,
- OsDetails: req.OsDetails,
- IsPlanningStage: isPlanningStage,
- IsFollowUp: isFollowUp,
- ApplyScriptSummary: applyScriptSummary,
- }
+ state.userPrompt = prompt
- finalPrompt = prompts.GetWrappedPrompt(params)
+ params := prompts.UserPromptParams{
+ CreatePromptParams: prompts.CreatePromptParams{
+ ExecMode: req.ExecEnabled,
+ AutoContext: req.AutoContext,
+ IsUserDebug: req.IsUserDebug,
+ IsApplyDebug: req.IsApplyDebug,
+ },
+ Prompt: prompt,
+ OsDetails: req.OsDetails,
+ CurrentStage: state.currentStage,
+ UnfinishedSubtaskReasoning: unfinishedSubtaskReasoning,
}
+ finalPrompt := prompts.GetWrappedPrompt(params)
+
// log.Println("Final prompt:", finalPrompt)
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: finalPrompt,
+ promptMessage = &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: finalPrompt,
+ },
+ },
}
}
diff --git a/app/server/model/plan/tell_stage.go b/app/server/model/plan/tell_stage.go
new file mode 100644
index 00000000..bbec7a2b
--- /dev/null
+++ b/app/server/model/plan/tell_stage.go
@@ -0,0 +1,95 @@
+package plan
+
+import (
+ "log"
+ "plandex-server/db"
+ shared "plandex-shared"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+func (state *activeTellStreamState) resolveCurrentStage() (activatedPaths map[string]bool) {
+ req := state.req
+ iteration := state.iteration
+ hasContextMap := state.hasContextMap
+ convo := state.convo
+ contextMapEmpty := state.contextMapEmpty
+
+ log.Printf("[resolveCurrentStage] Initial state: hasContextMap: %v, convo len: %d", hasContextMap, len(convo))
+
+ var lastConvoMsg *db.ConvoMessage
+ if len(convo) > 0 {
+ lastConvoMsg = convo[len(convo)-1]
+ log.Printf("[resolveCurrentStage] Last convo message - Role: %s, Flags: %+v", lastConvoMsg.Role, lastConvoMsg.Flags)
+ } else {
+ log.Println("[resolveCurrentStage] No previous conversation messages")
+ }
+
+ activatedPaths = map[string]bool{}
+
+ isContinueFromAssistantMsg := false
+
+ if lastConvoMsg != nil {
+ isContinueFromAssistantMsg = iteration == 0 && req.IsUserContinue && lastConvoMsg.Role == openai.ChatMessageRoleAssistant
+ log.Printf("[resolveCurrentStage] isContinueFromAssistantMsg: %v (IsUserContinue: %v, LastMsgRole: %s)",
+ isContinueFromAssistantMsg, req.IsUserContinue, lastConvoMsg.Role)
+ }
+
+ isUserPrompt := false
+
+ if !isContinueFromAssistantMsg {
+ isUserPrompt = lastConvoMsg == nil || lastConvoMsg.Role == openai.ChatMessageRoleUser
+ log.Printf("[resolveCurrentStage] isUserPrompt: %v", isUserPrompt)
+ }
+
+ var tellStage shared.TellStage
+ var planningPhase shared.PlanningPhase
+
+ if isUserPrompt {
+ tellStage = shared.TellStagePlanning
+ log.Println("[resolveCurrentStage] Set tellStage to Planning due to user prompt")
+ } else {
+ if lastConvoMsg != nil && lastConvoMsg.Flags.DidMakePlan {
+ tellStage = shared.TellStageImplementation
+ log.Println("[resolveCurrentStage] Set tellStage to Implementation - DidMakePlan: true, IsChatOnly: false")
+ } else if lastConvoMsg != nil && lastConvoMsg.Flags.CurrentStage.TellStage == shared.TellStageImplementation {
+ tellStage = shared.TellStageImplementation
+ log.Println("[resolveCurrentStage] Set tellStage to Implementation - CurrentStage: implementation")
+ } else {
+ tellStage = shared.TellStagePlanning
+ log.Printf("[resolveCurrentStage] Set tellStage to Planning - DidMakePlan: %v, IsChatOnly: %v",
+ lastConvoMsg != nil && lastConvoMsg.Flags.DidMakePlan, req.IsChatOnly)
+ }
+ }
+
+ wasContextStage := false
+ if lastConvoMsg != nil {
+ flags := lastConvoMsg.Flags
+ log.Printf("[resolveCurrentStage] Last convo message flags: %+v", flags)
+ if flags.CurrentStage.TellStage == shared.TellStagePlanning && flags.CurrentStage.PlanningPhase == shared.PlanningPhaseContext {
+ wasContextStage = true
+ activatedPaths = lastConvoMsg.ActivatedPaths
+ log.Printf("[resolveCurrentStage] Was context stage, copied activatedPaths: %v", activatedPaths)
+ }
+ }
+
+ if tellStage == shared.TellStagePlanning {
+ if req.AutoContext && hasContextMap && !contextMapEmpty && !wasContextStage {
+ planningPhase = shared.PlanningPhaseContext
+ log.Printf("[resolveCurrentStage] Set planningPhase to Context - AutoContext: %v, hasContextMap: %v, contextMapEmpty: %v, wasContextStage: %v",
+ req.AutoContext, hasContextMap, contextMapEmpty, wasContextStage)
+ } else {
+ planningPhase = shared.PlanningPhasePlanning
+ log.Printf("[resolveCurrentStage] Set planningPhase to Planning - AutoContext: %v, hasContextMap: %v, contextMapEmpty: %v, wasContextStage: %v",
+ req.AutoContext, hasContextMap, contextMapEmpty, wasContextStage)
+ }
+ }
+
+ state.currentStage = shared.CurrentStage{
+ TellStage: tellStage,
+ PlanningPhase: planningPhase,
+ }
+ log.Printf("[resolveCurrentStage] Final state - TellStage: %s, PlanningPhase: %s", tellStage, planningPhase)
+
+ return activatedPaths
+}
diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.go
index 66baaa70..5c475c16 100644
--- a/app/server/model/plan/tell_state.go
+++ b/app/server/model/plan/tell_state.go
@@ -4,6 +4,7 @@ import (
"plandex-server/db"
"plandex-server/model"
"plandex-server/types"
+ "time"
shared "plandex-shared"
@@ -38,24 +39,21 @@ type activeTellStreamState struct {
promptMessage *openai.ChatCompletionMessage
replyParser *types.ReplyParser
replyNumTokens int
- messages []openai.ChatCompletionMessage
+ messages []types.ExtendedChatMessage
tokensBeforeConvo int
totalRequestTokens int
settings *shared.PlanSettings
subtasks []*db.Subtask
currentSubtask *db.Subtask
hasAssistantReply bool
+ currentStage shared.CurrentStage
+ chunkProcessor *chunkProcessor
+ generationId string
- isContextStage bool
- isPlanningStage bool
- isImplementationStage bool
-
- isFollowUp bool
- willLoadFollowUpContext bool
-
- chunkProcessor *chunkProcessor
-
- generationId string
+ requestStartedAt time.Time
+ firstTokenAt time.Time
+ originalReq *types.ExtendedChatCompletionRequest
+ modelConfig *shared.ModelRoleConfig
}
type chunkProcessor struct {
diff --git a/app/server/model/plan/tell_stream_error.go b/app/server/model/plan/tell_stream_error.go
index 09839a53..1b310d5e 100644
--- a/app/server/model/plan/tell_stream_error.go
+++ b/app/server/model/plan/tell_stream_error.go
@@ -105,7 +105,7 @@ func (state *activeTellStreamState) onError(params onErrorParams) onErrorResult
}
}()
- err := db.GitClearUncommittedChanges(state.currentOrgId, planId)
+ err := db.GitClearUncommittedChanges(state.currentOrgId, planId, branch)
if err != nil {
log.Printf("Error clearing uncommitted changes for plan %s: %v\n", planId, err)
return err
@@ -116,12 +116,22 @@ func (state *activeTellStreamState) onError(params onErrorParams) onErrorResult
storedDesc := false
if convoMessageId == "" {
- assistantMsg, msg, err := state.storeAssistantReply(shared.ConvoMessageFlags{
- IsFollowUpReply: state.isFollowUp,
- IsPlanningStage: state.isPlanningStage,
- IsContextStage: state.isContextStage,
- IsImplementationStage: state.isImplementationStage,
- }, nil, nil)
+ hasUnfinishedSubtasks := false
+ for _, subtask := range state.subtasks {
+ if !subtask.IsFinished {
+ hasUnfinishedSubtasks = true
+ break
+ }
+ }
+
+ assistantMsg, msg, err := state.storeAssistantReply(storeAssistantReplyParams{
+ flags: shared.ConvoMessageFlags{
+ CurrentStage: state.currentStage,
+ HasUnfinishedSubtasks: hasUnfinishedSubtasks,
+ },
+ subtask: nil,
+ addedSubtasks: nil,
+ })
if err == nil {
convoMessageId = assistantMsg.Id
commitMsg = msg
diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.go
index 26d99ab7..02a1705d 100644
--- a/app/server/model/plan/tell_stream_finish.go
+++ b/app/server/model/plan/tell_stream_finish.go
@@ -6,15 +6,12 @@ import (
"net/http"
"plandex-server/db"
"plandex-server/types"
- "strings"
"time"
shared "plandex-shared"
-
- "github.com/sashabaranov/go-openai"
)
-const MaxAutoContinueIterations = 100
+const MaxAutoContinueIterations = 200
type handleStreamFinishedResult struct {
shouldContinueMainLoop bool
@@ -68,37 +65,34 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
}
}
- autoLoadContextFiles := state.checkAutoLoadContext()
+ autoLoadContextResult := state.checkAutoLoadContext()
addedSubtasks := state.checkNewSubtasks()
+ removedSubtasks := state.checkRemoveSubtasks()
hasNewSubtasks := len(addedSubtasks) > 0
- followUpNeedsContextStage := state.followUpNeedsContextStage()
- handleDescAndExecStatusRes := state.handleDescAndExecStatus(autoLoadContextFiles, hasNewSubtasks)
+ handleDescAndExecStatusRes := state.handleDescAndExecStatus()
if handleDescAndExecStatusRes.shouldContinueMainLoop || handleDescAndExecStatusRes.shouldReturn {
return handleDescAndExecStatusRes.handleStreamFinishedResult
}
generatedDescription := handleDescAndExecStatusRes.generatedDescription
- shouldContinue := handleDescAndExecStatusRes.shouldContinue
subtaskFinished := handleDescAndExecStatusRes.subtaskFinished
storeOnFinishedResult := state.storeOnFinished(storeOnFinishedParams{
- replyOperations: replyOperations,
- generatedDescription: generatedDescription,
- subtaskFinished: subtaskFinished,
- hasNewSubtasks: hasNewSubtasks,
- followUpNeedsContextStage: followUpNeedsContextStage,
- autoLoadContextFiles: autoLoadContextFiles,
- addedSubtasks: addedSubtasks,
+ replyOperations: replyOperations,
+ generatedDescription: generatedDescription,
+ subtaskFinished: subtaskFinished,
+ hasNewSubtasks: hasNewSubtasks,
+ autoLoadContextResult: autoLoadContextResult,
+ addedSubtasks: addedSubtasks,
+ removedSubtasks: removedSubtasks,
})
if storeOnFinishedResult.shouldContinueMainLoop || storeOnFinishedResult.shouldReturn {
return storeOnFinishedResult.handleStreamFinishedResult
}
allSubtasksFinished := storeOnFinishedResult.allSubtasksFinished
- didLoadFollowUpContext := state.willLoadFollowUpContext && len(autoLoadContextFiles) > 0
-
// summarize convo needs to come *after* the reply is stored in order to correctly summarize the latest message
- log.Println("summarize convo")
+ log.Println("summarizing convo in background")
// summarize in the background
go func() {
err := summarizeConvo(clients, settings.ModelPack.PlanSummary, summarizeConvoParams{
@@ -131,13 +125,14 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
ap.CurrentReplyDoneCh = nil
})
- log.Printf("len(autoLoadContextFiles): %d\n", len(autoLoadContextFiles))
- if len(autoLoadContextFiles) > 0 {
+ autoLoadPaths := autoLoadContextResult.autoLoadPaths
+ log.Printf("len(autoLoadPaths): %d\n", len(autoLoadPaths))
+ if len(autoLoadPaths) > 0 {
log.Println("Sending stream message to load context files")
active.Stream(shared.StreamMessage{
Type: shared.StreamMessageLoadContext,
- LoadContextFiles: autoLoadContextFiles,
+ LoadContextFiles: autoLoadPaths,
})
active.FlushStreamBuffer()
@@ -168,39 +163,22 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
}
}
- if followUpNeedsContextStage {
- log.Println("Clearing context before follow up context stage")
- }
+ willContinue := state.willContinuePlan(willContinuePlanParams{
+ hasNewSubtasks: hasNewSubtasks,
+ allSubtasksFinished: allSubtasksFinished,
+ activatePaths: autoLoadContextResult.activatePaths,
+ })
- // if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context
- log.Printf("req.AutoContinue: %v\n", req.AutoContinue)
- log.Printf("shouldContinue: %v\n", shouldContinue)
- log.Printf("iteration: %d\n", iteration)
- log.Printf("MaxAutoContinueIterations: %d\n", MaxAutoContinueIterations)
- log.Printf("hasNewSubtasks: %v\n", hasNewSubtasks)
- log.Printf("len(state.subtasks): %d\n", len(state.subtasks))
- log.Printf("allSubtasksFinished: %v\n", allSubtasksFinished)
- log.Printf("followUpNeedsContextStage: %v\n", followUpNeedsContextStage)
-
- if state.isContextStage ||
- followUpNeedsContextStage ||
- (len(autoLoadContextFiles) > 0 && !hasNewSubtasks) ||
- (len(autoLoadContextFiles) > 0 && req.IsChatOnly) ||
- (req.AutoContinue && shouldContinue && iteration < MaxAutoContinueIterations &&
- !(len(state.subtasks) > 0 && allSubtasksFinished)) {
+ if willContinue {
log.Println("Auto continue plan")
// continue plan
execTellPlan(execTellPlanParams{
- clients: clients,
- plan: plan,
- branch: branch,
- auth: auth,
- req: req,
- iteration: iteration + 1,
- shouldLoadFollowUpContext: followUpNeedsContextStage,
- didMakeFollowUpPlan: state.isFollowUp && !followUpNeedsContextStage && hasNewSubtasks,
- didLoadChatOnlyContext: len(autoLoadContextFiles) > 0 && req.IsChatOnly,
- didLoadFollowUpContext: didLoadFollowUpContext,
+ clients: clients,
+ plan: plan,
+ branch: branch,
+ auth: auth,
+ req: req,
+ iteration: iteration + 1,
})
} else {
var buildFinished bool
@@ -253,430 +231,3 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
return handleStreamFinishedResult{}
}
-
-type handleDescAndExecStatusResult struct {
- handleStreamFinishedResult
- subtaskFinished bool
- generatedDescription *db.ConvoMessageDescription
- shouldContinue bool
-}
-
-func (state *activeTellStreamState) handleDescAndExecStatus(autoLoadContextFiles []string, hasNewSubtasks bool) handleDescAndExecStatusResult {
- req := state.req
- currentOrgId := state.currentOrgId
- summarizedToMessageId := state.summarizedToMessageId
- planId := state.plan.Id
- branch := state.branch
- replyOperations := state.chunkProcessor.replyOperations
-
- active := GetActivePlan(planId, branch)
- if active == nil {
- state.onActivePlanMissingError()
- return handleDescAndExecStatusResult{
- handleStreamFinishedResult: handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
- },
- }
- }
-
- var generatedDescription *db.ConvoMessageDescription
- var shouldContinue bool
- var subtaskFinished bool
-
- var errCh = make(chan *shared.ApiError, 2)
-
- go func() {
- if len(replyOperations) > 0 {
- log.Println("Generating plan description")
-
- res, err := state.genPlanDescription()
- if err != nil {
- errCh <- err
- return
- }
-
- generatedDescription = res
- generatedDescription.OrgId = currentOrgId
- generatedDescription.SummarizedToMessageId = summarizedToMessageId
- generatedDescription.MadePlan = true
- generatedDescription.Operations = replyOperations
-
- log.Println("Generated plan description.")
- }
- errCh <- nil
- }()
-
- if req.IsChatOnly || len(autoLoadContextFiles) > 0 || hasNewSubtasks || !req.AutoContinue {
-
- // if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context (even if it's chat only)
- if len(autoLoadContextFiles) > 0 && !hasNewSubtasks {
- log.Printf("Auto loading context files, so continuing to planning phase")
- shouldContinue = true
- } else if req.IsChatOnly {
- log.Printf("Chat only, won't continue")
- shouldContinue = false
- } else if hasNewSubtasks {
- log.Printf("Has new subtasks, can continue")
- shouldContinue = req.AutoContinue
- }
-
- errCh <- nil
- } else {
- go func() {
- log.Println("Getting exec status")
- var err *shared.ApiError
- subtaskFinished, shouldContinue, err = state.execStatusShouldContinue(active.CurrentReplyContent, active.Ctx)
- if err != nil {
- errCh <- err
- return
- }
-
- log.Printf("Should continue: %v\n", shouldContinue)
-
- errCh <- nil
- }()
- }
-
- for i := 0; i < 2; i++ {
- err := <-errCh
- if err != nil {
- res := state.onError(onErrorParams{
- streamApiErr: err,
- storeDesc: true,
- })
- return handleDescAndExecStatusResult{
- handleStreamFinishedResult: handleStreamFinishedResult{
- shouldContinueMainLoop: res.shouldContinueMainLoop,
- shouldReturn: res.shouldReturn,
- },
- subtaskFinished: subtaskFinished,
- shouldContinue: shouldContinue,
- generatedDescription: generatedDescription,
- }
- }
- }
-
- return handleDescAndExecStatusResult{
- handleStreamFinishedResult: handleStreamFinishedResult{},
- subtaskFinished: subtaskFinished,
- shouldContinue: shouldContinue,
- generatedDescription: generatedDescription,
- }
-}
-
-type storeOnFinishedParams struct {
- replyOperations []*shared.Operation
- generatedDescription *db.ConvoMessageDescription
- subtaskFinished bool
- hasNewSubtasks bool
- followUpNeedsContextStage bool
- autoLoadContextFiles []string
- addedSubtasks []*db.Subtask
-}
-
-type storeOnFinishedResult struct {
- handleStreamFinishedResult
- allSubtasksFinished bool
-}
-
-func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams) storeOnFinishedResult {
- replyOperations := params.replyOperations
- generatedDescription := params.generatedDescription
- subtaskFinished := params.subtaskFinished
- hasNewSubtasks := params.hasNewSubtasks
- followUpNeedsContextStage := params.followUpNeedsContextStage
- autoLoadContextFiles := params.autoLoadContextFiles
- currentOrgId := state.currentOrgId
- currentUserId := state.currentUserId
- planId := state.plan.Id
- branch := state.branch
- auth := state.auth
- summarizedToMessageId := state.summarizedToMessageId
- active := state.activePlan
- addedSubtasks := params.addedSubtasks
-
- var allSubtasksFinished bool
-
- log.Println("[Subtasks] Locking repo to store assistant reply and description")
-
- repoLockId, err := db.LockRepo(
- db.LockRepoParams{
- OrgId: currentOrgId,
- UserId: currentUserId,
- PlanId: planId,
- Branch: branch,
- Scope: db.LockScopeWrite,
- Ctx: active.Ctx,
- CancelFn: active.CancelFn,
- },
- )
-
- if err != nil {
- log.Printf("Error locking repo: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error locking repo",
- }
- return storeOnFinishedResult{
- handleStreamFinishedResult: handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
- },
- allSubtasksFinished: false,
- }
- }
-
- log.Println("[Subtasks] Locked repo for assistant reply and description")
-
- err = func() error {
- defer func() {
- if err != nil {
- log.Printf("Error storing reply and description: %v\n", err)
- err = db.GitClearUncommittedChanges(auth.OrgId, planId)
- if err != nil {
- log.Printf("Error clearing uncommitted changes: %v\n", err)
- }
- }
-
- log.Println("[Subtasks] Unlocking repo for assistant reply and description")
-
- err = db.DeleteRepoLock(repoLockId, planId)
- if err != nil {
- log.Printf("Error unlocking repo: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error unlocking repo",
- }
- }
- }()
-
- var flags shared.ConvoMessageFlags
- if state.isFollowUp {
- flags.IsFollowUpReply = true
- }
- if state.isPlanningStage {
- flags.IsPlanningStage = true
- }
- if state.isContextStage {
- flags.IsContextStage = true
- }
- if state.isImplementationStage {
- flags.IsImplementationStage = true
- }
- if len(replyOperations) > 0 {
- flags.DidWriteCode = true
- }
- if hasNewSubtasks {
- flags.DidMakePlan = true
- }
- if len(autoLoadContextFiles) > 0 {
- flags.DidLoadContext = true
- }
- if state.isFollowUp {
- flags.IsFollowUpReply = true
- }
- if subtaskFinished && state.currentSubtask != nil {
- flags.DidCompleteTask = true
- }
- if allSubtasksFinished {
- flags.DidCompletePlan = true
- }
- if hasNewSubtasks && state.req.IsApplyDebug || state.req.IsUserDebug {
- flags.DidMakeDebuggingPlan = true
- }
-
- assistantMsg, convoCommitMsg, err := state.storeAssistantReply(flags, state.currentSubtask, addedSubtasks) // updates state.convo
-
- if err != nil {
- state.onError(onErrorParams{
- streamErr: fmt.Errorf("failed to store assistant message: %v", err),
- storeDesc: true,
- })
- return err
- }
-
- log.Println("getting description for assistant message: ", assistantMsg.Id)
-
- var description *db.ConvoMessageDescription
- if len(replyOperations) == 0 {
- description = &db.ConvoMessageDescription{
- OrgId: currentOrgId,
- PlanId: planId,
- ConvoMessageId: assistantMsg.Id,
- SummarizedToMessageId: summarizedToMessageId,
- BuildPathsInvalidated: map[string]bool{},
- MadePlan: false,
- }
- } else {
- description = generatedDescription
- description.ConvoMessageId = assistantMsg.Id
- }
-
- log.Println("[Subtasks] Storing description")
- err = db.StoreDescription(description)
-
- if err != nil {
- state.onError(onErrorParams{
- streamErr: fmt.Errorf("failed to store description: %v", err),
- storeDesc: false,
- convoMessageId: assistantMsg.Id,
- commitMsg: convoCommitMsg,
- })
- return err
- }
- log.Println("[Subtasks] Description stored")
-
- if hasNewSubtasks || subtaskFinished {
- if subtaskFinished && state.currentSubtask != nil {
- log.Printf("[Subtasks] Marking subtask as finished: %q", state.currentSubtask.Title)
- state.currentSubtask.IsFinished = true
-
- log.Printf("[Subtasks] Current subtask state after marking as finished: %+v", state.currentSubtask)
- }
-
- log.Printf("[Subtasks] Storing plan subtasks (hasNewSubtasks=%v, subtaskFinished=%v)", hasNewSubtasks, subtaskFinished)
- log.Printf("[Subtasks] Current subtasks state before storing:")
- for i, task := range state.subtasks {
- log.Printf("[Subtasks] Task %d: %q (finished=%v)", i+1, task.Title, task.IsFinished)
- }
-
- err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)
- if err != nil {
- log.Printf("Error storing plan subtasks: %v\n", err)
- state.onError(onErrorParams{
- streamErr: fmt.Errorf("failed to store plan subtasks: %v", err),
- storeDesc: false,
- convoMessageId: assistantMsg.Id,
- commitMsg: convoCommitMsg,
- })
- return err
- }
-
- state.currentSubtask = nil
- allSubtasksFinished = true
- for _, subtask := range state.subtasks {
- if !subtask.IsFinished {
- state.currentSubtask = subtask
- allSubtasksFinished = false
- break
- }
- }
-
- if state.currentSubtask != nil {
- log.Printf("[Subtasks] Set new current subtask: %q", state.currentSubtask.Title)
- } else {
- log.Println("[Subtasks] No new current subtask set")
- }
- log.Printf("[Subtasks] All subtasks finished: %v", allSubtasksFinished)
- }
-
- if followUpNeedsContextStage {
- log.Println("Clearing non-map/non-pending context before follow up context stage")
- err := db.ClearContext(db.ClearContextParams{
- OrgId: currentOrgId,
- PlanId: planId,
- SkipMaps: true,
- SkipPending: true,
- })
- if err != nil {
- log.Printf("Error clearing context: %v\n", err)
- }
- }
-
- log.Println("Comitting after store on finished")
-
- err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)
- if err != nil {
- state.onError(onErrorParams{
- streamErr: fmt.Errorf("failed to commit: %v", err),
- storeDesc: false,
- convoMessageId: assistantMsg.Id,
- commitMsg: convoCommitMsg,
- })
- return err
- }
- log.Println("Assistant reply, description, and subtasks committed")
-
- return nil
- }()
-
- if err != nil {
- return storeOnFinishedResult{
- handleStreamFinishedResult: handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
- },
- allSubtasksFinished: allSubtasksFinished,
- }
- }
-
- return storeOnFinishedResult{
- handleStreamFinishedResult: handleStreamFinishedResult{},
- allSubtasksFinished: allSubtasksFinished,
- }
-}
-
-func (state *activeTellStreamState) storeAssistantReply(flags shared.ConvoMessageFlags, subtask *db.Subtask, addedSubtasks []*db.Subtask) (*db.ConvoMessage, string, error) {
- currentOrgId := state.currentOrgId
- currentUserId := state.currentUserId
- planId := state.plan.Id
- branch := state.branch
- auth := state.auth
- replyNumTokens := state.replyNumTokens
- replyId := state.replyId
- convo := state.convo
-
- num := len(convo) + 1
-
- log.Printf("storing assistant reply | len(convo) %d | num %d\n", len(convo), num)
-
- activePlan := state.activePlan
-
- // fmt.Println("raw message: ", activePlan.CurrentReplyContent)
-
- assistantMsg := db.ConvoMessage{
- Id: replyId,
- OrgId: currentOrgId,
- PlanId: planId,
- UserId: currentUserId,
- Role: openai.ChatMessageRoleAssistant,
- Tokens: replyNumTokens,
- Num: num,
- Message: activePlan.CurrentReplyContent,
- Flags: flags,
- Subtask: subtask,
- AddedSubtasks: addedSubtasks,
- }
-
- commitMsg, err := db.StoreConvoMessage(&assistantMsg, auth.User.Id, branch, false)
-
- if err != nil {
- log.Printf("Error storing assistant message: %v\n", err)
- return nil, "", err
- }
-
- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
- ap.MessageNum = num
- ap.StoredReplyIds = append(ap.StoredReplyIds, replyId)
- })
-
- convo = append(convo, &assistantMsg)
- state.convo = convo
-
- return &assistantMsg, commitMsg, err
-}
-
-func (state *activeTellStreamState) followUpNeedsContextStage() bool {
- if !(state.isPlanningStage && state.isFollowUp && state.iteration == 0) {
- return false
- }
-
- active := state.activePlan
-
- return strings.Contains(active.CurrentReplyContent, "clear all context") ||
- strings.Contains(active.CurrentReplyContent, "decide what context") ||
- strings.Contains(active.CurrentReplyContent, "need more context")
-}
diff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.go
index a659d571..b5f50d7a 100644
--- a/app/server/model/plan/tell_stream_main.go
+++ b/app/server/model/plan/tell_stream_main.go
@@ -101,6 +101,10 @@ mainLoop:
state.generationId = response.ID
}
+ if state.firstTokenAt.IsZero() {
+ state.firstTokenAt = time.Now()
+ }
+
if len(response.Choices) == 0 {
if response.Usage != nil {
state.handleUsageChunk(response.Usage)
diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.go
index 83f4817e..2280e98f 100644
--- a/app/server/model/plan/tell_stream_processor.go
+++ b/app/server/model/plan/tell_stream_processor.go
@@ -88,7 +88,7 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr
// Handle file that is present in project paths but not in context
// Prompt user for what to do on the client side, stop the stream, and wait for user response before proceeding
- bufferOrStreamRes := processor.bufferOrStream(content, &parserRes, state.isImplementationStage)
+ bufferOrStreamRes := processor.bufferOrStream(content, &parserRes, state.currentStage)
if currentFile != "" &&
!req.IsChatOnly &&
@@ -137,9 +137,9 @@ type bufferOrStreamResult struct {
blockLang string
}
-func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types.ReplyParserRes, isImplementationStage bool) bufferOrStreamResult {
+func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types.ReplyParserRes, currentStage shared.CurrentStage) bufferOrStreamResult {
// no buffering in planning stages
- if !isImplementationStage {
+ if currentStage.TellStage == shared.TellStagePlanning {
return bufferOrStreamResult{
shouldStream: true,
content: content,
diff --git a/app/server/model/plan/tell_stream_processor_test.go b/app/server/model/plan/tell_stream_processor_test.go
index 635cccac..8e6da9e3 100644
--- a/app/server/model/plan/tell_stream_processor_test.go
+++ b/app/server/model/plan/tell_stream_processor_test.go
@@ -2,6 +2,7 @@ package plan
import (
"plandex-server/types"
+ shared "plandex-shared"
"testing"
)
@@ -389,7 +390,9 @@ func TestBufferOrStream(t *testing.T) {
IsInMoveBlock: tt.isInMoveBlock,
IsInRemoveBlock: tt.isInRemoveBlock,
IsInResetBlock: tt.isInResetBlock,
- }, true)
+ }, shared.CurrentStage{
+ TellStage: shared.TellStageImplementation,
+ })
if got.shouldStream != tt.want.shouldStream {
t.Errorf("shouldStream = %v, want %v", got.shouldStream, tt.want.shouldStream)
diff --git a/app/server/model/plan/tell_stream_status.go b/app/server/model/plan/tell_stream_status.go
new file mode 100644
index 00000000..df952d5b
--- /dev/null
+++ b/app/server/model/plan/tell_stream_status.go
@@ -0,0 +1,180 @@
+package plan
+
+import (
+ "log"
+ "plandex-server/db"
+ shared "plandex-shared"
+)
+
+type handleDescAndExecStatusResult struct {
+ handleStreamFinishedResult
+ subtaskFinished bool
+ generatedDescription *db.ConvoMessageDescription
+}
+
+func (state *activeTellStreamState) handleDescAndExecStatus() handleDescAndExecStatusResult {
+ currentOrgId := state.currentOrgId
+ summarizedToMessageId := state.summarizedToMessageId
+ planId := state.plan.Id
+ branch := state.branch
+ replyOperations := state.chunkProcessor.replyOperations
+
+ active := GetActivePlan(planId, branch)
+ if active == nil {
+ state.onActivePlanMissingError()
+ return handleDescAndExecStatusResult{
+ handleStreamFinishedResult: handleStreamFinishedResult{
+ shouldContinueMainLoop: true,
+ shouldReturn: false,
+ },
+ }
+ }
+
+ var generatedDescription *db.ConvoMessageDescription
+ var subtaskFinished bool
+
+ var errCh = make(chan *shared.ApiError, 2)
+
+ go func() {
+ if len(replyOperations) > 0 {
+ log.Println("Generating plan description")
+
+ res, err := state.genPlanDescription()
+ if err != nil {
+ errCh <- err
+ return
+ }
+
+ generatedDescription = res
+ generatedDescription.OrgId = currentOrgId
+ generatedDescription.SummarizedToMessageId = summarizedToMessageId
+ generatedDescription.MadePlan = true
+ generatedDescription.Operations = replyOperations
+
+ log.Println("Generated plan description.")
+ }
+ errCh <- nil
+ }()
+
+ if state.currentStage.TellStage == shared.TellStageImplementation {
+ go func() {
+ log.Println("Getting exec status")
+ var err *shared.ApiError
+ res, err := state.execStatusShouldContinue(active.CurrentReplyContent, active.Ctx)
+ if err != nil {
+ errCh <- err
+ return
+ }
+
+ subtaskFinished = res.subtaskFinished
+
+ log.Printf("subtaskFinished: %v\n", subtaskFinished)
+
+ errCh <- nil
+ }()
+
+ } else {
+ errCh <- nil
+ }
+
+ for i := 0; i < 2; i++ {
+ err := <-errCh
+ if err != nil {
+ res := state.onError(onErrorParams{
+ streamApiErr: err,
+ storeDesc: true,
+ })
+ return handleDescAndExecStatusResult{
+ handleStreamFinishedResult: handleStreamFinishedResult{
+ shouldContinueMainLoop: res.shouldContinueMainLoop,
+ shouldReturn: res.shouldReturn,
+ },
+ subtaskFinished: subtaskFinished,
+ generatedDescription: generatedDescription,
+ }
+ }
+ }
+
+ return handleDescAndExecStatusResult{
+ handleStreamFinishedResult: handleStreamFinishedResult{},
+ subtaskFinished: subtaskFinished,
+ generatedDescription: generatedDescription,
+ }
+}
+
+type willContinuePlanParams struct {
+ hasNewSubtasks bool
+ allSubtasksFinished bool
+ activatePaths map[string]bool
+}
+
+func (state *activeTellStreamState) willContinuePlan(params willContinuePlanParams) bool {
+ hasNewSubtasks := params.hasNewSubtasks
+ allSubtasksFinished := params.allSubtasksFinished
+ activatePaths := params.activatePaths
+
+ log.Printf("[willContinuePlan] Initial state - hasNewSubtasks: %v, allSubtasksFinished: %v, tellStage: %v, planningPhase: %v, iteration: %d, autoContinue: %v",
+ hasNewSubtasks, allSubtasksFinished, state.currentStage.TellStage, state.currentStage.PlanningPhase, state.iteration, state.req.AutoContinue)
+
+ if state.currentStage.TellStage == shared.TellStagePlanning {
+ log.Println("[willContinuePlan] In planning stage")
+
+ // always continue to response or planning phase after context phase
+ if state.currentStage.PlanningPhase == shared.PlanningPhaseContext {
+
+ // if it's the context stage but it's chat mode and no files were loaded, don't continue
+ if state.req.IsChatOnly && len(activatePaths) == 0 {
+ log.Println("[willContinuePlan] Chat only - no files loaded - stopping")
+ return false
+ }
+
+ log.Println("[willContinuePlan] In context phase - continuing to planning phase")
+ return true
+ }
+
+ if state.req.IsChatOnly {
+ log.Println("[willContinuePlan] Chat only - stopping")
+ return false
+ }
+
+ // otherwise, if auto-continue is disabled, never continue
+ if !state.req.AutoContinue {
+ log.Println("[willContinuePlan] Auto-continue disabled - stopping")
+ return false
+ }
+
+ // if there are new subtasks, continue
+ if hasNewSubtasks {
+ log.Println("[willContinuePlan] Has new subtasks - continuing")
+ return true
+ }
+
+ // if all subtasks are finished, don't continue
+ // otherwise, continue to implementation phase
+ log.Printf("[willContinuePlan] Checking subtasks finished - allSubtasksFinished: %v, will continue: %v",
+ allSubtasksFinished, !allSubtasksFinished)
+ return !allSubtasksFinished
+
+ } else if state.currentStage.TellStage == shared.TellStageImplementation {
+ log.Println("[willContinuePlan] In implementation stage")
+
+ // if all subtasks are finished, don't continue
+ if allSubtasksFinished {
+ log.Println("[willContinuePlan] All subtasks finished - stopping")
+ return false
+ }
+
+ // if we've automatically continued too many times, don't continue
+ if state.iteration >= MaxAutoContinueIterations {
+ log.Printf("[willContinuePlan] Reached max iterations (%d) - stopping", MaxAutoContinueIterations)
+ return false
+ }
+
+ // otherwise, continue with implementation
+ log.Println("[willContinuePlan] Continuing implementation")
+ return true
+ }
+
+ log.Printf("[willContinuePlan] Unknown tell stage: %v - won't continue", state.currentStage.TellStage)
+ return false
+}
diff --git a/app/server/model/plan/tell_stream_store.go b/app/server/model/plan/tell_stream_store.go
new file mode 100644
index 00000000..3598101d
--- /dev/null
+++ b/app/server/model/plan/tell_stream_store.go
@@ -0,0 +1,318 @@
+package plan
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "plandex-server/db"
+ "plandex-server/types"
+ shared "plandex-shared"
+
+ "github.com/sashabaranov/go-openai"
+)
+
+type storeOnFinishedParams struct {
+ replyOperations []*shared.Operation
+ generatedDescription *db.ConvoMessageDescription
+ subtaskFinished bool
+ hasNewSubtasks bool
+ autoLoadContextResult checkAutoLoadContextResult
+ addedSubtasks []*db.Subtask
+ removedSubtasks []string
+}
+
+type storeOnFinishedResult struct {
+ handleStreamFinishedResult
+ allSubtasksFinished bool
+}
+
+func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams) storeOnFinishedResult {
+ replyOperations := params.replyOperations
+ generatedDescription := params.generatedDescription
+ subtaskFinished := params.subtaskFinished
+ hasNewSubtasks := params.hasNewSubtasks
+ autoLoadContextResult := params.autoLoadContextResult
+ currentOrgId := state.currentOrgId
+ currentUserId := state.currentUserId
+ planId := state.plan.Id
+ branch := state.branch
+ auth := state.auth
+ summarizedToMessageId := state.summarizedToMessageId
+ active := state.activePlan
+ addedSubtasks := params.addedSubtasks
+ removedSubtasks := params.removedSubtasks
+ var allSubtasksFinished bool
+
+ log.Println("[storeOnFinished] Locking repo to store assistant reply and description")
+
+ repoLockId, err := db.LockRepo(
+ db.LockRepoParams{
+ OrgId: currentOrgId,
+ UserId: currentUserId,
+ PlanId: planId,
+ Branch: branch,
+ Scope: db.LockScopeWrite,
+ Ctx: active.Ctx,
+ CancelFn: active.CancelFn,
+ },
+ )
+
+ if err != nil {
+ log.Printf("Error locking repo: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error locking repo",
+ }
+ return storeOnFinishedResult{
+ handleStreamFinishedResult: handleStreamFinishedResult{
+ shouldContinueMainLoop: true,
+ shouldReturn: false,
+ },
+ allSubtasksFinished: false,
+ }
+ }
+
+ log.Println("[storeOnFinished] Locked repo for assistant reply and description")
+
+ err = func() error {
+ defer func() {
+ if err != nil {
+ log.Printf("Error storing reply and description: %v\n", err)
+ err = db.GitClearUncommittedChanges(auth.OrgId, planId, branch)
+ if err != nil {
+ log.Printf("Error clearing uncommitted changes: %v\n", err)
+ }
+ }
+
+ log.Println("[storeOnFinished] Unlocking repo for assistant reply and description")
+
+ err = db.DeleteRepoLock(repoLockId, planId)
+ if err != nil {
+ log.Printf("Error unlocking repo: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error unlocking repo",
+ }
+ }
+ }()
+
+ // first resolve subtask state
+ if hasNewSubtasks || subtaskFinished {
+ if subtaskFinished && state.currentSubtask != nil {
+ log.Printf("[storeOnFinished] Marking subtask as finished: %q", state.currentSubtask.Title)
+ state.currentSubtask.IsFinished = true
+
+ log.Printf("[storeOnFinished] Current subtask state after marking as finished: %+v", state.currentSubtask)
+ }
+
+ log.Printf("[storeOnFinished] Storing plan subtasks (hasNewSubtasks=%v, subtaskFinished=%v)", hasNewSubtasks, subtaskFinished)
+ log.Printf("[storeOnFinished] Current subtasks state before storing:")
+ for i, task := range state.subtasks {
+ log.Printf("[storeOnFinished] Task %d: %q (finished=%v)", i+1, task.Title, task.IsFinished)
+ }
+
+ state.currentSubtask = nil
+ allSubtasksFinished = true
+ for _, subtask := range state.subtasks {
+ if !subtask.IsFinished {
+ state.currentSubtask = subtask
+ allSubtasksFinished = false
+ break
+ }
+ }
+
+ if state.currentSubtask != nil {
+ log.Printf("[storeOnFinished] Set new current subtask: %q", state.currentSubtask.Title)
+ } else {
+ log.Println("[storeOnFinished] No new current subtask set")
+ }
+ log.Printf("[storeOnFinished] All subtasks finished: %v", allSubtasksFinished)
+ }
+
+ var flags shared.ConvoMessageFlags
+
+ flags.CurrentStage = state.currentStage
+
+ if len(replyOperations) > 0 {
+ flags.DidWriteCode = true
+ }
+ if hasNewSubtasks {
+ flags.DidMakePlan = true
+ }
+ if len(removedSubtasks) > 0 {
+ flags.DidRemoveTasks = true
+ }
+ if len(autoLoadContextResult.activatePaths) > 0 {
+ flags.DidLoadContext = true
+ }
+ if subtaskFinished && state.currentSubtask != nil {
+ flags.DidCompleteTask = true
+ }
+ if allSubtasksFinished {
+ flags.DidCompletePlan = true
+ }
+ if hasNewSubtasks && (state.req.IsApplyDebug || state.req.IsUserDebug) {
+ flags.DidMakeDebuggingPlan = true
+ }
+
+ assistantMsg, convoCommitMsg, err := state.storeAssistantReply(storeAssistantReplyParams{
+ flags: flags,
+ subtask: state.currentSubtask,
+ addedSubtasks: addedSubtasks,
+ activatedPaths: autoLoadContextResult.activatePaths,
+ removedSubtasks: removedSubtasks,
+ }) // updates state.convo
+
+ if err != nil {
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store assistant message: %v", err),
+ storeDesc: true,
+ })
+ return err
+ }
+
+ log.Println("getting description for assistant message: ", assistantMsg.Id)
+
+ var description *db.ConvoMessageDescription
+ if len(replyOperations) == 0 {
+ description = &db.ConvoMessageDescription{
+ OrgId: currentOrgId,
+ PlanId: planId,
+ ConvoMessageId: assistantMsg.Id,
+ SummarizedToMessageId: summarizedToMessageId,
+ BuildPathsInvalidated: map[string]bool{},
+ MadePlan: false,
+ }
+ } else {
+ description = generatedDescription
+ description.ConvoMessageId = assistantMsg.Id
+ }
+
+ log.Println("[storeOnFinished] Storing description")
+ err = db.StoreDescription(description)
+
+ if err != nil {
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store description: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
+ return err
+ }
+ log.Println("[storeOnFinished] Description stored")
+
+ // store subtasks if we've finished a subtask or added new ones
+ if hasNewSubtasks || subtaskFinished {
+ err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)
+ if err != nil {
+ log.Printf("Error storing plan subtasks: %v\n", err)
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store plan subtasks: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
+ return err
+ }
+ }
+
+ log.Println("Comitting after store on finished")
+
+ err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)
+ if err != nil {
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to commit: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
+ return err
+ }
+ log.Println("Assistant reply, description, and subtasks committed")
+
+ return nil
+ }()
+
+ if err != nil {
+ return storeOnFinishedResult{
+ handleStreamFinishedResult: handleStreamFinishedResult{
+ shouldContinueMainLoop: true,
+ shouldReturn: false,
+ },
+ allSubtasksFinished: allSubtasksFinished,
+ }
+ }
+
+ return storeOnFinishedResult{
+ handleStreamFinishedResult: handleStreamFinishedResult{},
+ allSubtasksFinished: allSubtasksFinished,
+ }
+}
+
+type storeAssistantReplyParams struct {
+ flags shared.ConvoMessageFlags
+ subtask *db.Subtask
+ addedSubtasks []*db.Subtask
+ activatedPaths map[string]bool
+ removedSubtasks []string
+}
+
+func (state *activeTellStreamState) storeAssistantReply(params storeAssistantReplyParams) (*db.ConvoMessage, string, error) {
+ flags := params.flags
+ subtask := params.subtask
+ addedSubtasks := params.addedSubtasks
+ activatedPaths := params.activatedPaths
+ removedSubtasks := params.removedSubtasks
+
+ currentOrgId := state.currentOrgId
+ currentUserId := state.currentUserId
+ planId := state.plan.Id
+ branch := state.branch
+ auth := state.auth
+ replyNumTokens := state.replyNumTokens
+ replyId := state.replyId
+ convo := state.convo
+ num := len(convo) + 1
+
+ log.Printf("storing assistant reply | len(convo) %d | num %d\n", len(convo), num)
+
+ activePlan := state.activePlan
+
+ // fmt.Println("raw message: ", activePlan.CurrentReplyContent)
+
+ assistantMsg := db.ConvoMessage{
+ Id: replyId,
+ OrgId: currentOrgId,
+ PlanId: planId,
+ UserId: currentUserId,
+ Role: openai.ChatMessageRoleAssistant,
+ Tokens: replyNumTokens,
+ Num: num,
+ Message: activePlan.CurrentReplyContent,
+ Flags: flags,
+ Subtask: subtask,
+ AddedSubtasks: addedSubtasks,
+ ActivatedPaths: activatedPaths,
+ RemovedSubtasks: removedSubtasks,
+ }
+
+ commitMsg, err := db.StoreConvoMessage(&assistantMsg, auth.User.Id, branch, false)
+
+ if err != nil {
+ log.Printf("Error storing assistant message: %v\n", err)
+ return nil, "", err
+ }
+
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.MessageNum = num
+ ap.StoredReplyIds = append(ap.StoredReplyIds, replyId)
+ })
+
+ convo = append(convo, &assistantMsg)
+ state.convo = convo
+
+ return &assistantMsg, commitMsg, err
+}
diff --git a/app/server/model/plan/tell_stream_usage.go b/app/server/model/plan/tell_stream_usage.go
index 3b27da6f..0ecdacd7 100644
--- a/app/server/model/plan/tell_stream_usage.go
+++ b/app/server/model/plan/tell_stream_usage.go
@@ -34,6 +34,13 @@ func (state *activeTellStreamState) handleUsageChunk(usage *openai.Usage) {
PlanId: plan.Id,
ModelStreamId: state.activePlan.ModelStreamId,
ConvoMessageId: state.replyId,
+
+ RequestStartedAt: state.requestStartedAt,
+ Streaming: true,
+ FirstTokenAt: state.firstTokenAt,
+ Req: state.originalReq,
+ StreamResult: state.activePlan.CurrentReplyContent,
+ ModelConfig: state.modelConfig,
},
})
@@ -79,6 +86,13 @@ func (state *activeTellStreamState) execHookOnStop(sendStreamErr bool) {
UserCancelled: !sendStreamErr,
HadError: sendStreamErr,
NoReportedUsage: true,
+
+ RequestStartedAt: state.requestStartedAt,
+ Streaming: true,
+ FirstTokenAt: state.firstTokenAt,
+ Req: state.originalReq,
+ StreamResult: state.activePlan.CurrentReplyContent,
+ ModelConfig: state.modelConfig,
},
})
diff --git a/app/server/model/plan/tell_subtasks.go b/app/server/model/plan/tell_subtasks.go
index b2caa95f..f32a9a60 100644
--- a/app/server/model/plan/tell_subtasks.go
+++ b/app/server/model/plan/tell_subtasks.go
@@ -141,3 +141,66 @@ func (state *activeTellStreamState) checkNewSubtasks() []*db.Subtask {
return newSubtasks
}
+
+func (state *activeTellStreamState) checkRemoveSubtasks() []string {
+ activePlan := GetActivePlan(state.plan.Id, state.branch)
+
+ if activePlan == nil {
+ return nil
+ }
+
+ content := activePlan.CurrentReplyContent
+
+ // Parse tasks to remove
+ tasksToRemove := parse.ParseRemoveSubtasks(content)
+
+ if len(tasksToRemove) == 0 {
+ log.Println("No tasks to remove found")
+ return nil
+ }
+
+ log.Println("Found tasks to remove:")
+ log.Println(spew.Sdump(tasksToRemove))
+
+ // Create a map of task titles to remove for efficient lookup
+ removeMap := make(map[string]bool)
+ for _, task := range tasksToRemove {
+ removeMap[task] = true
+ }
+
+ var removedSubtasks []*db.Subtask
+ var remainingSubtasks []*db.Subtask
+
+ // Keep tasks that aren't in the remove list
+ for _, subtask := range state.subtasks {
+ if removeMap[subtask.Title] {
+ // Only track unfinished tasks that are being removed
+ if !subtask.IsFinished {
+ removedSubtasks = append(removedSubtasks, subtask)
+ }
+ } else {
+ remainingSubtasks = append(remainingSubtasks, subtask)
+ }
+ }
+
+ state.subtasks = remainingSubtasks
+
+ // Update current subtask if it was removed
+ if state.currentSubtask != nil && removeMap[state.currentSubtask.Title] {
+ state.currentSubtask = nil
+ // Find the first unfinished subtask to set as current
+ for _, subtask := range state.subtasks {
+ if !subtask.IsFinished {
+ state.currentSubtask = subtask
+ break
+ }
+ }
+ }
+
+ removedSubtaskTitles := []string{}
+ for _, subtask := range removedSubtasks {
+ removedSubtaskTitles = append(removedSubtaskTitles, subtask.Title)
+ }
+
+ return removedSubtaskTitles
+}
diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.go
index 5fc38ecf..65d91362 100644
--- a/app/server/model/plan/tell_summary.go
+++ b/app/server/model/plan/tell_summary.go
@@ -33,7 +33,7 @@ func (state *activeTellStreamState) addConversationMessages() bool {
conversationTokens := 0
tokensUpToTimestamp := make(map[int64]int)
for _, convoMessage := range convo {
- conversationTokens += convoMessage.Tokens + shared.TokensPerMessage + shared.TokensPerName
+ conversationTokens += convoMessage.Tokens + model.TokensPerMessage + model.TokensPerName
timestamp := convoMessage.CreatedAt.UnixNano() / int64(time.Millisecond)
tokensUpToTimestamp[timestamp] = conversationTokens
// log.Printf("Timestamp: %s | Tokens: %d | Total: %d | conversationTokens\n", convoMessage.Timestamp, convoMessage.Tokens, conversationTokens)
@@ -128,16 +128,26 @@ func (state *activeTellStreamState) addConversationMessages() bool {
continue
}
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: convoMessage.Message,
+ },
+ },
})
// add the latest summary as a conversation message if this is the last message summarized, in order to reinforce the current state of the plan to the model
if latestSummary != nil && convoMessage.Id == latestSummary.LatestConvoMessageId {
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: latestSummary.Summary,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: latestSummary.Summary,
+ },
+ },
})
}
}
@@ -151,9 +161,14 @@ func (state *activeTellStreamState) addConversationMessages() bool {
return false
}
state.summarizedToMessageId = summary.LatestConvoMessageId
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: summary.Summary,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: summary.Summary,
+ },
+ },
})
// add messages after the last message in the summary
@@ -164,16 +179,26 @@ func (state *activeTellStreamState) addConversationMessages() bool {
}
if convoMessage.CreatedAt.After(summary.LatestConvoMessageCreatedAt) {
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: convoMessage.Message,
+ },
+ },
})
// add the latest summary as a conversation message if this is the last message summarized, in order to reinforce the current state of the plan to the model
if latestSummary != nil && convoMessage.Id == latestSummary.LatestConvoMessageId {
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: latestSummary.Summary,
+ state.messages = append(state.messages, types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: latestSummary.Summary,
+ },
+ },
})
}
}
@@ -229,7 +254,7 @@ func summarizeConvo(clients map[string]model.ClientInfo, config shared.ModelRole
// spew.Dump(promptMessage)
// log.Printf("currentOrgId: %s\n", currentOrgId)
- var summaryMessages []*openai.ChatCompletionMessage
+ var summaryMessages []*types.ExtendedChatMessage
var latestSummary *db.ConvoSummary
var numMessagesSummarized int = 0
var latestMessageSummarizedAt time.Time
@@ -249,22 +274,32 @@ func summarizeConvo(clients map[string]model.ClientInfo, config shared.ModelRole
if latestSummary == nil {
for _, convoMessage := range convo {
- summaryMessages = append(summaryMessages, &openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
+ summaryMessages = append(summaryMessages, &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: convoMessage.Message,
+ },
+ },
})
latestMessageId = convoMessage.Id
latestMessageSummarizedAt = convoMessage.CreatedAt
numMessagesSummarized++
- numTokens += convoMessage.Tokens + shared.TokensPerMessage + shared.TokensPerName
+ numTokens += convoMessage.Tokens + model.TokensPerMessage + model.TokensPerName
}
} else {
- summaryMessages = append(summaryMessages, &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: latestSummary.Summary,
+ summaryMessages = append(summaryMessages, &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: latestSummary.Summary,
+ },
+ },
})
- numTokens += latestSummary.Tokens + shared.TokensPerMessage + shared.TokensPerName
+ numTokens += latestSummary.Tokens + model.TokensPerMessage + model.TokensPerName
var found bool
for _, convoMessage := range convo {
@@ -273,12 +308,17 @@ func summarizeConvo(clients map[string]model.ClientInfo, config shared.ModelRole
continue
}
if found {
- summaryMessages = append(summaryMessages, &openai.ChatCompletionMessage{
- Role: convoMessage.Role,
- Content: convoMessage.Message,
+ summaryMessages = append(summaryMessages, &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: convoMessage.Message,
+ },
+ },
})
numMessagesSummarized++
- numTokens += convoMessage.Tokens + shared.TokensPerMessage + shared.TokensPerName
+ numTokens += convoMessage.Tokens + model.TokensPerMessage + model.TokensPerName
}
}
@@ -292,23 +332,33 @@ func summarizeConvo(clients map[string]model.ClientInfo, config shared.ModelRole
if userPrompt != "" {
if userPrompt != prompts.UserContinuePrompt && userPrompt != prompts.AutoContinuePrompt {
- summaryMessages = append(summaryMessages, &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: userPrompt,
+ summaryMessages = append(summaryMessages, &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: userPrompt,
+ },
+ },
})
tokens := shared.GetNumTokensEstimate(userPrompt)
- numTokens += tokens + shared.TokensPerMessage + shared.TokensPerName
+ numTokens += tokens + model.TokensPerMessage + model.TokensPerName
}
}
if currentReply != "" {
- summaryMessages = append(summaryMessages, &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: currentReply,
+ summaryMessages = append(summaryMessages, &types.ExtendedChatMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: []types.ExtendedChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: currentReply,
+ },
+ },
})
- numTokens += params.currentReplyNumTokens + shared.TokensPerMessage + shared.TokensPerName
+ numTokens += params.currentReplyNumTokens + model.TokensPerMessage + model.TokensPerName
}
log.Printf("Calling model for plan summary. Summarizing %d messages\n", len(summaryMessages))
diff --git a/app/server/model/plan/tell_sys_prompt.go b/app/server/model/plan/tell_sys_prompt.go
index 91121366..bf71d770 100644
--- a/app/server/model/plan/tell_sys_prompt.go
+++ b/app/server/model/plan/tell_sys_prompt.go
@@ -4,86 +4,179 @@ import (
"fmt"
"log"
"plandex-server/model/prompts"
+ "plandex-server/types"
+ shared "plandex-shared"
+
+ "github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) getTellSysPrompt(autoContextEnabled, smartContextEnabled, didLoadChatOnlyContext bool, modelContextText string) (string, error) {
+type getTellSysPromptParams struct {
+ autoContextEnabled bool
+ smartContextEnabled bool
+ basicContextMsg *types.ExtendedChatMessagePart
+ autoContextMsg *types.ExtendedChatMessagePart
+ smartContextMsg *types.ExtendedChatMessagePart
+}
+
+func (state *activeTellStreamState) getTellSysPrompt(params getTellSysPromptParams) ([]types.ExtendedChatMessagePart, error) {
+ autoContextEnabled := params.autoContextEnabled
+ smartContextEnabled := params.smartContextEnabled
+ basicContextMsg := params.basicContextMsg
+ autoContextMsg := params.autoContextMsg
+ smartContextMsg := params.smartContextMsg
req := state.req
- isPlanningStage := state.isPlanningStage
- isContextStage := state.isContextStage
- isFollowUp := state.isFollowUp
active := state.activePlan
+ currentStage := state.currentStage
- var sysCreate string
+ // var sysCreate string
- params := prompts.CreatePromptParams{
- ExecMode: req.ExecEnabled,
- AutoContext: autoContextEnabled,
- LastResponseLoadedContext: didLoadChatOnlyContext,
+ sysParts := []types.ExtendedChatMessagePart{}
+
+ createPromptParams := prompts.CreatePromptParams{
+ ExecMode: req.ExecEnabled,
+ AutoContext: autoContextEnabled,
+ IsUserDebug: req.IsUserDebug,
+ IsApplyDebug: req.IsApplyDebug,
}
- if req.IsChatOnly {
- sysCreate = prompts.GetChatSysPrompt(params)
- } else {
-
- if isPlanningStage {
- log.Println("isPlanningStage")
- log.Println("autoContextEnabled", autoContextEnabled)
- log.Println("isContextStage", isContextStage)
- if autoContextEnabled && isContextStage {
- log.Println("autoContextEnabled && isContextStage -- adding auto context preamble")
- sysCreate = prompts.GetAutoContextTellPreamble(params)
- } else if autoContextEnabled || smartContextEnabled {
- log.Println("autoContextEnabled || smartContextEnabled -- adding auto context preamble")
- sysCreate = prompts.SysPlanningAutoContext
-
- if isFollowUp && !req.IsApplyDebug {
- log.Println("isFollowUp && !req.IsApplyDebug && !req.IsUserDebug -- adding follow up classifier prompt")
- sysCreate = prompts.GetFollowUpPlanClassifierPrompt(params) + "\n\n" + sysCreate
- }
+ // log.Println("getTellSysPrompt - prompt params:", spew.Sdump(params))
+
+ if currentStage.TellStage == shared.TellStagePlanning {
+ if basicContextMsg != nil {
+ basicContextMsg.CacheControl = &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ }
+ sysParts = append(sysParts, *basicContextMsg)
+ }
+
+ if currentStage.PlanningPhase == shared.PlanningPhaseContext {
+ log.Println("Planning phase is context -- adding auto context prompt")
+
+ var txt string
+ if req.IsChatOnly {
+ txt = prompts.GetAutoContextChatPrompt(createPromptParams)
} else {
- log.Println("sysPlanningBasic")
- sysCreate = prompts.SysPlanningBasic
+ txt = prompts.GetAutoContextTellPrompt(createPromptParams)
}
- } else {
- log.Println("isImplementationStage")
- if state.currentSubtask == nil {
- return "", fmt.Errorf("no current subtask during implementation stage")
+
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: txt,
+ CacheControl: &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ },
+ })
+ } else if currentStage.PlanningPhase == shared.PlanningPhasePlanning {
+
+ var txt string
+ if req.IsChatOnly {
+ txt = prompts.GetChatSysPrompt(createPromptParams)
+ } else {
+ txt = prompts.GetPlanningPrompt(createPromptParams)
}
- sysCreate = prompts.GetImplementationPrompt(state.currentSubtask.Title)
- }
- if !isContextStage {
- if req.ExecEnabled {
- if isPlanningStage {
- sysCreate += prompts.ApplyScriptPlanningPrompt
- } else {
- sysCreate += prompts.ApplyScriptImplementationPrompt
- }
+ if len(state.subtasks) > 0 {
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: txt,
+ })
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: state.formatSubtasks(),
+ CacheControl: &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ },
+ })
} else {
- sysCreate += prompts.NoApplyScriptPrompt
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: txt,
+ CacheControl: &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ },
+ })
+ }
+
+ if !req.IsChatOnly {
+ if len(active.SkippedPaths) > 0 {
+ skippedPrompt := prompts.SkippedPathsPrompt
+ for skippedPath := range active.SkippedPaths {
+ skippedPrompt += fmt.Sprintf("- %s\n", skippedPath)
+ }
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: skippedPrompt,
+ })
+ }
}
}
- }
- // log.Println("sysCreate before context:\n", sysCreate)
+ if autoContextMsg != nil {
+ sysParts = append(sysParts, *autoContextMsg)
+ }
- sysCreate += modelContextText
+ if smartContextMsg != nil {
+ log.Println("smartContextMsg not supported during planning stage - only basic or auto context is supported")
+ return nil, fmt.Errorf("smartContextMsg not supported during planning stage - only basic or auto context is supported")
+ }
- if !req.IsChatOnly {
- if len(active.SkippedPaths) > 0 {
- skippedPrompt := prompts.SkippedPathsPrompt
- for skippedPath := range active.SkippedPaths {
- skippedPrompt += fmt.Sprintf("- %s\n", skippedPath)
+ } else if currentStage.TellStage == shared.TellStageImplementation {
+ if state.currentSubtask == nil {
+ return nil, fmt.Errorf("no current subtask during implementation stage")
+ }
+
+ if !smartContextEnabled && basicContextMsg != nil {
+ basicContextMsg.CacheControl = &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
}
- sysCreate += skippedPrompt
+ sysParts = append(sysParts, *basicContextMsg)
}
- }
- if len(state.subtasks) > 0 {
- subtasksPrompt := state.formatSubtasks()
- // log.Println("subtasksPrompt:\n", subtasksPrompt)
- sysCreate += subtasksPrompt
+ if len(state.subtasks) > 0 {
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: prompts.GetImplementationPrompt(state.currentSubtask.Title),
+ })
+ sysParts = append(sysParts,
+ types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: state.formatSubtasks(),
+ CacheControl: &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ },
+ })
+ } else {
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: prompts.GetImplementationPrompt(state.currentSubtask.Title),
+ CacheControl: &types.CacheControlSpec{
+ Type: types.CacheControlTypeEphemeral,
+ },
+ })
+ }
+
+ if !req.IsChatOnly {
+ if len(active.SkippedPaths) > 0 {
+ skippedPrompt := prompts.SkippedPathsPrompt
+ for skippedPath := range active.SkippedPaths {
+ skippedPrompt += fmt.Sprintf("- %s\n", skippedPath)
+ }
+ sysParts = append(sysParts, types.ExtendedChatMessagePart{
+ Type: openai.ChatMessagePartTypeText,
+ Text: skippedPrompt,
+ })
+ }
+ }
+
+ if smartContextMsg != nil {
+ sysParts = append(sysParts, *smartContextMsg)
+ }
+
+ if autoContextMsg != nil {
+ log.Println("autoContextMsg not supported during implementation stage - only basic or smart context is supported")
+ return nil, fmt.Errorf("autoContextMsg not supported during implementation stage - only basic or smart context is supported")
+ }
}
- return sysCreate, nil
+ return sysParts, nil
}
diff --git a/app/server/model/prompts/apply_exec.go b/app/server/model/prompts/apply_exec.go
index 0746665b..2542c33d 100644
--- a/app/server/model/prompts/apply_exec.go
+++ b/app/server/model/prompts/apply_exec.go
@@ -822,7 +822,7 @@ CRITICAL: The script must handle both program execution and security carefully:
- Apply the same principle to other commands. Be minimal and selective when choosing which commands to run.
`
-var NoApplyScriptPrompt = `
+var NoApplyScriptPlanningPrompt = `
## No execution of commands
@@ -835,7 +835,7 @@ When breaking up a task into subtasks, only include subtasks that you can do you
For tasks that you ARE able to complete because they only require creating or updating files, complete them thoroughly yourself and don't ask the user to do any part of them.
`
-const DebugPrompt = `You are debugging a failing shell command. Focus only on fixing this issue so that the command runs successfully; don't make other changes.
+const UserPlanningDebugPrompt = `You are debugging a failing shell command. Focus only on fixing this issue so that the command runs successfully; don't make other changes.
Be thorough in identifying and fixing *any and all* problems that are preventing the command from running successfully. If there are multiple problems, identify and fix all of them.
@@ -844,7 +844,7 @@ The command will be run again *automatically* on the user's machine once the cha
Command details:
`
-const ApplyDebugPrompt = `The _apply.sh script failed and you must debug. Focus only on fixing this issue so that the command runs successfully; don't make other changes.
+const ApplyPlanningDebugPrompt = `The _apply.sh script failed and you must debug. Focus only on fixing this issue so that the command runs successfully; don't make other changes.
Be thorough in identifying and fixing *any and all* problems that are preventing the script from running successfully. If there are multiple problems, identify and fix all of them.
diff --git a/app/server/model/prompts/chat.go b/app/server/model/prompts/chat.go
index ad509509..d610b3ca 100644
--- a/app/server/model/prompts/chat.go
+++ b/app/server/model/prompts/chat.go
@@ -25,14 +25,11 @@ Note that execution mode is not enabled, so while discussing potential solutions
contextHandling := ``
if params.AutoContext {
- if params.LastResponseLoadedContext {
- contextHandling = `
-Since context was just loaded in the previous response:
-- Continue the conversation naturally using the context you now have
-- You ABSOLUTELY MUST NOT load additional context in your response`
- } else {
- contextHandling = GetAutoContextChatPreamble(params)
- }
+
+ contextHandling = `
+Since context was just loaded (if needed) in the previous response:
+- Continue the conversation naturally using the context you now have access to`
+
} else {
contextHandling = `
Context handling:
diff --git a/app/server/model/prompts/context_load.go b/app/server/model/prompts/context_load.go
index 0bb11128..1e0e01af 100644
--- a/app/server/model/prompts/context_load.go
+++ b/app/server/model/prompts/context_load.go
@@ -1,27 +1,83 @@
package prompts
-func GetAutoContextTellPreamble(params CreatePromptParams) string {
+const ArchitectSummary = `
+[SUMMARY OF INSTRUCTIONS:]
+
+You are an expert software architect. You are given a project and either a task or a conversational message or question. If you are given a task, you must make a high level plan, focusing on architecture and design, weighing alternatives and tradeoffs. Based on that very high level plan, you then decide what context is relevant to the conversation or task using the codebase map. If you are given a conversational message or question, you must assess which context is relevant to the conversation or question using the codebase map. Respond in a natural way.
+
+More formally, you are in the Context Phase ("Decide and Declare") of a two-phase process:
+
+Phase 1 - Context (Current Phase):
+- Examine the user's request and available codebase information
+- Determine what context is truly relevant for the next phase
+- List categories and files needed
+- End with <PlandexFinish/>
+
+Phase 2 - Response (Next Phase):
+- System will incorporate only the context you selected
+- You'll then create a plan (tell mode) or provide an answer (chat mode)
+- Implementation happens only in Phase 2
+
+IMPORTANT CONCEPTS:
+- Relevant files are listed in a '### Files' section at the end of the response.
+- Only these files will be included in the next phase.
+- Be liberal about marking context as relevant. Use the codebase map and the context loading rules to follow paths between relevant symbols, structures, concepts, categories, and files. It's *much* *much* *much* worse to leave out a relevant file than to include a non-relevant file. Go GET that relevant context, and get it ALL.
+
+YOUR TASK:
+1. Assess Information
+ - Do you have enough detail about the user's request?
+ - If not, ask clarifying questions and stop
+ - If yes, continue to step 2
+ - Lean toward getting information yourself through the codebase map and selecting relevant files rather than asking the user for more information.
+ - That said, if you're really unsure, ask the user for more information.
+
+2. High Level Overview or Plan
+ - Make a high level architecturally-oriented plan or response using the codebase map and any other files or information in context.
+ - Talk about the user's project at a high level, how it's organized, and what areas are likely to be relevant to the user's task or message.
+ - Explain what parts of the codebase you'll need to examine. Start broadly and then narrow in on specific files and symbols.
+ - Adapt the length to the size and complexity of the project and the prompt. For simple tasks, a few sentences are sufficient. For complex tasks, a few paragraphs are appropriate. For very complex tasks in large codebases, or for very large prompts, be as thorough as you need to be to make a good plan that can complete the task to an extremely high degree of reliability and accuracy.
+
+3. Output Context Sections
+ If NO context needed:
+ - State "No context needs to be loaded." along with a brief conversational response and output <PlandexFinish/>
+
+ If context needed:
+ a) "### Context Categories"
+ - List categories of context to activate
+ - One line per category
+ - No file paths or symbols here
+
+ b) "### Files"
+ - Group by category from above
+ - Files must be in backticks
+ - List relevant symbols for each file
+
+ c) Output <PlandexFinish/> immediately after
+
+CRITICAL RULES:
+- Do NOT write any code or implementation details
+- Do NOT create tasks or plans
+- Stop immediately after <PlandexFinish/>
+
+--
+
+Even if context has been loaded previously in the conversation, you MUST load ALL relevant files again. Any context you do NOT include in the '### Files' section will be missing from the next phase. Be absolutely certain that you have included all relevant files.
+`
+
+func GetAutoContextTellPrompt(params CreatePromptParams) string {
s := `
[RESPONSE INSTRUCTIONS:]
-You are an expert architect. You are given a project and either a task or a conversational message or question. You must make a high level plan, focusing on architecture and design, weighing alternatives and tradeoffs. Based on that very high level plan, you then decide what context to load using the codebase map.
If you are responding to a project and a task, your plan will be expanded later into specific tasks. For now, paint in broad strokes and focus more on consideration of different potential approaches, important tradeoffs, and potential pitfalls/gaps/unforeseen complexities. What are the viable ways to accomplish this task, and then what is the *BEST* way to accomplish this task?
-Your high level plan should also be succinct. Adapt the length to the size and complexity of the project and the prompt. For simple tasks, a few sentences are sufficient. For complex tasks, a few paragraphs are appropriate. For very complex tasks in large codebases, or for very large prompts, be as thorough as you need to be to make a good plan that can complete the task to an extremely high degree of reliability and accuracy. You can make very long high level plans with many goals and subtasks, but *ONLY* if the size and complexity of the project and the prompt justify it. Your DEFAULT should be *brevity* and *conciseness*. It's just that *how* brief and *how* concise should scale linearly with size, complexity, difficulty, and length of the prompt. If you can make a strong plan in very few words or sentences, do so.
+Your high level plan should be succinct. Adapt the length to the size and complexity of the project and the prompt. For simple tasks, a few sentences are sufficient. For complex tasks, a few paragraphs are appropriate. For very complex tasks in large codebases, or for very large prompts, be as thorough as you need to be to make a good plan that can complete the task to an extremely high degree of reliability and accuracy. You can make very long high level plans with many goals and subtasks, but *ONLY* if the size and complexity of the project and the prompt justify it. Your DEFAULT should be *brevity* and *conciseness*. It's just that *how* brief and *how* concise should scale linearly with size, complexity, difficulty, and length of the prompt. If you can make a strong plan in very few words or sentences, do so.
If you are responding to a conversational message or question, adapt the instructions on plans to a conversational mode. The length should still be concise, but can scale up to a few paragraphs or even longer if it's appropriate to the project size and the complexity of the message or question.
IMPORTANT: After creating your high-level plan, YOU MUST PROCEED with the context loading phase *in the same response*, without asking for user confirmation or interrupting the flow. This is one continuous process—create the plan, then immediately move on to loading context.
-`
- if params.ExecMode {
- s += `
-*Execution mode is enabled.* This means that you are able to run commands on the user's machine. Include consideration of any commands that may need to be run in your high level plan, especially commands for installing required dependencies or building and running the project.
-
-Do not 'force it' when it comes to running commands. Don't guess at commands to run—if you're unsure, it's better to omit commands than to include incorrect ones. Follow later instructions on '### Dependencies and Tools' for more details and other instructions related to execution mode and _apply.sh.
+You MUST NOT write any code in this step. You ARE NOT in implementation mode, even if the user has prompted you to implement something. This step is ONLY for high level planning and context loading. Implementation will begin in a LATER step. Do NOT tell the user you are beginning implementation.
`
- }
-
s += `
[CONTEXT INSTRUCTIONS:]
@@ -34,11 +90,6 @@ In response to the user's latest prompt, do the following IN ORDER:
2. Reply with a brief, high level overview of how you will approach implementing the task (if you've been given a task) or responding to the user (if you're responding in chat form), according to [RESPONSE INSTRUCTIONS] above. Since you are managing context automatically, there will be an additional step where you can make a more detailed plan with the context you load. Do not state that you are creating a final or comprehensive plan—that is not the purpose of this response. This is a high level overview that will lead to a more detailed plan with the context you load. Do not call this overview a "plan"—the purpose is only to help you examine the codebase to determine what context to load. You will then make a plan in the next step.
`
- if params.ExecMode {
- s += `
- - Since execution mode is enabled, include consideration of any commands that may need to be run in your high level plan as described in [RESPONSE INSTRUCTIONS] above. Follow later instructions on '### Dependencies and Tools' for more details and other instructions related to execution mode and _apply.sh.
-`
- }
s += `
3. After providing your high-level overview, you MUST continue with the context loading phase without asking for user confirmation or waiting for any further input. This is one continuous process in a single response.
@@ -62,29 +113,34 @@ In response to the user's latest prompt, do the following IN ORDER:
return s
}
-func GetAutoContextChatPreamble(params CreatePromptParams) string {
+func GetAutoContextChatPrompt(params CreatePromptParams) string {
s := `
[CONTEXT INSTRUCTIONS:]
-You are operating in 'auto-context mode' for chat. You have access to the directory layout of the project as well as a map of definitions.
+You are operating in 'auto-context mode' for chat.
+
+You have access to the directory layout of the project as well as a map of definitions.
-First, assess if you need additional context:
+Your job is to assess which context in the project might be relevant or helpful to the user's question or message.
+
+Assess the following:
- Are there specific files referenced that you need to examine?
- Would related files help you give a more accurate or complete answer?
- Do you need to understand implementations or dependencies?
-- Have you already loaded similar context in a recent response? If so, avoid loading it again.
+
+Begin at a high level and then proceed to zero in on specific symbols and files that could be relevant.
+
+It's good to be eager about loading context. If in doubt, load it. Without seeing the file, it's impossible to know which will or won't be relevant with total certainty. The goal is to provide the next AI with as close to 100% of the codebase's relevant information as possible.
If NO additional context is needed:
- Continue with your response conversationally
If you need context:
-- Briefly mention what you need to check, e.g. "Let me look at the relevant files..." or "Let me look at those functions..." — use your judgment and respond in a natural, conversational manner.
+- Mention what you need to check, e.g. "Let me look at the relevant files..." or "Let me look at those functions..." — use your judgment and respond in a natural, conversational way.
- Then proceed with the context loading format:
` + GetAutoContextShared(params, false) + `
-Remember: Only load context when genuinely needed for accuracy. Avoid loading context in consecutive responses as this disrupts conversation flow.
-
[END OF CONTEXT INSTRUCTIONS]
`
@@ -96,7 +152,7 @@ func GetAutoContextShared(params CreatePromptParams, tellMode bool) string {
- In a section titled '### Context Categories', list one or more categories of context that are relevant to the user's task, question, or message. For example, if the user is asking you to implement an API endpoint, you might list 'API endpoints', 'database operations', 'frontend code', 'utilities', and so on. Make sure any and all relevant categories are included, but don't include more categories than necessary—if only a single category is relevant, then only list that one. Do not include file paths, symbols, or explanations—only the categories.`
if tellMode && params.ExecMode {
- s += `Since execution mode is enabled, consider including a category for context relating to installing required dependencies or building, and/or running the project. Adapt this to the user's project, task, and prompt. Don't force it—only include this category if it makes sense. Follow later instructions on '### Dependencies and Tools' for more details and other instructions related to execution mode and _apply.sh.`
+ s += `Since execution mode is enabled, consider including a category for context relating to installing required dependencies or building, and/or running the project. Adapt this to the user's project, task, and prompt. Don't force it—only include this category if it makes senses.`
}
s += `
@@ -174,8 +230,6 @@ Since execution mode is enabled, make sure to include any files that are necessa
If dependencies may be needed for the task and there are dependency files like requirements.txt, package.json, go.mod, Gemfile, or equivalent, include them.
-Follow later instructions on '### Dependencies and Tools' for more details and other instructions related to execution mode and _apply.sh.
-
Don't force it or overdo it. Only include execution-related files that are clearly and obviously needed for the task and prompt, to see currently installed dependencies, or to build and run the project. For example, do NOT include an entire directory of test files. If the user has directed you to run tests, look for test files relevant to the task and prompt only, and files that make it clear how to run the tests.
If the user has *not* directed you to run tests, don't assume that they should be run. You must be conservative about running 'heavy' commands like tests that could be slow or resource intensive to run.
@@ -188,7 +242,10 @@ This also applies to other potentially heavy commands like building Docker image
After outputting the '### Files' section, end your response. Do not output any additional text after that section.
***Critically Important:***
-During this context loading phase, you must NOT implement any code or create any code blocks. This phase is ONLY for identifying relevant context.`
+During this context loading phase, you must NOT implement any code or create any code blocks. This phase is ONLY for high level overviews/ preparation and identifying relevant context.
+`
+
+ s += ArchitectSummary
return s
}
diff --git a/app/server/model/prompts/exec_status.go b/app/server/model/prompts/exec_status.go
index 54a5c1f9..17da6115 100644
--- a/app/server/model/prompts/exec_status.go
+++ b/app/server/model/prompts/exec_status.go
@@ -5,44 +5,43 @@ import (
"github.com/sashabaranov/go-openai/jsonschema"
)
-const SysExecStatusShouldContinue = `You are tasked with evaluating a response generated by another AI (AI 1).
+const SysExecStatusFinishedSubtask = `You are tasked with evaluating a response generated by another AI (AI 1) that has been given a coding task to implement.
-Your goal is to determine two things:
-1. Whether the current subtask was fully implemented in the message
-2. Whether the plan can automatically continue or needs user input/action
+Your goal is to determine whether the current task was fully implemented in the supplied message(s) from AI 1.
-To do this, you need to analyze the latest message from AI 1 carefully and decide based on the following criteria:
+To do this, you need to analyze the latest message from AI 1, and possibly previous messages, and then carefully and decide based on the following criteria:
-First, assess whether the current subtask was fully implemented in the message. A subtask is only considered fully implemented if all necessary code changes for that subtask have been completed with no remaining todo placeholders or partial implementations.
+First, examining any previous messages along with the current message, assess whether the current task was fully implemented when these messages are taken together. A task is only considered fully implemented if all necessary code changes for that task have been completed with no remaining todo placeholders or partial implementations.
-Then, assess whether AI 1 has concluded with any statement that indicates either:
-- The user needs to take specific actions before the plan can proceed
-- The plan can't automatically continue for any other reason
+You *must* call the didFinishSubtask function with a JSON object containing the keys 'reasoning' and 'subtaskFinished'.
-You *must* call the shouldAutoContinue function with a JSON object containing the keys 'reasoning', 'subtaskFinished', and 'shouldContinue'.
+Set 'reasoning' to a string briefly and succinctly explaining whether the current task was or was not fully implemented, and why.
-Set 'reasoning' to a string briefly and succinctly explaining:
-1. Whether the current subtask was or was not fully implemented, and why
-2. Whether AI 1 indicated that user action/input is needed
+If AI 1 has stated that the task has been completed, consider that in your reasoning and response, but also assess the actual implementation and whether it really did complete the task. Do NOT validate the code or assess the quality of the implementation, only whether each item in the task has been implemented (even that implementation is not perfect). Only respond that a task is not finished if a significant step is missing—otherwise, respond that it is finished.
-The 'subtaskFinished' key is a boolean that indicates whether the current subtask has been fully implemented in the latest message from AI 1. If the current subtask has been fully implemented, 'subtaskFinished' must be true. If the current subtask has not been fully implemented or there are unexplained todo placeholders, 'subtaskFinished' must be false. If the subtask has been skipped because it is not necessary or was already implemented in an earlier step, 'subtaskFinished' must be true.
+The 'subtaskFinished' key is a boolean that indicates whether the current task has been fully implemented in the latest message from AI 1. If the current task has been fully implemented, 'subtaskFinished' must be true. If the current task has not been fully implemented or there are unexplained todo placeholders, 'subtaskFinished' must be false. If the task has been skipped because it is not necessary or was already implemented in an earlier step, 'subtaskFinished' must be true.
-Set 'shouldContinue' to false only if AI 1 explicitly states that user action/input is needed before continuing. In all other cases, including when there are unexplained todo placeholders, 'shouldContinue' must be true.
+You must always call 'didFinishSubtask'. Don't call any other function.`
-You must always call 'shouldAutoContinue'. Don't call any other function.`
-
-func GetExecStatusShouldContinue(userPrompt, message string) string {
- s := SysExecStatusShouldContinue
+func GetExecStatusFinishedSubtask(userPrompt, currentSubtask string, currentMessage string, previousMessages []string) string {
+ s := SysExecStatusFinishedSubtask
if userPrompt != "" {
s += "\n\n**Here is the user's prompt:**\n" + userPrompt
}
- s += "\n\n**Here is the latest message from AI 1:**\n" + message
+ s += "\n\n**Here is the current task:**\n" + currentSubtask
+
+ for _, msg := range previousMessages {
+ s += "\n\n**Here is a previous message from AI 1 that was working on the same task:**\n" + msg
+ }
+
+ s += "\n\n**Here is the latest message from AI 1:**\n" + currentMessage
+
return s
}
-var ShouldAutoContinueFn = openai.FunctionDefinition{
- Name: "shouldAutoContinue",
+var DidFinishSubtaskFn = openai.FunctionDefinition{
+ Name: "didFinishSubtask",
Parameters: &jsonschema.Definition{
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
@@ -52,10 +51,7 @@ var ShouldAutoContinueFn = openai.FunctionDefinition{
"subtaskFinished": {
Type: jsonschema.Boolean,
},
- "shouldContinue": {
- Type: jsonschema.Boolean,
- },
},
- Required: []string{"reasoning", "subtaskFinished", "shouldContinue"},
+ Required: []string{"reasoning", "subtaskFinished"},
},
}
diff --git a/app/server/model/prompts/implement.go b/app/server/model/prompts/implement.go
index 2f442b7c..8594e69c 100644
--- a/app/server/model/prompts/implement.go
+++ b/app/server/model/prompts/implement.go
@@ -1,11 +1,11 @@
package prompts
-func GetImplementationPrompt(subtask string) string {
+func GetImplementationPrompt(task string) string {
var prompt string
- prompt += `CURRENT SUBTASK:\n\n` + subtask + `\n\n` + `
+ prompt += `CURRENT TASK:\n\n` + task + `\n\n` + `
- Always refer to the current subtask by this *exact name*. Do NOT alter it in any way.
+ Always refer to the current task by this *exact name*. Do NOT alter it in any way.
`
prompt += `
@@ -104,6 +104,8 @@ As much as possible, do not include placeholders in code blocks like "// impleme
If you are outputting some code for illustrative or explanatory purpose and not because you are updating that code, you MUST NOT use a labelled file block. Instead output the label with NO PRECEDING DASH and NO COLON postfix. Use a conversational sentence like 'This code in src/main.rs.' to label the code. This is the only exception to the rule that all code blocks must be labelled with a file path. Labelled code blocks are ONLY for code that is being created or modified in the plan.
+DO NOT UNDER ANY CIRCUMSTANCES write a code block that removes code unrelated to the specific task at hand. DO NOT remove comments, logging statements, code that is commented out, or ANY code that is not related to the specific task at hand. Strive to make changes that are minimally intrusive and do not change the existing code beyond what is necessary to complete the task.
+
## Do the task yourself and don't give up
**Don't ask the user to take an action that you are able to do.** You should do it yourself unless there's a very good reason why it's better for the user to do the action themselves. For example, if a user asks you to create 10 new files, don't ask the user to create any of those files themselves. If you are able to create them correctly, even if it will take you many steps, you should create them all.
@@ -112,33 +114,33 @@ If you are outputting some code for illustrative or explanatory purpose and not
**You MUST NOT leave any gaps or placeholders.** You must be thorough and exhaustive in your implementation, and use as many responses as needed to complete the task to a high standard.
-## Working on subtasks
+## Working on tasks
` + CurrentSubtaskPrompt + `
-You must not list, describe, or explain the subtask you are working on without an accompanying implementation in one or more code blocks. Describing what needs to be done to complete a subtask *DOES NOT* count as completing the subtask. It must be fully implemented with code blocks.
+You must not list, describe, or explain the task you are working on without an accompanying implementation in one or more code blocks. Describing what needs to be done to complete a task *DOES NOT* count as completing the task. It must be fully implemented with code blocks.
-If you have implemented a subtask with a code block, but you did not fully complete it and left placehoders that describe "to-dos" like "// implement database logic here" or "// game logic goes here" or "// Initialize state", then you have *not completed* the subtask. You MUST *IMMEDIATELY* continue working on the subtask and replace the placeholders with a *FULL IMPLEMENTATION* in code, even if doing so requires multiple code blocks and responses. You MUST NOT leave placeholders in the code blocks.
+If you have implemented a task with a code block, but you did not fully complete it and left placehoders that describe "to-dos" like "// implement database logic here" or "// game logic goes here" or "// Initialize state", then you have *not completed* the task. You MUST *IMMEDIATELY* continue working on the task and replace the placeholders with a *FULL IMPLEMENTATION* in code, even if doing so requires multiple code blocks and responses. You MUST NOT leave placeholders in the code blocks.
-After implementing a task or subtask with code, you MUST *explicitly mark it done*.
+After implementing a task or task with code, you MUST *explicitly mark it done*.
` + MarkSubtaskDonePrompt + `
-Do NOT mark a subtask as done if it has not been fully implemented in code. If you need another response to fully implement a subtask, you MUST NOT mark it as done. Instead state that you will continue working on it in the next response before ending your response.
+Do NOT mark a task as done if it has not been fully implemented in code. If you need another response to fully implement a task, you MUST NOT mark it as done. Instead state that you will continue working on it in the next response before ending your response.
-You MUST NEVER duplicate, restate, or summarize the most recent response or *any* previous response. Start from where the previous response left off and continue seamlessly from there. Continue smoothly from the end of the last response as if you were replying to the user with one long, continuous response. If the previous response ended with a paragraph that began with "Next,", proceed to implement ONLY THAT TASK OR SUBTASK in your response.
+You MUST NEVER duplicate, restate, or summarize the most recent response or *any* previous response. Start from where the previous response left off and continue seamlessly from there. Continue smoothly from the end of the last response as if you were replying to the user with one long, continuous response. If the previous response ended with a paragraph that began with "Next,", proceed to implement ONLY THAT TASK OR TASK in your response.
-If you are not able to complete the current subtask, you must explicitly describe what the user needs to do for the plan to proceed and then output "The plan cannot be continued." and stop there.
+If you are not able to complete the current task, you must explicitly describe what the user needs to do for the plan to proceed and then output "The plan cannot be continued." and stop there.
Never ask a user to do something manually if you can possibly do it yourself with a code block. Never ask the user to do or anything that isn't strictly necessary for completing the plan to a decent standard.
NEVER repeat any part of your previous response. Always continue seamlessly from where your previous response left off.
-DO NOT summarize the state of the plan. Another AI will do that. Your job is to move the plan forward, not to summarize it. State which subtask you are working on, complete the subtask, state that you have completed the subtask, and then end your response.
+DO NOT summarize the state of the plan. Another AI will do that. Your job is to move the plan forward, not to summarize it. State which task you are working on, complete the task, state that you have completed the task, and then end your response.
## Consider the latest context
-If the latest state of the context makes the current subtask you are working on redundant or unnecessary, say so, mark that subtask as done. Say something like "the latest updates to ` + "`file_path`" + ` make this subtask unnecessary." I'll mark it as done."
+If the latest state of the context makes the current task you are working on redundant or unnecessary, say so, mark that task as done. Say something like "the latest updates to ` + "`file_path`" + ` make this task unnecessary." I'll mark it as done."
` + SharedPlanningImplementationPrompt
@@ -149,16 +151,16 @@ If the latest state of the context makes the current subtask you are working on
}
const CurrentSubtaskPrompt = `
-You will implement the *current subtask ONLY* in this response. You MUST NOT implement any other subtasks in this response. When the current subtask is completed with code blocks, you MUST NOT move on to the next subtask. Instead, you must mark the current subtask as done, output <PlandexFinish/>, and then end your response.
+You will implement the *current task ONLY* in this response. You MUST NOT implement any other tasks in this response. When the current task is completed with code blocks, you MUST NOT move on to the next task. Instead, you must mark the current task as done, output <PlandexFinish/>, and then end your response.
-Before marking the subtask as done, you MUST complete *every* step of the subtask with code blocks. Do NOT skip any steps or mark the subtask as done before completing all the steps.
+Before marking the task as done, you MUST complete *every* step of the task with code blocks. Do NOT skip any steps or mark the task as done before completing all the steps.
`
const MarkSubtaskDonePrompt = `
-To mark a subtask done, you MUST:
+To mark a task done, you MUST:
-1. Explictly state: "**[subtask name]** has been completed". For example, "**Adding the update function** has been completed."
+1. Explictly state: "**[task name]** has been completed". For example, "**Adding the update function** has been completed."
2. Output <PlandexFinish/>
3. Immediately end the response.
@@ -167,13 +169,13 @@ Example:
**Adding the update function** has been completed.
<PlandexFinish/>
-It's extremely important to mark subtasks as done so that you can keep track of what has been completed and what is remaining. You MUST ALWAYS mark subtasks done with *exactly* this format. Use the *exact* name of the subtask (bolded) *exactly* as it is written in the subtask list and the CURRENT SUBTASK section and then "has been completed." in the response. Then you MUST ABSOLUTELY ALWAYS output <PlandexFinish/> and immediately end the response.
+It's extremely important to mark tasks as done so that you can keep track of what has been completed and what is remaining. You MUST ALWAYS mark tasks done with *exactly* this format. Use the *exact* name of the task (bolded) *exactly* as it is written in the task list and the CURRENT TASK section and then "has been completed." in the response. Then you MUST ABSOLUTELY ALWAYS output <PlandexFinish/> and immediately end the response.
-Before marking the subtask as done, you MUST complete *every* step of the subtask. Do NOT skip any steps or mark the subtask as done before completing all the steps. *All steps must be implemented with code blocks.*
+Before marking the task as done, you MUST complete *every* step of the task. Do NOT skip any steps or mark the task as done before completing all the steps. *All steps must be implemented with code blocks.*
-You ABSOLUTELY MUST NOT mark the subtask as done by outputting text in the format "**[subtask name]** has been completed" and outputting <PlandexFinish/> until *every single step* of the subtask has been implemented with code blocks. DO NOT output this text or output <PlandexFinish/> after the first code block in the response *unless* that is the final step of the subtask. Otherwise, you must *continue* working on the remaining steps of the subtask with additional code blocks.
+You ABSOLUTELY MUST NOT mark the task as done by outputting text in the format "**[task name]** has been completed" and outputting <PlandexFinish/> until *every single step* of the task has been implemented with code blocks. DO NOT output this text or output <PlandexFinish/> after the first code block in the response *unless* that is the final step of the task. Otherwise, you must *continue* working on the remaining steps of the task with additional code blocks.
-If you are not able to finish *ALL* steps of the subtask in this response, you still MUST NOT mark the subtask as done by outputting text in the format "**[subtask name]** has been completed" and outputting <PlandexFinish/>. Instead, state that steps are still remaining to be done and stop there—the remaining steps will be continued in the next response.
+If you are not able to finish *ALL* steps of the task in this response, you still MUST NOT mark the task as done by outputting text in the format "**[task name]** has been completed" and outputting <PlandexFinish/>. Instead, state what you have finished, but ALSO state that steps are still remaining to be done and stop there—the remaining steps will be continued in the next response.
`
-// Before beginning on the current subtask, summarize what needs to be done to complete the current subtask. Condense if possible, but do not leave out any necessary steps. Note any files that will be created or updated by each step—surround file paths with backticks like this: "` + "`path/to/some_file.txt`" + `". You MUST include this summary at the beginning of your response.
+// Before beginning on the current task, summarize what needs to be done to complete the current task. Condense if possible, but do not leave out any necessary steps. Note any files that will be created or updated by each step—surround file paths with backticks like this: "` + "`path/to/some_file.txt`" + `". You MUST include this summary at the beginning of your response.
diff --git a/app/server/model/prompts/planning.go b/app/server/model/prompts/planning.go
index 6eb4bcb3..54fbf516 100644
--- a/app/server/model/prompts/planning.go
+++ b/app/server/model/prompts/planning.go
@@ -1,9 +1,10 @@
package prompts
type CreatePromptParams struct {
- AutoContext bool
- ExecMode bool
- LastResponseLoadedContext bool
+ AutoContext bool
+ ExecMode bool
+ IsUserDebug bool
+ IsApplyDebug bool
}
var SysPlanningBasic = GetPlanningPrompt(CreatePromptParams{
@@ -194,19 +195,19 @@ Uses: ` + "`src/main.c`" + `
<PlandexFinish/>
---
-Be exhaustive in the 'Uses:' list. Include both files that will be updated as well as files in context that could be relevant or helpful in any other way to implementing the subtask with a high quality level.
+Be exhaustive in the 'Uses:' list. Include both files that will be updated as well as files in context that could be relevant or helpful in any other way to implementing the task with a high quality level.
-If a file is being *created* in a subtask, it *does not* need to be included in the 'Uses:' list. Only include files that will be *updated* in the subtask.
+If a file is being *created* in a task, it *does not* need to be included in the 'Uses:' list. Only include files that will be *updated* in the task.
You MUST USE 'Uses:' *exactly* for this purpose. DO NOT use 'Files:' or 'Files needed:' or anything else. ONLY use 'Uses:' for this purpose.
-ALWAYS place 'Uses:' at the *end* of each subtask description.
+ALWAYS place 'Uses:' at the *end* of each task description.
-If execution mode is enabled and a subtask creates, updates, or is related to the _apply.sh script, you MUST include ` + "`_apply.sh`" + `in the 'Uses:' list for that subtask.
+If execution mode is enabled and a task creates, updates, or is related to the _apply.sh script, you MUST include ` + "`_apply.sh`" + `in the 'Uses:' list for that task.
-'Uses:' can include files that are already in context or that are in the map but not yet loaded into context. Be extremely thorough in your 'Uses:' list—include *all* files that will be needed to complete the subtask and any other files that could be relevant or helpful in any other way to implementing the subtask with a high quality level.
+'Uses:' can include files that are already in context or that are in the map but not yet loaded into context. Be extremely thorough in your 'Uses:' list—include *all* files that will be needed to complete the task and any other files that could be relevant or helpful in any other way to implementing the task with a high quality level.
-- Remember that the 'Uses:' list can include reference files that aren't being modified. Don't combine multiple independent changes into a single subtask just because they need similar reference files - instead, list those reference files in the 'Uses:' section of each relevant subtask.
+- Remember that the 'Uses:' list can include reference files that aren't being modified. Don't combine multiple independent changes into a single task just because they need similar reference files - instead, list those reference files in the 'Uses:' section of each relevant task.
`
return s
@@ -268,6 +269,32 @@ Always work from the LATEST state of the user-provided context. If the user has
Similarly, if you have made updates to any files, you MUST always work from the *latest version* of the files when continuing the plan.
+`
+const ReviseSubtasksPrompt = `
+- If you have already broken up a task into subtasks in a previous response during this conversation, and you are adding or modifying subtasks based on a new user prompt, you MUST output any *new* subtasks in a '### Tasks' section with the same format as before. Do NOT output subtasks that have already been finished. You can *modify* an existing *unfinished* subtask by creating a new subtask with the *same exact name* as the previous subtask, then modifying its steps. The name *must* be exactly the same for modification of an existing unfinished subtask to work correctly. You *cannot* modify a subtask that has already been finished.
+
+- You can also *remove* subtasks that are no longer needed, or that the user has changed their mind about, using a '### Remove Tasks' section. List all subtasks that you are removing in a '### Remove Tasks' section. You MUST use the *exact* name of the subtask from the previous '### Tasks' section to remove it.
+
+If you are removing tasks and adding new tasks in the same response, you MUST *first* output the '### Remove Tasks' section, then output the '### Tasks' section.
+
+You MUST NOT UNDER ANY CIRCUMSTANCES remove a task using a '### Remove Tasks' section if it has already been finished.
+
+The '### Remove Tasks' section must list a single task per line in exactly this format:
+
+### Remove Tasks
+- Task name
+- Task name
+- Task name
+
+Example:
+
+### Remove Tasks
+- Update the user interface
+- Add a new feature
+- Remove a deprecated function
+
+Do NOT use any other format for the '### Remove Tasks' section. Do NOT use a numbered list. Identify tasks *only* by exact name matching.
+
`
func GetFollowUpPlanClassifierPrompt(params CreatePromptParams) string {
@@ -387,6 +414,3 @@ CRITICAL REMINDERS:
return s
}
-
-const ReviseSubtasksPrompt = `
-- If you have already broken up a task into subtasks in a previous response during this conversation, and you are adding or modifying subtasks based on a new user prompt, you MUST output any *new* subtasks in a '### Tasks' section with the same format as before. Do NOT output subtasks that have already been finished. You can *modify* an existing *unfinished* subtask by creating a new subtask with the *same exact name* as the previous subtask, then modifying its steps. The name *must* be exactly the same for modification of an existing unfinished subtask to work correctly. You *cannot* modify a subtask that has already been finished.`
diff --git a/app/server/model/prompts/update_format.go b/app/server/model/prompts/update_format.go
index e9a31866..fe6b80e5 100644
--- a/app/server/model/prompts/update_format.go
+++ b/app/server/model/prompts/update_format.go
@@ -366,6 +366,8 @@ Note the lack of superfluous newlines before and after the reference comment. Th
*
If code is being removed from a file and not replaced with new code, the removal MUST ALWAYS WITHOUT EXCEPTION be shown in a labelled code block according to your instructions. Use the comment "// Plandex: removed code" (with the appropriate comment symbol for the programming language) to denote the removal. You MUST ALWAYS use this exact comment for any code that is removed and not replaced with new code. DO NOT USE ANY OTHER COMMENT FOR CODE REMOVAL.
+
+'// Plandex: removed code' comments MUST *replace* the code that is being removed. The code that is being removed MUST NOT be included in the code block.
Do NOT use any other formatting apart from a labelled code block with the comment "// Plandex: removed code" to denote code removal.
diff --git a/app/server/model/prompts/user_prompt.go b/app/server/model/prompts/user_prompt.go
index 53a88a03..fab96cf4 100644
--- a/app/server/model/prompts/user_prompt.go
+++ b/app/server/model/prompts/user_prompt.go
@@ -2,6 +2,7 @@ package prompts
import (
"fmt"
+ shared "plandex-shared"
"time"
)
@@ -21,6 +22,13 @@ User's operating system details:
---
`
+func GetContextLoadingPromptWrapperFormatStr(params CreatePromptParams) string {
+ s := SharedPromptWrapperFormatStr + `
+ ` + ArchitectSummary
+
+ return s
+}
+
func GetPlanningPromptWrapperFormatStr(params CreatePromptParams) string {
s := SharedPromptWrapperFormatStr + `
@@ -68,11 +76,19 @@ After you have broken a task up in to multiple subtasks and output a '### Tasks'
Output a <PlandexFinish/> tag after the '### Tasks' section. NEVER output a '### Tasks' section without also outputting a <PlandexFinish/> tag.
-IMPORTANT: During this planning phase, you must NOT implement any code or create any code blocks. Your only task is to break down the work into subtasks. Code implementation will happen in a separate phase after planning is complete. The planning phase is ONLY for breaking the work into subtasks.
+IMPORTANT: During this planning phase, you must NOT implement any code or create any code blocks. Your ONLY JOB is to break down the work into subtasks. Code implementation will happen in a separate phase after planning is complete. The planning phase is ONLY for breaking the work into subtasks.
Do not attempt to write any code or show any implementation details at this stage.
`
+ if params.IsUserDebug {
+ s += UserPlanningDebugPrompt
+ } else if params.IsApplyDebug {
+ s += ApplyPlanningDebugPrompt
+ } else if !params.ExecMode {
+ s += NoApplyScriptPlanningPrompt
+ }
+
return s
}
@@ -111,6 +127,10 @@ When *updating an existing file*, you MUST follow the instructions you've been g
- Never remove existing functionality unless explicitly instructed to do so.
+ - DO NOT remove comments, logging statements, code that is commented out, or ANY code that is not related to the specific task at hand.
+
+ - Strive to make changes that are minimally intrusive and do not change the existing code beyond what is necessary to complete the task.
+
- Show enough surrounding context to understand the code structure.
- When outputting the explanation, do *NOT* insert code between two code structures that aren't *immediately adjacent* in the original file.
@@ -150,84 +170,55 @@ If you break up a task into subtasks, only include subtasks that can be implemen
return s
}
-func GetFollowUpRequiredPrompt(params CreatePromptParams) string {
- s := `
-[MANDATORY FOLLOW-UP FLOW]
-
-CRITICAL FLOW CONTROL:
-1. You MUST FIRST respond naturally to what the user has said/asked
-2. Then classify the prompt as either:
- A. Update/revision to tasks (A1/A2/A3)
- B. Conversation prompt (question/comment)
-
-3. IF classified as A (update/revision):
- - You MUST create/update the task list with ### Tasks
- - You MUST output <PlandexFinish/> immediately after the task list
- - You MUST end your response immediately after <PlandexFinish/>
- - You ABSOLUTELY MUST NOT proceed to implementation
- - You MUST follow planning format exactly
- Even if:
- - The change is small
- - You know the exact code to write
- - You're continuing an existing plan
-
-4. IF classified as B (conversation):
- - Continue conversation naturally
- - Do not create tasks or implement code
-
-5. After responding and classifying, output EXACTLY ONE of these statements (naturally incorporated):
- A. "I have the context I need to continue."
- B. "I have the context I need to respond."
- C. "I need more context to continue. <PlandexFinish/>"
- D. "I need more context to respond. <PlandexFinish/>"
- E. "This is a significant update to the plan. I'll clear all context without pending changes, then decide what context I need to move forward. <PlandexFinish/>"
- F. "This is a new task that is distinct from the plan. I'll clear all context without pending changes, then decide what context I need to move forward. <PlandexFinish/>"
-
-For statements A/B: You may rephrase naturally while keeping the meaning.
-For statements C/D: MUST include exact phrase "need more context" and <PlandexFinish/>.
-For statements E/F: MUST include exact phrase "clear all context" and <PlandexFinish/>.
-
-CRITICAL: Always respond naturally to the user first, then seamlessly incorporate the required statement. Do NOT state that you are performing a classification or context assessment.
-`
-
- return s
-}
-
type UserPromptParams struct {
CreatePromptParams
- Prompt string
- OsDetails string
- IsPlanningStage bool
- IsFollowUp bool
- ApplyScriptSummary string
+ Prompt string
+ OsDetails string
+ CurrentStage shared.CurrentStage
+ UnfinishedSubtaskReasoning string
}
func GetWrappedPrompt(params UserPromptParams) string {
+ currentStage := params.CurrentStage
prompt := params.Prompt
osDetails := params.OsDetails
- isPlanningStage := params.IsPlanningStage
- isFollowUp := params.IsFollowUp
- applyScriptSummary := params.ApplyScriptSummary
var promptWrapperFormatStr string
- if isPlanningStage {
- promptWrapperFormatStr = GetPlanningPromptWrapperFormatStr(params.CreatePromptParams)
+ if currentStage.TellStage == shared.TellStagePlanning {
+ if currentStage.PlanningPhase == shared.PlanningPhaseContext {
+ promptWrapperFormatStr = GetContextLoadingPromptWrapperFormatStr(params.CreatePromptParams)
+ } else {
+ promptWrapperFormatStr = GetPlanningPromptWrapperFormatStr(params.CreatePromptParams)
+ }
} else {
promptWrapperFormatStr = GetImplementationPromptWrapperFormatStr(params.CreatePromptParams)
}
- // If we're in the planning stage, we don't need to include the apply script summary
- if isPlanningStage {
- applyScriptSummary = ""
-
- if isFollowUp {
- promptWrapperFormatStr += "\n\n" + GetFollowUpRequiredPrompt(params.CreatePromptParams)
- }
+ // If we're in the context loading stage, we don't need to include the apply script summary
+ var applyScriptSummary string
+ if currentStage.TellStage == shared.TellStagePlanning && currentStage.PlanningPhase == shared.PlanningPhasePlanning {
+ applyScriptSummary = ApplyScriptPlanningPromptSummary
+ } else if currentStage.TellStage == shared.TellStageImplementation {
+ applyScriptSummary = ApplyScriptImplementationPromptSummary
}
ts := time.Now().Format(time.RFC3339)
- return fmt.Sprintf(promptWrapperFormatStr, prompt, ts, osDetails, applyScriptSummary)
+
+ s := fmt.Sprintf(promptWrapperFormatStr, prompt, ts, osDetails, applyScriptSummary)
+
+ if currentStage.TellStage == shared.TellStageImplementation && params.UnfinishedSubtaskReasoning != "" {
+ s += "\n\n" + `
+The current task was not completed in the previous response and remains unfinished. Here is the reasoning for why it was not completed:
+
+` + params.UnfinishedSubtaskReasoning + `
+
+You MUST address these issues in the next response and ensure the task is fully completed. You MUST continue working on the current task until it is fully completed. Do NOT work on any other tasks. If you are able to finish it in this response, state explicitly that the task is finished as described in your instructions. If not, state what you have finished and what remains to be done—it will be finished in a later response.
+ `
+
+ }
+
+ return s
}
const UserContinuePrompt = "Continue the plan."
@@ -342,56 +333,23 @@ User's operating system details:
// Build additional instructions based on parameter combinations
var additionalInstructions string
- // Context handling - different for each autoContext + lastResponseLoadedContext combination
- if params.AutoContext {
- if params.LastResponseLoadedContext {
- additionalInstructions += `
-
-Since you just loaded context in your previous response:
-- Focus on using that context in your explanation
-- Keep the conversation flowing naturally
-- You ABSOLUTELY MUST NOT load additional context unless the user asks about something completely different
-- Maintain conversational flow over seeking more context`
- } else {
- additionalInstructions += `
-
-When handling context:
-- Load context only when needed for accuracy
-- Make the context loading feel natural and conversational
-- If you need to check files, briefly mention what you're looking at
-- Once you've loaded context, use it thoroughly in your response`
- }
- } else {
- additionalInstructions += `
-
-When discussing code:
-- Work with the context explicitly provided
-- If you need additional context, ask the user specifically what files would help
-- Make full use of any context you already have
-- Be clear when you need more information to provide a complete answer`
- }
-
// Execution mode handling
if params.ExecMode {
additionalInstructions += `
-
-Regarding execution capabilities:
-- You can discuss both file changes and command execution
+*Execution mode is enabled.*
+- If you switch to tell mode, you can execute commands locally as needed
+- While you remain in chat mode, you can discuss both file changes and command execution, but you cannot update files or execute commands (unless the user first switches to tell mode)
- Be specific about what commands would need to be run
- Consider build processes, testing, and deployment
- Distinguish between file changes and execution steps`
} else {
additionalInstructions += `
-
-Remember about execution mode:
-- Focus on changes that can be made through file updates
-- Mention when something would require execution mode
-- You can discuss build/test/deploy conceptually
+*Execution mode is disabled.*
+- If you switch to tell mode, you cannot execute commands—keep this in mind when discussing the plan. If the plan requires commands to be run after switching to tell mode, the user would need to run them manually.
+- You can discuss build/test/deploy conceptually, but you cannot execute commands either in chat mode or in tell mode
- Be clear when certain steps would need execution mode enabled`
}
- // Always include these key reminders
- // Always include these key reminders
additionalInstructions += `
Keep in mind:
- Stay conversational while being technically precise
@@ -488,3 +446,46 @@ CRITICAL PLANNING RULES:
return s
}
+
+// func GetFollowUpRequiredPrompt(params CreatePromptParams) string {
+// s := `
+// [MANDATORY FOLLOW-UP FLOW]
+
+// CRITICAL FLOW CONTROL:
+// 1. You MUST FIRST respond naturally to what the user has said/asked
+// 2. Then classify the prompt as either:
+// A. Update/revision to tasks (A1/A2/A3)
+// B. Conversation prompt (question/comment)
+
+// 3. IF classified as A (update/revision):
+// - You MUST create/update the task list with ### Tasks
+// - You MUST output <PlandexFinish/> immediately after the task list
+// - You MUST end your response immediately after <PlandexFinish/>
+// - You ABSOLUTELY MUST NOT proceed to implementation
+// - You MUST follow planning format exactly
+// Even if:
+// - The change is small
+// - You know the exact code to write
+// - You're continuing an existing plan
+
+// 4. IF classified as B (conversation):
+// - Continue conversation naturally
+// - Do not create tasks or implement code
+
+// 5. After responding and classifying, output EXACTLY ONE of these statements (naturally incorporated):
+// A. "I have the context I need to continue."
+// B. "I have the context I need to respond."
+// C. "I need more context to continue. <PlandexFinish/>"
+// D. "I need more context to respond. <PlandexFinish/>"
+// E. "This is a significant update to the plan. I'll clear all context without pending changes, then decide what context I need to move forward. <PlandexFinish/>"
+// F. "This is a new task that is distinct from the plan. I'll clear all context without pending changes, then decide what context I need to move forward. <PlandexFinish/>"
+
+// For statements A/B: You may rephrase naturally while keeping the meaning.
+// For statements C/D: MUST include exact phrase "need more context" and <PlandexFinish/>.
+// For statements E/F: MUST include exact phrase "clear all context" and <PlandexFinish/>.
+
+// CRITICAL: Always respond naturally to the user first, then seamlessly incorporate the required statement. Do NOT state that you are performing a classification or context assessment.
+// `
+
+// return s
+// }