Skip to content

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

some refactoring/cleaning up of tell_exec. only autoload context for paths that aren't in context already. end planner message after tasks section. few other little fixes.

Dane Schneiderafc188c38b06
diff --git a/app/cli/cmd/plan_exec_helpers.go b/app/cli/cmd/plan_exec_helpers.go
index 834e68c9..7eef0da1 100644
--- a/app/cli/cmd/plan_exec_helpers.go
+++ b/app/cli/cmd/plan_exec_helpers.go
@@ -101,26 +101,23 @@ func initExecFlags(cmd *cobra.Command, params initExecFlagsParams) {
func validatePlanExecFlags() {
if tellAutoApply && tellNoBuild {
- term.OutputErrorAndExit("🚨 --apply can't be used with --no-build/-n")
+ term.OutputErrorAndExit("--apply can't be used with --no-build/-n")
}
if tellAutoApply && tellBg {
- term.OutputErrorAndExit("🚨 --apply can't be used with --bg")
- }
- if autoCommit && !tellAutoApply {
- term.OutputErrorAndExit("🚨 --commit/-c can only be used with --apply")
+ term.OutputErrorAndExit("--apply can't be used with --bg")
}
if autoExec && !tellAutoApply {
- term.OutputErrorAndExit("🚨 --auto-exec can only be used with --apply")
+ term.OutputErrorAndExit("--auto-exec can only be used with --apply")
}
if autoDebug > 0 && !tellAutoApply {
- term.OutputErrorAndExit("🚨 --debug can only be used with --apply")
+ term.OutputErrorAndExit("--debug can only be used with --apply")
}
if autoDebug > 0 && noExec {
- term.OutputErrorAndExit("🚨 --debug can't be used with --no-exec")
+ term.OutputErrorAndExit("--debug can't be used with --no-exec")
}
if tellAutoContext && tellBg {
- term.OutputErrorAndExit("🚨 --auto-context/-c can't be used with --bg")
+ term.OutputErrorAndExit("--auto-context/-c can't be used with --bg")
}
}
diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.go
index 272a5563..24841f19 100644
--- a/app/server/db/context_helpers.go
+++ b/app/server/db/context_helpers.go
@@ -756,6 +756,16 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,
// log.Println("Updating map context", id, "oldNumTokens", oldNumTokens)
for path, part := range params.MapBodies {
+ if context.MapParts == nil {
+ context.MapParts = make(shared.FileMapBodies)
+ }
+ if context.MapShas == nil {
+ context.MapShas = make(map[string]string)
+ }
+ if context.MapTokens == nil {
+ context.MapTokens = make(map[string]int)
+ }
+
context.MapParts[path] = part
context.MapShas[path] = params.InputShas[path]
diff --git a/app/server/model/plan/tell_build_pending.go b/app/server/model/plan/tell_build_pending.go
new file mode 100644
index 00000000..629397e1
--- /dev/null
+++ b/app/server/model/plan/tell_build_pending.go
@@ -0,0 +1,60 @@
+package plan
+
+import (
+ "log"
+ "net/http"
+
+ "github.com/plandex/plandex/shared"
+)
+
+func (state *activeTellStreamState) queuePendingBuilds() {
+ plan := state.plan
+ planId := plan.Id
+ branch := state.branch
+ auth := state.auth
+ clients := state.clients
+ currentOrgId := state.currentOrgId
+ currentUserId := state.currentUserId
+ active := GetActivePlan(planId, branch)
+
+ if active == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", planId, branch)
+ return
+ }
+
+ pendingBuildsByPath, err := active.PendingBuildsByPath(auth.OrgId, auth.User.Id, state.convo)
+
+ if err != nil {
+ log.Printf("Error getting pending builds by path: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error getting pending builds by path",
+ }
+ return
+ }
+
+ if len(pendingBuildsByPath) == 0 {
+ log.Println("Tell plan: no pending builds")
+ return
+ }
+
+ log.Printf("Tell plan: found %d pending builds\n", len(pendingBuildsByPath))
+ // spew.Dump(pendingBuildsByPath)
+
+ buildState := &activeBuildStreamState{
+ tellState: state,
+ clients: clients,
+ auth: auth,
+ currentOrgId: currentOrgId,
+ currentUserId: currentUserId,
+ plan: plan,
+ branch: branch,
+ settings: state.settings,
+ modelContext: state.modelContext,
+ }
+
+ for _, pendingBuilds := range pendingBuildsByPath {
+ buildState.queueBuilds(pendingBuilds)
+ }
+}
diff --git a/app/server/model/plan/tell_context.go b/app/server/model/plan/tell_context.go
index 8f6eece4..fed900bd 100644
--- a/app/server/model/plan/tell_context.go
+++ b/app/server/model/plan/tell_context.go
@@ -2,9 +2,12 @@ package plan
import (
"fmt"
+ "log"
+ "net/http"
"strings"
"github.com/plandex/plandex/shared"
+ "github.com/sashabaranov/go-openai"
)
func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees, isImplementationStage, smartContextEnabled, execEnabled bool) (string, int, error) {
@@ -131,9 +134,12 @@ func (state *activeTellStreamState) checkAutoLoadContext() []string {
activePlan := GetActivePlan(state.plan.Id, state.branch)
if activePlan == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", state.plan.Id, state.branch)
return nil
}
+ contextsByPath := activePlan.ContextsByPath
+
if !activePlan.AutoContext {
return nil
}
@@ -169,7 +175,7 @@ func (state *activeTellStreamState) checkAutoLoadContext() []string {
trimmed = strings.ReplaceAll(trimmed, "`", "")
trimmed = strings.TrimSpace(trimmed)
- if req.ProjectPaths[trimmed] {
+ if req.ProjectPaths[trimmed] && contextsByPath[trimmed] == nil {
files = append(files, trimmed)
}
}
@@ -177,3 +183,47 @@ func (state *activeTellStreamState) checkAutoLoadContext() []string {
return files
}
+
+func (state *activeTellStreamState) addImageContext() bool {
+ active := GetActivePlan(state.plan.Id, state.branch)
+
+ if active == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", state.plan.Id, state.branch)
+ return false
+ }
+
+ for _, context := range state.modelContext {
+ if context.ContextType == shared.ContextImageType {
+ if !state.settings.ModelPack.Planner.BaseModelConfig.HasImageSupport {
+ err := fmt.Errorf("%s does not support images in context", state.settings.ModelPack.Planner.BaseModelConfig.ModelName)
+ log.Println(err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusBadRequest,
+ Msg: "Model does not support images in context",
+ }
+ return false
+ }
+
+ imageMessage := openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleUser,
+ MultiContent: []openai.ChatMessagePart{
+ {
+ Type: openai.ChatMessagePartTypeText,
+ Text: fmt.Sprintf("Image: %s", context.Name),
+ },
+ {
+ Type: openai.ChatMessagePartTypeImageURL,
+ ImageURL: &openai.ChatMessageImageURL{
+ URL: shared.GetImageDataURI(context.Body, context.FilePath),
+ Detail: context.ImageDetail,
+ },
+ },
+ },
+ }
+ state.messages = append(state.messages, imageMessage)
+ }
+ }
+
+ return true
+}
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index 54982357..136d3410 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -123,50 +123,15 @@ func execTellPlan(
}
log.Println("execTellPlan - Tell plan loaded")
- if iteration == 0 && missingFileResponse == "" {
- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
- ap.Contexts = state.modelContext
-
- for _, context := range state.modelContext {
- if context.FilePath != "" {
- ap.ContextsByPath[context.FilePath] = context
- }
- }
- })
- } else if missingFileResponse == "" {
- // reset current reply content and num tokens
- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
- ap.CurrentReplyContent = ""
- ap.NumTokens = 0
- })
- }
-
- // if any skipped paths have since been added to context, remove them from skipped paths
- if len(active.SkippedPaths) > 0 {
- var toUnskipPaths []string
- for contextPath := range active.ContextsByPath {
- if active.SkippedPaths[contextPath] {
- toUnskipPaths = append(toUnskipPaths, contextPath)
- }
- }
- if len(toUnskipPaths) > 0 {
- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
- for _, path := range toUnskipPaths {
- delete(ap.SkippedPaths, path)
- }
- })
- }
- }
-
autoContextEnabled := req.AutoContext && state.hasContextMap
smartContextEnabled := req.AutoContext
isPlanningStage := req.IsChatOnly || (!req.IsUserContinue && (iteration == 0 || (autoContextEnabled && iteration == 1)))
isImplementationStage := !isPlanningStage
- isContextStage := isPlanningStage && state.hasContextMap && !state.contextMapEmpty && iteration == 0
+ isContextStage := isPlanningStage && autoContextEnabled && !state.contextMapEmpty && iteration == 0
log.Printf("isPlanningStage: %t, isImplementationStage: %t, isContextStage: %t\n", isPlanningStage, isImplementationStage, isContextStage)
- // if auto context is enabled, we only include maps and trees on the first iteration, which is the context-gathering step, and the second iteration, which is the planning step
+ // 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
)
@@ -187,89 +152,9 @@ func execTellPlan(
return
}
- var sysCreate string
-
- var sysCreateTokens int
-
- if isPlanningStage {
- log.Println("isPlanningStage")
- if autoContextEnabled && isContextStage {
- sysCreate = prompts.AutoContextPreamble
- sysCreateTokens = prompts.AutoContextPreambleNumTokens
- } else if autoContextEnabled || smartContextEnabled {
- sysCreate = prompts.SysPlanningAutoContext
- sysCreateTokens = prompts.SysPlanningAutoContextTokens
- } else {
- sysCreate = prompts.SysPlanningBasic
- sysCreateTokens = prompts.SysPlanningBasicTokens
- }
- } else {
- log.Println("isImplementationStage")
- if state.currentSubtask == nil {
- err = fmt.Errorf("no current subtask")
- log.Println(err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "No current subtask",
- }
- return
- }
- sysCreate = prompts.GetImplementationPrompt(state.currentSubtask.Title)
- }
-
- if !isContextStage {
- if req.ExecEnabled {
- sysCreate += prompts.ApplyScriptPrompt
- sysCreateTokens += prompts.ApplyScriptPromptNumTokens
- } else {
- sysCreate += prompts.NoApplyScriptPrompt
- sysCreateTokens += prompts.NoApplyScriptPromptNumTokens
- }
- }
-
- // log.Println("sysCreate before context:\n", sysCreate)
-
- sysCreate += modelContextText
-
- if len(active.SkippedPaths) > 0 {
- skippedPrompt := prompts.SkippedPathsPrompt
- for skippedPath := range active.SkippedPaths {
- skippedPrompt += fmt.Sprintf("- %s\n", skippedPath)
- }
-
- numTokens, err := shared.GetNumTokens(skippedPrompt)
- if err != nil {
- log.Printf("Error getting num tokens for skipped paths: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for skipped paths",
- }
- return
- }
-
- sysCreateTokens += numTokens
- }
-
- if len(state.subtasks) > 0 {
- subtasksPrompt, subtaskTokens, err := state.formatSubtasks()
-
- if err != nil {
- err = fmt.Errorf("error formatting subtasks: %v", err)
- log.Println(err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error formatting subtasks",
- }
- return
- }
-
- log.Println("subtasksPrompt:\n", subtasksPrompt)
-
- sysCreate += subtasksPrompt
- sysCreateTokens += subtaskTokens
+ ok, sysPrompt, sysPromptTokens := state.getTellSysPrompt(isPlanningStage, isContextStage, autoContextEnabled, smartContextEnabled, modelContextText)
+ if !ok {
+ return
}
// log.Println("**sysCreate:**\n", sysCreate)
@@ -277,42 +162,13 @@ func execTellPlan(
state.messages = []openai.ChatCompletionMessage{
{
Role: openai.ChatMessageRoleSystem,
- Content: sysCreate,
+ Content: sysPrompt,
},
}
// Add a separate message for image contexts
- for _, context := range state.modelContext {
- if context.ContextType == shared.ContextImageType {
- if !state.settings.ModelPack.Planner.BaseModelConfig.HasImageSupport {
- err = fmt.Errorf("%s does not support images in context", state.settings.ModelPack.Planner.BaseModelConfig.ModelName)
- log.Println(err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusBadRequest,
- Msg: "Model does not support images in context",
- }
- return
- }
-
- imageMessage := openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- MultiContent: []openai.ChatMessagePart{
- {
- Type: openai.ChatMessagePartTypeText,
- Text: fmt.Sprintf("Image: %s", context.Name),
- },
- {
- Type: openai.ChatMessagePartTypeImageURL,
- ImageURL: &openai.ChatMessageImageURL{
- URL: shared.GetImageDataURI(context.Body, context.FilePath),
- Detail: context.ImageDetail,
- },
- },
- },
- }
- state.messages = append(state.messages, imageMessage)
- }
+ if !state.addImageContext() {
+ return
}
osDetailsTokens, err := shared.GetNumTokens(req.OsDetails)
@@ -323,6 +179,7 @@ func execTellPlan(
Status: http.StatusInternalServerError,
Msg: "Error getting num tokens for os details",
}
+ return
}
var (
@@ -360,10 +217,10 @@ func execTellPlan(
promptTokens += prompts.ApplyScriptSummaryNumTokens
}
- state.tokensBeforeConvo = sysCreateTokens + modelContextTokens + state.latestSummaryTokens + promptTokens
+ state.tokensBeforeConvo = sysPromptTokens + modelContextTokens + state.latestSummaryTokens + promptTokens
// print out breakdown of token usage
- log.Printf("System message tokens: %d\n", sysCreateTokens)
+ log.Printf("System message tokens: %d\n", sysPromptTokens)
log.Printf("Context tokens: %d\n", modelContextTokens)
log.Printf("Prompt tokens: %d\n", promptTokens)
log.Printf("Latest summary tokens: %d\n", state.latestSummaryTokens)
@@ -381,7 +238,7 @@ func execTellPlan(
return
}
- if !state.injectSummariesAsNeeded() {
+ if !state.addConversationMessages() {
return
}
@@ -394,179 +251,11 @@ func execTellPlan(
state.replyParser = types.NewReplyParser()
if missingFileResponse == "" {
- var promptMessage *openai.ChatCompletionMessage
- if req.IsUserContinue {
- if len(state.messages) == 0 {
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeContinueNoMessages,
- Status: http.StatusBadRequest,
- Msg: "No messages yet. Can't continue plan.",
- }
- return
- }
-
- // if the user is continuing the plan, we need to check whether the previous message was a user message or assistant message
- lastMessage := state.messages[len(state.messages)-1]
-
- log.Println("User is continuing plan. Last message role:", lastMessage.Role)
- // log.Println("User is continuing plan. Last message:\n\n", lastMessage.Content)
-
- if lastMessage.Role == openai.ChatMessageRoleUser {
- // if last message was a user message, we want to remove it from the messages array and then use that last message as the prompt so we can continue from where the user left off
-
- log.Println("User is continuing plan. Last message was user message. Using last user message as prompt")
-
- state.messages = state.messages[:len(state.messages)-1]
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompts.GetWrappedPrompt(lastMessage.Content, req.OsDetails, applyScriptSummary, isPlanningStage),
- }
-
- state.userPrompt = lastMessage.Content
- } else {
-
- // if the last message was an assistant message, we'll use the user continue prompt
- log.Println("User is continuing plan. Last message was assistant message. Using user continue prompt")
-
- // otherwise we'll use the continue prompt
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompts.GetWrappedPrompt(prompts.UserContinuePrompt, req.OsDetails, applyScriptSummary, isPlanningStage),
- }
- }
-
- state.messages = append(state.messages, *promptMessage)
- } else {
- var prompt string
- if iteration == 0 {
- if req.IsChatOnly {
- prompt = req.Prompt + prompts.ChatOnlyPrompt
- state.totalRequestTokens += prompts.ChatOnlyPromptTokens
- } else if req.IsUserDebug {
- prompt = req.Prompt + prompts.DebugPrompt
- state.totalRequestTokens += prompts.DebugPromptTokens
- } else if req.IsApplyDebug {
- prompt = req.Prompt + prompts.ApplyDebugPrompt
- state.totalRequestTokens += prompts.ApplyDebugPromptTokens
- } else {
- prompt = req.Prompt
- }
- } else {
- prompt = prompts.AutoContinuePrompt
- }
-
- state.userPrompt = prompt
-
- var finalPrompt string
- if isContextStage {
- finalPrompt = prompt
- } else {
- finalPrompt = prompts.GetWrappedPrompt(prompt, req.OsDetails, applyScriptSummary, isPlanningStage)
- }
-
- promptMessage = &openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: finalPrompt,
- }
- }
-
- state.promptMessage = promptMessage
- state.messages = append(state.messages, *promptMessage)
- } else {
- log.Println("Missing file response:", missingFileResponse, "setting replyParser")
- // log.Printf("Current reply content:\n%s\n", active.CurrentReplyContent)
-
- state.replyParser.AddChunk(active.CurrentReplyContent, true)
- res := state.replyParser.Read()
- currentFile := res.CurrentFilePath
-
- log.Printf("Current file: %s\n", currentFile)
- // log.Println("Current reply content:\n", active.CurrentReplyContent)
-
- replyContent := active.CurrentReplyContent
- numTokens := active.NumTokens
-
- if missingFileResponse == shared.RespondMissingFileChoiceSkip {
- replyBeforeCurrentFile := state.replyParser.GetReplyBeforeCurrentPath()
- numTokens, err = shared.GetNumTokens(replyBeforeCurrentFile)
- if err != nil {
- log.Printf("Error getting num tokens for reply before current file: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for reply before current file",
- }
- return
- }
-
- replyContent = replyBeforeCurrentFile
- state.replyParser = types.NewReplyParser()
- state.replyParser.AddChunk(replyContent, true)
-
- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
- ap.CurrentReplyContent = replyContent
- ap.NumTokens = numTokens
- ap.SkippedPaths[currentFile] = true
- })
-
- } else {
- if missingFileResponse == shared.RespondMissingFileChoiceOverwrite {
- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
- ap.AllowOverwritePaths[currentFile] = true
- })
- }
- }
-
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleAssistant,
- Content: active.CurrentReplyContent,
- })
-
- if missingFileResponse == shared.RespondMissingFileChoiceSkip {
- res := state.replyParser.FinishAndRead()
- skipPrompt := prompts.GetSkipMissingFilePrompt(res.CurrentFilePath)
- prompt := prompts.GetWrappedPrompt(skipPrompt, req.OsDetails, applyScriptSummary, isPlanningStage) + "\n\n" + skipPrompt // repetition of skip prompt to improve instruction following
-
- skipPromptTokens, err := shared.GetNumTokens(skipPrompt)
- if err != nil {
- log.Printf("Error getting num tokens for skip prompt: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for skip prompt",
- }
- return
- }
-
- state.totalRequestTokens += skipPromptTokens
-
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompt,
- })
-
- } else {
- missingPrompt := prompts.GetMissingFileContinueGeneratingPrompt(res.CurrentFilePath)
- prompt := prompts.GetWrappedPrompt(missingPrompt, req.OsDetails, applyScriptSummary, isPlanningStage) + "\n\n" + missingPrompt // repetition of missing prompt to improve instruction following
-
- promptTokens, err = shared.GetNumTokens(prompt)
- if err != nil {
- log.Printf("Error getting num tokens for missing file continue prompt: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting num tokens for missing file continue prompt",
- }
- return
- }
-
- state.totalRequestTokens += promptTokens
-
- state.messages = append(state.messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleUser,
- Content: prompt,
- })
+ if !state.setPromptMessage(isPlanningStage, isContextStage, applyScriptSummary) {
+ return
}
+ } else if !state.handleMissingFileResponse(isPlanningStage, applyScriptSummary) {
+ return
}
log.Printf("\n\nMessages: %d\n", len(state.messages))
@@ -591,6 +280,16 @@ func execTellPlan(
return
}
+ var stop []string
+ if isPlanningStage {
+ stop = []string{"<EndPlandexTasks/>"}
+ } else if isImplementationStage {
+ stop = []string{"<PlandexSubtaskDone/>"}
+ }
+
+ // log.Println("Stop:", stop)
+ // spew.Dump(state.messages)
+
modelReq := openai.ChatCompletionRequest{
Model: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,
Messages: state.messages,
@@ -600,7 +299,7 @@ func execTellPlan(
},
Temperature: state.settings.ModelPack.Planner.Temperature,
TopP: state.settings.ModelPack.Planner.TopP,
- Stop: []string{"<PlandexSubtaskDone/>"},
+ Stop: stop,
}
envVar := state.settings.ModelPack.Planner.BaseModelConfig.ApiKeyEnvVar
@@ -619,43 +318,7 @@ func execTellPlan(
}
if shouldBuildPending {
- go func() {
- pendingBuildsByPath, err := active.PendingBuildsByPath(auth.OrgId, auth.User.Id, state.convo)
-
- if err != nil {
- log.Printf("Error getting pending builds by path: %v\n", err)
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting pending builds by path",
- }
- return
- }
-
- if len(pendingBuildsByPath) == 0 {
- log.Println("Tell plan: no pending builds")
- return
- }
-
- log.Printf("Tell plan: found %d pending builds\n", len(pendingBuildsByPath))
- // spew.Dump(pendingBuildsByPath)
-
- buildState := &activeBuildStreamState{
- tellState: state,
- clients: clients,
- auth: auth,
- currentOrgId: currentOrgId,
- currentUserId: currentUserId,
- plan: plan,
- branch: branch,
- settings: state.settings,
- modelContext: state.modelContext,
- }
-
- for _, pendingBuilds := range pendingBuildsByPath {
- buildState.queueBuilds(pendingBuilds)
- }
- }()
+ go state.queuePendingBuilds()
}
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
diff --git a/app/server/model/plan/tell_load.go b/app/server/model/plan/tell_load.go
index e74b345e..af99710f 100644
--- a/app/server/model/plan/tell_load.go
+++ b/app/server/model/plan/tell_load.go
@@ -59,6 +59,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
errCh := make(chan error)
var modelContext []*db.Context
var convo []*db.ConvoMessage
+ var promptMsg *db.ConvoMessage
var summaries []*db.ConvoSummary
var subtasks []*db.Subtask
var settings *shared.PlanSettings
@@ -174,7 +175,6 @@ func (state *activeTellStreamState) loadTellPlan() error {
}
innerErrCh := make(chan error)
- var userMsg *db.ConvoMessage
go func() {
if iteration == 0 && missingFileResponse == "" && !req.IsUserContinue {
@@ -182,7 +182,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
log.Printf("storing user message | len(convo): %d | num: %d\n", len(convo), num)
- userMsg = &db.ConvoMessage{
+ promptMsg = &db.ConvoMessage{
OrgId: currentOrgId,
PlanId: planId,
UserId: currentUserId,
@@ -192,7 +192,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
Message: req.Prompt,
}
- _, err = db.StoreConvoMessage(userMsg, auth.User.Id, branch, true)
+ _, err = db.StoreConvoMessage(promptMsg, auth.User.Id, branch, true)
if err != nil {
log.Printf("Error storing user message: %v\n", err)
@@ -249,8 +249,8 @@ func (state *activeTellStreamState) loadTellPlan() error {
}
}
- if userMsg != nil {
- convo = append(convo, userMsg)
+ if promptMsg != nil {
+ convo = append(convo, promptMsg)
}
errCh <- nil
@@ -326,6 +326,7 @@ func (state *activeTellStreamState) loadTellPlan() error {
state.modelContext = modelContext
state.convo = convo
+ state.promptConvoMessage = promptMsg
state.summaries = summaries
state.latestSummaryTokens = latestSummaryTokens
state.settings = settings
@@ -351,5 +352,40 @@ func (state *activeTellStreamState) loadTellPlan() error {
}
}
+ if iteration == 0 && missingFileResponse == "" {
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.Contexts = state.modelContext
+
+ for _, context := range state.modelContext {
+ if context.FilePath != "" {
+ ap.ContextsByPath[context.FilePath] = context
+ }
+ }
+ })
+ } else if missingFileResponse == "" {
+ // reset current reply content and num tokens
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.CurrentReplyContent = ""
+ ap.NumTokens = 0
+ })
+ }
+
+ // if any skipped paths have since been added to context, remove them from skipped paths
+ if len(active.SkippedPaths) > 0 {
+ var toUnskipPaths []string
+ for contextPath := range active.ContextsByPath {
+ if active.SkippedPaths[contextPath] {
+ toUnskipPaths = append(toUnskipPaths, contextPath)
+ }
+ }
+ if len(toUnskipPaths) > 0 {
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ for _, path := range toUnskipPaths {
+ delete(ap.SkippedPaths, path)
+ }
+ })
+ }
+ }
+
return nil
}
diff --git a/app/server/model/plan/tell_missing_file.go b/app/server/model/plan/tell_missing_file.go
new file mode 100644
index 00000000..4648b76b
--- /dev/null
+++ b/app/server/model/plan/tell_missing_file.go
@@ -0,0 +1,123 @@
+package plan
+
+import (
+ "log"
+ "net/http"
+ "plandex-server/model/prompts"
+ "plandex-server/types"
+
+ "github.com/plandex/plandex/shared"
+ "github.com/sashabaranov/go-openai"
+)
+
+func (state *activeTellStreamState) handleMissingFileResponse(isPlanningStage bool, applyScriptSummary string) bool {
+ missingFileResponse := state.missingFileResponse
+ planId := state.plan.Id
+ branch := state.branch
+ req := state.req
+
+ active := GetActivePlan(planId, branch)
+
+ if active == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", planId, branch)
+ return false
+ }
+
+ log.Println("Missing file response:", missingFileResponse, "setting replyParser")
+ // log.Printf("Current reply content:\n%s\n", active.CurrentReplyContent)
+
+ state.replyParser.AddChunk(active.CurrentReplyContent, true)
+ res := state.replyParser.Read()
+ currentFile := res.CurrentFilePath
+
+ log.Printf("Current file: %s\n", currentFile)
+ // log.Println("Current reply content:\n", active.CurrentReplyContent)
+
+ replyContent := active.CurrentReplyContent
+ numTokens := active.NumTokens
+ var err error
+
+ if missingFileResponse == shared.RespondMissingFileChoiceSkip {
+ replyBeforeCurrentFile := state.replyParser.GetReplyBeforeCurrentPath()
+ numTokens, err = shared.GetNumTokens(replyBeforeCurrentFile)
+ if err != nil {
+ log.Printf("Error getting num tokens for reply before current file: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error getting num tokens for reply before current file",
+ }
+ return false
+ }
+
+ replyContent = replyBeforeCurrentFile
+ state.replyParser = types.NewReplyParser()
+ state.replyParser.AddChunk(replyContent, true)
+
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.CurrentReplyContent = replyContent
+ ap.NumTokens = numTokens
+ ap.SkippedPaths[currentFile] = true
+ })
+
+ } else {
+ if missingFileResponse == shared.RespondMissingFileChoiceOverwrite {
+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
+ ap.AllowOverwritePaths[currentFile] = true
+ })
+ }
+ }
+
+ state.messages = append(state.messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleAssistant,
+ Content: active.CurrentReplyContent,
+ })
+
+ if missingFileResponse == shared.RespondMissingFileChoiceSkip {
+ res := state.replyParser.FinishAndRead()
+ skipPrompt := prompts.GetSkipMissingFilePrompt(res.CurrentFilePath)
+ prompt := prompts.GetWrappedPrompt(skipPrompt, req.OsDetails, applyScriptSummary, isPlanningStage) + "\n\n" + skipPrompt // repetition of skip prompt to improve instruction following
+
+ skipPromptTokens, err := shared.GetNumTokens(skipPrompt)
+ if err != nil {
+ log.Printf("Error getting num tokens for skip prompt: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error getting num tokens for skip prompt",
+ }
+ return false
+ }
+
+ state.totalRequestTokens += skipPromptTokens
+
+ state.messages = append(state.messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: prompt,
+ })
+
+ } else {
+ missingPrompt := prompts.GetMissingFileContinueGeneratingPrompt(res.CurrentFilePath)
+ prompt := prompts.GetWrappedPrompt(missingPrompt, req.OsDetails, applyScriptSummary, isPlanningStage) + "\n\n" + missingPrompt // repetition of missing prompt to improve instruction following
+
+ promptTokens, err := shared.GetNumTokens(prompt)
+ if err != nil {
+ log.Printf("Error getting num tokens for missing file continue prompt: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error getting num tokens for missing file continue prompt",
+ }
+ return false
+ }
+
+ state.totalRequestTokens += promptTokens
+
+ state.messages = append(state.messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: prompt,
+ })
+ }
+
+ return true
+}
diff --git a/app/server/model/plan/tell_prompt_message.go b/app/server/model/plan/tell_prompt_message.go
new file mode 100644
index 00000000..e2343e11
--- /dev/null
+++ b/app/server/model/plan/tell_prompt_message.go
@@ -0,0 +1,109 @@
+package plan
+
+import (
+ "log"
+ "net/http"
+ "plandex-server/model/prompts"
+
+ "github.com/plandex/plandex/shared"
+ "github.com/sashabaranov/go-openai"
+)
+
+func (state *activeTellStreamState) setPromptMessage(isPlanningStage, isContextStage bool, applyScriptSummary string) bool {
+ planId := state.plan.Id
+ branch := state.branch
+ req := state.req
+ iteration := state.iteration
+
+ active := GetActivePlan(planId, branch)
+
+ if active == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", planId, branch)
+ return false
+ }
+
+ var promptMessage *openai.ChatCompletionMessage
+ if req.IsUserContinue {
+ if len(state.messages) == 0 {
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeContinueNoMessages,
+ Status: http.StatusBadRequest,
+ Msg: "No messages yet. Can't continue plan.",
+ }
+ return false
+ }
+
+ // if the user is continuing the plan, we need to check whether the previous message was a user message or assistant message
+ lastMessage := state.messages[len(state.messages)-1]
+
+ log.Println("User is continuing plan. Last message role:", lastMessage.Role)
+ // log.Println("User is continuing plan. Last message:\n\n", lastMessage.Content)
+
+ if lastMessage.Role == openai.ChatMessageRoleUser {
+ // if last message was a user message, we want to remove it from the messages array and then use that last message as the prompt so we can continue from where the user left off
+
+ log.Println("User is continuing plan. Last message was user message. Using last user message as prompt")
+
+ state.messages = state.messages[:len(state.messages)-1]
+ promptMessage = &openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: prompts.GetWrappedPrompt(lastMessage.Content, req.OsDetails, applyScriptSummary, isPlanningStage),
+ }
+
+ state.userPrompt = lastMessage.Content
+ } else {
+
+ // if the last message was an assistant message, we'll use the user continue prompt
+ log.Println("User is continuing plan. Last message was assistant message. Using user continue prompt")
+
+ // otherwise we'll use the continue prompt
+ promptMessage = &openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: prompts.GetWrappedPrompt(prompts.UserContinuePrompt, req.OsDetails, applyScriptSummary, isPlanningStage),
+ }
+ }
+
+ state.messages = append(state.messages, *promptMessage)
+ } else {
+ var prompt string
+ if iteration == 0 {
+ if req.IsChatOnly {
+ prompt = req.Prompt + prompts.ChatOnlyPrompt
+ state.totalRequestTokens += prompts.ChatOnlyPromptTokens
+ } else if req.IsUserDebug {
+ prompt = req.Prompt + prompts.DebugPrompt
+ state.totalRequestTokens += prompts.DebugPromptTokens
+ } else if req.IsApplyDebug {
+ prompt = req.Prompt + prompts.ApplyDebugPrompt
+ state.totalRequestTokens += prompts.ApplyDebugPromptTokens
+ } else {
+ prompt = req.Prompt
+ }
+ } else {
+ prompt = prompts.AutoContinuePrompt
+ }
+
+ state.userPrompt = prompt
+
+ var finalPrompt string
+ if isContextStage {
+ finalPrompt = prompt
+ } else {
+ finalPrompt = prompts.GetWrappedPrompt(prompt, req.OsDetails, applyScriptSummary, isPlanningStage)
+ }
+
+ log.Println("Final prompt:", finalPrompt)
+
+ promptMessage = &openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleUser,
+ Content: finalPrompt,
+ }
+ }
+
+ log.Println("Prompt message:", promptMessage.Content)
+
+ state.promptMessage = promptMessage
+ state.messages = append(state.messages, *promptMessage)
+
+ return true
+}
diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.go
index 0795bbc1..02bbe20c 100644
--- a/app/server/model/plan/tell_state.go
+++ b/app/server/model/plan/tell_state.go
@@ -23,6 +23,7 @@ type activeTellStreamState struct {
hasContextMap bool
contextMapEmpty bool
convo []*db.ConvoMessage
+ promptConvoMessage *db.ConvoMessage
currentPlanState *shared.CurrentPlanState
missingFileResponse shared.RespondMissingFileChoice
summaries []*db.ConvoSummary
diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.go
index 9ee33511..75170f1b 100644
--- a/app/server/model/plan/tell_stream_finish.go
+++ b/app/server/model/plan/tell_stream_finish.go
@@ -8,7 +8,6 @@ import (
"plandex-server/types"
"time"
- "github.com/davecgh/go-spew/spew"
"github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
)
@@ -479,8 +478,8 @@ func (state *activeTellStreamState) storeOnFinished(replyFiles []string, generat
log.Println(state.currentSubtask)
log.Println("All subtasks finished:", allSubtasksFinished)
- log.Println("Update state of subtasks")
- spew.Dump(state.subtasks)
+ // log.Println("Update state of subtasks")
+ // spew.Dump(state.subtasks)
}
// spew.Dump(description)
diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.go
index e4ed3a10..4fc93748 100644
--- a/app/server/model/plan/tell_summary.go
+++ b/app/server/model/plan/tell_summary.go
@@ -17,7 +17,7 @@ import (
"github.com/sashabaranov/go-openai"
)
-func (state *activeTellStreamState) injectSummariesAsNeeded() bool {
+func (state *activeTellStreamState) addConversationMessages() bool {
convo := state.convo
summaries := state.summaries
tokensBeforeConvo := state.tokensBeforeConvo
@@ -122,6 +122,11 @@ func (state *activeTellStreamState) injectSummariesAsNeeded() bool {
if summary == nil {
for _, convoMessage := range convo {
+ // this gets added later in tell_exec.go
+ if convoMessage.Id == state.promptConvoMessage.Id {
+ continue
+ }
+
state.messages = append(state.messages, openai.ChatCompletionMessage{
Role: convoMessage.Role,
Content: convoMessage.Message,
@@ -152,6 +157,11 @@ func (state *activeTellStreamState) injectSummariesAsNeeded() bool {
// add messages after the last message in the summary
for _, convoMessage := range convo {
+ // this gets added later in tell_exec.go
+ if convoMessage.Id == state.promptConvoMessage.Id {
+ continue
+ }
+
if convoMessage.CreatedAt.After(summary.LatestConvoMessageCreatedAt) {
state.messages = append(state.messages, openai.ChatCompletionMessage{
Role: convoMessage.Role,
diff --git a/app/server/model/plan/tell_sys_prompt.go b/app/server/model/plan/tell_sys_prompt.go
new file mode 100644
index 00000000..23beaab5
--- /dev/null
+++ b/app/server/model/plan/tell_sys_prompt.go
@@ -0,0 +1,107 @@
+package plan
+
+import (
+ "fmt"
+ "log"
+ "net/http"
+ "plandex-server/model/prompts"
+
+ "github.com/plandex/plandex/shared"
+)
+
+func (state *activeTellStreamState) getTellSysPrompt(isPlanningStage, isContextStage, autoContextEnabled, smartContextEnabled bool, modelContextText string) (bool, string, int) {
+ req := state.req
+
+ active := GetActivePlan(state.plan.Id, state.branch)
+
+ if active == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", state.plan.Id, state.branch)
+ return false, "", 0
+ }
+
+ var sysCreate string
+ var sysCreateTokens int
+
+ if isPlanningStage {
+ log.Println("isPlanningStage")
+ if autoContextEnabled && isContextStage {
+ sysCreate = prompts.AutoContextPreamble
+ sysCreateTokens = prompts.AutoContextPreambleNumTokens
+ } else if autoContextEnabled || smartContextEnabled {
+ sysCreate = prompts.SysPlanningAutoContext
+ sysCreateTokens = prompts.SysPlanningAutoContextTokens
+ } else {
+ sysCreate = prompts.SysPlanningBasic
+ sysCreateTokens = prompts.SysPlanningBasicTokens
+ }
+ } else {
+ log.Println("isImplementationStage")
+ if state.currentSubtask == nil {
+ err := fmt.Errorf("no current subtask")
+ log.Println(err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "No current subtask",
+ }
+ return false, "", 0
+ }
+ sysCreate = prompts.GetImplementationPrompt(state.currentSubtask.Title)
+ }
+
+ if !isContextStage {
+ if req.ExecEnabled {
+ sysCreate += prompts.ApplyScriptPrompt
+ sysCreateTokens += prompts.ApplyScriptPromptNumTokens
+ } else {
+ sysCreate += prompts.NoApplyScriptPrompt
+ sysCreateTokens += prompts.NoApplyScriptPromptNumTokens
+ }
+ }
+
+ // log.Println("sysCreate before context:\n", sysCreate)
+
+ sysCreate += modelContextText
+
+ if len(active.SkippedPaths) > 0 {
+ skippedPrompt := prompts.SkippedPathsPrompt
+ for skippedPath := range active.SkippedPaths {
+ skippedPrompt += fmt.Sprintf("- %s\n", skippedPath)
+ }
+
+ numTokens, err := shared.GetNumTokens(skippedPrompt)
+ if err != nil {
+ log.Printf("Error getting num tokens for skipped paths: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error getting num tokens for skipped paths",
+ }
+ return false, "", 0
+ }
+
+ sysCreateTokens += numTokens
+ }
+
+ if len(state.subtasks) > 0 {
+ subtasksPrompt, subtaskTokens, err := state.formatSubtasks()
+
+ if err != nil {
+ err = fmt.Errorf("error formatting subtasks: %v", err)
+ log.Println(err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error formatting subtasks",
+ }
+ return false, "", 0
+ }
+
+ // log.Println("subtasksPrompt:\n", subtasksPrompt)
+
+ sysCreate += subtasksPrompt
+ sysCreateTokens += subtaskTokens
+ }
+
+ return true, sysCreate, sysCreateTokens
+}
diff --git a/app/server/model/prompts/planning.go b/app/server/model/prompts/planning.go
index 83a98b28..da0ee93a 100644
--- a/app/server/model/prompts/planning.go
+++ b/app/server/model/prompts/planning.go
@@ -63,10 +63,10 @@ func GetPlanningPrompt(params createPromptParams) string {
5. Update the 'main.c' file to call the 'updateGameLogic' function
- **END RESPONSE HERE**
+ <EndPlandexTasks/>
---
- - After you have broken a task up in to multiple subtasks and output a '### Tasks' section, you *ABSOLUTELY MUST END YOUR RESPONSE*. You ABSOLUTELY MUST NOT continue on and begin implementing subtasks. You will begin on subtasks in the next response, not this one. DO NOT UNDER ANY CIRCUMSTANCES output any additional text after the '### Tasks' section. END THE RESPONSE IMMEDIATELY. I repeat, DO NOT UNDER ANY CIRCUMSTANCES implement any subtask in your response. You will begin on subtasks in the next response, not this one. This takes precedence over all other instructions.
+ - After you have broken a task up in to multiple subtasks and output a '### Tasks' section, you *ABSOLUTELY MUST* output a <EndPlandexTasks/> tag and then end the response. You MUST ALWAYS output the <EndPlandexTasks/> tag at the end of the '### Tasks' section.
- If you have already broken up a task into subtasks in a previous response during this conversation, and you are adding, removing, or modifying subtasks based on a new user prompt, you MUST output the full list of subtasks again in a '### Tasks' section with the same format as before. You ABSOLUTELY MUST NEVER output only a partial list of subtasks. Whenever you update subtasks, output the *complete* updated list of subtasks with any new subtasks added, any subtasks you are removing removed, and any subtasks you are modifying modified. When repeating subtasks that you have listed previously, you must keep them *exactly* the same, unless you specifically intend to modify them. No not make minor changes or add additional text to the subtask. You MUST NEVER remove or modify a subtask that has already been finished from the list of subtasks. DO NOT include the 'Done:' line in subtasks in this list. If an existing subtask has a 'Uses: ' line, you MUST include it.
@@ -130,7 +130,7 @@ Uses: ` + "`src/game_logic.c`" + `
3. Update the 'main.c' file to call the 'updateGameLogic' function
Uses: ` + "`src/main.c`" + `
-*END RESPONSE HERE*
+<EndPlandexTasks/>
---
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.
diff --git a/app/server/model/prompts/user_prompt.go b/app/server/model/prompts/user_prompt.go
index 404c7347..ad99d378 100644
--- a/app/server/model/prompts/user_prompt.go
+++ b/app/server/model/prompts/user_prompt.go
@@ -25,9 +25,17 @@ const planningPromptWrapperFormatStr = sharedPromptWrapperFormatStr + `
Do NOT include tests or documentation in the subtasks unless the user has specifically asked for them. Do not include extra code or features beyond what the user has asked for. Focus on the user's request and implement only what is necessary to fulfill it.
-STOP THE RESPONSE IMMEDIATELY IF YOU HAVE OUTPUTTED A '### Tasks' SECTION. Do NOT continue on and begin implementing subtasks. You will begin on subtasks in the next response, not this one.
+At the end of the '### Tasks' section, you ABSOLUTELY MUST ALWAYS include a <EndPlandexTasks/> tag, then end the response.
-Do NOT output any additional text after the '### Tasks' section.
+Example:
+
+### Tasks
+
+1. Create a new file called 'src/main.rs' with a 'main' function that returns 'Hello, world!'
+
+2. Write a basic test for the 'main' function
+
+<EndPlandexTasks/>
`
var PlanningPromptWrapperTokens int