Skip to content

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

refactor: improve build state management with better model ID handling

Dane Schneider1d44791b06c8
diff --git a/app/server/model/plan/commit_msg.go b/app/server/model/plan/commit_msg.go
index 382be36d..ba18f3b9 100644
--- a/app/server/model/plan/commit_msg.go
+++ b/app/server/model/plan/commit_msg.go
@@ -12,6 +12,7 @@ import (
"plandex-server/model"
"plandex-server/model/prompts"
"plandex-server/types"
+ "plandex-server/utils"
"time"
shared "plandex-shared"
@@ -89,7 +90,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
- OutputTokens: config.GetReservedOutputTokens(),
+ OutputTokens: config.BaseModelConfig.MaxOutputTokens - numTokens,
ModelName: config.BaseModelConfig.ModelName,
},
})
@@ -114,7 +115,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
req.ToolChoice = *toolChoice
}
- descResp, err := model.CreateChatCompletionWithRetries(
+ descResp, err := model.CreateChatCompletion(
clients,
&config,
activePlan.Ctx,
@@ -136,7 +137,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
if config.BaseModelConfig.PreferredModelOutputFormat == shared.ModelOutputFormatXml {
content := descResp.Choices[0].Message.Content
- commitMsg = GetXMLContent(content, "commitMsg")
+ commitMsg = utils.GetXMLContent(content, "commitMsg")
if commitMsg == "" {
return nil, &shared.ApiError{
Type: shared.ApiErrorTypeOther,
@@ -188,6 +189,11 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
outputTokens = shared.GetNumTokensEstimate(commitMsg)
}
+ var cachedTokens int
+ if descResp.Usage.PromptTokensDetails != nil {
+ cachedTokens = descResp.Usage.PromptTokensDetails.CachedTokens
+ }
+
log.Println("Sending DidSendModelRequest hook")
go func() {
@@ -197,6 +203,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
+ CachedTokens: cachedTokens,
ModelName: config.BaseModelConfig.ModelName,
ModelProvider: config.BaseModelConfig.Provider,
ModelPackName: settings.ModelPack.Name,
@@ -204,7 +211,7 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
Purpose: "Generated commit message for suggested changes",
GenerationId: descResp.ID,
PlanId: planId,
- ModelStreamId: activePlan.ModelStreamId,
+ ModelStreamId: state.modelStreamId,
ConvoMessageId: state.replyId,
RequestStartedAt: reqStarted,
@@ -273,7 +280,7 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
- OutputTokens: config.GetReservedOutputTokens(),
+ OutputTokens: config.BaseModelConfig.MaxOutputTokens - numTokens,
ModelName: config.BaseModelConfig.ModelName,
},
})
@@ -289,7 +296,7 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
TopP: config.TopP,
}
- resp, err := model.CreateChatCompletionWithRetries(
+ resp, err := model.CreateChatCompletion(
clients,
&config,
ctx,
@@ -318,12 +325,18 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
outputTokens = shared.GetNumTokensEstimate(commitMsg)
}
+ var cachedTokens int
+ if resp.Usage.PromptTokensDetails != nil {
+ cachedTokens = resp.Usage.PromptTokensDetails.CachedTokens
+ }
+
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
Auth: auth,
Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
+ CachedTokens: cachedTokens,
ModelName: config.BaseModelConfig.ModelName,
ModelProvider: config.BaseModelConfig.Provider,
ModelPackName: settings.ModelPack.Name,
diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.go
index 3052468b..fa62ae9d 100644
--- a/app/server/model/plan/exec_status.go
+++ b/app/server/model/plan/exec_status.go
@@ -5,10 +5,12 @@ import (
"encoding/json"
"fmt"
"log"
+ "net/http"
"plandex-server/hooks"
"plandex-server/model"
"plandex-server/model/prompts"
"plandex-server/types"
+ "plandex-server/utils"
"strings"
"time"
@@ -37,7 +39,7 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
if state.currentSubtask != nil {
completionMarker := fmt.Sprintf("**%s** has been completed", state.currentSubtask.Title)
log.Printf("[ExecStatus] Checking for subtask completion marker: %q", completionMarker)
- log.Printf("[ExecStatus] Current subtask: %q (finished=%v)", state.currentSubtask.Title, state.currentSubtask.IsFinished)
+ log.Printf("[ExecStatus] Current subtask: %q", state.currentSubtask.Title)
if strings.Contains(currentMessage, completionMarker) {
log.Printf("[ExecStatus] ✓ Subtask completion marker found")
@@ -66,6 +68,13 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
if !potentialProblem {
log.Printf("[ExecStatus] ✓ Subtask completion marker found and no potential problem - will mark as completed")
+
+ return execStatusShouldContinueResult{
+ subtaskFinished: true,
+ }, nil
+ } else if state.currentSubtask.NumTries >= 1 {
+ log.Printf("[ExecStatus] ✓ Subtask completion marker found, but the operations are questionable -- marking it done anyway since it's the second try and we can't risk an infinite loop")
+
return execStatusShouldContinueResult{
subtaskFinished: true,
}, nil
@@ -101,7 +110,13 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
}, nil
}
- content := prompts.GetExecStatusFinishedSubtask(state.userPrompt, fullSubtask, currentMessage, previousMessages)
+ content := prompts.GetExecStatusFinishedSubtask(prompts.GetExecStatusFinishedSubtaskParams{
+ UserPrompt: state.userPrompt,
+ CurrentSubtask: fullSubtask,
+ CurrentMessage: currentMessage,
+ PreviousMessages: previousMessages,
+ PreferredModelOutputFormat: config.BaseModelConfig.PreferredModelOutputFormat,
+ })
messages := []types.ExtendedChatMessage{
{
@@ -122,7 +137,7 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
- OutputTokens: config.GetReservedOutputTokens(),
+ OutputTokens: config.BaseModelConfig.MaxOutputTokens - numTokens,
ModelName: config.BaseModelConfig.ModelName,
},
})
@@ -155,7 +170,7 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
}
}
- resp, err := model.CreateChatCompletionWithRetries(
+ resp, err := model.CreateChatCompletion(
clients,
&config,
ctx,
@@ -172,8 +187,8 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
if config.BaseModelConfig.PreferredModelOutputFormat == shared.ModelOutputFormatXml {
content := resp.Choices[0].Message.Content
- reasoning = GetXMLContent(content, "reasoning")
- subtaskFinishedStr := GetXMLContent(content, "subtaskFinished")
+ reasoning = utils.GetXMLContent(content, "reasoning")
+ subtaskFinishedStr := utils.GetXMLContent(content, "subtaskFinished")
subtaskFinished = subtaskFinishedStr == "true"
if reasoning == "" || subtaskFinishedStr == "" {
@@ -222,6 +237,11 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
outputTokens = shared.GetNumTokensEstimate(reasoning)
}
+ var cachedTokens int
+ if resp.Usage.PromptTokensDetails != nil {
+ cachedTokens = resp.Usage.PromptTokensDetails.CachedTokens
+ }
+
go func() {
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
Auth: auth,
@@ -229,6 +249,7 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
+ CachedTokens: cachedTokens,
ModelName: config.BaseModelConfig.ModelName,
ModelProvider: config.BaseModelConfig.Provider,
ModelPackName: settings.ModelPack.Name,
@@ -236,7 +257,7 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
Purpose: "Evaluate if task was finished",
GenerationId: resp.ID,
PlanId: plan.Id,
- ModelStreamId: state.activePlan.ModelStreamId,
+ ModelStreamId: state.modelStreamId,
ConvoMessageId: state.replyId,
RequestStartedAt: reqStarted,
@@ -256,4 +277,3 @@ func (state *activeTellStreamState) execStatusShouldContinue(currentMessage stri
subtaskFinished: subtaskFinished,
}, nil
}
-
diff --git a/app/server/model/plan/state.go b/app/server/model/plan/state.go
index 4121ab34..d9ed74cf 100644
--- a/app/server/model/plan/state.go
+++ b/app/server/model/plan/state.go
@@ -87,18 +87,12 @@ func CreateActivePlan(orgId, userId, planId, branch, prompt string, buildOnly, a
func DeleteActivePlan(orgId, userId, planId, branch string) {
log.Printf("Deleting active plan %s - %s - %s\n", planId, branch, orgId)
- var ctx context.Context
- var cancelFn context.CancelFunc
-
activePlan := GetActivePlan(planId, branch)
if activePlan == nil {
log.Printf("DeleteActivePlan - No active plan found for plan ID %s on branch %s\n", planId, branch)
return
}
- // If the plan is still around, use the plan’s context
- ctx, cancelFn = context.WithCancel(activePlan.Ctx)
-
repoLockId, err := db.LockRepo(
db.LockRepoParams{
UserId: userId,
@@ -106,8 +100,8 @@ func DeleteActivePlan(orgId, userId, planId, branch string) {
PlanId: planId,
Branch: branch,
Scope: db.LockScopeWrite,
- Ctx: ctx,
- CancelFn: cancelFn,
+ Ctx: context.Background(),
+ CancelFn: func() {},
},
)
diff --git a/app/server/model/plan/tell_context.go b/app/server/model/plan/tell_context.go
index 05a9150a..d445c467 100644
--- a/app/server/model/plan/tell_context.go
+++ b/app/server/model/plan/tell_context.go
@@ -18,7 +18,7 @@ type formatModelContextParams struct {
smartContextEnabled bool
execEnabled bool
basicOnly bool
- cache bool
+ cacheControl bool
activeOnly bool
autoOnly bool
activatedPaths map[string]bool
@@ -186,7 +186,7 @@ func (state *activeTellStreamState) formatModelContext(params formatModelContext
Text: s,
}
- if params.cache {
+ if params.cacheControl {
res.CacheControl = &types.CacheControlSpec{
Type: types.CacheControlTypeEphemeral,
}
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index 8d65d890..367e0923 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -136,6 +136,7 @@ func execTellPlan(params execTellPlanParams) {
log.Println("execTellPlan - Plan status set to replying")
state := &activeTellStreamState{
+ modelStreamId: active.ModelStreamId,
execTellPlanParams: params,
clients: clients,
req: req,
@@ -173,7 +174,7 @@ func execTellPlan(params execTellPlanParams) {
smartContextEnabled: req.SmartContext,
execEnabled: req.ExecEnabled,
basicOnly: true,
- cache: true,
+ cacheControl: true,
})
if state.currentStage.PlanningPhase == shared.PlanningPhasePlanning {
@@ -295,6 +296,17 @@ func execTellPlan(params execTellPlanParams) {
modelConfig = state.settings.ModelPack.GetCoder().GetRoleForInputTokens(requestTokens)
}
+ // if the model doesn't support cache control, remove the cache control spec from the messages
+ if !modelConfig.BaseModelConfig.SupportsCacheControl {
+ for i := range state.messages {
+ for j := range state.messages[i].Content {
+ if state.messages[i].Content[j].CacheControl != nil {
+ state.messages[i].Content[j].CacheControl = nil
+ }
+ }
+ }
+ }
+
log.Println("totalRequestTokens:", requestTokens)
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
@@ -302,7 +314,7 @@ func execTellPlan(params execTellPlanParams) {
Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: requestTokens,
- OutputTokens: modelConfig.GetReservedOutputTokens(),
+ OutputTokens: modelConfig.BaseModelConfig.MaxOutputTokens - requestTokens,
ModelName: modelConfig.BaseModelConfig.ModelName,
},
})
@@ -343,7 +355,7 @@ func execTellPlan(params execTellPlanParams) {
// log.Printf("Error marshaling model request to JSON: %v\n", err)
// }
- stream, err := model.CreateChatCompletionStreamWithRetries(clients, &modelConfig, active.ModelStreamCtx, modelReq)
+ stream, err := model.CreateChatCompletionStream(clients, &modelConfig, active.ModelStreamCtx, modelReq)
if err != nil {
log.Printf("Error starting reply stream: %v\n", err)